-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlx_loader.c
2784 lines (2401 loc) · 108 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
/**
* 2ine; an OS/2 emulator for Linux.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#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 "lib2ine.h"
// !!! FIXME: move this into an lx_common.c file.
static int sanityCheckLxModule(const uint8 *exe, const uint32 exelen)
{
if (sizeof (LxHeader) >= exelen) {
fprintf(stderr, "not an OS/2 EXE\n");
return 0;
}
const LxHeader *lx = (const LxHeader *) exe;
if ((lx->byte_order != 0) || (lx->word_order != 0)) {
fprintf(stderr, "Module is not little-endian!\n");
return 0;
}
if (lx->lx_version != 0) {
fprintf(stderr, "Module is unknown LX version (%u)\n", (uint) lx->lx_version);
return 0;
}
if (lx->cpu_type > 3) { // 1==286, 2==386, 3==486
fprintf(stderr, "Module 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, "Module needs unknown OS type (%u)\n", (uint) lx->os_type);
return 0;
}
if (lx->page_size != 4096) {
fprintf(stderr, "Module 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 int sanityCheckNeModule(const uint8 *exe, const uint32 exelen)
{
if (sizeof (NeHeader) >= exelen) {
fprintf(stderr, "not an OS/2 EXE\n");
return 0;
}
const NeHeader *ne = (const NeHeader *) exe;
if (ne->exe_type > 1) {
fprintf(stderr, "Not an OS/2 NE module file (exe_type is %d, not 1)\n", (int) ne->exe_type);
return 0;
}
return 1;
} // sanityCheckNeModule
static int sanityCheckModule(uint8 **_exe, uint32 *_exelen, int *_is_lx)
{
if (*_exelen < 62) {
fprintf(stderr, "not an OS/2 module\n");
return 0;
}
const uint32 header_offset = *((uint32 *) (*_exe + 0x3C));
//printf("header offset is %u\n", (uint) header_offset);
*_exe += header_offset; // skip the DOS stub, etc.
*_exelen -= header_offset;
const uint8 *magic = *_exe;
if ((magic[0] == 'L') && (magic[1] == 'X')) {
*_is_lx = 1;
return sanityCheckLxModule(*_exe, *_exelen);
} else if ((magic[0] == 'N') && (magic[1] == 'E')) {
*_is_lx = 0;
return sanityCheckNeModule(*_exe, *_exelen);
}
fprintf(stderr, "not an OS/2 module\n");
return 0;
} // sanityCheckModule
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 *lxMakeUnixPath(const char *os2path, uint32 *err)
{
const char *mountpoint = NULL;
const char *cwd = NULL;
FIXME("map devices in 2ine.cfg");
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')) && (os2path[1] == ':')) { // it's a drive letter.
os2path += 2; // skip "C:"
} else {
drive = (GLoaderState.current_disk-1) + 'A';
}
const int driveidx = drive - 'A';
mountpoint = GLoaderState.disks[driveidx];
if (!mountpoint) {
*err = 26; //ERROR_NOT_DOS_DISK;
return NULL;
}
if (*os2path != '\\') {
cwd = GLoaderState.current_dir[driveidx];
}
}
const size_t len = (mountpoint ? strlen(mountpoint) : 0) + (cwd ? strlen(cwd) : 0) + strlen(os2path) + 3;
char *retval = (char *) malloc(len);
if (!retval) {
*err = 8; //ERROR_NOT_ENOUGH_MEMORY;
return NULL;
}
snprintf(retval, len, "%s%s%s%s%s", mountpoint ? mountpoint : "", cwd ? "/" : "", cwd ? cwd : "", ((!*os2path) || (*os2path == '/')) ? "" : "/", os2path);
for (char *ptr = strchr(retval, '\\'); ptr; ptr = strchr(ptr + 1, '\\'))
*ptr = '/'; // convert to Unix-style path separators.
FIXME("this could be more efficient");
char *ptr = retval;
while ((ptr = strstr(ptr, "//")) != NULL) {
memmove(ptr, ptr + 1, strlen(ptr));
}
locatePathCaseInsensitive(retval);
return retval;
} // lxMakeUnixPath
// So exepack2 sometimes copies between pieces of the destination buffer,
// but you can't memmove() since you actually want it to copy the data as
// it changes in case of overlap. But to prevent debugging tools from
// complaining about overlapping memcpy()'s, we just do a simple for-loop.
static void linearmove(uint8 *dst, const uint8 *src, uint8 len)
{
while (len--) {
*dst = *src;
dst++;
src++;
}
} // linearmove
/* this algorithm is from lxlite 138u. */
static int decompressExePack2(uint8 *dst, const uint32 dstlen, const uint8 *src, const uint32 srclen)
{
sint32 sOf = 0;
sint32 dOf = 0;
sint32 bOf = 0;
uint8 b1 = 0;
uint8 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;
linearmove(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)) {
linearmove(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;
linearmove(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
static inline uint16 lxSelectorToSegment(const uint16 selector)
{
return (selector << 3) | 7;
} // lxSelectorToSegment
// !!! FIXME: mutex this
static int allocateSelector(const uint16 selector, const int pages, const uint32 addr, const unsigned int contents, const int is32bit)
{
assert(selector < LX_MAX_LDT_SLOTS);
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 = pages; //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 lxFindSelector(const uint32 _addr, uint16 *outselector, uint16 *outoffset, int iscode)
{
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 happens 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 < LX_MAX_LDT_SLOTS; 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
// decide if there is code or data mapped here. If there's an OS/2 API to
// change page permissions, we'll need to update the mapping and our state.
for (LxModule *lxmod = GLoaderState.loaded_modules; (iscode == -1) && lxmod; lxmod = lxmod->next) {
LxMmaps *mmaps = lxmod->mmaps;
for (uint32 i = 0; i < lxmod->num_mmaps; i++, mmaps++) {
const size_t lo = (size_t) mmaps->addr;
const size_t hi = lo + mmaps->size;
if ((addr >= lo) && (addr <= hi)) {
iscode = ((mmaps->prot & PROT_EXEC) != 0);
break;
} // if
} // for
} // for
if (iscode == -1) {
iscode = 0;
}
const uint32 diff = addr % 0x10000;
addr -= diff; // make sure we start on a 64k border.
const uint16 selector = (uint16) (preferred != -1) ? preferred : available;
//printf("setting up LDT mapping for %s at selector %u\n", iscode ? "code" : "data", (unsigned int) selector);
if (!allocateSelector(selector, 16, addr, iscode ? MODIFY_LDT_CONTENTS_CODE : MODIFY_LDT_CONTENTS_DATA, 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;
} // lxFindSelector
// !!! FIXME: mutex this
static void lxFreeSelector(const uint16 selector)
{
assert(selector < LX_MAX_LDT_SLOTS);
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;
} // lxFreeSelector
static void *lxConvert1616to32(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!).
//printf("lxConvert1616to32: 0x%X -> %p\n", (uint) addr1616, (void *) (size_t) (GLoaderState.ldt[selector] + offset));
assert(GLoaderState.ldt[selector] != 0);
return (void *) (size_t) (GLoaderState.ldt[selector] + offset);
} // lxConvert1616to32
static uint32 lxConvert32to1616(void *addr32)
{
if (addr32 == NULL)
return 0;
uint16 selector = 0;
uint16 offset = 0;
if (!lxFindSelector((uint32) addr32, &selector, &offset, -1)) {
fprintf(stderr, "Uhoh, ran out of LDT entries?!\n");
return 0; // oh well, crash, probably.
} // if
//printf("selector=0x%X, segment=0x%X\n", (uint) selector, (uint) lxSelectorToSegment(selector));
return (((uint32)lxSelectorToSegment(selector)) << 16) | ((uint32) offset);
} // lxConvert32to1616
static inline void *lxConvertSegmentOffsetto32(const uint16 seg, const uint16 off)
{
return lxConvert1616to32((((uint32) seg) << 16) | ((uint32) off));
} // lxConvertSegmentOffsetto32
// 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 DosFlatToSel(). 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) {
lxFreeSelector((uint16) (addr >> 16));
} else {
if (!allocateSelector((uint16) (addr >> 16), 16, addr, MODIFY_LDT_CONTENTS_DATA, 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 lxSetOs2Tib(uint8 *tibspace)
{
// !!! 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)tibspace);
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 lxFindSelector() 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;
} // lxSetOs2Tib
static LxTIB2 *lxGetOs2Tib2(void)
{
// just read the FS register, since we have to stick it there anyhow...
LxTIB2 *ptib2;
__asm__ __volatile__ ( "movl %%fs:0xC, %0 \n\t" : "=r" (ptib2) );
return ptib2;
} // lxGetTib2
static LxTIB *lxGetOs2Tib(void)
{
// we store the TIB2 struct right after the TIB struct on the stack,
// so get the TIB2's linear address from %fs:0xC, then step back
// to the TIB's linear address.
uint8 *ptib2 = (uint8 *) lxGetOs2Tib2();
return (LxTIB *) (ptib2 - sizeof (LxTIB));
} // lxGetOs2Tib
static void lxDeinitOs2Tib(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!");
} // lsDeinitOs2Tib
static void freeLxModule(LxModule *lxmod);
static __attribute__((noreturn)) void lxTerminate(const uint32 exitcode)
{
GLoaderState.lib2ine_shutdown();
// free the actual .exe
freeLxModule(GLoaderState.main_module);
// clear out anything that is still loaded...
// presumably everything in the loaded_modules list is sorted in order
// of dependency, since we prepend the newest loads to the front of the
// list, and anything a load depends on gets listed before the dependent
// module, pushing it futher down.
// if this doesn't work out, maybe just run everything's termination code
// and free everything after there's nothing left to run.
while (GLoaderState.loaded_modules) {
LxModule *lxmod = GLoaderState.loaded_modules;
lxmod->refcount = 1; // force it to free now.
freeLxModule(lxmod);
} // while
free(GLoaderState.ldt);
GLoaderState.ldt = NULL;
// 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));
} // lxTerminate
static __attribute__((noreturn)) void endLxProcess(const uint32 exitcode)
{
if (GLoaderState.dosExit)
GLoaderState.dosExit(1, exitcode); // let exit lists run. Should call lxTerminate!
lxTerminate(exitcode); // just in case.
} // endLxProcess
static void *lxAllocSegment(uint16 *selector, const int iscode)
{
// These are meant to be 64k segments mapped for use by 16-bit code, which means we
// need them under 512 megabytes so their segments can convert directly to a linear
// address with some bit twiddling.
static size_t baseaddr = 136 * 1024 * 1024; // just start at a random low address that (hopefully) doesn't overlap anything.
const uint32 segmentsize = 0x10000;
void *segment = mmap((void *) baseaddr, segmentsize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (segment == ((void *) MAP_FAILED)) {
FIXME("This could be more robust.");
fprintf(stderr, "Failed to mmap a 16-bit friendly memory segment.\n");
return NULL;
}
baseaddr += segmentsize;
uint16 offset = 0xFFFF;
*selector = 0xFFFF;
lxFindSelector((uint32) segment, selector, &offset, iscode);
assert(*selector != 0xFFFF);
assert(offset == 0);
//printf("lxAllocSegment: addr=%p, selector=%x\n", segment, (uint) *selector);
return segment;
} // lxAllocSegment
static void lxFreeSegment(const uint16 selector)
{
const uint32 addr32 = GLoaderState.ldt[selector];
if (addr32) {
void *addr = (void *) ((size_t) addr32);
//printf("lxFreeSegment: addr=%p, selector=%x\n", addr, (uint) selector);
munmap(addr, 0x10000);
lxFreeSelector(selector);
} // if
} // lxFreeSegment
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);
lxTerminate(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 *segment = NULL;
static uint32 segmentused = 0;
const uint32 segmentsize = 0x10000;
static uint16 selector = 0xFFFF;
if ((!segment) || ((segmentsize - segmentused) < 64))
{
if (segment)
mprotect(segment, segmentsize, PROT_READ | PROT_EXEC);
segment = lxAllocSegment(&selector, 1);
assert(segment != NULL);
assert(selector != 0xFFFF);
segmentused = 0;
} // if
void *trampoline = segment + segmentused;
char *ptr = (char *) trampoline;
char *module = strdup(_module);
char *entry = strdup(_entry);
// USE16
*(ptr++) = 0x89; /* mov cx,sp... */
*(ptr++) = 0xE1; /* ...mov cx,sp */
*(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;
// USE32
*(ptr++) = 0x66; /* mov ax,ss... */
*(ptr++) = 0x8C; /* ...mov ax,ss */
*(ptr++) = 0xD0; /* ...mov ax,ss */
*(ptr++) = 0x66; /* shr ax,byte 0x3... */
*(ptr++) = 0xC1; /* ...shr ax,byte 0x3 */
*(ptr++) = 0xE8; /* ...shr ax,byte 0x3 */
*(ptr++) = 0x03; /* ...shr ax,byte 0x3 */
*(ptr++) = 0xC1; /* shl eax,byte 0x10... */
*(ptr++) = 0xE0; /* ...shl eax,byte 0x10 */
*(ptr++) = 0x10; /* ...shl eax,byte 0x10 */
*(ptr++) = 0x66; /* mov ax,cx... */
*(ptr++) = 0x89; /* ...mov ax,cx */
*(ptr++) = 0xC8; /* ...mov ax,cx */
*(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 */
if (GLoaderState.original_ss != GLoaderState.original_ds) {
*(ptr++) = 0x66; /* mov cx,0x8888... */
*(ptr++) = 0xB9; /* ...mov cx,0x8888 */
memcpy(ptr, &GLoaderState.original_ds, 2); ptr += 2;
}
*(ptr++) = 0x8E; /* mov ds,ecx... */
*(ptr++) = 0xD9; /* ...mov ds,ecx */
if (GLoaderState.original_es != GLoaderState.original_ds) {
*(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);
segmentused += trampoline_len;
if (segmentused % 4) // keep these aligned to 32 bits.
segmentused += (4 - (segmentused % 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 = segment;
lxmmap.size = 0x10000;
lxmmap.alias = selector;
*_lxexp = &lxexp;
return trampoline;
} // generateMissingTrampoline16
static __attribute__((noreturn)) void runLxModule(LxModule *lxmod)
{
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"
);
(void) endLxProcess; // make compiler happy.
__builtin_unreachable();
} // runLxModule
static __attribute__((noreturn)) void runNeModule(LxModule *lxmod)
{
//fprintf(stderr, "jumping into NE land for exe '%s'...! cs:ip=%X:%X (%p) ss:sp=%X:%X (%p)\n", lxmod->name, (uint) (lxmod->eip >> 16), (uint) (lxmod->eip & 0xFFFF), lxConvert1616to32(lxmod->eip), (uint) (lxmod->esp >> 16), (uint) (lxmod->esp & 0xFFFF), lxConvert1616to32(lxmod->esp)); fflush(stderr);
GLoaderState.running = 1;
// According to https://github.com/open-watcom/open-watcom-v2/blob/master/bld/clib/startup/c/maino16.c ,
// The stack at startup should have, pushed in this order: cmdline offset, env segment, far* to top of stack, far* to bottom of stack.
// Microsoft C 5.1 wants things in registers (maybe Watcom does too, elsewhere, and I'm reading it wrong?),
// so we do both.
const uint16 stacksize = (uint16) GLoaderState.mainstacksize;
const uint16 ss = (lxmod->esp >> 16) & 0xFFFF; // stack segment
const uint32 cmd1616 = lxConvert32to1616(GLoaderState.pib.pib_pchcmd);
const uint16 cmdlineoffset = cmd1616 & 0xFFFF;
const uint16 envseg = (cmd1616 >> 16) & 0xFFFF;
uint8 *stack = (uint8 *) lxConvert1616to32(lxmod->esp);
//printf("stack is at 32=%p 16=%x:%x\n", stack, (uint) ss, (uint) (lxmod->esp & 0xFFFF));
stack -= 2; *((uint16 *) stack) = cmdlineoffset; // cmdline offset
stack -= 2; *((uint16 *) stack) = envseg; // env segment
stack -= 2; *((uint16 *) stack) = lxmod->esp & 0xFFFF; // top of stack
stack -= 2; *((uint16 *) stack) = ss;
stack -= 2; *((uint16 *) stack) = (lxmod->esp & 0xFFFF) - stacksize; // bottom of stack
stack -= 2; *((uint16 *) stack) = ss; // bottom of stack
uint16 selector = 0xFFFF;
void *segment = lxAllocSegment(&selector, 1);
assert(segment != NULL);
assert(selector != 0xFFFF);
char *ptr = (char *) segment;
/*
; instructions are in Intel syntax here, not AT&T.
USE32
JMP WORD 0xAAAA:0xBBBB ; jump into 16-bit land (the next instruction!).
USE16
MOV AX,0x1111 ; set stack segment
MOV SS,AX
MOV SP,0x2222 ; set stack pointer
MOV AX,0x3333 ; set data segment
MOV DS,AX
XOR AX,AX ; set extra segment to zero.
MOV ES,AX
MOV AX,0x4444 ; AX=env segment
MOV BX,0x5555 ; BX=cmdline offset
MOV CX,0x6666 ; CX=size of auto data segment
XOR DX,DX ; clear remaining general registers.
XOR SI,SI
XOR DI,DI