[runtime] Switch getenv to use heap memory
[mono.git] / mono / metadata / locales.c
1 /*
2  * locales.c: Culture-sensitive handling
3  *
4  * Authors:
5  *      Dick Porter (dick@ximian.com)
6  *      Mohammad DAMT (mdamt@cdl2000.com)
7  *      Marek Safar (marek.safar@gmail.com)
8  *
9  * Copyright 2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  * (C) 2003 PT Cakram Datalingga Duaribu  http://www.cdl2000.com
12  * Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
13  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
14  */
15
16 #include <config.h>
17 #include <glib.h>
18 #include <string.h>
19
20 #include <mono/metadata/debug-helpers.h>
21 #include <mono/metadata/object.h>
22 #include <mono/metadata/appdomain.h>
23 #include <mono/metadata/exception.h>
24 #include <mono/metadata/monitor.h>
25 #include <mono/metadata/locales.h>
26 #include <mono/metadata/culture-info.h>
27 #include <mono/metadata/culture-info-tables.h>
28 #include <mono/utils/bsearch.h>
29
30 #ifndef DISABLE_NORMALIZATION
31 #include <mono/metadata/normalization-tables.h>
32 #endif
33
34 #include <locale.h>
35 #if defined(__APPLE__)
36 #include <CoreFoundation/CoreFoundation.h>
37 #endif
38
39 #undef DEBUG
40
41 static gint32 string_invariant_compare_char (gunichar2 c1, gunichar2 c2,
42                                              gint32 options);
43 static gint32 string_invariant_compare (MonoString *str1, gint32 off1,
44                                         gint32 len1, MonoString *str2,
45                                         gint32 off2, gint32 len2,
46                                         gint32 options);
47 static gint32 string_invariant_indexof (MonoString *source, gint32 sindex,
48                                         gint32 count, MonoString *value,
49                                         MonoBoolean first);
50 static gint32 string_invariant_indexof_char (MonoString *source, gint32 sindex,
51                                              gint32 count, gunichar2 value,
52                                              MonoBoolean first);
53
54 static const CultureInfoEntry* culture_info_entry_from_lcid (int lcid);
55
56 static const RegionInfoEntry* region_info_entry_from_lcid (int lcid);
57
58 /* Lazy class loading functions */
59 static GENERATE_GET_CLASS_WITH_CACHE (culture_info, "System.Globalization", "CultureInfo")
60
61 static int
62 culture_lcid_locator (const void *a, const void *b)
63 {
64         const int *lcid = (const int *)a;
65         const CultureInfoEntry *bb = (const CultureInfoEntry *)b;
66
67         return *lcid - bb->lcid;
68 }
69
70 static int
71 culture_name_locator (const void *a, const void *b)
72 {
73         const char *aa = (const char *)a;
74         const CultureInfoNameEntry *bb = (const CultureInfoNameEntry *)b;
75         int ret;
76         
77         ret = strcmp (aa, idx2string (bb->name));
78
79         return ret;
80 }
81
82 static int
83 region_name_locator (const void *a, const void *b)
84 {
85         const char *aa = (const char *)a;
86         const RegionInfoNameEntry *bb = (const RegionInfoNameEntry *)b;
87         int ret;
88         
89         ret = strcmp (aa, idx2string (bb->name));
90
91         return ret;
92 }
93
94 static MonoArray*
95 create_group_sizes_array (const gint *gs, gint ml, MonoError *error)
96 {
97         MonoArray *ret;
98         int i, len = 0;
99
100         error_init (error);
101
102         for (i = 0; i < ml; i++) {
103                 if (gs [i] == -1)
104                         break;
105                 len++;
106         }
107         
108         ret = mono_array_new_cached (mono_domain_get (),
109                                      mono_get_int32_class (), len, error);
110         return_val_if_nok (error, NULL);
111
112         for(i = 0; i < len; i++)
113                 mono_array_set (ret, gint32, i, gs [i]);
114
115         return ret;
116 }
117
118 static MonoArray*
119 create_names_array_idx (const guint16 *names, int ml, MonoError *error)
120 {
121         MonoArray *ret;
122         MonoDomain *domain;
123         int i;
124
125         error_init (error);
126
127         if (names == NULL)
128                 return NULL;
129
130         domain = mono_domain_get ();
131
132         ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), ml, error);
133         return_val_if_nok (error, NULL);
134
135         for(i = 0; i < ml; i++)
136                 mono_array_setref (ret, i, mono_string_new (domain, dtidx2string (names [i])));
137
138         return ret;
139 }
140
141 static MonoArray*
142 create_names_array_idx_dynamic (const guint16 *names, int ml, MonoError *error)
143 {
144         MonoArray *ret;
145         MonoDomain *domain;
146         int i, len = 0;
147
148         error_init (error);
149
150         if (names == NULL)
151                 return NULL;
152
153         domain = mono_domain_get ();
154
155         for (i = 0; i < ml; i++) {
156                 if (names [i] == 0)
157                         break;
158                 len++;
159         }
160
161         ret = mono_array_new_cached (mono_domain_get (), mono_get_string_class (), len, error);
162         return_val_if_nok (error, NULL);
163
164         for(i = 0; i < len; i++)
165                 mono_array_setref (ret, i, mono_string_new (domain, pattern2string (names [i])));
166
167         return ret;
168 }
169
170 MonoBoolean
171 ves_icall_System_Globalization_CalendarData_fill_calendar_data (MonoCalendarData *this_obj, MonoString *name, gint32 calendar_index)
172 {
173         MonoError error;
174         MonoDomain *domain;
175         const DateTimeFormatEntry *dfe;
176         const CultureInfoNameEntry *ne;
177         const CultureInfoEntry *ci;
178         char *n;
179
180         n = mono_string_to_utf8_checked (name, &error);
181         if (mono_error_set_pending_exception (&error))
182                 return FALSE;
183         ne = (const CultureInfoNameEntry *)mono_binary_search (n, culture_name_entries, NUM_CULTURE_ENTRIES,
184                         sizeof (CultureInfoNameEntry), culture_name_locator);
185         g_free (n);
186         if (ne == NULL) {
187                 return FALSE;
188         }
189
190         ci = &culture_entries [ne->culture_entry_index];
191         dfe = &datetime_format_entries [ci->datetime_format_index];
192
193         domain = mono_domain_get ();
194
195         MONO_OBJECT_SETREF (this_obj, NativeName, mono_string_new (domain, idx2string (ci->nativename)));
196         MonoArray *short_date_patterns = create_names_array_idx_dynamic (dfe->short_date_patterns,
197                                                                          NUM_SHORT_DATE_PATTERNS, &error);
198         return_val_and_set_pending_if_nok (&error, FALSE);
199         MONO_OBJECT_SETREF (this_obj, ShortDatePatterns, short_date_patterns);
200         MonoArray *year_month_patterns =create_names_array_idx_dynamic (dfe->year_month_patterns,
201                                                                         NUM_YEAR_MONTH_PATTERNS, &error);
202         return_val_and_set_pending_if_nok (&error, FALSE);
203         MONO_OBJECT_SETREF (this_obj, YearMonthPatterns, year_month_patterns);
204
205         MonoArray *long_date_patterns = create_names_array_idx_dynamic (dfe->long_date_patterns,
206                                                                         NUM_LONG_DATE_PATTERNS, &error);
207         return_val_and_set_pending_if_nok (&error, FALSE);
208         MONO_OBJECT_SETREF (this_obj, LongDatePatterns, long_date_patterns);
209
210         MONO_OBJECT_SETREF (this_obj, MonthDayPattern, mono_string_new (domain, pattern2string (dfe->month_day_pattern)));
211
212         MonoArray *day_names = create_names_array_idx (dfe->day_names, NUM_DAYS, &error);
213         return_val_and_set_pending_if_nok (&error, FALSE);
214         MONO_OBJECT_SETREF (this_obj, DayNames, day_names);
215
216         MonoArray *abbr_day_names = create_names_array_idx (dfe->abbreviated_day_names, 
217                                                             NUM_DAYS, &error);
218         return_val_and_set_pending_if_nok (&error, FALSE);
219         MONO_OBJECT_SETREF (this_obj, AbbreviatedDayNames, abbr_day_names);
220
221         MonoArray *ss_day_names = create_names_array_idx (dfe->shortest_day_names, NUM_DAYS, &error);
222         return_val_and_set_pending_if_nok (&error, FALSE);
223         MONO_OBJECT_SETREF (this_obj, SuperShortDayNames, ss_day_names);
224
225         MonoArray *month_names = create_names_array_idx (dfe->month_names, NUM_MONTHS, &error);
226         return_val_and_set_pending_if_nok (&error, FALSE);
227         MONO_OBJECT_SETREF (this_obj, MonthNames, month_names);
228
229         MonoArray *abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_names,
230                                                             NUM_MONTHS, &error);
231         return_val_and_set_pending_if_nok (&error, FALSE);
232         MONO_OBJECT_SETREF (this_obj, AbbreviatedMonthNames, abbr_mon_names);
233
234         
235         MonoArray *gen_month_names = create_names_array_idx (dfe->month_genitive_names, NUM_MONTHS, &error);
236         return_val_and_set_pending_if_nok (&error, FALSE);
237         MONO_OBJECT_SETREF (this_obj, GenitiveMonthNames, gen_month_names);
238
239         MonoArray *gen_abbr_mon_names = create_names_array_idx (dfe->abbreviated_month_genitive_names, NUM_MONTHS, &error);
240         return_val_and_set_pending_if_nok (&error, FALSE);
241         MONO_OBJECT_SETREF (this_obj, GenitiveAbbreviatedMonthNames, gen_abbr_mon_names);
242
243         return TRUE;
244 }
245
246 void
247 ves_icall_System_Globalization_CultureData_fill_culture_data (MonoCultureData *this_obj, gint32 datetime_index)
248 {
249         MonoError error;
250         MonoDomain *domain;
251         const DateTimeFormatEntry *dfe;
252
253         g_assert (datetime_index >= 0);
254
255         dfe = &datetime_format_entries [datetime_index];
256
257         domain = mono_domain_get ();
258
259         MONO_OBJECT_SETREF (this_obj, AMDesignator, mono_string_new (domain, idx2string (dfe->am_designator)));
260         MONO_OBJECT_SETREF (this_obj, PMDesignator, mono_string_new (domain, idx2string (dfe->pm_designator)));
261         MONO_OBJECT_SETREF (this_obj, TimeSeparator, mono_string_new (domain, idx2string (dfe->time_separator)));
262
263         MonoArray *long_time_patterns = create_names_array_idx_dynamic (dfe->long_time_patterns,
264                                                                         NUM_LONG_TIME_PATTERNS, &error);
265         if (mono_error_set_pending_exception (&error))
266                 return;
267         MONO_OBJECT_SETREF (this_obj, LongTimePatterns, long_time_patterns);
268
269         MonoArray *short_time_patterns = create_names_array_idx_dynamic (dfe->short_time_patterns,
270                                                                          NUM_SHORT_TIME_PATTERNS, &error);
271         if (mono_error_set_pending_exception (&error))
272                 return;
273         MONO_OBJECT_SETREF (this_obj, ShortTimePatterns, short_time_patterns);
274         this_obj->FirstDayOfWeek = dfe->first_day_of_week;
275         this_obj->CalendarWeekRule = dfe->calendar_week_rule;
276 }
277
278 void
279 ves_icall_System_Globalization_CultureData_fill_number_data (MonoNumberFormatInfo* number, gint32 number_index)
280 {
281         MonoError error;
282         MonoDomain *domain;
283         const NumberFormatEntry *nfe;
284
285         g_assert (number_index >= 0);
286
287         nfe = &number_format_entries [number_index];
288
289         domain = mono_domain_get ();
290
291         number->currencyDecimalDigits = nfe->currency_decimal_digits;
292         MONO_OBJECT_SETREF (number, currencyDecimalSeparator, mono_string_new (domain,
293                         idx2string (nfe->currency_decimal_separator)));
294         MONO_OBJECT_SETREF (number, currencyGroupSeparator, mono_string_new (domain,
295                         idx2string (nfe->currency_group_separator)));
296         MonoArray *currency_sizes_arr = create_group_sizes_array (nfe->currency_group_sizes,
297                                                                   GROUP_SIZE, &error);
298         if (mono_error_set_pending_exception (&error))
299                 return;
300         MONO_OBJECT_SETREF (number, currencyGroupSizes, currency_sizes_arr);
301         number->currencyNegativePattern = nfe->currency_negative_pattern;
302         number->currencyPositivePattern = nfe->currency_positive_pattern;
303         MONO_OBJECT_SETREF (number, currencySymbol, mono_string_new (domain, idx2string (nfe->currency_symbol)));
304         MONO_OBJECT_SETREF (number, naNSymbol, mono_string_new (domain, idx2string (nfe->nan_symbol)));
305         MONO_OBJECT_SETREF (number, negativeInfinitySymbol, mono_string_new (domain,
306                         idx2string (nfe->negative_infinity_symbol)));
307         MONO_OBJECT_SETREF (number, negativeSign, mono_string_new (domain, idx2string (nfe->negative_sign)));
308         number->numberDecimalDigits = nfe->number_decimal_digits;
309         MONO_OBJECT_SETREF (number, numberDecimalSeparator, mono_string_new (domain,
310                         idx2string (nfe->number_decimal_separator)));
311         MONO_OBJECT_SETREF (number, numberGroupSeparator, mono_string_new (domain, idx2string (nfe->number_group_separator)));
312         MonoArray *number_sizes_arr = create_group_sizes_array (nfe->number_group_sizes,
313                                                                 GROUP_SIZE, &error);
314         if (mono_error_set_pending_exception (&error))
315                 return;
316         MONO_OBJECT_SETREF (number, numberGroupSizes, number_sizes_arr);
317         number->numberNegativePattern = nfe->number_negative_pattern;
318         number->percentNegativePattern = nfe->percent_negative_pattern;
319         number->percentPositivePattern = nfe->percent_positive_pattern;
320         MONO_OBJECT_SETREF (number, percentSymbol, mono_string_new (domain, idx2string (nfe->percent_symbol)));
321         MONO_OBJECT_SETREF (number, perMilleSymbol, mono_string_new (domain, idx2string (nfe->per_mille_symbol)));
322         MONO_OBJECT_SETREF (number, positiveInfinitySymbol, mono_string_new (domain,
323                         idx2string (nfe->positive_infinity_symbol)));
324         MONO_OBJECT_SETREF (number, positiveSign, mono_string_new (domain, idx2string (nfe->positive_sign)));
325 }
326
327 static MonoBoolean
328 construct_culture (MonoCultureInfo *this_obj, const CultureInfoEntry *ci, MonoError *error)
329 {
330         MonoDomain *domain = mono_domain_get ();
331
332         error_init (error);
333
334         this_obj->lcid = ci->lcid;
335         MONO_OBJECT_SETREF (this_obj, name, mono_string_new (domain, idx2string (ci->name)));
336         MONO_OBJECT_SETREF (this_obj, englishname, mono_string_new (domain, idx2string (ci->englishname)));
337         MONO_OBJECT_SETREF (this_obj, nativename, mono_string_new (domain, idx2string (ci->nativename)));
338         MONO_OBJECT_SETREF (this_obj, win3lang, mono_string_new (domain, idx2string (ci->win3lang)));
339         MONO_OBJECT_SETREF (this_obj, iso3lang, mono_string_new (domain, idx2string (ci->iso3lang)));
340         MONO_OBJECT_SETREF (this_obj, iso2lang, mono_string_new (domain, idx2string (ci->iso2lang)));
341
342         // It's null for neutral cultures
343         if (ci->territory > 0)
344                 MONO_OBJECT_SETREF (this_obj, territory, mono_string_new (domain, idx2string (ci->territory)));
345
346         MonoArray *native_calendar_names = create_names_array_idx (ci->native_calendar_names, NUM_CALENDARS, error);
347         return_val_if_nok (error, FALSE);
348         MONO_OBJECT_SETREF (this_obj, native_calendar_names, native_calendar_names);
349         this_obj->parent_lcid = ci->parent_lcid;
350         this_obj->datetime_index = ci->datetime_format_index;
351         this_obj->number_index = ci->number_format_index;
352         this_obj->calendar_type = ci->calendar_type;
353         this_obj->text_info_data = &ci->text_info;
354         
355         return TRUE;
356 }
357
358 static MonoBoolean
359 construct_region (MonoRegionInfo *this_obj, const RegionInfoEntry *ri)
360 {
361         MonoDomain *domain = mono_domain_get ();
362
363         this_obj->geo_id = ri->geo_id;
364         MONO_OBJECT_SETREF (this_obj, iso2name, mono_string_new (domain, idx2string (ri->iso2name)));
365         MONO_OBJECT_SETREF (this_obj, iso3name, mono_string_new (domain, idx2string (ri->iso3name)));
366         MONO_OBJECT_SETREF (this_obj, win3name, mono_string_new (domain, idx2string (ri->win3name)));
367         MONO_OBJECT_SETREF (this_obj, english_name, mono_string_new (domain, idx2string (ri->english_name)));
368         MONO_OBJECT_SETREF (this_obj, native_name, mono_string_new (domain, idx2string (ri->native_name)));
369         MONO_OBJECT_SETREF (this_obj, currency_symbol, mono_string_new (domain, idx2string (ri->currency_symbol)));
370         MONO_OBJECT_SETREF (this_obj, iso_currency_symbol, mono_string_new (domain, idx2string (ri->iso_currency_symbol)));
371         MONO_OBJECT_SETREF (this_obj, currency_english_name, mono_string_new (domain, idx2string (ri->currency_english_name)));
372         MONO_OBJECT_SETREF (this_obj, currency_native_name, mono_string_new (domain, idx2string (ri->currency_native_name)));
373         
374         return TRUE;
375 }
376
377 static const CultureInfoEntry*
378 culture_info_entry_from_lcid (int lcid)
379 {
380         const CultureInfoEntry *ci;
381
382         ci = (const CultureInfoEntry *)mono_binary_search (&lcid, culture_entries, NUM_CULTURE_ENTRIES, sizeof (CultureInfoEntry), culture_lcid_locator);
383
384         return ci;
385 }
386
387 static const RegionInfoEntry*
388 region_info_entry_from_lcid (int lcid)
389 {
390         const RegionInfoEntry *entry;
391         const CultureInfoEntry *ne;
392
393         ne = (const CultureInfoEntry *)mono_binary_search (&lcid, culture_entries, NUM_CULTURE_ENTRIES, sizeof (CultureInfoEntry), culture_lcid_locator);
394
395         if (ne == NULL)
396                 return FALSE;
397
398         entry = &region_entries [ne->region_entry_index];
399
400         return entry;
401 }
402
403 #if defined (__APPLE__)
404 static gchar*
405 get_darwin_locale (void)
406 {
407         static gchar *darwin_locale = NULL;
408         CFLocaleRef locale = NULL;
409         CFStringRef locale_language = NULL;
410         CFStringRef locale_country = NULL;
411         CFStringRef locale_script = NULL;
412         CFStringRef locale_cfstr = NULL;
413         CFIndex bytes_converted;
414         CFIndex bytes_written;
415         CFIndex len;
416         int i;
417
418         if (darwin_locale != NULL)
419                 return g_strdup (darwin_locale);
420
421         locale = CFLocaleCopyCurrent ();
422
423         if (locale) {
424                 locale_language = CFLocaleGetValue (locale, kCFLocaleLanguageCode);
425                 if (locale_language != NULL && CFStringGetBytes(locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
426                         len = bytes_converted + 1;
427
428                         locale_country = CFLocaleGetValue (locale, kCFLocaleCountryCode);
429                         if (locale_country != NULL && CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
430                                 len += bytes_converted + 1;
431
432                                 locale_script = CFLocaleGetValue (locale, kCFLocaleScriptCode);
433                                 if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, NULL, 0, &bytes_converted) > 0) {
434                                         len += bytes_converted + 1;
435                                 }
436
437                                 darwin_locale = (char *) g_malloc (len + 1);
438                                 CFStringGetBytes (locale_language, CFRangeMake (0, CFStringGetLength (locale_language)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) darwin_locale, len, &bytes_converted);
439
440                                 darwin_locale[bytes_converted] = '-';
441                                 bytes_written = bytes_converted + 1;
442                                 if (locale_script != NULL && CFStringGetBytes (locale_script, CFRangeMake (0, CFStringGetLength (locale_script)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted) > 0) {
443                                         darwin_locale[bytes_written + bytes_converted] = '-';
444                                         bytes_written += bytes_converted + 1;
445                                 }
446
447                                 CFStringGetBytes (locale_country, CFRangeMake (0, CFStringGetLength (locale_country)), kCFStringEncodingMacRoman, 0, FALSE, (UInt8 *) &darwin_locale[bytes_written], len - bytes_written, &bytes_converted);
448                                 darwin_locale[bytes_written + bytes_converted] = '\0';
449                         }
450                 }
451
452                 if (darwin_locale == NULL) {
453                         locale_cfstr = CFLocaleGetIdentifier (locale);
454
455                         if (locale_cfstr) {
456                                 len = CFStringGetMaximumSizeForEncoding (CFStringGetLength (locale_cfstr), kCFStringEncodingMacRoman) + 1;
457                                 darwin_locale = (char *) g_malloc (len);
458                                 if (!CFStringGetCString (locale_cfstr, darwin_locale, len, kCFStringEncodingMacRoman)) {
459                                         g_free (darwin_locale);
460                                         CFRelease (locale);
461                                         darwin_locale = NULL;
462                                         return NULL;
463                                 }
464
465                                 for (i = 0; i < strlen (darwin_locale); i++)
466                                         if (darwin_locale [i] == '_')
467                                                 darwin_locale [i] = '-';
468                         }                       
469                 }
470
471                 CFRelease (locale);
472         }
473
474         return g_strdup (darwin_locale);
475 }
476 #endif
477
478 static char *
479 get_posix_locale (void)
480 {
481         char *locale;
482
483         locale = g_getenv ("LC_ALL");
484         if (locale == NULL) {
485                 locale = g_getenv ("LANG");
486                 if (locale == NULL) {
487                         char *static_locale = setlocale (LC_ALL, NULL);
488                         if (static_locale)
489                                 locale = g_strdup (static_locale);
490                 }
491         }
492         if (locale == NULL)
493                 return NULL;
494
495         /* Skip English-only locale 'C' */
496         if (strcmp (locale, "C") == 0) {
497                 g_free (locale);
498                 return NULL;
499         }
500
501         return locale;
502 }
503
504
505 static gchar *
506 get_current_locale_name (void)
507 {
508         char *locale;
509         char *p, *ret;
510                 
511 #ifdef HOST_WIN32
512         locale = g_win32_getlocale ();
513 #elif defined (__APPLE__)       
514         locale = get_darwin_locale ();
515         if (!locale)
516                 locale = get_posix_locale ();
517 #else
518         locale = get_posix_locale ();
519 #endif
520
521         if (locale == NULL)
522                 return NULL;
523
524         p = strchr (locale, '.');
525         if (p != NULL)
526                 *p = 0;
527         p = strchr (locale, '@');
528         if (p != NULL)
529                 *p = 0;
530         p = strchr (locale, '_');
531         if (p != NULL)
532                 *p = '-';
533
534         ret = g_ascii_strdown (locale, -1);
535         g_free (locale);
536
537         return ret;
538 }
539
540 MonoString*
541 ves_icall_System_Globalization_CultureInfo_get_current_locale_name (void)
542 {
543         gchar *locale;
544         MonoString* ret;
545         MonoDomain *domain;
546
547         locale = get_current_locale_name ();
548         if (locale == NULL)
549                 return NULL;
550
551         domain = mono_domain_get ();
552         ret = mono_string_new (domain, locale);
553         g_free (locale);
554
555         return ret;
556 }
557
558 MonoBoolean
559 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_lcid (MonoCultureInfo *this_obj,
560                 gint lcid)
561 {
562         MonoError error;
563         const CultureInfoEntry *ci;
564         
565         ci = culture_info_entry_from_lcid (lcid);
566         if(ci == NULL)
567                 return FALSE;
568
569         if (!construct_culture (this_obj, ci, &error)) {
570                 mono_error_set_pending_exception (&error);
571                 return FALSE;
572         }
573         return TRUE;
574 }
575
576 MonoBoolean
577 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_name (MonoCultureInfo *this_obj,
578                 MonoString *name)
579 {
580         MonoError error;
581         const CultureInfoNameEntry *ne;
582         char *n;
583         
584         n = mono_string_to_utf8_checked (name, &error);
585         if (mono_error_set_pending_exception (&error))
586                 return FALSE;
587         ne = (const CultureInfoNameEntry *)mono_binary_search (n, culture_name_entries, NUM_CULTURE_ENTRIES,
588                         sizeof (CultureInfoNameEntry), culture_name_locator);
589
590         if (ne == NULL) {
591                 /*g_print ("ne (%s) is null\n", n);*/
592                 g_free (n);
593                 return FALSE;
594         }
595         g_free (n);
596
597         if (!construct_culture (this_obj, &culture_entries [ne->culture_entry_index], &error)) {
598                 mono_error_set_pending_exception (&error);
599                 return FALSE;
600         }
601         return TRUE;
602 }
603 /*
604 MonoBoolean
605 ves_icall_System_Globalization_CultureInfo_construct_internal_locale_from_specific_name (MonoCultureInfo *ci,
606                 MonoString *name)
607 {
608         gchar *locale;
609         gboolean ret;
610
611         locale = mono_string_to_utf8 (name);
612         ret = construct_culture_from_specific_name (ci, locale);
613         g_free (locale);
614
615         return ret;
616 }
617 */
618 MonoBoolean
619 ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_lcid (MonoRegionInfo *this_obj,
620                 gint lcid)
621 {
622         const RegionInfoEntry *ri;
623         
624         ri = region_info_entry_from_lcid (lcid);
625         if(ri == NULL)
626                 return FALSE;
627
628         return construct_region (this_obj, ri);
629 }
630
631 MonoBoolean
632 ves_icall_System_Globalization_RegionInfo_construct_internal_region_from_name (MonoRegionInfo *this_obj,
633                 MonoString *name)
634 {
635         MonoError error;
636         const RegionInfoNameEntry *ne;
637         char *n;
638         
639         n = mono_string_to_utf8_checked (name, &error);
640         if (mono_error_set_pending_exception (&error))
641                 return FALSE;
642         ne = (const RegionInfoNameEntry *)mono_binary_search (n, region_name_entries, NUM_REGION_ENTRIES,
643                 sizeof (RegionInfoNameEntry), region_name_locator);
644
645         if (ne == NULL) {
646                 /*g_print ("ne (%s) is null\n", n);*/
647                 g_free (n);
648                 return FALSE;
649         }
650         g_free (n);
651
652         return construct_region (this_obj, &region_entries [ne->region_entry_index]);
653 }
654
655 MonoArray*
656 ves_icall_System_Globalization_CultureInfo_internal_get_cultures (MonoBoolean neutral,
657                 MonoBoolean specific, MonoBoolean installed)
658 {
659         MonoError error;
660         MonoArray *ret;
661         MonoClass *klass;
662         MonoCultureInfo *culture;
663         MonoDomain *domain;
664         const CultureInfoEntry *ci;
665         gint i, len;
666         gboolean is_neutral;
667
668         domain = mono_domain_get ();
669
670         len = 0;
671         for (i = 0; i < NUM_CULTURE_ENTRIES; i++) {
672                 ci = &culture_entries [i];
673                 is_neutral = ci->territory == 0;
674                 if ((neutral && is_neutral) || (specific && !is_neutral))
675                         len++;
676         }
677
678         klass = mono_class_get_culture_info_class ();
679
680         /* The InvariantCulture is not in culture_entries */
681         /* We reserve the first slot in the array for it */
682         if (neutral)
683                 len++;
684
685         ret = mono_array_new_checked (domain, klass, len, &error);
686         if (!is_ok (&error))
687                 goto fail;
688
689         if (len == 0)
690                 return ret;
691
692         len = 0;
693         if (neutral)
694                 mono_array_setref (ret, len++, NULL);
695
696         for (i = 0; i < NUM_CULTURE_ENTRIES; i++) {
697                 ci = &culture_entries [i];
698                 is_neutral = ci->territory == 0;
699                 if ((neutral && is_neutral) || (specific && !is_neutral)) {
700                         culture = (MonoCultureInfo *) mono_object_new_checked (domain, klass, &error);
701                         if (!is_ok (&error)) goto fail;
702                         mono_runtime_object_init_checked ((MonoObject *) culture, &error);
703                         if (!is_ok (&error)) goto fail;
704                         if (!construct_culture (culture, ci, &error))
705                                 goto fail;
706                         culture->use_user_override = TRUE;
707                         mono_array_setref (ret, len++, culture);
708                 }
709         }
710
711         return ret;
712
713 fail:
714         mono_error_set_pending_exception (&error);
715         return ret;
716 }
717
718 int ves_icall_System_Globalization_CompareInfo_internal_compare (MonoCompareInfo *this_obj, MonoString *str1, gint32 off1, gint32 len1, MonoString *str2, gint32 off2, gint32 len2, gint32 options)
719 {
720         /* Do a normal ascii string compare, as we only know the
721          * invariant locale if we dont have ICU
722          */
723         return(string_invariant_compare (str1, off1, len1, str2, off2, len2,
724                                          options));
725 }
726
727 void ves_icall_System_Globalization_CompareInfo_assign_sortkey (MonoCompareInfo *this_obj, MonoSortKey *key, MonoString *source, gint32 options)
728 {
729         MonoError error;
730         MonoArray *arr;
731         gint32 keylen, i;
732
733         keylen=mono_string_length (source);
734         
735         arr=mono_array_new_checked (mono_domain_get (), mono_get_byte_class (),
736                                     keylen, &error);
737         if (mono_error_set_pending_exception (&error))
738                 return;
739
740         for(i=0; i<keylen; i++) {
741                 mono_array_set (arr, guint8, i, mono_string_chars (source)[i]);
742         }
743         
744         MONO_OBJECT_SETREF (key, key, arr);
745 }
746
747 int ves_icall_System_Globalization_CompareInfo_internal_index (MonoCompareInfo *this_obj, MonoString *source, gint32 sindex, gint32 count, MonoString *value, gint32 options, MonoBoolean first)
748 {
749         return(string_invariant_indexof (source, sindex, count, value, first));
750 }
751
752 int ves_icall_System_Globalization_CompareInfo_internal_index_char (MonoCompareInfo *this_obj, MonoString *source, gint32 sindex, gint32 count, gunichar2 value, gint32 options, MonoBoolean first)
753 {
754         return(string_invariant_indexof_char (source, sindex, count, value,
755                                               first));
756 }
757
758 int ves_icall_System_Threading_Thread_current_lcid (void)
759 {
760         /* Invariant */
761         return(0x007F);
762 }
763
764 static gint32 string_invariant_compare_char (gunichar2 c1, gunichar2 c2,
765                                              gint32 options)
766 {
767         gint32 result;
768
769         /* Ordinal can not be mixed with other options, and must return the difference, not only -1, 0, 1 */
770         if (options & CompareOptions_Ordinal) 
771                 return (gint32) c1 - c2;
772         
773         if (options & CompareOptions_IgnoreCase) {
774                 GUnicodeType c1type, c2type;
775
776                 c1type = g_unichar_type (c1);
777                 c2type = g_unichar_type (c2);
778         
779                 result = (gint32) (c1type != G_UNICODE_LOWERCASE_LETTER ? g_unichar_tolower(c1) : c1) -
780                         (c2type != G_UNICODE_LOWERCASE_LETTER ? g_unichar_tolower(c2) : c2);
781         } else {
782                 /*
783                  * No options. Kana, symbol and spacing options don't
784                  * apply to the invariant culture.
785                  */
786
787                 /*
788                  * FIXME: here we must use the information from c1type and c2type
789                  * to find out the proper collation, even on the InvariantCulture, the
790                  * sorting is not done by computing the unicode values, but their
791                  * actual sort order.
792                  */
793                 result = (gint32) c1 - c2;
794         }
795
796         return ((result < 0) ? -1 : (result > 0) ? 1 : 0);
797 }
798
799 static gint32 string_invariant_compare (MonoString *str1, gint32 off1,
800                                         gint32 len1, MonoString *str2,
801                                         gint32 off2, gint32 len2,
802                                         gint32 options)
803 {
804         /* c translation of C# code from old string.cs.. :) */
805         gint32 length;
806         gint32 charcmp;
807         gunichar2 *ustr1;
808         gunichar2 *ustr2;
809         gint32 pos;
810
811         if(len1 >= len2) {
812                 length=len1;
813         } else {
814                 length=len2;
815         }
816
817         ustr1 = mono_string_chars(str1)+off1;
818         ustr2 = mono_string_chars(str2)+off2;
819
820         pos = 0;
821
822         for (pos = 0; pos != length; pos++) {
823                 if (pos >= len1 || pos >= len2)
824                         break;
825
826                 charcmp = string_invariant_compare_char(ustr1[pos], ustr2[pos],
827                                                         options);
828                 if (charcmp != 0) {
829                         return(charcmp);
830                 }
831         }
832
833         /* the lesser wins, so if we have looped until length we just
834          * need to check the last char
835          */
836         if (pos == length) {
837                 return(string_invariant_compare_char(ustr1[pos - 1],
838                                                      ustr2[pos - 1], options));
839         }
840
841         /* Test if one of the strings has been compared to the end */
842         if (pos >= len1) {
843                 if (pos >= len2) {
844                         return(0);
845                 } else {
846                         return(-1);
847                 }
848         } else if (pos >= len2) {
849                 return(1);
850         }
851
852         /* if not, check our last char only.. (can this happen?) */
853         return(string_invariant_compare_char(ustr1[pos], ustr2[pos], options));
854 }
855
856 static gint32 string_invariant_indexof (MonoString *source, gint32 sindex,
857                                         gint32 count, MonoString *value,
858                                         MonoBoolean first)
859 {
860         gint32 lencmpstr;
861         gunichar2 *src;
862         gunichar2 *cmpstr;
863         gint32 pos,i;
864         
865         lencmpstr = mono_string_length(value);
866         
867         src = mono_string_chars(source);
868         cmpstr = mono_string_chars(value);
869
870         if(first) {
871                 count -= lencmpstr;
872                 for(pos=sindex;pos <= sindex+count;pos++) {
873                         for(i=0;src[pos+i]==cmpstr[i];) {
874                                 if(++i==lencmpstr) {
875                                         return(pos);
876                                 }
877                         }
878                 }
879                 
880                 return(-1);
881         } else {
882                 for(pos=sindex-lencmpstr+1;pos>sindex-count;pos--) {
883                         if(memcmp (src+pos, cmpstr,
884                                    lencmpstr*sizeof(gunichar2))==0) {
885                                 return(pos);
886                         }
887                 }
888                 
889                 return(-1);
890         }
891 }
892
893 static gint32 string_invariant_indexof_char (MonoString *source, gint32 sindex,
894                                              gint32 count, gunichar2 value,
895                                              MonoBoolean first)
896 {
897         gint32 pos;
898         gunichar2 *src;
899
900         src = mono_string_chars(source);
901         if(first) {
902                 for (pos = sindex; pos != count + sindex; pos++) {
903                         if (src [pos] == value) {
904                                 return(pos);
905                         }
906                 }
907
908                 return(-1);
909         } else {
910                 for (pos = sindex; pos > sindex - count; pos--) {
911                         if (src [pos] == value)
912                                 return(pos);
913                 }
914
915                 return(-1);
916         }
917 }
918
919 void ves_icall_System_Text_Normalization_load_normalization_resource (guint8 **argProps,
920                                                                                                                                           guint8 **argMappedChars,
921                                                                                                                                           guint8 **argCharMapIndex,
922                                                                                                                                           guint8 **argHelperIndex,
923                                                                                                                                           guint8 **argMapIdxToComposite,
924                                                                                                                                           guint8 **argCombiningClass)
925 {
926 #ifdef DISABLE_NORMALIZATION
927         mono_set_pending_exception (mono_get_exception_not_supported ("This runtime has been compiled without string normalization support."));
928         return;
929 #else
930         *argProps = (guint8*)props;
931         *argMappedChars = (guint8*) mappedChars;
932         *argCharMapIndex = (guint8*) charMapIndex;
933         *argHelperIndex = (guint8*) helperIndex;
934         *argMapIdxToComposite = (guint8*) mapIdxToComposite;
935         *argCombiningClass = (guint8*)combiningClass;
936 #endif
937 }
938
939