Repository navigation
Expand file tree
/
Copy pathasm.cpp
More file actions
6545 lines (6195 loc) · 212 KB
/
Copy pathasm.cpp
File metadata and controls
6545 lines (6195 loc) · 212 KB
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
/*
MIT License
Copyright (c) 2017 Franck GOTTHOLD, xor2003
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "asm.h"
#include <exception>
#ifndef __BORLANDC__
#ifndef _WIN32
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <strings.h>
#endif
#ifndef __DJGPP__
#ifndef NOSDL
#include <SDL2/SDL.h>
#endif
#endif
// #include <thread>
#endif
#ifdef __DJGPP__
#include <pc.h>
#include <dos.h>
#include <dpmi.h>
#include <go32.h>
#include <sys/farptr.h>
#endif
#ifdef _WIN32
//#include <windows.h>
#endif
//#include <assert.h>
//#include <time.h>
#include <cassert>
#include <cerrno>
#include <string>
#include <ctime>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <execinfo.h>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <thread>
#include <vector>
#include <map>
#include <fstream>
#ifndef M2C_LOAD_SEG
#define M2C_LOAD_SEG 0x192
#endif
// DOS program segment prefix paragraph. For hosted .COM-style runs it equals
// M2C_LOAD_SEG; for EXE-style two-segment programs the code loads at
// M2C_LOAD_SEG while the PSP lives one paragraph below it.
#ifndef M2C_PSP_SEG
#define M2C_PSP_SEG M2C_LOAD_SEG
#endif
#ifndef NOCURSES
#include <curses.h>
#endif
static m2c::m2c_game_hooks g_hooks;
static m2c::m2c_palette_map g_palette_map;
static bool g_palette_mapped = false;
m2c::m2c_overlay_module* m2c::m2c_overlays[8];
void m2c::m2c_set_game_hooks(const m2c_game_hooks* hooks) {
g_hooks = hooks ? *hooks : m2c_game_hooks{};
}
void m2c::m2c_register_palette_map(const m2c_palette_map* map) {
if (map) { g_palette_map = *map; g_palette_mapped = true; }
else { g_palette_map = m2c_palette_map{}; g_palette_mapped = false; }
}
bool m2c::m2c_register_overlay_module(m2c_overlay_module* mod) {
for (auto& slot : m2c_overlays) {
if (!slot) { slot = mod; return true; }
}
return false;
}
static m2c::m2c_overlay_module* m2c_find_overlay(dw seg) {
for (auto* mod : m2c::m2c_overlays) {
if (mod && mod->code_seg && seg == mod->code_seg) return mod;
}
return nullptr;
}
static m2c::m2c_overlay_module* m2c_overlay_image_at(dw segment, dw offset) {
for (auto* mod : m2c::m2c_overlays) {
if (mod && mod->img_paras && segment >= mod->seg &&
segment < mod->seg + mod->img_paras) {
(void)offset;
return mod;
}
}
return nullptr;
}
/* https://commons.wikimedia.org/wiki/File:Table_of_x86_Registers_svg.svg */
//struct uc_x86_state {
// REGDEF_nol(flags);
//};
/*
#undef REGDEF_hl
#undef REGDEF_l
#undef REGDEF_bwd
#undef REGDEF_nol
struct __fl
{
bool _CF:1;
bool res1:1;
bool _PF:1;
bool res2:1;
bool _AF:1;
bool res3:1;
bool _ZF:1;
bool _SF:1;
bool _TF:1;
bool _IF:1;
bool _DF:1;
bool _OF:1;
int _IOPL:2;
bool _NT:1;
bool res4:1;
bool res5:16;
};
static struct __fl __eflags;
#define CF __eflags._CF
#define ZF __eflags._ZF
#define DF __eflags._DF
#define SF __eflags._SF
*/
// VRAM logical window is VGA-state (not SDL) — needed by headless builds for
// the deterministic frame-flip machinery below.
static const size_t VGA_WINDOW_SIZE = 0x20000;
// SDL2 VGA
#ifndef NOSDL
#if SDL_MAJOR_VERSION == 2
SDL_Renderer *renderer;
SDL_Window *window;
static bool vga_render_dirty;
static unsigned vga_render_writes;
static int vga_logical_width = 320;
static int vga_logical_height = 200;
static const unsigned VGA_RENDER_WRITE_FLUSH_THRESHOLD = 8 * 1024;
static db vgaPlanarPixels[640 * 200];
static db vgaMode13Pixels[VGA_WINDOW_SIZE * 4];
static unsigned char vga_wr_hit[VGA_WINDOW_SIZE]; // per-byte write coverage (M2C_WRHIT)
static db vgaReadLatch[4];
static db vgaPendingReadLatch[4][4];
static size_t vgaPendingReadLatchCount;
static size_t vgaPendingReadLatchNext;
static uint32_t vgaSdlFrame[640 * 400];
static SDL_Texture *vgaTexture;
db vgaRamPaddingBefore[VGARAM_SIZE];
db vgaRam[VGARAM_SIZE];
db vgaRamPaddingAfter[VGARAM_SIZE];
#endif
#endif
bool from_callf=false;
namespace m2c {
int last_ret_popped=-1;
size_t last_ret_mark_id=0;
int last_ret_mark_mode=0;
dd last_ret_site=0;
#ifdef M2CDEBUG
/* Per-instruction tracing is expensive enough to freeze a program, so it
* is strictly opt-in: M2CDEBUG only compiles the support in, M2C_DEBUG
* must be set explicitly to turn it on (default off). */
size_t debug = std::getenv("M2C_DEBUG") ? (size_t)atoi(std::getenv("M2C_DEBUG")) : 0;
#else
size_t debug = 0;
#endif
bool defered_irqs=false;
size_t counter = 0;
int m2c_ret_dbg = [](){ const char* e=getenv("M2C_RETDBG"); return e && *e=='1'; }();
unsigned m2c_last_callsite_i = 0, m2c_last_callsite_eip = 0, m2c_last_callsite_rip = 0;
std::vector<NativeReturnMark> native_return_marks;
std::vector<NativeReturnMark> native_return_values;
std::unordered_map<MWORDSIZE, SentinelResumeInfo> sentinel_resume_map;
size_t native_return_next_id = 0;
size_t native_return_call_depth = 0;
bool suppress_native_return_push_transfer = false;
/* Default to strict (exact-match) native-return bookkeeping. The
non-strict register-carried (`carry`/`take`) and frame-skip/reloc
fallback heuristics mis-consume marks on Tornado's call patterns:
a `pop`/`push` juggling the return word steals or drops the mark, the
later `ret` then misses, dispatches to the proc *entry* instead of the
post-call continuation, and re-enters the proc -> unbounded recursion.
Exact-match marks are semantically correct for this code; opt back into
the heuristics with M2C_STRICT_RET=0 if a different game needs them. */
int m2c_strict_native_return = [](){ const char* e=getenv("M2C_STRICT_RET"); return e && *e=='0' ? 0 : 1; }();
/* M2C_DISPASSERT: verbose dump when a far/near target cannot be resolved.
Default ON so dispatch misses surface their full context (seg, off, cs,
eip, which resolver failed) instead of a bare "Don't know how to call".
Set M2C_DISPASSERT=0 to silence. */
int m2c_dispassert = [](){ const char* e=getenv("M2C_DISPASSERT"); return e && *e=='0' ? 0 : 1; }();
/* cs invariant: while running translated code the emulated cs must be a
plausible code segment -- 0 (bare near dispatch), 0xf000 (BIOS), a
generated-proc host paragraph (m2c_seg_func_for), or a real loaded
segment. Anything else means a return-table word or data pointer was
popped into cs, which is the exact corruption class that produced the
seg:off "Don't know how to call" aborts. Checked at dispatch entry so
the first bad cs is flagged at the point it is *used*, not deep inside
a wrong-module run. */
static bool m2c_cs_sane(dw v) {
if (v == 0 || v == 0xf000) return true;
if (m2c_seg_func_for(v)) return true;
if (linked_code_segment_raddr(v, 0) || m2c_alloc_segment_raddr(v, 0)) return true;
return false;
}
static void m2c_check_cs(_STATE* _state, _offsets disp, const char* where) {
if (!m2c_dispassert) return;
const dw v = _state->cs;
if (!m2c_cs_sane(v)) {
fprintf(stderr,
"[CSBAD] %s cs=%04x (not 0/f000/func-seg/real-seg) disp=%08x eip=%04x\n",
where, (unsigned)v, (unsigned)disp, (unsigned)(_state->eip & 0xffff));
}
}
int m2c_dump_marks(_STATE* st, unsigned disp) {
fprintf(stderr, "MARKDUMP disp=%08x state=%p depth=%d nmarks=%d\n",
disp, (void*)st, (int)native_return_call_depth, (int)native_return_marks.size());
const unsigned rip = disp & 0xffff;
for (auto& mk : native_return_marks) {
if ((unsigned)mk.return_ip == rip || mk.state == st)
fprintf(stderr, " mk st=%p ss=%x sp=%x rip=%x d=%d id=%d %s\n",
(void*)mk.state,(unsigned)mk.stack_segment,(unsigned)mk.stack_offset,
(unsigned)mk.return_ip,(int)mk.call_depth,(int)mk.id,
mk.state==st?"<SAMEST":"");
}
return 0;
}
db _indent=0;
const char *_str="";
bool fix_segs(){return true;}
void interpret_unknown_callf(dw cs, dd eip, db source){assert(0);}
__attribute__((weak)) db* linked_code_segment_raddr(dw, dw){return nullptr;}
__attribute__((weak)) db* linked_data_segment_raddr(dw, dw){return nullptr;}
__attribute__((weak)) void set_segment_register(dw& reg, dw value){reg = value;}
__attribute__((weak)) void copy_linked_program_segment_prefix(dw, const void*, size_t) {}
// BIOS ROM shadow for the F000 segment (see asm.h). Zeroed by default; a
// program that emulates a specific machine plants its signature bytes via
// the overlay/game glue before the guest first reads the F000 segment.
db m2c_bios_rom[0x10000] = {};
bool host_try_overlay_retf(_offsets __disp, _STATE* _state, bool* out_result);
__attribute__((weak)) bool m2c_guest_thunk(_offsets __disp, _STATE* _state) {
(void)__disp; (void)_state;
return false;
}
__attribute__((weak)) m2cf* m2c_seg_func_for(dw seg) {
(void)seg;
return nullptr;
}
__attribute__((weak)) bool dispatch_external_code(_offsets __disp, _STATE* _state, bool* handled) {
bool res = true;
if (host_try_overlay_retf(__disp, _state, &res)) {
if (handled) {
*handled = true;
}
return res;
}
if (handled) {
*handled = false;
}
return true;
}
ShadowStack shadow_stack;
x87_t fpu;
long double fpu_ld80(const void* p) {
if (sizeof(long double) >= 10) {
long double v = 0;
memcpy(&v, p, 10);
return v;
}
// Portable decode for hosts where long double is not 80-bit x87 ext.
const db* b = (const db*)p;
uint64_t mant;
memcpy(&mant, b, 8);
int se = b[8] | (b[9] << 8);
int sign = se >> 15;
int exp = se & 0x7fff;
if (exp == 0 && mant == 0) return sign ? -0.0L : 0.0L;
return (long double)std::ldexp((long double)mant, exp - 16383 - 63) * (sign ? -1.0L : 1.0L);
}
void fpu_st80(void* p, long double v) {
db* b = (db*)p;
if (sizeof(long double) >= 10) {
memcpy(b, &v, 10);
return;
}
// Portable encode to 80-bit x87 extended.
int sign = std::signbit(v);
long double a = std::fabs(v);
uint64_t mant = 0;
int se = 0;
if (a != 0 && std::isfinite(a)) {
int exp;
long double f = std::frexp(a, &exp); // a = f * 2^exp, f in [0.5,1)
mant = (uint64_t)std::ldexp(f, 64); // 1 bit int + 63 fraction
se = exp - 1 + 16383;
}
memcpy(b, &mant, 8);
b[8] = se & 0xff;
b[9] = ((se >> 8) & 0x7f) | (sign ? 0x80 : 0);
}
void fpu_init() {
memset(&fpu, 0, sizeof(fpu));
fpu.cw = 0x037f;
std::fesetround(FE_TONEAREST);
}
//db vgaPalette[256*3];
#include "vgapal.h"
// Legacy selector table — superseded by m2c_ldt (emulated LDT). Kept
// because historical asm_16.h copies reference `selectors[segment]` under
// _PROTECTED_MODE; the shared runtime no longer uses it.
dd selectorsPointer;
dd selectors[NB_SELECTORS];
dd heapPointer;
struct find_t;
static db defaultDiskTransferArea[128] = {};
struct find_t * diskTransferAddr = reinterpret_cast<find_t *>(defaultDiskTransferArea);
/* Win16 / protected-mode descriptor table (emulated LDT). Under real
protected mode, segment registers hold *selectors*: 16-bit values encoded
as (index<<3 | TI<<2 | RPL). Each selector indexes a descriptor
{base, limit, rights}. We emulate that:
- m2c_ldt[] is the descriptor store, indexed by selector>>3.
- base is a HOST pointer: either inside `m` (aliases of real-mode
segments / the loaded image) or a malloc'd block (DPMI/RTM allocations).
- lin is the guest-visible linear base (m-offset for m-aliases, a
synthetic address for owned blocks).
- Real-mode paragraphs in segregs are not descriptors: they resolve
through the `m` paragraph view in raddr_().
Allocated selectors are encoded (idx<<3 | 7) starting at m2c_pm_sel_base
(default 0x4000 -> index 2048), above normal image paragraphs, so plain
paragraph values never alias a used descriptor. Because the encoding is
the real one, guest descriptor arithmetic works: sel+8 (__AHINCR) steps
to the next descriptor and sel>>3 (__AHSHIFT) yields the table index. */
PmDesc m2c_ldt[NB_LDT];
static unsigned m2c_ldt_next_idx; // allocation cursor (index)
// First allocated selector *value*. Weak so a program can place its
// descriptor space above its loaded image; default suits images < 256KB.
__attribute__((weak)) dw m2c_pm_sel_base = 0x4000;
static unsigned m2c_pm_next_linear = 0x1000000; // synthetic linear base for owned blocks
int m2c_ldt_idx(dw sel) { return (sel >> 3) & (NB_LDT - 1); }
// Allocate n consecutive descriptors; returns the base selector value
// (idx<<3 | 7) or 0 on exhaustion. Entries are marked used with no base —
// the client sets base/limit via INT31 0007/0008 or the m2c_ldt_* helpers.
dw m2c_ldt_alloc(int n) {
if (!m2c_ldt_next_idx) m2c_ldt_next_idx = m2c_ldt_idx(m2c_pm_sel_base);
unsigned start = m2c_ldt_next_idx;
if (start + n >= NB_LDT) {
log_error("ldt: out of descriptors (need %d at %u)\n", n, start);
return 0;
}
for (int i = 0; i < n; ++i) {
PmDesc& d = m2c_ldt[start + i];
if (d.used) { // shouldn't happen past the cursor; be loud
log_error("ldt: descriptor %u already used\n", start + i);
}
d.base = nullptr;
d.limit = 0xffff;
d.rights = 0x00f3; // data, read/write, accessed (DPMI default)
d.lin = 0;
d.used = 1;
d.owned = 0;
}
m2c_ldt_next_idx = start + n;
return (dw)((start << 3) | 7);
}
void m2c_ldt_free(dw sel) {
int idx = m2c_ldt_idx(sel);
PmDesc& d = m2c_ldt[idx];
if (!d.used) return;
if (d.owned) {
db* blk = d.base;
dd ext = d.extent ? d.extent : 0x10000;
free(blk);
// Clear every descriptor aliasing the freed block.
for (int i = 0; i < NB_LDT; ++i) {
if (m2c_ldt[i].used && m2c_ldt[i].base >= blk &&
m2c_ldt[i].base < blk + ext)
m2c_ldt[i] = PmDesc{};
}
} else {
d = PmDesc{};
}
}
// `struct Memory` is program-defined and incomplete here; its layout ends
// with the `heap` array (a link-bound reference into m), so the usable
// extent of `m` linear addresses is (&heap - &m) + HEAP_SIZE.
static inline dd m2c_m_extent() {
return (dd)((db*)&heap - (db*)&m) + HEAP_SIZE;
}
// Guest linear base for INT31 0006: m-offset for m-aliased descriptors,
// the recorded synthetic base for owned regions.
dd m2c_ldt_get_lin(dw sel) {
const PmDesc& d = m2c_ldt[m2c_ldt_idx(sel)];
if (!d.base) return d.lin;
if (d.base >= (db*)&m && d.base < (db*)&m + m2c_m_extent())
return (dd)(d.base - (db*)&m);
return d.lin;
}
// Allocate a 64KB-backed region and return its selector. Real selectors
// cover the full 64KB regardless of the requested size — guest code may
// legally touch any 16-bit offset — so the host block is always 64KB.
dw m2c_pm_alloc_paras(dw paras) {
dw sel = m2c_ldt_alloc(1);
if (!sel) {
log_error("pm alloc: out of descriptors (req=%04x)\n", (unsigned)paras);
return 0;
}
db* p = static_cast<db*>(calloc(1, 0x10000));
if (!p) { m2c_ldt_free(sel); return 0; }
PmDesc& d = m2c_ldt[m2c_ldt_idx(sel)];
d.base = p;
d.limit = 0xffff;
d.lin = m2c_pm_next_linear;
d.extent = 0x10000;
m2c_pm_next_linear += 0x10000;
d.owned = 1;
log_debug2("pm alloc req=%04x -> sel=%04x lin=%x\n", (unsigned)paras, sel, d.lin);
return sel;
}
void m2c_pm_free(dw sel) { m2c_ldt_free(sel); }
// Under the protected-mode memory model, `seg X` must produce a *selector*:
// value stored into ds/es/ss/cs, passed to DPMI, or written by NE fixups.
// Resolve a paragraph to a descriptor aliasing that m storage. Aliases are
// shared (same paragraph -> same selector) and cached for the common
// repeated `seg DGROUP` pattern.
dw m2c_seg_selector(dw para) {
dd lin = (dd)para << 4;
static dw last_para = 0xffff, last_sel = 0;
if (para == last_para) return last_sel;
for (int i = 0; i < NB_LDT; ++i) {
const PmDesc& d = m2c_ldt[i];
if (d.used && !d.owned && d.lin == lin) {
last_para = para;
last_sel = (dw)((i << 3) | 7);
return last_sel;
}
}
dw sel = m2c_ldt_alloc(1);
if (!sel) return para; // LDT exhausted — paragraph still resolves via m
PmDesc& d = m2c_ldt[m2c_ldt_idx(sel)];
d.base = (db*)&m + lin;
d.lin = lin;
last_para = para;
last_sel = sel;
return sel;
}
// `seg X` where X names a segment the NE loader mapped: the descriptor the
// loader created is the guest-visible selector value (ds/ss hold selectors,
// NE fixups store selectors), so data initializers and `seg` expressions
// must agree with them. Paragraphs with no descriptor keep their real-mode
// identity, so DOS programs see no behaviour change. Lookup only — unlike
// m2c_seg_selector this never allocates, and misses are not cached so it is
// safe to call before the loader runs.
dw m2c_seg_selector_or_para(dw para) {
const dd lin = (dd)para << 4;
static dw last_para = 0xffff, last_sel = 0;
if (para == last_para) return last_sel;
for (int i = 0; i < NB_LDT; ++i) {
const PmDesc& d = m2c_ldt[i];
if (d.used && !d.owned && d.lin == lin) {
last_para = para;
last_sel = (dw)((i << 3) | 7);
return last_sel;
}
}
return para;
}
/* Generic NE (Win16) image loader — shared implementation behind the
m2c_ne_entry_setup hook. The caller owns where each segment lives
(M2cNeSegHost::base/para); this routine does the format work: descriptor
creation, file-data copies, internal-reference fixups, entry state. */
static dw ne_w(const db* p) { return (dw)(p[0] | (p[1] << 8)); }
static void ne_w_set(db* p, dw v) { p[0] = db(v); p[1] = db(v >> 8); }
static dd ne_d(const db* p) {
return (dd)p[0] | ((dd)p[1] << 8) | ((dd)p[2] << 16) | ((dd)p[3] << 24);
}
static M2cNeImport s_ne_imports[512];
static char s_ne_mod_names[32][16];
M2cNeImport* m2c_ne_imports = s_ne_imports;
dw m2c_ne_import_count = 0;
const char* m2c_ne_import_mod_name(dw mod_idx) {
if (!mod_idx || mod_idx > 32 || !s_ne_mod_names[mod_idx - 1][0]) return "?";
return s_ne_mod_names[mod_idx - 1];
}
static dw ne_import_add(dw mod_idx, dw ord) {
for (dw i = 0; i < m2c_ne_import_count; ++i)
if (s_ne_imports[i].mod_idx == mod_idx && s_ne_imports[i].ordinal == ord)
return i;
dw idx = m2c_ne_import_count;
if (idx < sizeof(s_ne_imports) / sizeof(*s_ne_imports)) {
s_ne_imports[idx].mod_idx = mod_idx;
s_ne_imports[idx].ordinal = ord;
++m2c_ne_import_count;
}
return idx;
}
bool m2c_ne_load(_STATE* _state, const db* image, dd image_size,
M2cNeSegHost* segs) {
X86_REGREF
if (!image || image_size < 0x40 || ne_w(image) != 0x5a4d /*'MZ'*/) {
log_error("NE load: not an MZ image\n");
return false;
}
dd ne = ne_d(image + 0x3c);
if (ne + 0x40 > image_size || ne_w(image + ne) != 0x454e /*'NE'*/) {
log_error("NE load: no NE signature\n");
return false;
}
const db* hdr = image + ne;
const dw ds_idx = ne_w(hdr + 0x0e); // automatic data segment
const dw entry_ip = ne_w(hdr + 0x14);
const dw cs_idx = ne_w(hdr + 0x16);
const dw entry_sp = ne_w(hdr + 0x18);
const dw ss_idx = ne_w(hdr + 0x1a);
const dw nseg = ne_w(hdr + 0x1c);
const dw segoff = ne_w(hdr + 0x22); // segment table, rel to NE
const dw shift = ne_w(hdr + 0x32); // logical sector shift
if (!nseg || ne + segoff + nseg * 8 > image_size) {
log_error("NE load: bad segment table (count=%u)\n", nseg);
return false;
}
const db* stab = hdr + segoff;
for (int i = 0; i < nseg; ++i) {
const db* e = stab + i * 8;
dd foff = (dd)ne_w(e) << shift;
dd len = ne_w(e + 2); if (!len) len = 0x10000;
dw flags = ne_w(e + 4);
segs[i].flags = flags;
if (!segs[i].base && segs[i].para)
segs[i].base = (db*)&m + ((dd)segs[i].para << 4);
if (!segs[i].base) {
log_error("NE load: segment %d has no host storage\n", i + 1);
return false;
}
// File bytes (code images, preinitialized data) into host storage.
if (foff && foff + len <= image_size)
memcpy(segs[i].base, image + foff, len);
// Selector aliasing the segment storage; keep lin = paragraph
// linear so get-base and the PM-vector IVT mirror stay consistent.
dw sel = m2c_ldt_alloc(1);
if (!sel) return false;
PmDesc& d = m2c_ldt[m2c_ldt_idx(sel)];
d.base = segs[i].base;
d.lin = (dd)segs[i].para << 4;
segs[i].selector = sel;
}
// Module-reference table -> imported module names (for diagnostics).
const dw nmods = ne_w(hdr + 0x1e);
const db* mrt = hdr + ne_w(hdr + 0x28); // module-reference table
const db* itab = hdr + ne_w(hdr + 0x2a); // imported names table
for (dw mi = 0; mi < nmods && mi < 32 && mrt + 2 * mi + 2 <= image + image_size; ++mi) {
const db* np = itab + ne_w(mrt + 2 * mi);
dw nl = np[0]; if (nl > 15) nl = 15;
if (np + 1 + nl <= image + image_size) {
memcpy(s_ne_mod_names[mi], np + 1, nl);
s_ne_mod_names[mi][nl] = 0;
}
}
// Relocation records.
// Non-additive records (flag bit2 clear) are CHAIN records: the stored
// word at each site holds the offset of the next site and 0xffff ends
// the list; the record supplies the whole fixup value. Additive records
// are single sites whose stored word is an addend to the record target.
// rtype&3 == 0 internal ref -> seg selector / target offset
// rtype&3 == 1 imported ordinal / 2 imported name -> sentinel 0000:80NN
// rtype&3 == 3 osfixup (x87 emulator patching) -> skipped: real FPU
for (int i = 0; i < nseg; ++i) {
const db* e = stab + i * 8;
dd foff = (dd)ne_w(e) << shift;
dd len = ne_w(e + 2); if (!len) len = 0x10000;
if (!(segs[i].flags & 0x0100)) continue; // no relocations
dd rp = foff + len;
if (rp + 2 > image_size) break;
dw count = ne_w(image + rp);
rp += 2;
for (dw r = 0; r < count && rp + 8 <= image_size; ++r, rp += 8) {
const db* rec = image + rp;
const db atype = rec[0];
const db rtype = rec[1];
const dw rkind = rtype & 3;
const bool additive = (rtype & 4) != 0;
if (rkind == 3) continue;
dw off = ne_w(rec + 2);
dw guard = 0;
if (rkind == 1 || rkind == 2) {
const dw mod = ne_w(rec + 4);
const dw ord = ne_w(rec + 6);
const dw sentinel = (dw)(0x8000 | ne_import_add(mod, ord));
do {
db* loc = segs[i].base + off;
dw link = ne_w(loc);
switch (atype) {
case 2: *(dw*)loc = 0; break; // seg word -> null
case 3: *(dw*)loc = sentinel; *(dw*)(loc + 2) = 0; break; // far ptr -> 0000:80NN
case 5: *(dw*)loc = sentinel; break; // off16 -> sentinel
default: log_error("NE load: import addr type %u\n", atype); break;
}
off = additive ? 0xffff : link;
} while (off != 0xffff && ++guard < 0x8000);
continue;
}
const dw tseg = ne_w(rec + 4);
const dw toff = ne_w(rec + 6);
if (!tseg || tseg > nseg) continue;
const dw tsel = segs[tseg - 1].selector;
do {
db* loc = segs[i].base + off;
dw link = ne_w(loc);
switch (atype) {
case 2: ne_w_set(loc, tsel); break; // selector word
case 3: ne_w_set(loc, toff); ne_w_set(loc + 2, tsel); break; // far ptr
case 5: ne_w_set(loc, additive ? (dw)(link + toff) : toff); break;
default:
log_error("NE load: addr type %u unsupported\n", atype);
}
off = additive ? 0xffff : link;
} while (off != 0xffff && ++guard < 0x8000);
}
}
cs = segs[cs_idx - 1].selector;
eip = entry_ip;
if (ss_idx) { ss = segs[ss_idx - 1].selector; }
sp = entry_sp ? entry_sp : (dw)(STACK_SIZE - 4);
if (ds_idx) { ds = es = segs[ds_idx - 1].selector; }
log_debug("NE load: entry %04x:%04x stack %04x:%04x ds %04x (%u segs)\n",
cs, entry_ip, ss, sp, ds, nseg);
return true;
}
db* m2c_alloc_segment_raddr(dw segment, dw offset) {
const PmDesc& d = m2c_ldt[m2c_ldt_idx(segment)];
// Only values with the LDT table-indicator bit (sel&4) are selectors;
// plain paragraphs fall through to the `m` view. Lenient on the limit:
// blocks are backed by 64KB so every 16-bit offset resolves; the limit
// is recorded for get/set fidelity.
if ((segment & 4) && d.used && d.base)
return d.base + offset;
return nullptr;
}
// Protected-mode vectors installed via INT31 0203/0205 (CX:EDX = sel:eip).
// Recorded verbatim for faithful get/set round-trips; additionally mirrored
// into the real-mode IVT when the handler selector aliases `m`.
static dw pm_vec_sel[256];
static dd pm_vec_off[256];
static db pm_vec_set[256];
/* Real-mode IVT entries installed via int21 ah=25h are program vectors: their
segment is the translated code's (opaque, often >=0xa000), so host_fire_ivt
must not discard them as BIOS/adapter-ROM vectors. BIOS-resident entries the
program never overwrote keep the >=0xa000 filter. */
static db rm_vec_set[256];
// Compatibility name used by NE/RTM-style translated programs (asm.h).
// Weak so a program harness can substitute its own allocator.
__attribute__((weak)) dw tlink_rtm_alloc_paras(dw paras) { return m2c_pm_alloc_paras(paras); }
// DOS file-handle table: handles 0..4 are the predefined std devices;
// regular files occupy 5..N (like DOS's SFT).
static dw dta_seg = 0; // guest-visible seg:off of the DTA (as set by AH=1Ah)
static dw dta_off = 0x80;
static FILE * dos_files[0x40] = {};
static const dw DOS_HANDLE_BASE = 5;
static int dos_last_child_rc = 0;
static FILE * dos_std[5] = {};
static FILE * dos_get_file(dw h) {
if (h < DOS_HANDLE_BASE) {
// Predefined DOS devices 0..4 (stdin/stdout/stderr/aux/prn). Map to
// dup'd host stdio so guest dup()/close() on them is harmless.
if (!dos_std[h]) {
FILE * sf = (h == 0) ? stdin : (h == 1) ? stdout : (h == 2) ? stderr
: (h == 3) ? stdout : stderr;
int fd = dup(fileno(sf));
int acc = fd >= 0 ? (fcntl(fd, F_GETFL) & O_ACCMODE) : -1;
const char * sm = acc == O_RDONLY ? "r" : acc == O_WRONLY ? "a" : "r+";
dos_std[h] = fd >= 0 ? fdopen(fd, sm) : nullptr;
}
return dos_std[h];
}
if (h - DOS_HANDLE_BASE >= 0x40) return nullptr;
return dos_files[h - DOS_HANDLE_BASE];
}
static dw dos_alloc_handle(FILE * f) {
for (dw h = 0; h < 0x40; ++h)
if (!dos_files[h]) { dos_files[h] = f; return DOS_HANDLE_BASE + h; }
fclose(f);
return 0xffff;
}
// DOS file names are case-insensitive. Resolve a guest path against the
// host filesystem component-by-component, folding case via directory
// listing, so "hello.obj" finds "HELLO.OBJ". Returns true on success.
static bool dos_resolve_case(const char *path, char *out, size_t outsz) {
if (!path || !*path || !out || outsz < 2) return false;
char buf[1024];
std::snprintf(buf, sizeof(buf), "%s", path);
for (char *p = buf; *p; ++p) if (*p == '\\') *p = '/';
std::string resolved;
size_t pos = 0;
if (buf[0] == '/') { resolved = "/"; pos = 1; }
while (pos <= strlen(buf)) {
const char *sep = strchr(buf + pos, '/');
size_t len = sep ? (size_t)(sep - (buf + pos)) : strlen(buf + pos);
if (len == 0) {
if (!sep) break;
pos += 1;
continue;
}
char comp[256];
if (len >= sizeof(comp)) return false;
std::memcpy(comp, buf + pos, len);
comp[len] = 0;
const char *dir = resolved.empty() ? "." : resolved.c_str();
// exact match first
std::string cand = resolved + comp;
if (access(cand.c_str(), F_OK) != 0) {
DIR *d = opendir(dir);
if (!d) return false;
struct dirent *e;
bool found = false;
while ((e = readdir(d))) {
if (!strcasecmp(e->d_name, comp)) {
cand = resolved + e->d_name;
found = true;
break;
}
}
closedir(d);
if (!found) return false;
}
resolved = cand;
if (!sep) break;
resolved += "/";
pos += len + 1;
}
if (resolved.size() >= outsz) return false;
std::memcpy(out, resolved.c_str(), resolved.size() + 1);
return true;
}
//#include "memmgr.c"
bool isLittle;
bool jumpToBackGround;
//char *path;
bool executionFinished;
db exitCode;
FILE * logDebug=NULL;
struct HostMouse {
bool installed = true;
bool visible = false;
int x = 160;
int y = 100;
int last_x = 160;
int last_y = 100;
int min_x = 0;
int max_x = 319;
int min_y = 0;
int max_y = 199;
int buttons = 0;
int motion_x = 0;
int motion_y = 0;
};
struct HostVga {
static const int TEXT_PAGES = 8;
static const int TEXT_ROWS = 25;
static const int TEXT_COLS = 80;
struct TextCell {
db ch = ' ';
db attr = 0x07;
};
db seq_index = 0;
db gc_index = 0;
db crtc_index = 0;
db attr_index = 0;
bool attr_waiting_for_index = true;
db seq_regs[0x100] = {};
db gc_regs[0x100] = {};
db crtc_regs[0x100] = {};
db attr_regs[0x100] = {};
size_t dac_read_index = 0;
size_t dac_write_index = 0;
size_t dac_write_start = 0;
size_t dac_write_count = 0;
db cursor_start = 0;
db cursor_end = 0;
db current_mode = 3;
db active_page = 0;
db cursor_row[TEXT_PAGES] = {};
db cursor_col[TEXT_PAGES] = {};
TextCell text[TEXT_PAGES][TEXT_ROWS][TEXT_COLS] = {};
// CGA graphics-mode state (modes 4/5 = 320x200x2bpp, 6 = 640x200x1bpp):
// pixel data lives in guest VRAM at B800:0000/B800:2000 and is rasterized
// from `m` directly. These mirror the BIOS color-select/int10-AH=0Bh
// settings plus a per-cell char shadow so AH=08 read-back works (the real
// BIOS pattern-matches pixels; keeping the written char is equivalent for
// software that reads back what it wrote, e.g. GW-BASIC's screen editor).
db cga_color_select = 0; // int10 AH=0Bh BH=0: low nibble bg(med res)/fg(hi res), bit4 intensity
db cga_palette = 0; // int10 AH=0Bh BH=1: bit0 = palette 0/1
db cga_cells[TEXT_ROWS][TEXT_COLS] = {};
};
struct HostPit {
db channel0_latch = 0;
bool channel0_waiting_high = false;
db channel0_low = 0;
uint16_t channel0_divisor = 0;
};
struct HostTimer {
bool enabled = false;
bool in_callback = false;
std::atomic<bool> background_running{false};
std::atomic<bool> irq_running{false};
uint64_t last_us = 0;
uint64_t accum_us = 0;
int divider_20hz = 0;
};
struct HostHardware {
HostMouse mouse;
HostVga vga;
HostPit pit;
HostTimer timer;
dw current_psp = M2C_PSP_SEG;
db ppi_port_b = 0;
db keyboard_scan_code = 0;
dw keyboard_buffer[16] = {};
db keyboard_head = 0;
db keyboard_tail = 0;
// Segments populated by EXEC AL=03h overlay loads (e.g. MSC sound drivers).
// Their x86 code is not translated; far calls into them are treated as
// no-ops by dispatch_external_code, which emulates the driver's retf.
std::vector<std::pair<dw, dw>> overlay_segs;
};
static HostHardware host;
// Accessor for NE-harness glue (zeek16.cpp) which installs a fake PSP after
// segment binding; HostHardware itself is file-local.
void m2c_set_current_psp(dw psp) { host.current_psp = psp; }
dw m2c_current_psp() { return host.current_psp; }
bool is_dos_terminate_vector(dw segment, dw offset) {
// 0:0 is the sentinel pushed for synthesized interrupt frames (IVT IRQ
// delivery); reaching it means unwind to C++, not program termination.
if (segment == 0 && offset == 0) {
return true;
}
if (segment != host.current_psp || offset != 0) {
return false;
}
log_error("terminate vector hit at %x:%x\n", segment, offset);
jumpToBackGround = true;
executionFinished = true;
exitCode = 0;
return true;
}
static db* host_physical_address(dw segment, dw offset) {
// A translated overlay's image lives in its private buffer: the EXEC load
// segment may alias regions the game writes through, so the image must not
// sit inside struct Memory's heap.
if (m2c_overlay_module* mod = m2c_overlay_image_at(segment, offset))
return mod->img + ((segment - mod->seg) << 4) + offset;
// PM selectors resolve through the emulated LDT (DOS services given a
// selector must see the same memory the guest sees).
if (db* sel_mem = m2c_alloc_segment_raddr(segment, offset))
return sel_mem;
return reinterpret_cast<db*>(&m2c::m) + (static_cast<size_t>(segment) << 4) + offset;
}
static db host_text_page(db page) {
return page < HostVga::TEXT_PAGES ? page : 0;
}
static db host_text_row(db row) {
return row < HostVga::TEXT_ROWS ? row : HostVga::TEXT_ROWS - 1;
}
static db host_text_col(db col) {
return col < HostVga::TEXT_COLS ? col : HostVga::TEXT_COLS - 1;
}
// Guest-visible text VRAM page inside `m`. BIOS mode-2/3 pages are 0x1000
// bytes each at B800:0000 — int10 text services must keep this region in
// sync with the host.vga.text shadow so direct-VRAM programs (GW-BASIC
// writes through ES=B800) and BIOS-driven programs see identical memory.
static db* host_text_vram_page(db page) {
return reinterpret_cast<db*>(&m2c::m) + 0xB8000 +
static_cast<size_t>(host_text_page(page)) * 0x1000;
}
static void host_text_clear_page(db page, db attr = 0x07) {
page = host_text_page(page);
db *vram = host_text_vram_page(page);
for (int row = 0; row < HostVga::TEXT_ROWS; ++row) {
for (int col = 0; col < HostVga::TEXT_COLS; ++col) {
host.vga.text[page][row][col].ch = ' ';
host.vga.text[page][row][col].attr = attr;
vram[(row * HostVga::TEXT_COLS + col) * 2] = ' ';
vram[(row * HostVga::TEXT_COLS + col) * 2 + 1] = attr;
}
}
host.vga.cursor_row[page] = 0;
host.vga.cursor_col[page] = 0;
}
static void host_text_clear_all(db attr = 0x07) {
for (int page = 0; page < HostVga::TEXT_PAGES; ++page) {
host_text_clear_page(static_cast<db>(page), attr);
}
}
static void host_text_scroll_up_window(db page, db attr, db top, db left, db bottom, db right, db lines) {
page = host_text_page(page);
top = host_text_row(top);
bottom = host_text_row(bottom);
left = host_text_col(left);
right = host_text_col(right);
if (top > bottom || left > right) {
return;
}
if (lines == 0 || lines > bottom - top + 1) {