forked from icculus/mojosetup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mojosetup.c
1292 lines (1062 loc) · 35.4 KB
/
mojosetup.c
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
/**
* MojoSetup; a portable, flexible installation application.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include <stdarg.h>
#include "universal.h"
#include "platform.h"
#include "gui.h"
#include "lua_glue.h"
#include "fileio.h"
#define TEST_LAUNCH_BROWSER_CODE 0
int MojoSetup_testLaunchBrowserCode(int argc, char **argv);
#define TEST_ARCHIVE_CODE 0
int MojoSetup_testArchiveCode(int argc, char **argv);
#define TEST_NETWORK_CODE 0
int MojoSetup_testNetworkCode(int argc, char **argv);
uint8 scratchbuf_128k[128 * 1024];
uint8 *scratchbuf_pos = scratchbuf_128k;
uint8* get_scratch(int64 *size)
{
uint8 *scratch;
if (scratchbuf_pos + *size > scratchbuf_128k + sizeof(scratchbuf_128k))
{
scratchbuf_pos = scratchbuf_128k;
// if necessary reduce size to avoid overflows
if (*size > sizeof(scratchbuf_128k))
*size = sizeof(scratchbuf_128k);
}
scratch = scratchbuf_pos;
// always leave scratchbuf_pos in a place with usable space
scratchbuf_pos += *size;
if (scratchbuf_pos >= scratchbuf_128k + sizeof(scratchbuf_128k))
scratchbuf_pos = scratchbuf_128k;
return scratch;
}
int get_scratch_size(void)
{
return scratchbuf_128k + sizeof(scratchbuf_128k) - scratchbuf_pos;
}
const MojoSetupEntryPoints GEntryPoints =
{
xmalloc,
xrealloc,
xstrdup,
xstrncpy,
translate,
logWarning,
logError,
logInfo,
logDebug,
format,
numstr,
MojoPlatform_ticks,
utf8codepoint,
utf8len,
splitText,
isValidProductKey,
};
int GArgc = 0;
const char **GArgv = NULL;
static char *crashedmsg = NULL;
static char *termedmsg = NULL;
void MojoSetup_crashed(void)
{
if (crashedmsg == NULL)
panic("BUG: crash at startup");
else
fatal(crashedmsg);
} // MojoSetup_crash
void MojoSetup_terminated(void)
{
if (termedmsg == NULL) // no translation yet.
panic("The installer has been stopped by the system.");
else
fatal(termedmsg);
} // MojoSetup_crash
#if !SUPPORT_MULTIARCH
#define trySwitchBinaries()
#else
static void trySwitchBinary(MojoArchive *ar)
{
MojoInput *io = ar->openCurrentEntry(ar);
if (io != NULL)
{
const uint32 imglen = (uint32) io->length(io);
uint8 *img = (uint8 *) xmalloc(imglen);
const uint32 br = io->read(io, img, imglen);
io->close(io);
if (br == imglen)
{
logInfo("Switching binary with '%0'...", ar->prevEnum.filename);
MojoPlatform_switchBin(img, imglen); // no return on success.
logError("...Switch binary failed.");
} // if
free(img);
} // if
} // trySwitchBinary
static void trySwitchBinaries(void)
{
if (cmdlinestr("nobinswitch", "MOJOSETUP_NOBINSWITCH", NULL) != NULL)
return; // we are already switched or the user is preventing it.
setenv("MOJOSETUP_NOBINSWITCH", "1", 1);
setenv("MOJOSETUP_BASE", GBaseArchivePath, 1);
if (GBaseArchive->enumerate(GBaseArchive))
{
const MojoArchiveEntry *entinfo;
while ((entinfo = GBaseArchive->enumNext(GBaseArchive)) != NULL)
{
if (entinfo->type != MOJOARCHIVE_ENTRY_FILE)
continue;
if (strncmp(entinfo->filename, "arch/", 5) != 0)
continue;
trySwitchBinary(GBaseArchive);
} // while
} // if
} // trySwitchBinaries
#endif
static boolean trySpawnTerminalGui(void)
{
if (cmdlinestr("notermspawn", "MOJOSETUP_NOTERMSPAWN", NULL) != NULL)
return false; // we already spawned or the user is preventing it.
if (MojoPlatform_istty()) // maybe we can spawn a terminal for stdio?
return false; // We're a terminal already, no need to spawn one.
logInfo("No usable GUI found. Trying to spawn a terminal...");
if (!MojoPlatform_spawnTerminal())
{
logError("...Terminal spawning failed.");
return false;
} // if
assert(MojoPlatform_istty());
return (MojoGui_initGuiPlugin() != NULL);
} // trySpawnTerminalGui
static boolean initEverything(void)
{
MojoLog_initLogging();
logInfo("MojoSetup starting up...");
// We have to panic on errors until the GUI is ready. Try to make things
// "succeed" unless they are catastrophic, and report problems later.
// Start with the base archive work, since it might have GUI plugins.
// None of these panic() calls are localized, since localization isn't
// functional until MojoLua_initLua() succeeds.
if (!MojoArchive_initBaseArchive())
panic("Initial setup failed. Cannot continue.");
trySwitchBinaries(); // may not return.
if (!MojoGui_initGuiPlugin())
{
// This could terminate the process (and relaunch).
if (!trySpawnTerminalGui())
panic("Failed to start GUI. Is your download incomplete or corrupt?");
} // if
else if (!MojoLua_initLua())
{
// (...but if you're the developer: are your files in the wrong place?)
panic("Failed to start. Is your download incomplete or corrupt?");
} // else if
crashedmsg = xstrdup(_("The installer has crashed due to a bug."));
termedmsg = xstrdup(_("The installer has been stopped by the system."));
return true;
} // initEverything
static void deinitEverything(void)
{
char *tmp = NULL;
logInfo("MojoSetup shutting down...");
MojoLua_deinitLua();
MojoGui_deinitGuiPlugin();
MojoArchive_deinitBaseArchive();
MojoLog_deinitLogging();
tmp = crashedmsg;
crashedmsg = NULL;
free(tmp);
tmp = termedmsg;
termedmsg = NULL;
free(tmp);
} // deinitEverything
void MojoChecksum_init(MojoChecksumContext *ctx)
{
memset(ctx, '\0', sizeof (MojoChecksumContext));
#if SUPPORT_CRC32
MojoCrc32_init(&ctx->crc32);
#endif
#if SUPPORT_MD5
MojoMd5_init(&ctx->md5);
#endif
#if SUPPORT_SHA1
MojoSha1_init(&ctx->sha1);
#endif
} // MojoChecksum_init
void MojoChecksum_append(MojoChecksumContext *ctx, const uint8 *d, uint32 len)
{
#if SUPPORT_CRC32
MojoCrc32_append(&ctx->crc32, d, len);
#endif
#if SUPPORT_MD5
MojoMd5_append(&ctx->md5, d, len);
#endif
#if SUPPORT_SHA1
MojoSha1_append(&ctx->sha1, d, len);
#endif
} // MojoChecksum_append
void MojoChecksum_finish(MojoChecksumContext *ctx, MojoChecksums *sums)
{
memset(sums, '\0', sizeof (MojoChecksums));
#if SUPPORT_CRC32
MojoCrc32_finish(&ctx->crc32, &sums->crc32);
#endif
#if SUPPORT_MD5
MojoMd5_finish(&ctx->md5, sums->md5);
#endif
#if SUPPORT_SHA1
MojoSha1_finish(&ctx->sha1, sums->sha1);
#endif
} // MojoChecksum_finish
boolean cmdline(const char *arg)
{
int argc = GArgc;
const char **argv = GArgv;
int i;
if ((arg == NULL) || (argv == NULL))
return false;
while (*arg == '-') // Skip all '-' chars, so "--nosound" == "-nosound"
arg++;
for (i = 1; i < argc; i++)
{
const char *thisarg = argv[i];
if (*thisarg != '-')
continue; // no dash in the string, skip it.
while (*(++thisarg) == '-') { /* keep looping. */ }
if (strcmp(arg, thisarg) == 0)
return true;
} // for
return false;
} // cmdline
const char *cmdlinestr(const char *arg, const char *envr, const char *deflt)
{
uint32 len = 0;
int argc = GArgc;
const char **argv = GArgv;
int i;
if (envr != NULL)
{
const char *val = getenv(envr);
if (val != NULL)
return val;
} // if
if (arg == NULL)
return deflt;
while (*arg == '-') // Skip all '-' chars, so "--nosound" == "-nosound"
arg++;
len = strlen(arg);
for (i = 1; i < argc; i++)
{
const char *thisarg = argv[i];
if (*thisarg != '-')
continue; // no dash in the string, skip it.
while (*(++thisarg) == '-') { /* keep looping. */ }
if (strncmp(arg, thisarg, len) != 0)
continue; // not us.
thisarg += len; // skip ahead in string to end of match.
if (*thisarg == '=') // --a=b format.
return (thisarg + 1);
else if (*thisarg == '\0') // --a b format.
return ((argv[i+1] == NULL) ? deflt : argv[i+1]);
} // for
return deflt;
} // cmdlinestr
boolean wildcardMatch(const char *str, const char *pattern)
{
char sch = *(str++);
while (true)
{
const char pch = *(pattern++);
if (pch == '?')
{
if ((sch == '\0') || (sch == '/'))
return false;
sch = *(str++);
} // else if
else if (pch == '*')
{
char nextpch = *pattern;
if ((nextpch != '?') && (nextpch != '*'))
{
while ((sch != '\0') && (sch != nextpch))
sch = *(str++);
} // if
} // else if
else
{
if (pch != sch)
return false;
else if (pch == '\0')
break;
sch = *(str++);
} // else
} // while
return true;
} // wildcardMatch
const char *numstr(int val)
{
int64 size = 12;
char *str = (char*)get_scratch(&size);
snprintf(str, size, "%d", val);
return str;
} // numstr
static char *format_internal(const char *fmt, va_list ap)
{
// This is kinda nasty. String manipulation in C always is.
char *retval = NULL;
const char *strs[10]; // 0 through 9.
const char *ptr = NULL;
char *wptr = NULL;
size_t len = 0;
int maxfmtid = -2;
int i;
// figure out what this format string contains...
for (ptr = fmt; *ptr; ptr++)
{
if (*ptr == '%')
{
const char ch = *(++ptr);
if (ch == '%') // a literal '%'
maxfmtid = (maxfmtid == -2) ? -1 : maxfmtid;
else if ((ch >= '0') && (ch <= '9'))
maxfmtid = ((maxfmtid > (ch - '0')) ? maxfmtid : (ch - '0'));
else
fatal(_("BUG: Invalid format() string"));
} // if
} // while
if (maxfmtid == -2) // no formatters present at all.
return xstrdup(fmt); // just copy it, we're done.
for (i = 0; i <= maxfmtid; i++) // referenced varargs --> linear array.
{
strs[i] = va_arg(ap, const char *);
if (strs[i] == NULL)
strs[i] = "(null)"; // just to match sprintf() behaviour...
} // for
// allocate the string we'll need in one shot, so we don't have to resize.
for (ptr = fmt; *ptr; ptr++)
{
if (*ptr != '%')
len++;
else
{
const char ch = *(++ptr);
if (ch == '%') // a literal '%'
len++; // just want '%' char.
else //if ((ch >= '0') && (ch <= '9'))
len += strlen(strs[ch - '0']);
} // else
} // while
// Now write the formatted string...
wptr = retval = (char *) xmalloc(len+1);
for (ptr = fmt; *ptr; ptr++)
{
const char strch = *ptr;
if (strch != '%')
*(wptr++) = strch;
else
{
const char ch = *(++ptr);
if (ch == '%') // a literal '%'
*(wptr++) = '%';
else //if ((ch >= '0') && (ch <= '9'))
{
const char *str = strs[ch - '0'];
strcpy(wptr, str);
wptr += strlen(str);
} // else
} // else
} // while
*wptr = '\0';
return retval;
} // format_internal
char *format(const char *fmt, ...)
{
char *retval = NULL;
va_list ap;
va_start(ap, fmt);
retval = format_internal(fmt, ap);
va_end(ap);
return retval;
} // format
#if ((defined _NDEBUG) || (defined NDEBUG))
#define DEFLOGLEV "info"
#else
#define DEFLOGLEV "everything"
#endif
MojoSetupLogLevel MojoLog_logLevel = MOJOSETUP_LOG_EVERYTHING;
static void *logFile = NULL;
void MojoLog_initLogging(void)
{
const char *level = cmdlinestr("loglevel","MOJOSETUP_LOGLEVEL", DEFLOGLEV);
const char *fname = cmdlinestr("log", "MOJOSETUP_LOG", NULL);
if (strcmp(level, "nothing") == 0)
MojoLog_logLevel = MOJOSETUP_LOG_NOTHING;
else if (strcmp(level, "errors") == 0)
MojoLog_logLevel = MOJOSETUP_LOG_ERRORS;
else if (strcmp(level, "warnings") == 0)
MojoLog_logLevel = MOJOSETUP_LOG_WARNINGS;
else if (strcmp(level, "info") == 0)
MojoLog_logLevel = MOJOSETUP_LOG_INFO;
else if (strcmp(level, "debug") == 0)
MojoLog_logLevel = MOJOSETUP_LOG_DEBUG;
else // Unknown string gets everything...that'll teach you.
MojoLog_logLevel = MOJOSETUP_LOG_EVERYTHING;
if ((fname != NULL) && (strcmp(fname, "-") == 0))
logFile = MojoPlatform_stdout();
else if (fname != NULL)
{
const uint32 flags = MOJOFILE_WRITE|MOJOFILE_CREATE|MOJOFILE_TRUNCATE|MOJOFILE_APPEND;
const uint16 mode = MojoPlatform_defaultFilePerms();
logFile = MojoPlatform_open(fname, flags, mode);
} // if
} // MojoLog_initLogging
void MojoLog_deinitLogging(void)
{
if (logFile != NULL)
{
MojoPlatform_close(logFile);
logFile = NULL;
} // if
} // MojoLog_deinitLogging
static inline void addLog(MojoSetupLogLevel level, char levelchar,
const char *fmt, va_list ap)
{
if (level <= MojoLog_logLevel)
{
char *str = format_internal(fmt, ap);
//int len = vsnprintf(buf + 2, sizeof (buf) - 2, fmt, ap) + 2;
//buf[0] = levelchar;
//buf[1] = ' ';
int len = strlen(str);
while ( (--len >= 0) && ((str[len] == '\n') || (str[len] == '\r')) ) {}
str[len+1] = '\0'; // delete trailing newline crap.
MojoPlatform_log(str);
if (logFile != NULL)
{
const char *endl = MOJOPLATFORM_ENDLINE;
MojoPlatform_write(logFile, str, strlen(str));
MojoPlatform_write(logFile, endl, strlen(endl));
MojoPlatform_flush(logFile);
} // if
free(str);
} // if
} // addLog
void logWarning(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
addLog(MOJOSETUP_LOG_WARNINGS, '-', fmt, ap);
va_end(ap);
} // logWarning
void logError(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
addLog(MOJOSETUP_LOG_ERRORS, '!', fmt, ap);
va_end(ap);
} // logError
void logInfo(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
addLog(MOJOSETUP_LOG_INFO, '*', fmt, ap);
va_end(ap);
} // logInfo
void logDebug(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
addLog(MOJOSETUP_LOG_DEBUG, '#', fmt, ap);
va_end(ap);
} // logDebug
uint32 profile(const char *what, uint32 start_time)
{
uint32 retval = MojoPlatform_ticks() - start_time;
if (what != NULL)
logDebug("%0 took %1 ms.", what, numstr((int) retval));
return retval;
} // profile_start
int fatal(const char *fmt, ...)
{
static boolean in_fatal = false;
if (in_fatal)
return panic("BUG: fatal() called more than once!");
in_fatal = true;
// may not want to show a message, since we displayed one elsewhere, etc.
if (fmt != NULL)
{
char *buf = NULL;
va_list ap;
va_start(ap, fmt);
buf = format_internal(fmt, ap);
va_end(ap);
logError("FATAL: %0", buf);
if (GGui != NULL)
GGui->msgbox(_("Fatal error"), buf);
free(buf);
} // if
// Shouldn't call fatal() before app is initialized!
if ( (GGui == NULL) || (!MojoLua_initialized()) )
panic("fatal() called before app is initialized! Panicking...");
MojoLua_callProcedure("revertinstall");
deinitEverything();
exit(23);
return 0;
} // fatal
int panic(const char *err)
{
static int panic_runs = 0;
panic_runs++;
if (panic_runs == 1)
{
logError("PANIC: %0", err);
panic(err);
} // if
else if (panic_runs == 2)
{
boolean domsgbox = ((GGui != NULL) && (GGui->msgbox != NULL));
if (domsgbox)
GGui->msgbox(_("PANIC"), err);
if ((GGui != NULL) && (GGui->deinit != NULL))
GGui->deinit();
if (!domsgbox)
panic(err); /* no GUI plugin...double-panic. */
} // if
else if (panic_runs == 3) // no GUI or panic panicked...write to stderr...
fprintf(stderr, "\n\n\n%s\n %s\n\n\n", _("PANIC"), err);
else // panic is panicking in a loop, terminate without any cleanup...
MojoPlatform_die();
exit(22);
return 0; // shouldn't hit this.
} // panic
char *xstrncpy(char *dst, const char *src, size_t len)
{
snprintf(dst, len, "%s", src);
return dst;
} // xstrncpy
uint32 utf8codepoint(const char **_str)
{
const char *str = *_str;
uint32 retval = 0;
uint32 octet = (uint32) ((uint8) *str);
uint32 octet2, octet3, octet4;
if (octet == 0) // null terminator, end of string.
return 0;
else if (octet < 128) // one octet char: 0 to 127
{
(*_str)++; // skip to next possible start of codepoint.
return octet;
} // else if
else if ((octet > 127) && (octet < 192)) // bad (starts with 10xxxxxx).
{
// Apparently each of these is supposed to be flagged as a bogus
// char, instead of just resyncing to the next valid codepoint.
(*_str)++; // skip to next possible start of codepoint.
return UNICODE_BOGUS_CHAR_VALUE;
} // else if
else if (octet < 224) // two octets
{
(*_str)++; // advance at least one byte in case of an error
octet -= (128+64);
octet2 = (uint32) ((uint8) *(++str));
if ((octet2 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
*_str += 1; // skip to next possible start of codepoint.
retval = ((octet << 6) | (octet2 - 128));
if ((retval >= 0x80) && (retval <= 0x7FF))
return retval;
} // else if
else if (octet < 240) // three octets
{
(*_str)++; // advance at least one byte in case of an error
octet -= (128+64+32);
octet2 = (uint32) ((uint8) *(++str));
if ((octet2 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet3 = (uint32) ((uint8) *(++str));
if ((octet3 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
*_str += 2; // skip to next possible start of codepoint.
retval = ( ((octet << 12)) | ((octet2-128) << 6) | ((octet3-128)) );
// There are seven "UTF-16 surrogates" that are illegal in UTF-8.
switch (retval)
{
case 0xD800:
case 0xDB7F:
case 0xDB80:
case 0xDBFF:
case 0xDC00:
case 0xDF80:
case 0xDFFF:
return UNICODE_BOGUS_CHAR_VALUE;
} // switch
// 0xFFFE and 0xFFFF are illegal, too, so we check them at the edge.
if ((retval >= 0x800) && (retval <= 0xFFFD))
return retval;
} // else if
else if (octet < 248) // four octets
{
(*_str)++; // advance at least one byte in case of an error
octet -= (128+64+32+16);
octet2 = (uint32) ((uint8) *(++str));
if ((octet2 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet3 = (uint32) ((uint8) *(++str));
if ((octet3 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet4 = (uint32) ((uint8) *(++str));
if ((octet4 & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
*_str += 3; // skip to next possible start of codepoint.
retval = ( ((octet << 18)) | ((octet2 - 128) << 12) |
((octet3 - 128) << 6) | ((octet4 - 128)) );
if ((retval >= 0x10000) && (retval <= 0x10FFFF))
return retval;
} // else if
// Five and six octet sequences became illegal in rfc3629.
// We throw the codepoint away, but parse them to make sure we move
// ahead the right number of bytes and don't overflow the buffer.
else if (octet < 252) // five octets
{
(*_str)++; // advance at least one byte in case of an error
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
*_str += 4; // skip to next possible start of codepoint.
return UNICODE_BOGUS_CHAR_VALUE;
} // else if
else // six octets
{
(*_str)++; // advance at least one byte in case of an error
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
octet = (uint32) ((uint8) *(++str));
if ((octet & (128+64)) != 128) // Format isn't 10xxxxxx?
return UNICODE_BOGUS_CHAR_VALUE;
*_str += 5; // skip to next possible start of codepoint.
return UNICODE_BOGUS_CHAR_VALUE;
} // else if
return UNICODE_BOGUS_CHAR_VALUE;
} // utf8codepoint
int utf8len(const char *str)
{
int retval = 0;
while (utf8codepoint(&str))
retval++;
return retval;
} // utf8len
static char *strfrombuf(const char *text, int len)
{
char *retval = xmalloc(len + 1);
memcpy(retval, text, len);
retval[len] = '\0';
return retval;
} // strfrombuf
char **splitText(const char *text, int scrw, int *_count, int *_w)
{
int i = 0;
int j = 0;
char **retval = NULL;
int count = 0;
int w = 0;
*_count = *_w = 0;
while (*text)
{
const char *utf8text = text;
uint32 ch = 0;
int pos = 0;
int furthest = 0;
for (i = 0; ((ch = utf8codepoint(&utf8text))) && (i < scrw); i++)
{
if ((ch == '\r') || (ch == '\n'))
{
const char nextbyte = *utf8text;
count++;
retval = (char **) xrealloc(retval, count * sizeof (char *));
retval[count-1] = strfrombuf(text, utf8text - text);
if ((ch == '\r') && (nextbyte == '\n')) // DOS endlines!
utf8text++; // skip it.
text = (char *) utf8text; // update to start of new line.
if (i > w)
w = i;
i = -1; // will be zero on next iteration...
} // if
else if ((ch == ' ') || (ch == '\t'))
{
if (i != 0) // trim spaces from start of line...
furthest = i;
else
{
text++;
i = -1; // it'll be zero on next iteration.
} // else
} // else if
} // for
// line overflow or end of stream...
pos = (ch) ? furthest : i;
if ((ch) && (furthest == 0)) // uhoh, no split at all...hack it.
{
pos = utf8len(text);
if (pos > scrw) // too big, have to chop a string in the middle.
pos = scrw;
} // if
if (pos > 0)
{
utf8text = text; // adjust pointer by redecoding from start...
for (j = 0; j < pos; j++)
utf8codepoint(&utf8text);
count++;
retval = (char **) xrealloc(retval, count * sizeof (char*));
retval[count-1] = strfrombuf(text, utf8text - text);
text = (char *) utf8text;
if (pos > w)
w = pos;
} // if
} // while
*_count = count;
*_w = w;
return retval;
} // splitText
static void outOfMemory(void)
{
// Try to translate "out of memory", but not if it causes recursion.
static boolean already_panicked = false;
const char *errstr = "out of memory";
if (!already_panicked)
{
already_panicked = true;
errstr = translate(errstr);
} // if
panic(errstr);
} // outOfMemory
#undef calloc
void *xmalloc(size_t bytes)
{
void *retval = calloc(1, bytes);
if (retval == NULL)
outOfMemory();
return retval;
} // xmalloc
#define calloc(x,y) DO_NOT_CALL_CALLOC__USE_XMALLOC_INSTEAD
#undef realloc
void *xrealloc(void *ptr, size_t bytes)
{
void *retval = realloc(ptr, bytes);
if (retval == NULL)
outOfMemory();
return retval;
} // xrealloc
#define realloc(x,y) DO_NOT_CALL_REALLOC__USE_XREALLOC_INSTEAD
char *xstrdup(const char *str)
{
char *retval = (char *) xmalloc(strlen(str) + 1);
strcpy(retval, str);
return retval;
} // xstrdup
// We have to supply this function under certain build types.
#if MOJOSETUP_INTERNAL_BZLIB && BZ_NO_STDIO
void bz_internal_error(int errcode)
{
fatal(_("bzlib triggered an internal error: %0"), numstr(errcode));
} // bz_internal_error
#endif
#if SUPPORT_STBIMAGE
unsigned char *stbi_load_from_memory(unsigned char *buffer, int len, int *x,
int *y, int *comp, int req_comp);
#endif
uint8 *decodeImage(const uint8 *data, uint32 size, uint32 *w, uint32 *h)
{
uint8 *retval = MojoPlatform_decodeImage(data, size, w, h);
#if SUPPORT_STBIMAGE
if (retval == NULL) // try our built-in routines.
{
const int siz = (int) size;
unsigned char *buf = (unsigned char *) data;
int x = 0, y = 0, comp = 0;
retval = (uint8 *) stbi_load_from_memory(buf, siz, &x, &y, &comp, 4);
*w = (uint32) x;
*h = (uint32) y;
} // if
#endif
if (retval == NULL)
*w = *h = 0;
return retval;
} // decodeImage
boolean isValidProductKey(const char *fmt, const char *key)
{
if (fmt == NULL)
return true;
else if (key == NULL)
return false;
while (*fmt)