/
lx_loader.c
2121 lines (1816 loc) · 79.2 KB
/
lx_loader.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
#define _GNU_SOURCE 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <sys/mman.h>
#include <assert.h>
#include <dlfcn.h>
#include <dirent.h>
#include <pthread.h>
#include <signal.h>
#include <ucontext.h>
// 16-bit selector kernel nonsense...
#include <sys/syscall.h>
#include <sys/types.h>
#include <asm/ldt.h>
#include "lx_loader.h"
static LxLoaderState _GLoaderState;
static LxLoaderState *GLoaderState = &_GLoaderState;
// !!! FIXME: move this into an lx_common.c file.
static int sanityCheckLxModule(uint8 **_exe, uint32 *_exelen)
{
if (*_exelen < 196) {
fprintf(stderr, "not an OS/2 LX module\n");
return 0;
}
const uint32 header_offset = *((uint32 *) (*_exe + 0x3C));
//printf("header offset is %u\n", (uint) header_offset);
if ((header_offset + sizeof (LxHeader)) >= *_exelen) {
fprintf(stderr, "not an OS/2 LX module\n");
return 0;
}
*_exe += header_offset; // skip the DOS stub, etc.
*_exelen -= header_offset;
const LxHeader *lx = (const LxHeader *) *_exe;
if ((lx->magic_l != 'L') || (lx->magic_x != 'X')) {
fprintf(stderr, "not an OS/2 LX module\n");
return 0;
}
if ((lx->byte_order != 0) || (lx->word_order != 0)) {
fprintf(stderr, "Program is not little-endian!\n");
return 0;
}
if (lx->lx_version != 0) {
fprintf(stderr, "Program is unknown LX module version (%u)\n", (uint) lx->lx_version);
return 0;
}
if (lx->cpu_type > 3) { // 1==286, 2==386, 3==486
fprintf(stderr, "Program needs unknown CPU type (%u)\n", (uint) lx->cpu_type);
return 0;
}
if (lx->os_type != 1) { // 1==OS/2, others: dos4, windows, win386, unknown.
fprintf(stderr, "Program needs unknown OS type (%u)\n", (uint) lx->os_type);
return 0;
}
if (lx->page_size != 4096) {
fprintf(stderr, "Program page size isn't 4096 (%u)\n", (uint) lx->page_size);
return 0;
}
if (lx->module_flags & 0x2000) {
fprintf(stderr, "Module is flagged as not-loadable\n");
return 0;
}
// !!! FIXME: check if EIP and ESP are non-zero vs per-process library bits, etc.
return 1;
} // sanityCheckLxModule
static char *makeOS2Path(const char *fname)
{
char *full = realpath(fname, NULL);
if (!full)
return NULL;
char *retval = (char *) malloc(strlen(full) + 3);
if (!retval)
return NULL;
retval[0] = 'C';
retval[1] = ':';
strcpy(retval + 2, full);
free(full);
for (char *ptr = retval + 2; *ptr; ptr++) {
if (*ptr == '/')
*ptr = '\\';
} // for
return retval;
} // makeOS2Path
// based on case-insensitive search code from PhysicsFS:
// https://icculus.org/physfs/
// It's also zlib-licensed, plus I wrote it. :) --ryan.
// !!! FIXME: this doesn't work as-is for UTF-8 case folding, since string
// !!! FIXNE: length can change!
static int locateOneElement(char *buf)
{
if (access(buf, F_OK) == 0)
return 1; // quick rejection: exists in current case.
DIR *dirp;
char *ptr = strrchr(buf, '/'); // find entry at end of path.
if (ptr == NULL) {
dirp = opendir(".");
ptr = buf;
} else if (ptr == buf) {
dirp = opendir("/");
} else {
*ptr = '\0';
dirp = opendir(buf);
*ptr = '/';
ptr++; // point past dirsep to entry itself.
} // else
for (struct dirent *dent = readdir(dirp); dent; dent = readdir(dirp)) {
if (strcasecmp(dent->d_name, ptr) == 0) {
strcpy(ptr, dent->d_name); // found a match. Overwrite with this case.
closedir(dirp);
return 1;
} // if
} // for
// no match at all...
closedir(dirp);
return 0;
} // locateOneElement
static int locatePathCaseInsensitive(char *buf)
{
int rc;
char *ptr = buf;
if (*ptr == '\0')
return 0; // Uh...I guess that's success?
if (access(buf, F_OK) == 0)
return 0; // quick rejection: exists in current case.
while ( (ptr = strchr(ptr + 1, '/')) != NULL ) {
*ptr = '\0'; // block this path section off
rc = locateOneElement(buf);
*ptr = '/'; // restore path separator
if (!rc)
return -2; // missing element in path.
} // while
// check final element...
return locateOneElement(buf) ? 0 : -1;
} // locatePathCaseInsensitive
static char *makeUnixPath(const char *os2path, uint32 *err)
{
if ((strcasecmp(os2path, "NUL") == 0) || (strcasecmp(os2path, "\\DEV\\NUL") == 0))
os2path = "/dev/null";
// !!! FIXME: emulate other OS/2 device names (CON, etc).
//else if (strcasecmp(os2path, "CON") == 0)
else {
char drive = os2path[0];
if ((drive >= 'a') && (drive <= 'z'))
drive += 'A' - 'a';
if ((drive >= 'A') && (drive <= 'Z')) {
if (os2path[1] == ':') { // it's a drive letter.
if (drive == 'C')
os2path += 2; // skip "C:" if it's there.
else {
*err = 26; //ERROR_NOT_DOS_DISK;
return NULL;
} // else
} // if
} // if
} // else
const size_t len = strlen(os2path);
char *retval = (char *) malloc(len + 1);
if (!retval) {
*err = 8; //ERROR_NOT_ENOUGH_MEMORY;
return NULL;
} // else
strcpy(retval, os2path);
for (char *ptr = strchr(retval, '\\'); ptr; ptr = strchr(ptr + 1, '\\'))
*ptr = '/'; // convert to Unix-style path separators.
locatePathCaseInsensitive(retval);
return retval;
} // makeUnixPath
/* this algorithm is from lxlite 138u. */
static int decompressExePack2(uint8 *dst, const uint32 dstlen, const uint8 *src, const uint32 srclen)
{
uint32 sOf = 0;
uint32 dOf = 0;
uint32 bOf = 0;
uint32 b1 = 0;
uint32 b2 = 0;
#define SRCAVAIL(n) ((sOf + (n)) <= srclen)
#define DSTAVAIL(n) ((dOf + (n)) <= dstlen)
do {
if (!SRCAVAIL(1))
break;
b1 = src[sOf];
switch (b1 & 3) {
case 0:
if (b1 == 0) {
if (SRCAVAIL(2)) {
if (src[sOf + 1] == 0) {
sOf += 2;
break;
} else if (SRCAVAIL(3) && DSTAVAIL(src[sOf + 1])) {
memset(dst + dOf, src[sOf + 2], src[sOf + 1]);
sOf += 3;
dOf += src[sOf - 2];
} else {
return 0;
}
} else {
return 0;
}
} else if (SRCAVAIL((b1 >> 2) + 1) && DSTAVAIL(b1 >> 2)) {
memcpy(dst + dOf, src + (sOf + 1), b1 >> 2);
dOf += b1 >> 2;
sOf += (b1 >> 2) + 1;
} else {
return 0;
}
break;
case 1:
if (!SRCAVAIL(2))
return 0;
bOf = (*((const uint16 *) (src + sOf))) >> 7;
b2 = ((b1 >> 4) & 7) + 3;
b1 = ((b1 >> 2) & 3);
sOf += 2;
if (SRCAVAIL(b1) && DSTAVAIL(b1 + b2) && (dOf + b1 - bOf >= 0)) {
memcpy(dst + dOf, src + sOf, b1);
dOf += b1;
sOf += b1;
memmove(dst + dOf, dst + (dOf - bOf), b2);
dOf += b2;
} else {
return 0;
} // else
break;
case 2:
if (!SRCAVAIL(2))
return 0;
bOf = (*((const uint16 *) (src + sOf))) >> 4;
b1 = ((b1 >> 2) & 3) + 3;
if (DSTAVAIL(b1) && (dOf - bOf >= 0)) {
memmove(dst + dOf, dst + (dOf - bOf), b1);
dOf += b1;
sOf += 2;
} else {
return 0;
} // else
break;
case 3:
if (!SRCAVAIL(3))
return 0;
b2 = ((*((const uint16 *) (src + sOf))) >> 6) & 0x3F;
b1 = (src[sOf] >> 2) & 0x0F;
bOf = (*((const uint16 *) (src + (sOf + 1)))) >> 4;
sOf += 3;
if (SRCAVAIL(b1) && DSTAVAIL(b1 + b2) && (dOf + b1 - bOf >= 0))
{
memcpy(dst + dOf, src + sOf, b1);
dOf += b1;
sOf += b1;
memmove(dst + dOf, dst + (dOf - bOf), b2);
dOf += b2;
} else {
return 0;
} // else
break;
} // switch
} while (dOf < dstlen);
#undef SRCAVAIL
#undef DSTAVAIL
// pad out the rest of the page with zeroes.
if ((dstlen - dOf) > 0)
memset(dst + dOf, '\0', dstlen - dOf);
return 1;
} // decompressExePack2
static int decompressIterated(uint8 *dst, uint32 dstlen, const uint8 *src, uint32 srclen)
{
while (srclen) {
if (srclen < 4)
return 0;
const uint16 iterations = *((uint16 *) src); src += 2;
const uint16 len = *((uint16 *) src); src += 2;
srclen -= 4;
if (dstlen < (iterations * len))
return 0;
else if (srclen < len)
return 0;
for (uint16 i = 0; i < iterations; i++) {
memcpy(dst, src, len);
dst += len;
dstlen -= len;
} // for
src += len;
srclen -= len;
} // while
// pad out the rest of the page with zeroes.
if (dstlen > 0)
memset(dst, '\0', dstlen);
return 1;
} // decompressIterated
// !!! FIXME: mutex this
static int allocateSelector(const uint16 selector, const uint32 addr, const unsigned int contents, const int is32bit)
{
assert(selector < (sizeof (GLoaderState->ldt) / sizeof (GLoaderState->ldt[0])));
if (GLoaderState->ldt[selector])
return 0; // already in use.
//const int expand_down = (contents == MODIFY_LDT_CONTENTS_STACK);
struct user_desc entry;
entry.entry_number = (unsigned int) selector;
entry.base_addr = (unsigned int) addr; //(expand_down ? (addr + 0x10000) : addr);
entry.limit = 16; //expand_down ? 0 : 16;
entry.seg_32bit = is32bit;
entry.contents = contents;
entry.read_exec_only = 0;
entry.limit_in_pages = 1;
entry.seg_not_present = 0;
entry.useable = 1;
if (syscall(SYS_modify_ldt, 1, &entry, sizeof (entry)) != 0)
return 0;
GLoaderState->ldt[selector] = addr;
return 1;
} // allocateSelector
// !!! FIXME: mutex this
static int findSelector(const uint32 _addr, uint16 *outselector, uint16 *outoffset)
{
uint32 addr = _addr;
if (addr < 4096)
return 0; // we won't map the NULL page.
const uint32 *ldt = GLoaderState->ldt;
int available = -1;
int preferred = -1;
// optimize for the case where we need a selector that happenes to be in tiled memory,
// since it's fast to look up.
if (addr < (1024 * 1024 * 512)) {
const uint16 idx = (uint16) (addr >> 16);
const uint32 tile = ldt[idx];
if (tile == 0) {
preferred = available = idx; // we can use this piece.
} else if ((tile <= addr) && ((tile + 0x10000) > addr)) {
*outselector = idx;
*outoffset = (uint16) (addr - tile);
//printf("SELECTOR: found tiled selector 0x%X for address %p\n", (uint) idx, (void *) addr);
return 1; // already allocated to this address.
} // if
} // if
for (int i = 0; i < (sizeof (GLoaderState->ldt) / sizeof (GLoaderState->ldt[0])); i++) {
const uint32 tile = ldt[i];
if (tile == 0)
available = i;
else if ((tile <= addr) && ((tile + 0x10000) > addr)) {
*outselector = (uint16) i;
*outoffset = (uint16) (addr - tile);
//printf("SELECTOR: found existing selector 0x%X for address %p\n", (uint) i, (void *) addr);
return 1; // already allocated to this address.
} // else if
} // for
// nothing allocated to this address so far. Try to allocate something.
if (available == -1) {
fprintf(stderr, "Uhoh, we've run out of LDT selectors! Probably about to crash...\n"); fflush(stderr);
return 0; // uh oh, out of selectors!
} // if
const uint32 diff = addr % 0x10000;
addr -= diff; // make sure we start on a 64k border.
const uint16 selector = (uint16) (preferred != -1) ? preferred : available;
if (!allocateSelector(selector, addr, MODIFY_LDT_CONTENTS_CODE, 0)) {
fprintf(stderr, "Uhoh, we've failed to allocate LDT selector %u! Probably about to crash...\n", (uint) selector); fflush(stderr);
return 0;
} // if
//printf("SELECTOR: allocated selector 0x%X for address %p\n", (uint) selector, (void *) addr);
*outselector = selector;
*outoffset = (uint16) diff;
return 1;
} // findSelector
// !!! FIXME: mutex this
static void freeSelector(const uint16 selector)
{
assert(selector < (sizeof (GLoaderState->ldt) / sizeof (GLoaderState->ldt[0])));
if (!GLoaderState->ldt[selector])
return; // already free.
struct user_desc entry;
memset(&entry, '\0', sizeof (entry));
entry.entry_number = (unsigned int) selector;
entry.read_exec_only = 1;
entry.seg_not_present = 1;
if (syscall(SYS_modify_ldt, 1, &entry, sizeof (entry)) != 0)
return; // oh well.
GLoaderState->ldt[selector] = 0;
} // freeSelector
static void *convert1616to32(const uint32 addr1616)
{
if (addr1616 == 0)
return NULL;
const uint16 selector = (uint16) (addr1616 >> 19); // slide segment down, and shift out control bits.
const uint16 offset = (uint16) (addr1616 % 0x10000); // all our LDT segments start at 64k boundaries (at the moment!).
assert(GLoaderState->ldt[selector] != 0);
//printf("convert1616to32: 0x%X -> %p\n", (uint) addr1616, (void *) (size_t) (GLoaderState->ldt[selector] + offset));
return (void *) (size_t) (GLoaderState->ldt[selector] + offset);
} // convert1616to32
static uint32 convert32to1616(void *addr32)
{
if (addr32 == NULL)
return 0;
uint16 selector = 0;
uint16 offset = 0;
if (!findSelector((uint32) addr32, &selector, &offset)) {
fprintf(stderr, "Uhoh, ran out of LDT entries?!\n");
return 0; // oh well, crash, probably.
} // if
//printf("selector: 0x%X\n", (uint) selector);
selector = (selector << 3) | 7;
//printf("shifted selector: 0x%X\n", (uint) selector);
return (((uint32)selector) << 16) | ((uint32) offset);
} // convert32to1616
// EMX (and probably many other things) occasionally has to call a 16-bit
// system API, and assumes its stack is tiled in the LDT; it'll just shift
// the stack pointer and use it as a stack segment for the 16-bit call
// without calling DosFlatToSeg(). So we tile the main thread's stack and
// pray that covers it. If we have to tile _every_ thread's stack, we can do
// that later.
// !!! FIXME: if we do this for secondary thread stacks, we'll need to mutex this.
static void initOs2StackSegments(uint32 addr, uint32 stacklen, const int deinit)
{
//printf("base == %p, stacklen == %u\n", (void*)addr, (uint) stacklen);
const uint32 diff = addr % 0x10000;
addr -= diff; // make sure we start on a 64k border.
stacklen += diff; // make sure we start on a 64k border.
// We fill in LDT tiles for the entire stack (EMX, etc, assume this will work).
if (stacklen % 0x10000) // pad this out to 64k
stacklen += 0x10000 - (stacklen % 0x10000);
// !!! FIXME: do we have to allocate these backwards? (stack grows down).
while (stacklen) {
//printf("Allocating selector 0x%X for stack %p ... \n", (uint) (addr >> 16), (void *) addr);
if (deinit) {
freeSelector((uint16) (addr >> 16));
} else {
if (!allocateSelector((uint16) (addr >> 16), addr, MODIFY_LDT_CONTENTS_DATA/*STACK*/, 0)) {
FIXME("uhoh, couldn't set up an LDT entry for a stack segment! Might crash later!");
} // if
} // else
stacklen -= 0x10000;
addr += 0x10000;
} // while
} // initOs2StackSegments
// OS/2 threads keep their Thread Information Block at FS:0x0000, so we have
// to ask the Linux kernel to screw around with 16-bit selectors on our
// behalf so we don't crash out when apps try to access it directly.
// OS/2 provides a C-callable API to obtain the (32-bit linear!) TIB address
// without going directly to the FS register, but lots of programs (including
// the EMX runtime) touch the register directly, so we have to deal with it.
// You must call this once for each thread that will go into LX land, from
// that thread, as soon as possible after starting.
static uint16 initOs2Tib(uint8 *tibspace, void *_topOfStack, const size_t stacklen, const uint32 tid)
{
uint8 *topOfStack = (uint8 *) _topOfStack;
LxTIB *tib = (LxTIB *) tibspace;
LxTIB2 *tib2 = (LxTIB2 *) (tib + 1);
FIXME("This is probably 50% wrong");
tib->tib_pexchain = NULL;
tib->tib_pstack = topOfStack - stacklen;
tib->tib_pstacklimit = (void *) topOfStack;
tib->tib_ptib2 = tib2;
tib->tib_version = 20; // !!! FIXME
tib->tib_ordinal = 79; // !!! FIXME
tib2->tib2_ultid = tid;
tib2->tib2_ulpri = 512;
tib2->tib2_version = 20;
tib2->tib2_usMCCount = 0;
tib2->tib2_fMCForceFlag = 0;
// !!! FIXME: I barely know what I'm doing here, this could all be wrong.
struct user_desc entry;
entry.entry_number = -1;
entry.base_addr = (unsigned int) ((size_t)tib);
entry.limit = LXTIBSIZE;
entry.seg_32bit = 1;
entry.contents = MODIFY_LDT_CONTENTS_DATA;
entry.read_exec_only = 0;
entry.limit_in_pages = 0;
entry.seg_not_present = 0;
entry.useable = 1;
const long rc = syscall(SYS_set_thread_area, &entry);
assert(rc == 0); FIXME("this can legit fail, though!");
// The "<< 3 | 3" makes this a GDT selector at ring 3 permissions.
// If this did "| 7" instead of "| 3", it'd be an LDT selector.
// Use findSelector() or allocateSelector() for LDT entries, though!
const unsigned int segment = (entry.entry_number << 3) | 3;
__asm__ __volatile__ ( "movw %%ax, %%fs \n\t" : : "a" (segment) );
return (uint16) entry.entry_number;
} // initOs2Tib
static void deinitOs2Tib(const uint16 selector)
{
// !!! FIXME: I barely know what I'm doing here, this could all be wrong.
struct user_desc entry;
memset(&entry, '\0', sizeof (entry));
entry.entry_number = selector;
entry.read_exec_only = 1;
entry.seg_not_present = 1;
const long rc = syscall(SYS_set_thread_area, &entry);
assert(rc == 0); FIXME("this can legit fail, though!");
} // deinitOs2Tib
static void freeLxModule(LxModule *lxmod);
static __attribute__((noreturn)) void terminate(const uint32 exitcode)
{
freeLxModule(GLoaderState->main_module);
// clear out anything that is still loaded...
while (GLoaderState->loaded_modules) {
LxModule *lowest_mod = GLoaderState->loaded_modules;
for (LxModule *i = GLoaderState->loaded_modules; i; i = i->next) {
if (i->refcount < lowest_mod->refcount)
lowest_mod = i;
} // for
freeLxModule(lowest_mod);
} // while
// OS/2's docs say this only keeps the lower 16 bits of exitcode.
// !!! FIXME: ...but Unix only keeps the lowest 8 bits. Will have to
// !!! FIXME: tapdance to pass larger values back to OS/2 parent processes.
if (exitcode > 255)
FIXME("deal with process exit codes > 255. We clamped this one!");
_exit((int) (exitcode & 0xFF));
} // terminate
static __attribute__((noreturn)) void endLxProcess(const uint32 exitcode)
{
if (GLoaderState->dosExit)
GLoaderState->dosExit(1, exitcode); // let exit lists run. Should call terminate!
terminate(exitcode); // just in case.
} // endLxProcess
static void missingEntryPointCalled(const char *module, const char *entry)
{
fflush(stdout);
fflush(stderr);
fprintf(stderr, "\n\nMissing entry point '%s' in module '%s'! Aborting.\n\n\n", entry, module);
//STUBBED("output backtrace");
fflush(stderr);
terminate(1);
} // missingEntryPointCalled
static void *generateMissingTrampoline(const char *_module, const char *_entry)
{
static void *page = NULL;
static uint32 pageused = 0;
static uint32 pagesize = 0;
if (pagesize == 0)
pagesize = getpagesize();
if ((!page) || ((pagesize - pageused) < 32))
{
if (page)
mprotect(page, pagesize, PROT_READ | PROT_EXEC);
page = mmap(NULL, pagesize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
pageused = 0;
} // if
void *trampoline = page + pageused;
char *ptr = (char *) trampoline;
char *module = strdup(_module);
char *entry = strdup(_entry);
*(ptr++) = 0x55; // pushl %ebp
*(ptr++) = 0x89; // movl %esp,%ebp
*(ptr++) = 0xE5; // ...movl %esp,%ebp
*(ptr++) = 0x68; // pushl immediate
memcpy(ptr, &entry, sizeof (char *));
ptr += sizeof (uint32);
*(ptr++) = 0x68; // pushl immediate
memcpy(ptr, &module, sizeof (char *));
ptr += sizeof (uint32);
*(ptr++) = 0xB8; // movl immediate to %eax
const void *fn = missingEntryPointCalled;
memcpy(ptr, &fn, sizeof (void *));
ptr += sizeof (void *);
*(ptr++) = 0xFF; // call absolute in %eax.
*(ptr++) = 0xD0; // ...call absolute in %eax.
const uint32 trampoline_len = (uint32) (ptr - ((char *) trampoline));
assert(trampoline_len <= 32);
pageused += trampoline_len;
if (pageused % 4) // keep these aligned to 32 bits.
pageused += (4 - (pageused % 4));
//printf("Generated trampoline %p for module '%s' export '%s'\n", trampoline, module, entry);
return trampoline;
} // generateMissingTrampoline
static void *generateMissingTrampoline16(const char *_module, const char *_entry, const LxExport **_lxexp)
{
static void *page = NULL;
static uint32 pageused = 0;
const uint32 pagesize = 0x10000;
static uint16 selector = 0xFFFF;
if ((!page) || ((pagesize - pageused) < 64))
{
if (page)
mprotect(page, pagesize, PROT_READ | PROT_EXEC);
page = mmap(NULL, pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
const size_t diff = (((size_t)page) % 0x10000);
if (diff) { // align to 64k, unmap the difference.
void *origpage = page;
page = ((uint8 *) page) + (0x10000 - diff);
munmap(origpage, 0x10000 - diff);
} else {
munmap(((uint8 *)page) + 0x10000, 0x10000); // unmap the extra half we didn't need.
} // else
pageused = 0;
uint16 offset = 0xFFFF;
selector = 0xFFFF;
findSelector((uint32) page, &selector, &offset);
assert(selector != 0xFFFF);
assert(offset == 0);
} // if
void *trampoline = page + pageused;
char *ptr = (char *) trampoline;
char *module = strdup(_module);
char *entry = strdup(_entry);
// convert stack to linear address...
*(ptr++) = 0x8C; /* mov ax,ss... */
*(ptr++) = 0xD0; /* ...mov ax,ss */
*(ptr++) = 0xC1; /* shr ax,byte 0x3... */
*(ptr++) = 0xE8; /* ...shr ax,byte 0x3 */
*(ptr++) = 0x03; /* ...shr ax,byte 0x3 */
*(ptr++) = 0x66; /* shl eax,byte 0x10... */
*(ptr++) = 0xC1; /* ...shl eax,byte 0x10 */
*(ptr++) = 0xE0; /* ...shl eax,byte 0x10 */
*(ptr++) = 0x10; /* ...shl eax,byte 0x10 */
*(ptr++) = 0x89; /* mov ax,sp... */
*(ptr++) = 0xE0; /* ...mov ax,sp */
// jmp to 32-bit code...
*(ptr++) = 0x66; /* jmp dword 0x7788:0x33332222... */
*(ptr++) = 0xEA; /* ...jmp dword 0x7788:0x33332222 */
const uint32 jmp32addr = (uint32) (ptr + 6);
memcpy(ptr, &jmp32addr, 4); ptr += 4;
memcpy(ptr, &GLoaderState->original_cs, 2); ptr += 2;
// now we're in 32-bit land again.
*(ptr++) = 0x66; /* mov cx,0xabcd... */
*(ptr++) = 0xB9; /* ...mov cx,0xabcd */
memcpy(ptr, &GLoaderState->original_ss, 2); ptr += 2;
*(ptr++) = 0x8E; /* mov ss,ecx... */
*(ptr++) = 0xD1; /* ...mov ss,ecx */
*(ptr++) = 0x89; /* mov esp,eax... */
*(ptr++) = 0xC4; /* ...mov esp,eax */
*(ptr++) = 0x66; /* mov cx,0x8888... */
*(ptr++) = 0xB9; /* ...mov cx,0x8888 */
memcpy(ptr, &GLoaderState->original_ds, 2); ptr += 2;
*(ptr++) = 0x66; /* mov cx,0x8888... */
*(ptr++) = 0xB9; /* ...mov cx,0x8888 */
memcpy(ptr, &GLoaderState->original_es, 2); ptr += 2;
*(ptr++) = 0x8E; /* mov es,ecx... */ \
*(ptr++) = 0xC1; /* ...mov es,ecx */ \
// okay, CPU is in a sane state again, call the trampoline. Don't bother cleaning up.
*(ptr++) = 0x68; // pushl immediate
memcpy(ptr, &entry, sizeof (char *));
ptr += sizeof (uint32);
*(ptr++) = 0x68; // pushl immediate
memcpy(ptr, &module, sizeof (char *));
ptr += sizeof (uint32);
*(ptr++) = 0xB8; // movl immediate to %eax
const void *fn = missingEntryPointCalled;
memcpy(ptr, &fn, sizeof (void *));
ptr += sizeof (void *);
*(ptr++) = 0xFF; // call absolute in %eax.
*(ptr++) = 0xD0; // ...call absolute in %eax.
// (and never return.)
const uint32 trampoline_len = (uint32) (ptr - ((char *) trampoline));
assert(trampoline_len <= 64);
pageused += trampoline_len;
if (pageused % 4) // keep these aligned to 32 bits.
pageused += (4 - (pageused % 4));
//printf("Generated trampoline %p for module '%s' 16-bit export '%s'\n", trampoline, module, entry);
// this hack is not thread safe and only works at all because we don't store this long-term.
static LxExport lxexp;
static LxMmaps lxmmap;
lxexp.addr = trampoline;
lxexp.object = &lxmmap;
lxmmap.mapped = lxmmap.addr = page;
lxmmap.size = 0x10000;
lxmmap.alias = selector;
*_lxexp = &lxexp;
return trampoline;
} // generateMissingTrampoline16
static __attribute__((noreturn)) void runLxModule(LxModule *lxmod, const int argc, char **argv, char **envp)
{
uint8 *stack = (uint8 *) ((size_t) lxmod->esp);
// ...and you pass it the pointer to argv0. This is (at least as far as the docs suggest) appended to the environment table.
//fprintf(stderr, "jumping into LX land for exe '%s'...! eip=%p esp=%p\n", lxmod->name, (void *) lxmod->eip, stack); fflush(stderr);
GLoaderState->running = 1;
__asm__ __volatile__ (
"movl %%esi,%%esp \n\t" // use the OS/2 process's stack.
"pushl %%eax \n\t" // cmd
"pushl %%ecx \n\t" // env
"pushl $0 \n\t" // reserved
"pushl %%edx \n\t" // module handle
"leal 1f,%%eax \n\t" // address that entry point should return to.
"pushl %%eax \n\t"
"pushl %%edi \n\t" // the OS/2 process entry point (we'll "ret" to it instead of jmp, so stack and registers are all correct).
"xorl %%eax,%%eax \n\t"
"xorl %%ebx,%%ebx \n\t"
"xorl %%ecx,%%ecx \n\t"
"xorl %%edx,%%edx \n\t"
"xorl %%esi,%%esi \n\t"
"xorl %%edi,%%edi \n\t"
"xorl %%ebp,%%ebp \n\t"
"ret \n\t" // go to OS/2 land!
"1: \n\t" // ...and return here.
"pushl %%eax \n\t" // push exit code from OS/2 app.
"call endLxProcess \n\t" // never returns.
// If we returned here, %eax has the exit code from the app.
: // no outputs.
: "a" (GLoaderState->pib.pib_pchcmd),
"c" (GLoaderState->pib.pib_pchenv),
"d" (lxmod), "S" (stack), "D" (lxmod->eip)
: "memory"
);
__builtin_unreachable();
} // runLxModule
static void runLxLibraryInitOrTerm(LxModule *lxmod, const int isTermination)
{
uint8 *stack = NULL;
// force us over to OS/2 main module's stack if we aren't already on it.
if (!GLoaderState->running)
stack = (uint8 *) ((size_t) GLoaderState->main_module->esp);
//fprintf(stderr, "jumping into LX land to %s library '%s'...! eip=%p esp=%p\n", isTermination ? "terminate" : "initialize", lxmod->name, (void *) lxmod->eip, stack); fflush(stderr);
__asm__ __volatile__ (
"pushal \n\t" // save all the current registers.
"pushfl \n\t" // save all the current flags.
"movl %%esp,%%ecx \n\t" // save our stack to a temporary register.
"testl %%esi,%%esi \n\t" // force the OS/2 process's stack?
"je 1f \n\t" // if 0, nope, we're already good.
"movl %%esi,%%esp \n\t" // use the OS/2 process's stack.
"1: \n\t" //
"pushl %%ecx \n\t" // save original stack pointer for real.
"pushl %%eax \n\t" // isTermination
"pushl %%edx \n\t" // library module handle
"leal 2f,%%eax \n\t" // address that entry point should return to.
"pushl %%eax \n\t"
"pushl %%edi \n\t" // the OS/2 library entry point (we'll "ret" to it instead of jmp, so stack and registers are all correct).
"xorl %%eax,%%eax \n\t"
"xorl %%ebx,%%ebx \n\t"
"xorl %%ecx,%%ecx \n\t"
"xorl %%edx,%%edx \n\t"
"xorl %%esi,%%esi \n\t"
"xorl %%edi,%%edi \n\t"
"xorl %%ebp,%%ebp \n\t"
"ret \n\t" // go to OS/2 land!
"2: \n\t" // ...and return here.
"addl $8,%%esp \n\t" // drop arguments to entry point.
"popl %%esp \n\t" // restore native process stack now.
"popfl \n\t" // restore our original flags.
"popal \n\t" // restore our original registers.
: // no outputs
: "a" (isTermination), "d" (lxmod), "S" (stack), "D" (lxmod->eip)
: "memory"
);
//fprintf(stderr, "...survived time in LX land!\n"); fflush(stderr);
// !!! FIXME: this entry point returns a result...do we abort if it reports error?
// !!! FIXME: (actually, DosLoadModule() can report that failure. Abort if (GLoaderState->running == 0), though!)
} // runLxLibraryInitOrTerm
static void runLxLibraryInit(LxModule *lxmod)
{
// we don't check the LIBINIT flag, because if the EIP fields are valid
// but this bit is missing, we're supposed to do "global" initialization,
// which I guess means it runs once for all processes on the system
// instead of once per process...but we aren't really a full OS/2 system
// so maybe it's okay to do global init in isolation...? We'll cross that
// bridge when we come to it, I guess. Either way: this is running here,
// flag or not.
if (1) { //if (lxmod->module_flags & 0x4) { // LIBINIT flag
if (lxmod->lx.eip_object != 0)
runLxLibraryInitOrTerm(lxmod, 0);
} // if
} // runLxLibraryInit
static void runLxLibraryTerm(LxModule *lxmod)
{
// See notes about global initialization in runLxLibraryInit(); it
// applies to deinit here, too.
if (1) { //if (lxmod->module_flags & 0x40000000) { // LIBTERM flag
if (lxmod->lx.eip_object != 0)
runLxLibraryInitOrTerm(lxmod, 1);
} // if
} // runLxLibraryTerm
static void freeLxModule(LxModule *lxmod)
{
if (!lxmod)
return;
// !!! FIXME: mutex from here
lxmod->refcount--;
//fprintf(stderr, "unref'd module '%s' to %u\n", lxmod->name, (uint) lxmod->refcount);
if (lxmod->refcount > 0)
return; // something is still using it.
if ((lxmod->initialized) && (lxmod != GLoaderState->main_module)) {
if (!lxmod->nativelib) {
runLxLibraryTerm(lxmod);
} else {
LxNativeModuleDeinitEntryPoint fn = (LxNativeModuleDeinitEntryPoint) dlsym(lxmod->nativelib, "lxNativeModuleDeinit");
if (fn)
fn();
} // else
} // if
if (lxmod->next)
lxmod->next->prev = lxmod->prev;
if (lxmod->prev)
lxmod->prev->next = lxmod->next;
if (lxmod == GLoaderState->loaded_modules)
GLoaderState->loaded_modules = lxmod->next;
if (GLoaderState->main_module == lxmod) {
GLoaderState->main_module = NULL;
LxMmaps *lxmmap = &lxmod->mmaps[lxmod->lx.esp_object - 1];
const uint32 stackbase = (uint32) ((size_t)lxmmap->addr);
initOs2StackSegments(stackbase, lxmmap->size, 1);
lxmmap->mapped = NULL; // don't unmap the stack we're probably using!
} // if
// !!! FIXME: mutex to here
for (uint32 i = lxmod->lx.num_import_mod_entries; i > 0; i--)
freeLxModule(lxmod->dependencies[i-1]);
free(lxmod->dependencies);
for (uint32 i = 0; i < lxmod->lx.module_num_objects; i++) {
if (lxmod->mmaps[i].alias != 0xFFFF)
freeSelector(lxmod->mmaps[i].alias);
if (lxmod->mmaps[i].mapped)
munmap(lxmod->mmaps[i].mapped, lxmod->mmaps[i].size);
} // for
free(lxmod->mmaps);
if (lxmod->nativelib)
dlclose(lxmod->nativelib);
else {
for (uint32 i = 0; i < lxmod->num_exports; i++)
free((void *) lxmod->exports[i].name);
free((void *) lxmod->exports);
} // else
free(lxmod);
} // freeLxModule
static LxModule *loadLxModuleByModuleNameInternal(const char *modname, const int dependency_tree_depth);
static void *getModuleProcAddrByOrdinal(const LxModule *module, const uint32 ordinal, const LxExport **_lxexp, const int want16bit)
{
//printf("lookup module == '%s', ordinal == %u\n", module->name, (uint) ordinal);
const LxExport *lxexp = module->exports;
for (uint32 i = 0; i < module->num_exports; i++, lxexp++) {
if (lxexp->ordinal == ordinal) {
if (_lxexp)
*_lxexp = lxexp;
void *retval = lxexp->addr;
if (lxexp->object && lxexp->object->alias != 0xFFFF) // 16-bit bridge? this is actually a void**, due to some macro salsa. :/
retval = *((void**) retval);
return retval;
} // if
} // for
if (_lxexp)
*_lxexp = NULL;
#if 1
char entry[128];
snprintf(entry, sizeof (entry), "ordinal #%u", (uint) ordinal);
return want16bit ? generateMissingTrampoline16(module->name, entry, _lxexp) : generateMissingTrampoline(module->name, entry);
#else
return NULL;
#endif
} // getModuleProcAddrByOrdinal
static void *getModuleProcAddrByName(const LxModule *module, const char *name, const LxExport **_lxexp, const int want16bit)
{
//printf("lookup module == '%s', name == '%s'\n", module->name, name);
const LxExport *lxexp = module->exports;
for (uint32 i = 0; i < module->num_exports; i++, lxexp++) {
if (strcmp(lxexp->name, name) == 0) {
if (_lxexp)
*_lxexp = lxexp;
void *retval = lxexp->addr;
if (lxexp->object && lxexp->object->alias != 0xFFFF) // 16-bit bridge? this is actually a void**, due to some macro salsa. :/
retval = *((void**) retval);
return retval;
} // if
} // for
if (_lxexp)
*_lxexp = NULL;
#if 1