-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathIntlEngineInterfaceExtensionObject.cpp
3321 lines (2833 loc) · 148 KB
/
IntlEngineInterfaceExtensionObject.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeLibraryPch.h"
#include "EngineInterfaceObject.h"
#include "IntlEngineInterfaceExtensionObject.h"
#include "Types/DeferredTypeHandler.h"
#include "Base/WindowsGlobalizationAdapter.h"
#ifdef ENABLE_INTL_OBJECT
#include "ByteCode/ByteCodeSerializer.h"
#include "errstr.h"
#include "ByteCode/ByteCodeDumper.h"
#include "Codex/Utf8Helper.h"
#ifdef INTL_WINGLOB
using namespace Windows::Globalization;
#endif
#ifdef INTL_ICU
#include <CommonPal.h>
#include "PlatformAgnostic/ChakraICU.h"
using namespace PlatformAgnostic::ICUHelpers;
#if defined(DBG) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
#define INTL_TRACE(fmt, ...) Output::Trace(Js::IntlPhase, _u("%S(): " fmt "\n"), __func__, __VA_ARGS__)
#else
#define INTL_TRACE(fmt, ...)
#endif
#define ICU_ASSERT(e, expr) \
do \
{ \
if (e == U_MEMORY_ALLOCATION_ERROR) \
{ \
Js::Throw::OutOfMemory(); \
} \
else if (ICU_FAILURE(e)) \
{ \
AssertOrFailFastMsg(false, ICU_ERRORMESSAGE(e)); \
} \
else if (!(expr)) \
{ \
AssertOrFailFast(expr); \
} \
} while (false)
#endif // INTL_ICU
// The following macros allow the key-value pairs to be C++ enums as well as JS objects
// in Intl.js. When adding a new macro, follow the same format as the _VALUES macros below,
// and add your new _VALUES macro to PROJECTED_ENUMS along with the name of the enum.
// NOTE: make sure the last VALUE macro has the highest integer value, since the C++ enum's ::Max
// value is added to the end of the C++ enum definition as an increment of the previous value.
// The ::Max value is used in a defensive assert, and we want to make sure its always 1 greater
// than the highest valid value.
#define NUMBERFORMATSTYLE_VALUES(VALUE) \
VALUE(Default, default_, 0) \
VALUE(Decimal, decimal, 0) \
VALUE(Percent, percent, 1) \
VALUE(Currency, currency, 2)
#define NUMBERFORMATCURRENCYDISPLAY_VALUES(VALUE) \
VALUE(Default, default_, 0) \
VALUE(Symbol, symbol, 0) \
VALUE(Code, code, 1) \
VALUE(Name, name, 2)
#define COLLATORSENSITIVITY_VALUES(VALUE) \
VALUE(Default, default_, 3) \
VALUE(Base, base, 0) \
VALUE(Accent, accent, 1) \
VALUE(Case, case_, 2) \
VALUE(Variant, variant, 3)
#define COLLATORCASEFIRST_VALUES(VALUE) \
VALUE(Default, default_, 2) \
VALUE(Upper, upper, 0) \
VALUE(Lower, lower, 1) \
VALUE(False, false_, 2)
// LocaleDataKind intentionally has no Default value
#define LOCALEDATAKIND_VALUES(VALUE) \
VALUE(Collation, co, 0) \
VALUE(CaseFirst, kf, 1) \
VALUE(Numeric, kn, 2) \
VALUE(Calendar, ca, 3) \
VALUE(NumberingSystem, nu, 4) \
VALUE(HourCycle, hc, 5)
//BuiltInFunctionID intentionally has no Default value
#define BUILTINFUNCTIONID_VALUES(VALUE) \
VALUE(DateToLocaleString, DateToLocaleString, 0) \
VALUE(DateToLocaleDateString, DateToLocaleDateString, 1) \
VALUE(DateToLocaleTimeString, DateToLocaleTimeString, 2) \
VALUE(NumberToLocaleString, NumberToLocaleString, 3) \
VALUE(StringLocaleCompare, StringLocaleCompare, 4)
#define ENUM_VALUE(enumName, propId, value) enumName = value,
#define PROJECTED_ENUM(ClassName, VALUES) \
enum class ClassName \
{ \
VALUES(ENUM_VALUE) \
Max \
};
#define PROJECTED_ENUMS(PROJECT) \
PROJECT(LocaleDataKind, LOCALEDATAKIND_VALUES) \
PROJECT(CollatorCaseFirst, COLLATORCASEFIRST_VALUES) \
PROJECT(CollatorSensitivity, COLLATORSENSITIVITY_VALUES) \
PROJECT(NumberFormatCurrencyDisplay, NUMBERFORMATCURRENCYDISPLAY_VALUES) \
PROJECT(NumberFormatStyle, NUMBERFORMATSTYLE_VALUES) \
PROJECT(BuiltInFunctionID, BUILTINFUNCTIONID_VALUES)
PROJECTED_ENUMS(PROJECTED_ENUM)
#undef PROJECTED_ENUM
#undef ENUM_VALUE
#pragma warning(push)
#pragma warning(disable:4309) // truncation of constant value
#pragma warning(disable:4838) // conversion from 'int' to 'const char' requires a narrowing conversion
#if DISABLE_JIT
#if TARGET_64
#include "InJavascript/Intl.js.nojit.bc.64b.h"
#else
#include "InJavascript/Intl.js.nojit.bc.32b.h"
#endif
#else
#if TARGET_64
#include "InJavascript/Intl.js.bc.64b.h"
#else
#include "InJavascript/Intl.js.bc.32b.h"
#endif
#endif
#pragma warning(pop)
#define IfFailAssertAndThrowHr(op) \
if (FAILED(hr=(op))) \
{ \
AssertMsg(false, "HRESULT was a failure."); \
JavascriptError::MapAndThrowError(scriptContext, hr); \
} \
#define IfFailAssertMsgAndThrowHr(op, msg) \
if (FAILED(hr=(op))) \
{ \
AssertMsg(false, msg); \
JavascriptError::MapAndThrowError(scriptContext, hr); \
} \
#ifdef INTL_WINGLOB
#define TO_JSBOOL(sc, b) ((b) ? (sc)->GetLibrary()->GetTrue() : (sc)->GetLibrary()->GetFalse())
#define IfCOMFailIgnoreSilentlyAndReturn(op) \
if(FAILED(hr=(op))) \
{ \
return; \
} \
#define HandleOOMSOEHR(hr) \
if (hr == E_OUTOFMEMORY) \
{ \
JavascriptError::ThrowOutOfMemoryError(scriptContext); \
} \
else if(hr == VBSERR_OutOfStack) \
{ \
JavascriptError::ThrowStackOverflowError(scriptContext); \
} \
#define IfFailThrowHr(op) \
if (FAILED(hr=(op))) \
{ \
JavascriptError::MapAndThrowError(scriptContext, hr); \
} \
#define SetPropertyOn(obj, propID, value) \
obj->SetProperty(propID, value, Js::PropertyOperationFlags::PropertyOperation_None, nullptr) \
#define SetStringPropertyOn(obj, propID, propValue) \
SetPropertyOn(obj, propID, Js::JavascriptString::NewCopySz(propValue, scriptContext)) \
#define SetPropertyLOn(obj, literalProperty, value) \
obj->SetProperty(Js::JavascriptString::NewCopySz(literalProperty, scriptContext), value, Js::PropertyOperationFlags::PropertyOperation_None, nullptr) \
#define SetStringPropertyLOn(obj, literalProperty, propValue) \
SetPropertyLOn(obj, literalProperty, Js::JavascriptString::NewCopySz(propValue, scriptContext)) \
#define SetPropertyBuiltInOn(obj, builtInPropID, value) \
SetPropertyOn(obj, Js::PropertyIds::builtInPropID, value) \
#define SetStringPropertyBuiltInOn(obj, builtInPropID, propValue) \
SetPropertyBuiltInOn(obj, builtInPropID, Js::JavascriptString::NewCopySz(propValue, scriptContext))
#define GetPropertyFrom(obj, propertyID) \
Js::JavascriptOperators::GetProperty(obj, propertyID, &propertyValue, scriptContext) \
#define GetPropertyLFrom(obj, propertyName) \
GetPropertyFrom(obj, scriptContext->GetOrAddPropertyIdTracked(propertyName, wcslen(propertyName)))
#define GetPropertyBuiltInFrom(obj, builtInPropID) \
GetPropertyFrom(obj, Js::PropertyIds::builtInPropID) \
#define GetTypedPropertyBuiltInFrom(obj, builtInPropID, Type) \
(GetPropertyFrom(obj, Js::PropertyIds::builtInPropID) && Type::Is(propertyValue)) \
#define HasPropertyOn(obj, propID) \
Js::JavascriptOperators::HasProperty(obj, propID) \
#define HasPropertyBuiltInOn(obj, builtInPropID) \
HasPropertyOn(obj, Js::PropertyIds::builtInPropID) \
#define HasPropertyLOn(obj, propertyName) \
HasPropertyOn(obj, scriptContext->GetOrAddPropertyIdTracked(propertyName, wcslen(propertyName)))
#define SetHSTRINGPropertyOn(obj, propID, hstringValue) \
SetStringPropertyOn(obj, propID, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
#define SetHSTRINGPropertyLOn(obj, literalProperty, hstringValue) \
SetStringPropertyLOn(obj, literalProperty, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
#define SetHSTRINGPropertyBuiltInOn(obj, builtInPropID, hstringValue) \
SetStringPropertyBuiltInOn(obj, builtInPropID, wgl->WindowsGetStringRawBuffer(hstringValue, &length)) \
#endif
#define INTL_CHECK_ARGS(argcheck) AssertOrFailFastMsg((argcheck), "Intl platform function given bad arguments")
namespace Js
{
#ifdef ENABLE_INTL_OBJECT
#ifdef INTL_WINGLOB
class AutoHSTRING
{
PREVENT_COPY(AutoHSTRING)
private:
HSTRING value;
public:
HSTRING *operator&() { Assert(value == nullptr); return &value; }
HSTRING operator*() const { Assert(value != nullptr); return value; }
AutoHSTRING()
: value(nullptr)
{ }
~AutoHSTRING()
{
Clear();
}
void Clear()
{
if (value != nullptr)
{
WindowsDeleteString(value);
value = nullptr;
}
}
};
#endif
// Defining Finalizable wrappers for Intl data
#if defined(INTL_WINGLOB)
class AutoCOMJSObject : public FinalizableObject
{
IInspectable *instance;
public:
DEFINE_VTABLE_CTOR_NOBASE(AutoCOMJSObject);
AutoCOMJSObject(IInspectable *object)
: instance(object)
{ }
static AutoCOMJSObject * New(Recycler * recycler, IInspectable *object)
{
return RecyclerNewFinalized(recycler, AutoCOMJSObject, object);
}
void Finalize(bool isShutdown) override
{
}
void Dispose(bool isShutdown) override
{
if (!isShutdown)
{
instance->Release();
}
}
void Mark(Recycler * recycler) override
{
}
IInspectable *GetInstance()
{
return instance;
}
};
#elif defined(INTL_ICU)
template<typename TResource, void(__cdecl * CloseFunction)(TResource)>
class FinalizableICUObject : public FinalizableObject
{
private:
FieldNoBarrier(TResource) resource;
public:
FinalizableICUObject(TResource resource) : resource(resource)
{
}
static FinalizableICUObject<TResource, CloseFunction> *New(Recycler *recycler, TResource resource)
{
return RecyclerNewFinalized(recycler, FinalizableICUObject, resource);
}
TResource GetInstance()
{
return resource;
}
operator TResource()
{
return resource;
}
void Finalize(bool isShutdown) override
{
}
void Dispose(bool isShutdown) override
{
if (!isShutdown)
{
CloseFunction(resource);
}
}
void Mark(Recycler *recycler) override
{
}
};
typedef FinalizableICUObject<UNumberFormat *, unum_close> FinalizableUNumberFormat;
typedef FinalizableICUObject<UDateFormat *, udat_close> FinalizableUDateFormat;
typedef FinalizableICUObject<UFieldPositionIterator *, ufieldpositer_close> FinalizableUFieldPositionIterator;
typedef FinalizableICUObject<UCollator *, ucol_close> FinalizableUCollator;
typedef FinalizableICUObject<UPluralRules *, uplrules_close> FinalizableUPluralRules;
template<typename TExecutor>
static void EnsureBuffer(_In_ TExecutor executor, _In_ Recycler *recycler, _Outptr_result_buffer_(*returnLength) char16 **ret, _Out_ int *returnLength, _In_ bool allowZeroLengthStrings = false, _In_ int firstTryLength = 8)
{
UErrorCode status = U_ZERO_ERROR;
*ret = RecyclerNewArrayLeaf(recycler, char16, firstTryLength);
*returnLength = executor(reinterpret_cast<UChar *>(*ret), firstTryLength, &status);
AssertOrFailFast(allowZeroLengthStrings ? *returnLength >= 0 : *returnLength > 0);
if (ICU_BUFFER_FAILURE(status))
{
AssertOrFailFastMsg(*returnLength >= firstTryLength, "Executor reported buffer failure but did not require additional space");
int secondTryLength = *returnLength + 1;
INTL_TRACE("Buffer of length %d was too short, retrying with buffer of length %d", firstTryLength, secondTryLength);
status = U_ZERO_ERROR;
*ret = RecyclerNewArrayLeaf(recycler, char16, secondTryLength);
*returnLength = executor(reinterpret_cast<UChar *>(*ret), secondTryLength, &status);
AssertOrFailFastMsg(*returnLength == secondTryLength - 1, "Second try of executor returned unexpected length");
}
else
{
AssertOrFailFastMsg(*returnLength < firstTryLength, "Executor required additional length but reported successful status");
}
AssertOrFailFastMsg(!ICU_FAILURE(status), ICU_ERRORMESSAGE(status));
}
template <typename T>
static T *AssertProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
{
Var propertyValue = nullptr;
JavascriptOperators::GetProperty(state, propertyId, &propertyValue, state->GetScriptContext());
AssertOrFailFast(propertyValue && T::Is(propertyValue));
return T::UnsafeFromVar(propertyValue);
}
static JavascriptString *AssertStringProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
{
return AssertProperty<JavascriptString>(state, propertyId);
}
static int AssertIntegerProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
{
Var propertyValue = nullptr;
JavascriptOperators::GetProperty(state, propertyId, &propertyValue, state->GetScriptContext());
AssertOrFailFast(propertyValue);
if (TaggedInt::Is(propertyValue))
{
return TaggedInt::ToInt32(propertyValue);
}
else
{
AssertOrFailFast(JavascriptNumber::Is(propertyValue));
int ret;
AssertOrFailFast(JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(propertyValue), &ret));
return ret;
}
}
static bool AssertBooleanProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
{
return AssertProperty<JavascriptBoolean>(state, propertyId)->GetValue();
}
template <typename T>
static T AssertEnumProperty(_In_ DynamicObject *state, _In_ PropertyIds propertyId)
{
int p = AssertIntegerProperty(state, propertyId);
T ret = static_cast<T>(p);
AssertMsg(p >= 0 && ret < T::Max, "Invalid value for enum property");
return ret;
}
template <typename T>
static _Ret_notnull_ T ThrowOOMIfNull(_In_ T value)
{
if (value == nullptr)
{
Throw::OutOfMemory();
}
return value;
}
template <size_t N>
static void LangtagToLocaleID(_In_count_(langtagLength) const char16 *langtag, _In_ charcount_t langtagLength, _Out_ char(&localeID)[N])
{
static_assert(N >= ULOC_FULLNAME_CAPACITY, "LocaleID must be large enough to fit the largest possible ICU localeID");
UErrorCode status = U_ZERO_ERROR;
utf8::WideToNarrow langtag8(langtag, langtagLength);
int32_t localeIDLength = 0;
uloc_forLanguageTag(langtag8, localeID, N, &localeIDLength, &status);
ICU_ASSERT(status, localeIDLength > 0 && static_cast<size_t>(localeIDLength) < N);
}
template <size_t N>
static void LangtagToLocaleID(_In_ JavascriptString *langtag, _Out_ char(&localeID)[N])
{
LangtagToLocaleID(langtag->GetString(), langtag->GetLength(), localeID);
}
template <typename Callback>
static void ForEachUEnumeration(UEnumeration *enumeration, Callback callback)
{
int valueLength = 0;
UErrorCode status = U_ZERO_ERROR;
for (int index = 0, const char *value = uenum_next(enumeration, &valueLength, &status); value != nullptr; index++, value = uenum_next(enumeration, &valueLength, &status))
{
ICU_ASSERT(status, valueLength > 0);
// cast valueLength now since we have verified its greater than 0
callback(index, value, static_cast<charcount_t>(valueLength));
}
}
template <typename Callback>
static void ForEachUEnumeration16(UEnumeration *enumeration, Callback callback)
{
int valueLength = 0;
UErrorCode status = U_ZERO_ERROR;
int index = 0;
for (const UChar *value = uenum_unext(enumeration, &valueLength, &status); value != nullptr; index++, value = uenum_unext(enumeration, &valueLength, &status))
{
ICU_ASSERT(status, valueLength > 0);
// cast valueLength now since we have verified its greater than 0
callback(index, reinterpret_cast<const char16 *>(value), static_cast<charcount_t>(valueLength));
}
}
#endif
IntlEngineInterfaceExtensionObject::IntlEngineInterfaceExtensionObject(Js::ScriptContext* scriptContext) :
EngineExtensionObjectBase(EngineInterfaceExtensionKind_Intl, scriptContext),
dateToLocaleString(nullptr),
dateToLocaleTimeString(nullptr),
dateToLocaleDateString(nullptr),
numberToLocaleString(nullptr),
stringLocaleCompare(nullptr),
intlNativeInterfaces(nullptr),
intlByteCode(nullptr),
wasInitialized(false)
{
}
// Initializes the IntlEngineInterfaceExtensionObject::EntryInfo struct
#ifdef INTL_ENTRY
#undef INTL_ENTRY
#endif
#define INTL_ENTRY(id, func) \
NoProfileFunctionInfo IntlEngineInterfaceExtensionObject::EntryInfo::Intl_##func##(FORCE_NO_WRITE_BARRIER_TAG(IntlEngineInterfaceExtensionObject::EntryIntl_##func##));
#include "IntlExtensionObjectBuiltIns.h"
#undef INTL_ENTRY
#ifdef INTL_WINGLOB
WindowsGlobalizationAdapter* IntlEngineInterfaceExtensionObject::GetWindowsGlobalizationAdapter(_In_ ScriptContext * scriptContext)
{
return scriptContext->GetThreadContext()->GetWindowsGlobalizationAdapter();
}
#endif
void IntlEngineInterfaceExtensionObject::Initialize()
{
if (wasInitialized)
{
return;
}
JavascriptLibrary* library = scriptContext->GetLibrary();
// Ensure JsBuiltIns are initialized before initializing Intl which uses some of them.
library->EnsureBuiltInEngineIsReady();
DynamicObject* commonObject = library->GetEngineInterfaceObject()->GetCommonNativeInterfaces();
if (scriptContext->IsIntlEnabled())
{
Assert(library->GetEngineInterfaceObject() != nullptr);
this->intlNativeInterfaces = DynamicObject::New(library->GetRecycler(),
DynamicType::New(scriptContext, TypeIds_Object, commonObject, nullptr,
DeferredTypeHandler<InitializeIntlNativeInterfaces>::GetDefaultInstance()));
library->AddMember(library->GetEngineInterfaceObject(), Js::PropertyIds::Intl, this->intlNativeInterfaces);
// Only show the platform object publicly if -IntlPlatform is passed
if (CONFIG_FLAG(IntlPlatform))
{
library->AddMember(library->GetIntlObject(), PropertyIds::platform, this->intlNativeInterfaces);
}
}
wasInitialized = true;
}
#if DBG
void IntlEngineInterfaceExtensionObject::DumpByteCode()
{
Output::Print(_u("Dumping Intl Byte Code:"));
Assert(this->intlByteCode);
Js::ByteCodeDumper::DumpRecursively(intlByteCode);
}
#endif
bool IntlEngineInterfaceExtensionObject::InitializeIntlNativeInterfaces(DynamicObject* intlNativeInterfaces, DeferredTypeHandlerBase * typeHandler, DeferredInitializeMode mode)
{
int initSlotCapacity = 0;
// automatically get the initSlotCapacity from everything we are about to add to intlNativeInterfaces
#define INTL_ENTRY(id, func) initSlotCapacity++;
#include "IntlExtensionObjectBuiltIns.h"
#undef INTL_ENTRY
#define PROJECTED_ENUM(ClassName, VALUES) initSlotCapacity++;
PROJECTED_ENUMS(PROJECTED_ENUM)
#undef PROJECTED_ENUM
// add capacity for platform.winglob and platform.FallbackSymbol
initSlotCapacity += 2;
typeHandler->Convert(intlNativeInterfaces, mode, initSlotCapacity);
ScriptContext* scriptContext = intlNativeInterfaces->GetScriptContext();
JavascriptLibrary* library = scriptContext->GetLibrary();
// gives each entrypoint a property ID on the intlNativeInterfaces library object
#define INTL_ENTRY(id, func) library->AddFunctionToLibraryObject(intlNativeInterfaces, Js::PropertyIds::##id, &IntlEngineInterfaceExtensionObject::EntryInfo::Intl_##func, 1);
#include "IntlExtensionObjectBuiltIns.h"
#undef INTL_ENTRY
library->AddMember(intlNativeInterfaces, PropertyIds::FallbackSymbol, library->CreateSymbol(BuiltInPropertyRecords::_intlFallbackSymbol));
DynamicObject * enumObj = nullptr;
// Projects the exact layout of our C++ enums into Intl.js so that we dont have to remember to keep them in sync
#define ENUM_VALUE(enumName, propId, value) library->AddMember(enumObj, PropertyIds::##propId, JavascriptNumber::ToVar(value, scriptContext));
#define PROJECTED_ENUM(ClassName, VALUES) \
enumObj = library->CreateObject(); \
VALUES(ENUM_VALUE) \
library->AddMember(intlNativeInterfaces, PropertyIds::##ClassName, enumObj); \
PROJECTED_ENUMS(PROJECTED_ENUM)
#undef PROJECTED_ENUM
#undef ENUM_VALUE
#if INTL_WINGLOB
library->AddMember(intlNativeInterfaces, Js::PropertyIds::winglob, library->GetTrue());
#else
library->AddMember(intlNativeInterfaces, Js::PropertyIds::winglob, library->GetFalse());
// when using ICU, we can call ulocdata_getCLDRVersion to ensure that ICU is functioning properly before allowing Intl to continue.
// ulocdata_getCLDRVersion will cause the data file to be loaded, and if we don't have enough memory to do so, we can throw OutOfMemory here.
// This is to protect against spurious U_MISSING_RESOURCE_ERRORs and U_FILE_ACCESS_ERRORs coming from early-lifecycle
// functions that require ICU data.
// See OS#16897150, OS#16896933, and others relating to bad statuses returned by GetLocaleData and IsLocaleAvailable
// This was initially attempted using u_init, however u_init does not work with Node's default small-icu data file
// because it contains no converters.
UErrorCode status = U_ZERO_ERROR;
UVersionInfo cldrVersion;
ulocdata_getCLDRVersion(cldrVersion, &status);
if (status == U_MEMORY_ALLOCATION_ERROR || status == U_FILE_ACCESS_ERROR || status == U_MISSING_RESOURCE_ERROR)
{
// Trace that this happens in case there are build system changes that actually cause the data file to be not found
INTL_TRACE("Could not initialize ICU - ulocdata_getCLDRVersion returned status %S", u_errorName(status));
Throw::OutOfMemory();
}
else
{
INTL_TRACE("Using CLDR version %d.%d.%d.%d", cldrVersion[0], cldrVersion[1], cldrVersion[2], cldrVersion[3]);
}
AssertOrFailFastMsg(U_SUCCESS(status), "ulocdata_getCLDRVersion returned non-OOM failure");
#endif // else !INTL_WINGLOB
intlNativeInterfaces->SetHasNoEnumerableProperties(true);
return true;
}
void IntlEngineInterfaceExtensionObject::deletePrototypePropertyHelper(ScriptContext* scriptContext, DynamicObject* intlObject, Js::PropertyId objectPropertyId, Js::PropertyId getterFunctionId)
{
DynamicObject *prototypeObject = nullptr;
DynamicObject *functionObj = nullptr;
Var propertyValue = nullptr;
Var prototypeValue = nullptr;
Var resolvedOptionsValue = nullptr;
Var getter = nullptr;
Var setter = nullptr;
if (!JavascriptOperators::GetProperty(intlObject, objectPropertyId, &propertyValue, scriptContext) ||
!JavascriptOperators::IsObject(propertyValue))
{
return;
}
if (!JavascriptOperators::GetProperty(DynamicObject::FromVar(propertyValue), Js::PropertyIds::prototype, &prototypeValue, scriptContext) ||
!JavascriptOperators::IsObject(prototypeValue))
{
return;
}
prototypeObject = DynamicObject::FromVar(prototypeValue);
if (!JavascriptOperators::GetProperty(prototypeObject, Js::PropertyIds::resolvedOptions, &resolvedOptionsValue, scriptContext) ||
!JavascriptOperators::IsObject(resolvedOptionsValue))
{
return;
}
functionObj = DynamicObject::FromVar(resolvedOptionsValue);
functionObj->SetConfigurable(Js::PropertyIds::prototype, true);
functionObj->DeleteProperty(Js::PropertyIds::prototype, Js::PropertyOperationFlags::PropertyOperation_None);
if (!JavascriptOperators::GetOwnAccessors(prototypeObject, getterFunctionId, &getter, &setter, scriptContext) ||
!JavascriptOperators::IsObject(getter))
{
return;
}
functionObj = DynamicObject::FromVar(getter);
functionObj->SetConfigurable(Js::PropertyIds::prototype, true);
functionObj->DeleteProperty(Js::PropertyIds::prototype, Js::PropertyOperationFlags::PropertyOperation_None);
}
void IntlEngineInterfaceExtensionObject::cleanUpIntl(ScriptContext *scriptContext, DynamicObject* intlObject)
{
this->dateToLocaleString = nullptr;
this->dateToLocaleTimeString = nullptr;
this->dateToLocaleDateString = nullptr;
this->numberToLocaleString = nullptr;
this->stringLocaleCompare = nullptr;
//Failed to setup Intl; Windows.Globalization.dll is most likely missing.
if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::Collator))
{
intlObject->DeleteProperty(Js::PropertyIds::Collator, Js::PropertyOperationFlags::PropertyOperation_None);
}
if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::NumberFormat))
{
intlObject->DeleteProperty(Js::PropertyIds::NumberFormat, Js::PropertyOperationFlags::PropertyOperation_None);
}
if (Js::JavascriptOperators::HasProperty(intlObject, Js::PropertyIds::DateTimeFormat))
{
intlObject->DeleteProperty(Js::PropertyIds::DateTimeFormat, Js::PropertyOperationFlags::PropertyOperation_None);
}
}
void IntlEngineInterfaceExtensionObject::EnsureIntlByteCode(_In_ ScriptContext * scriptContext)
{
if (this->intlByteCode == nullptr)
{
SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(Js::Constants::NoHostSourceContext, NULL);
Assert(sourceContextInfo != nullptr);
SRCINFO si;
memset(&si, 0, sizeof(si));
si.sourceContextInfo = sourceContextInfo;
SRCINFO *hsi = scriptContext->AddHostSrcInfo(&si);
uint32 flags = fscrIsLibraryCode | (CONFIG_FLAG(CreateFunctionProxy) && !scriptContext->IsProfiling() ? fscrAllowFunctionProxy : 0);
HRESULT hr = Js::ByteCodeSerializer::DeserializeFromBuffer(scriptContext, flags, (LPCUTF8)nullptr, hsi, (byte*)Library_Bytecode_Intl, nullptr, &this->intlByteCode);
IfFailAssertMsgAndThrowHr(hr, "Failed to deserialize Intl.js bytecode - very probably the bytecode needs to be rebuilt.");
this->SetHasBytecode();
}
}
void IntlEngineInterfaceExtensionObject::InjectIntlLibraryCode(_In_ ScriptContext * scriptContext, DynamicObject* intlObject, IntlInitializationType intlInitializationType)
{
JavascriptExceptionObject *pExceptionObject = nullptr;
#ifdef INTL_WINGLOB
WindowsGlobalizationAdapter* globAdapter = GetWindowsGlobalizationAdapter(scriptContext);
#endif
try {
this->EnsureIntlByteCode(scriptContext);
Assert(intlByteCode != nullptr);
#ifdef INTL_WINGLOB
DelayLoadWindowsGlobalization *library = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
#endif
JavascriptString* initType = nullptr;
#ifdef INTL_WINGLOB
HRESULT hr;
//Ensure we have initialized all appropriate COM objects for the adapter (we will be using them now)
IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureCommonObjectsInitialized(library));
#endif
switch (intlInitializationType)
{
default:
AssertMsg(false, "Not a valid intlInitializationType.");
// fall thru
case IntlInitializationType::Intl:
#ifdef INTL_WINGLOB
IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureNumberFormatObjectsInitialized(library));
IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureDateTimeFormatObjectsInitialized(library));
#endif
initType = scriptContext->GetPropertyString(PropertyIds::Intl);
break;
case IntlInitializationType::StringPrototype:
// No other windows globalization adapter needed. Common adapter should suffice
initType = scriptContext->GetPropertyString(PropertyIds::String);
break;
case IntlInitializationType::DatePrototype:
#ifdef INTL_WINGLOB
IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureDateTimeFormatObjectsInitialized(library));
#endif
initType = scriptContext->GetPropertyString(PropertyIds::Date);
break;
case IntlInitializationType::NumberPrototype:
#ifdef INTL_WINGLOB
IfCOMFailIgnoreSilentlyAndReturn(globAdapter->EnsureNumberFormatObjectsInitialized(library));
#endif
initType = scriptContext->GetPropertyString(PropertyIds::Number);
break;
}
Js::ScriptFunction *function = scriptContext->GetLibrary()->CreateScriptFunction(intlByteCode->GetNestedFunctionForExecution(0));
#ifdef ENABLE_SCRIPT_PROFILING
// If we are profiling, we need to register the script to the profiler callback, so the script compiled event will be sent.
if (scriptContext->IsProfiling())
{
scriptContext->RegisterScript(function->GetFunctionProxy());
}
#endif
#ifdef ENABLE_SCRIPT_DEBUGGING
// Mark we are profiling library code already, so that any initialization library code called here won't be reported to profiler.
// Also tell the debugger not to record events during intialization so that we don't leak information about initialization.
AutoInitLibraryCodeScope autoInitLibraryCodeScope(scriptContext);
#endif
Js::Var args[] = { scriptContext->GetLibrary()->GetUndefined(), scriptContext->GetLibrary()->GetEngineInterfaceObject(), initType };
Js::CallInfo callInfo(Js::CallFlags_Value, _countof(args));
Js::Arguments arguments(callInfo, args);
scriptContext->GetThreadContext()->ExecuteImplicitCall(function, Js::ImplicitCall_Accessor, [=]()->Js::Var
{
return JavascriptFunction::CallRootFunctionInScript(function, arguments);
});
// Delete prototypes on functions if initialized Intl object
if (intlInitializationType == IntlInitializationType::Intl)
{
deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::Collator, Js::PropertyIds::compare);
deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::NumberFormat, Js::PropertyIds::format);
deletePrototypePropertyHelper(scriptContext, intlObject, Js::PropertyIds::DateTimeFormat, Js::PropertyIds::format);
}
#if DBG_DUMP
if (PHASE_DUMP(Js::ByteCodePhase, function->GetFunctionProxy()) && Js::Configuration::Global.flags.Verbose)
{
DumpByteCode();
}
#endif
}
catch (const JavascriptException& err)
{
pExceptionObject = err.GetAndClear();
}
if (pExceptionObject)
{
if (intlInitializationType == IntlInitializationType::Intl)
{
cleanUpIntl(scriptContext, intlObject);
}
if (pExceptionObject == ThreadContext::GetContextForCurrentThread()->GetPendingOOMErrorObject() ||
pExceptionObject == ThreadContext::GetContextForCurrentThread()->GetPendingSOErrorObject())
{
// Reset factory objects that are might not have fully initialized
#ifdef INTL_WINGLOB
globAdapter->ResetCommonFactoryObjects();
#endif
switch (intlInitializationType) {
default:
AssertMsg(false, "Not a valid intlInitializationType.");
// fall thru
case IntlInitializationType::Intl:
#ifdef INTL_WINGLOB
globAdapter->ResetNumberFormatFactoryObjects();
globAdapter->ResetDateTimeFormatFactoryObjects();
#endif
scriptContext->GetLibrary()->ResetIntlObject();
break;
case IntlInitializationType::StringPrototype:
// No other windows globalization adapter is created. Resetting common adapter should suffice
break;
case IntlInitializationType::DatePrototype:
#ifdef INTL_WINGLOB
globAdapter->ResetDateTimeFormatFactoryObjects();
#endif
break;
case IntlInitializationType::NumberPrototype:
#ifdef INTL_WINGLOB
globAdapter->ResetNumberFormatFactoryObjects();
#endif
break;
}
JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
}
#if DEBUG
JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
#else
JavascriptError::ThrowTypeError(scriptContext, JSERR_IntlNotAvailable);
#endif
}
}
// First parameter is boolean.
Var IntlEngineInterfaceExtensionObject::EntryIntl_RaiseAssert(RecyclableObject* function, CallInfo callInfo, ...)
{
EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
if (args.Info.Count < 2 || !JavascriptError::Is(args.Values[1]))
{
AssertMsg(false, "Intl's Assert platform API was called incorrectly.");
return scriptContext->GetLibrary()->GetUndefined();
}
#if DEBUG
#ifdef INTL_ICU_DEBUG
Output::Print(_u("EntryIntl_RaiseAssert\n"));
#endif
JavascriptExceptionOperators::Throw(JavascriptError::FromVar(args.Values[1]), scriptContext);
#else
return scriptContext->GetLibrary()->GetUndefined();
#endif
}
Var IntlEngineInterfaceExtensionObject::EntryIntl_IsWellFormedLanguageTag(RecyclableObject* function, CallInfo callInfo, ...)
{
#if defined(INTL_ICU)
AssertOrFailFastMsg(false, "IsWellFormedLanguageTag is not implemented using ICU");
return nullptr;
#else
EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
{
// IsWellFormedLanguageTag of undefined or non-string is false
return scriptContext->GetLibrary()->GetFalse();
}
JavascriptString *argString = JavascriptString::FromVar(args.Values[1]);
return TO_JSBOOL(scriptContext, GetWindowsGlobalizationAdapter(scriptContext)->IsWellFormedLanguageTag(scriptContext, argString->GetSz()));
#endif
}
Var IntlEngineInterfaceExtensionObject::EntryIntl_NormalizeLanguageTag(RecyclableObject* function, CallInfo callInfo, ...)
{
EngineInterfaceObject_CommonFunctionProlog(function, callInfo);
#if defined(INTL_ICU)
INTL_CHECK_ARGS(args.Info.Count == 2 && JavascriptString::Is(args[1]));
UErrorCode status = U_ZERO_ERROR;
JavascriptString *langtag = JavascriptString::UnsafeFromVar(args[1]);
utf8::WideToNarrow langtag8(langtag->GetSz(), langtag->GetLength());
// ICU doesn't have a full-fledged canonicalization implementation that correctly replaces all preferred values
// and grandfathered tags, as required by #sec-canonicalizelanguagetag.
// However, passing the locale through uloc_forLanguageTag -> uloc_toLanguageTag gets us most of the way there
// by replacing some(?) values, correctly capitalizing the tag, and re-ordering extensions
int parsedLength = 0;
char localeID[ULOC_FULLNAME_CAPACITY] = { 0 };
int forLangTagResultLength = uloc_forLanguageTag(langtag8, localeID, ULOC_FULLNAME_CAPACITY, &parsedLength, &status);
AssertOrFailFast(parsedLength >= 0);
if (status == U_ILLEGAL_ARGUMENT_ERROR || ((charcount_t) parsedLength) < langtag->GetLength())
{
// The string passed in to NormalizeLanguageTag has already passed IsStructurallyValidLanguageTag.
// However, duplicate unicode extension keys, such as "de-u-co-phonebk-co-phonebk", are structurally
// valid according to RFC5646 yet still trigger U_ILLEGAL_ARGUMENT_ERROR
// V8 ~6.2 says that the above language tag is invalid, while SpiderMonkey ~58 handles it.
// Until we have a more spec-compliant implementation of CanonicalizeLanguageTag, err on the side
// of caution and say it is invalid.
// We also check for parsedLength < langtag->GetLength() because there are cases when status == U_ZERO_ERROR
// but the langtag was not valid, such as "en-tesTER-TESter" (OSS-Fuzz #6657).
JavascriptError::ThrowRangeError(scriptContext, JSERR_LocaleNotWellFormed, langtag);
}
// forLangTagResultLength can be 0 if langtag is "und".
// uloc_toLanguageTag("") returns "und", so this works out (forLanguageTag can return >= 0 but toLanguageTag must return > 0)
ICU_ASSERT(status, forLangTagResultLength >= 0 && ((charcount_t) parsedLength) == langtag->GetLength());
char canonicalized[ULOC_FULLNAME_CAPACITY] = { 0 };
int toLangTagResultLength = uloc_toLanguageTag(localeID, canonicalized, ULOC_FULLNAME_CAPACITY, true, &status);
ICU_ASSERT(status, toLangTagResultLength > 0);
// allocate toLangTagResultLength + 1 to leave room for null terminator
char16 *canonicalized16 = RecyclerNewArrayLeaf(scriptContext->GetRecycler(), char16, toLangTagResultLength + 1);
charcount_t canonicalized16Len = 0;
HRESULT hr = utf8::NarrowStringToWideNoAlloc(
canonicalized,
toLangTagResultLength,
canonicalized16,
toLangTagResultLength + 1,
&canonicalized16Len
);
AssertOrFailFast(hr == S_OK && ((int) canonicalized16Len) == toLangTagResultLength);
return JavascriptString::NewWithBuffer(canonicalized16, toLangTagResultLength, scriptContext);
#else
if (args.Info.Count < 2 || !JavascriptString::Is(args.Values[1]))
{
// NormalizeLanguageTag of undefined or non-string is undefined
return scriptContext->GetLibrary()->GetUndefined();
}
JavascriptString *argString = JavascriptString::FromVar(args.Values[1]);
JavascriptString *retVal;
HRESULT hr;
AutoHSTRING str;
hr = GetWindowsGlobalizationAdapter(scriptContext)->NormalizeLanguageTag(scriptContext, argString->GetSz(), &str);
DelayLoadWindowsGlobalization *wsl = scriptContext->GetThreadContext()->GetWindowsGlobalizationLibrary();
PCWSTR strBuf = wsl->WindowsGetStringRawBuffer(*str, NULL);
retVal = Js::JavascriptString::NewCopySz(strBuf, scriptContext);
if (FAILED(hr))
{
HandleOOMSOEHR(hr);
//If we can't normalize the tag; return undefined.
return scriptContext->GetLibrary()->GetUndefined();
}
return retVal;
#endif
}
#ifdef INTL_ICU
template <const char *(__cdecl *GetAvailableLocalesFunc)(int), int(__cdecl *CountAvailableLocalesFunc)(void)>
static bool BinarySearchForLocale(const char *localeID)
{