This repository was archived by the owner on Nov 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathovm.c
1802 lines (1682 loc) · 54.5 KB
/
ovm.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
/* -*- mode: c; c-basic-offset: 3 -*- */
/* Owl Lisp runtime */
#include <stdint.h>
#ifndef NOT_RT
#define RT
#endif
#ifndef RT
static void* heap = 0;
#endif
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#define NOGDI
#define NOUSER
#define _INC_MMSYSTEM
typedef struct tagMSG *LPMSG;
#include <winsock2.h>
#include <ws2tcpip.h>
#undef VOID
/* defined like that, so it can be downloaded as 1 file, and also used with extensions */
#ifndef __OVM_H__
#define __OVM_H__
#include <inttypes.h>
typedef unsigned int uint;
typedef uint8_t byte;
typedef uintptr_t word; /* heap cell */
typedef uint32_t hval; /* heap value */
typedef intptr_t wdiff;
/*** Macros ***/
#define car(l) G(l, 1)
#define cdr(l) G(l, 2)
#define PTR(t) mkseq((byte*)&t, sizeof(uintptr_t), TBVEC)
#define cptr(v) ((void*)*(uintptr_t*)(v+W))
#define mkstring(s) mkseq(s, strlen(s), TSTRING)
#define mkbvec(vp, n) mkseq(vp, n, TBVEC)
#define MIN2(a,b) ((a)<(b)?(a):(b))
#define ABS(a) ((a<0)?-(a):(a))
#define mkport(fd) make_immediate(fd, TPORT)
#define cstr(s) ((char*)s+W) /* word as cstring */
#define IPOS 8 /* offset of immediate payload */
#define SPOS 16 /* offset of size bits in header immediate values */
#define TPOS 2 /* offset of type bits in header */
#define V(ob) (*(word *)(ob))
#define W ((uint)sizeof(word))
#define LDW ((W >> 3) + 2) /* poor man's log2(W), valid for 4, 8, 16 */
#define NWORDS 1024*1024*8 /* static malloc'd heap size if used as a library */
#define FBITS 24 /* bits in fixnum, on the way to 24 and beyond */
#define FMAX ((1<<FBITS)-1) /* maximum fixnum (and most negative fixnum) */
#define MAXOBJ 0xffff /* max words in tuple including header */
#define MAXPAYL ((MAXOBJ - 1) * W) /* maximum payload in an allocated object */
#define RAWBIT 2048
#define FPOS (SPOS - LDW) /* offset of the fractional part in the header size */
#define payl_len(hdr) (((hval)hdr >> FPOS) - W - (W - 1))
#define make_immediate(value, type) ((hval)(value) << IPOS | (type) << TPOS | 2)
#define make_header(size, type) ((hval)(size) << SPOS | (type) << TPOS | 2)
#define BOOL(cval) ((cval) ? ITRUE : IFALSE)
#define immval(desc) ((hval)(desc) >> IPOS)
#define fixnump(desc) (((desc) & 255) == 2)
#define NR 98 /* FIXME: should be ~32, see owl/register.scm:/define.n-registers/ */
#define header(x) V(x)
#define is_type(x, t) (((x) & (63 << TPOS | 2)) == ((t) << TPOS | 2))
#define objsize(x) ((hval)(x) >> SPOS)
#define immediatep(x) ((word)(x) & 2)
#define allocp(x) (!immediatep(x))
#define rawp(hdr) ((hdr) & RAWBIT)
#define NEXT(n) ip += n; continue
#define PAIRHDR make_header(3, 1)
#define NUMHDR make_header(3, 40) /* <- on the way to 40, see type-int+ in defmac.scm */
#define NUMNHDR make_header(3, 41)
#define pairp(ob) (allocp(ob) && V(ob) == PAIRHDR)
#define cons(a, d) mkpair(PAIRHDR, a, d)
#define INULL make_immediate(0, 13)
#define IFALSE make_immediate(1, 13)
#define ITRUE make_immediate(2, 13)
#define IEMPTY make_immediate(3, 13) /* empty ff */
#define IEOF make_immediate(4, 13)
#define IHALT make_immediate(5, 13)
#define TNUM 0
#define TTUPLE 2
#define TSTRING 3
#define TPORT 12
#define TTHREAD 31
#define TNUMN 32
#define TBVEC 19
#define TBYTECODE 16
#define TPROC 17
#define TCLOS 18
#define TRAT 42
#define F(value) make_immediate(value, TNUM)
#define stringp(ob) (allocp(ob) && (V(ob) & make_header(0, 63)) == make_header(0, TSTRING))
#define FLAG 1
#define cont(n) V((word)(n) & ~FLAG)
#define flag(n) ((word)(n) ^ FLAG)
#define flagged(n) ((word)(n) & FLAG)
#define flagged_or_raw(n) ((word)(n) & (RAWBIT | FLAG))
#define TBIT 1024
#define teardown_needed(hdr) ((word)(hdr) & TBIT)
#define A0 R[*ip]
#define A1 R[ip[1]]
#define A2 R[ip[2]]
#define A3 R[ip[3]]
#define A4 R[ip[4]]
#define A5 R[ip[5]]
#define G(ptr, n) (((word *)(ptr))[n])
#define TICKS 10000 /* # of function calls in a thread quantum */
#define allocate(size, to) (to = fp, fp += size)
#define error(opcode, a, b) do { R[4] = F(opcode); R[5] = (word)(a); R[6] = (word)(b); goto invoke_mcp; } while (0)
#define assert(exp, val, code) if (!(exp)) error(code, val, ITRUE)
#define assert_not(exp, val, code) if (exp) error(code, val, ITRUE)
#define MEMPAD (NR + 2) * 8 /* space at end of heap for starting GC */
#define MINGEN 1024 * 32 /* minimum generation size before doing full GC */
#define INITCELLS 100000
#define SIGGC 9 /* signal 9=SIGKILL cannot be caught, so use its place for gc signaling */
uint llen(word *ptr);
word mkpair(word h, word a, word d);
word mkint(uint64_t x);
int64_t cnum(word a);
word onum(int64_t n, uint s);
word mkrat(int64_t p, int64_t q);
word mkrat_approx(float f);
double cdouble(word);
word mkseq(uint8_t *v, unsigned long n, uint T);
#endif
#ifdef SILENT
#define not_implemented(s, why) (void)0;
#else
#define not_implemented(s, why) fprintf(stderr, "vm-error: %s: not implemented: %s (why?: %s)\n", __func__, s, why)
#endif
#ifdef PRIM_CUSTOM
word prim_custom(int op, word a, word b, word c);
#endif
#ifndef EMULTIHOP
#define EMULTIHOP -1
#endif
#ifndef ENODATA
#define ENODATA -1
#endif
#ifndef ENOLINK
#define ENOLINK -1
#endif
#ifndef ENOSR
#define ENOSR -1
#endif
#ifndef ENOSTR
#define ENOSTR -1
#endif
#ifndef ENOTRECOVERABLE
#define ENOTRECOVERABLE -1
#endif
#ifndef EOWNERDEAD
#define EOWNERDEAD -1
#endif
#ifndef ETIME
#define ETIME -1
#endif
#ifndef F_DUPFD_CLOEXEC
#define F_DUPFD_CLOEXEC -1
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#ifndef O_EXEC
#define O_EXEC 0
#endif
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
#ifndef O_RSYNC
#define O_RSYNC 0
#endif
#ifndef O_DSYNC
#define O_DSYNC 0
#endif
#ifndef O_SEARCH
#define O_SEARCH 0
#endif
#ifndef O_TTY_INIT
#define O_TTY_INIT 0
#endif
#ifdef __APPLE__
#define st_atim st_atimespec
#define st_mtim st_mtimespec
#define st_ctim st_ctimespec
#endif
/* winrt defines */
enum {
O_DIRECTORY,
O_NOCTTY,
O_NONBLOCK,
O_SYNC,
FD_CLOEXEC,
F_DUPFD,
F_GETFD,
F_SETFD,
F_GETFL,
F_SETFL,
F_GETOWN,
F_SETOWN,
F_GETLK,
F_SETLK,
F_SETLKW,
F_RDLCK,
F_UNLCK,
F_WRLCK,
};
/* winrt defines */
int
fcntl(int fd, int cmd, intptr_t arg)
{
switch (cmd) {
case F_DUPFD: not_implemented("F_DUPFD", ""); break;
case F_GETFD: not_implemented("F_GETFD", ""); break;
case F_SETFD: not_implemented("F_SETFD", ""); break;
case F_GETFL: return 0; // me when i lie :3
case F_SETFL: {
unsigned long mode = arg & O_NONBLOCK ? 1 : 0;
return ioctlsocket(fd, FIONBIO, &mode);
}
case F_GETOWN: not_implemented("F_GETOWN", ""); break;
case F_SETOWN: not_implemented("F_SETOWN", ""); break;
case F_GETLK: not_implemented("F_GETLK", ""); break;
case F_SETLK: not_implemented("F_SETLK", ""); break;
case F_SETLKW: not_implemented("F_SETLKW", ""); break;
case F_RDLCK: not_implemented("F_RDLCK", ""); break;
case F_UNLCK: not_implemented("F_UNLCK", ""); break;
case F_WRLCK: not_implemented("F_WRLCK", ""); break;
}
return -1;
}
volatile unsigned int signals; /* caught signals */
void catch_signal(int signal) {
//fprintf(stderr, "[vm: caught signal %d]\n", signal);
signals |= (1 << signal);
}
/*** Globals and Prototypes ***/
WSADATA wsa;
int wsaerrno = -1;
extern char **environ;
/* memstart <= genstart <= memend */
word *genstart;
word *memstart;
word *memend;
hval max_heap_mb; /* max heap size in MB */
word state; /* IFALSE | previous program state across runs */
const byte *hp;
word *fp;
byte *file_heap;
uint64_t nalloc;
size_t maxheap;
/*** Garbage Collector, based on "Efficient Garbage Compaction Algorithm" by Johannes Martin (1982) ***/
void rev(word pos) {
word val = V(pos);
word next = cont(val);
V(pos) = next;
cont(val) = (pos | FLAG) ^ (val & FLAG);
}
word *chase(word *pos) {
word val = cont(pos);
while (allocp(val) && flagged(val)) {
pos = (word *)val;
val = cont(pos);
}
return pos;
}
void mark(word *pos, word *end) {
while (pos != end) {
word val = *pos;
if (allocp(val) && val >= (word)genstart) {
if (flagged(val)) {
pos = (word *)flag(chase((word *)val));
} else {
word hdr = header(val);
rev((word) pos);
if (!flagged_or_raw(hdr))
pos = (word *)val + objsize(hdr);
}
}
--pos;
}
}
word *compact() {
word *new = genstart;
word *old = new;
word *end = memend - 1;
while (old < end) {
word val = *old;
if (flagged(val)) {
hval h;
*new = val;
do { /* unthread */
rev((word) new);
} while (flagged(*new));
h = objsize(*new);
if (old == new) {
old += h;
new += h;
} else {
while (--h)
*++new = *++old;
old++;
new++;
}
} else {
/* if (teardown_needed(val))
printf("gc: would teardown\n"); */
old += objsize(val);
}
}
return new;
}
void fix_pointers(word *pos, wdiff delta) {
for (;;) {
word hdr = *pos;
hval n = objsize(hdr);
if (hdr == 0) /* end marker reached. only dragons beyond this point. */
return;
if (rawp(hdr)) {
pos += n; /* no pointers in raw objects */
} else {
for (++pos; --n; ++pos) {
word val = *pos;
if (allocp(val))
*pos = val + delta;
}
}
}
}
/* emulate sbrk with malloc'd memory, because sbrk is no longer properly supported */
/* n-cells-wanted → heap-delta (to be added to pointers), updates memstart and memend */
wdiff adjust_heap(wdiff cells) {
word *old = memstart;
word nwords = memend - memstart + MEMPAD; /* MEMPAD is after memend */
word new_words = nwords + (cells > 0xffffff ? 0xffffff : cells); /* limit heap growth speed */
if (((cells > 0) && (new_words*W < nwords*W)) || ((cells < 0) && (new_words*W > nwords*W)))
return 0; /* don't try to adjust heap, if the size_t would overflow in realloc */
memstart = realloc(memstart, new_words*W);
if (!memstart) {
catch_signal(SIGGC);
return 0;
} else {
wdiff delta = (word)memstart - (word)old;
memend = memstart + new_words - MEMPAD; /* leave MEMPAD words alone */
if (delta)
fix_pointers(memstart, delta); /* d'oh! we need to O(n) all the pointers... */
return delta;
}
}
/* input desired allocation size and (the only) pointer to root object
return a pointer to the same object after heap compaction, possible heap size change and relocation */
word *gc(int size, word *regs) {
word *root;
word *realend = memend;
wdiff nfree;
fp = regs + objsize(*regs);
root = fp+1;
*root = (word) regs;
memend = fp;
nalloc += fp - genstart;
mark(root, fp);
fp = compact();
regs = (word *)*root;
memend = realend;
nfree = (word)memend - (word)regs;
if (genstart == memstart) {
word heapsize = (word) memend - (word) memstart;
word nused = heapsize - nfree;
if (maxheap < nused)
maxheap = nused;
if (heapsize / (1024 * 1024) > max_heap_mb)
catch_signal(SIGGC);
nfree -= size*W + MEMPAD; /* how much really could be snipped off */
if (nfree < (heapsize / 3) || nfree < 0) {
/* increase heap size if less than 33% is free by ~10% of heap size (growth usually implies more growth) */
regs[objsize(*regs)] = 0; /* use an invalid descriptor to denote end live heap data */
regs = (word *) ((word)regs + adjust_heap(size*W + nused/10 + 4096));
nfree = memend - regs;
if (nfree <= size)
catch_signal(SIGGC);
} else if (nfree > (heapsize/2)) {
/* decrease heap size if more than 50% is free by 10% of the free space */
wdiff dec = -(nfree / 10);
wdiff new = nfree - dec;
if (new > size*W*2 + MEMPAD) {
regs[objsize(*regs)] = 0; /* as above */
regs = (word *) ((word)regs + adjust_heap(dec+MEMPAD*W));
heapsize = (word)memend - (word)memstart;
nfree = (word)memend - (word)regs;
}
}
genstart = regs; /* always start new generation */
} else if (nfree < MINGEN || nfree < size*W*2) {
genstart = memstart; /* start full generation */
return gc(size, regs);
} else {
genstart = regs; /* start new generation */
}
return regs;
}
/*** OS Interaction and Helpers ***/
/* list length, no overflow or valid termination checks */
uint llen(word *ptr) {
uint len = 0;
while (pairp(ptr)) {
len++;
ptr = (word *) ptr[2];
}
return len;
}
word mkpair(word h, word a, word d) {
word *pair;
allocate(3, pair);
pair[0] = h;
pair[1] = a;
pair[2] = d;
return (word)pair;
}
/* recursion depth does not exceed two */
word mkint(uint64_t x) {
return mkpair(NUMHDR, F(x), x > FMAX ? mkint(x >> FBITS) : INULL);
}
/* make a raw object to hold len bytes (compute size, advance fp, clear padding) */
word mkraw(uint type, hval len) {
word *ob;
byte *end;
hval hdr = (W + len + W - 1) << FPOS | RAWBIT | make_header(0, type);
uint pads = -len % W;
allocate(objsize(hdr), ob);
*ob = hdr;
end = (byte *)ob + W + len;
while (pads--)
*end++ = 0; /* clear the padding bytes */
return (word)ob;
}
word mkseq(uint8_t *v, unsigned long n, uint T) {
size_t len = memend - fp,
max = len > MAXOBJ ? MAXPAYL + 1 : (len - 1) * W,
N = MIN2(max-1, n);
memcpy((uint8_t*)fp + W, v, N);
return mkraw(T, N);
}
word mkrat(int64_t p, int64_t q) {
word s = 2, *ob, po = onum(p, 1), qo = onum(q, 1);
allocate(s+1, ob);
*ob = make_header(s+1, TRAT);
ob[1] = po;
ob[2] = qo;
return (word)ob;
}
// not copying the new function yet
word mkrat_approx(float f) {
int64_t v = 1, m = f < 0;
f = ABS(f);
if (f >= (float)INT64_MAX)
return IFALSE;
while ((float)(f - (int64_t)f) > 0.0) {
f *= 10, v *= 10;
if (v < 0) /* v overflew */
return IFALSE;
}
return mkrat(m ? -f : f, v);
}
double cdouble(word x) {
if (allocp(x)) {
if (is_type(*(word *)x,TRAT))
return (double)cnum(car(x))/(double)cnum(cdr(x));
else if (header(x) == NUMHDR || header(x) == NUMNHDR)
return (double)cnum(x);
} else if (is_type(x,TNUM)||is_type(x,TNUMN))
return (double)cnum(x);
return 0.0/0.0;
}
/*** Primops called from VM and generated C-code ***/
/* win32 sockets are not ports, so you cannot write() to them */
#define MAX_SOCKETS (2<<12)
int sockets[MAX_SOCKETS] = {0};
#define issocket(fd) ((fd) < MAX_SOCKETS && sockets[(fd)])
int
w32write(int fd, char* buf, size_t n)
{
if (issocket(fd))
return send(fd, buf, n, 0);
return write(fd, buf, n);
}
int
w32read(int fd, char* buf, size_t n)
{
if (issocket(fd))
return recv(fd, buf, n, 0);
return read(fd, buf, n);
}
int
w32close(int fd)
{
if (issocket(fd)) {
sockets[fd] = 0;
return closesocket(fd);
}
return close(fd);
}
hval prim_connect(word *host, word port, word type) {
int sock;
byte *ip = (byte *)host + W;
unsigned long ipfull;
struct sockaddr_in addr;
char udp = (immval(type) == 1);
port = immval(port);
if ((sock = socket(AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), (udp ? IPPROTO_UDP : IPPROTO_TCP))) == INVALID_SOCKET) {
return IFALSE;
}
if (udp)
return make_immediate(sock, TPORT);
if (!allocp(host)) /* bad host type */
return IFALSE;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
/* addr.sin_addr.s_addr = (ULONG)host[1]; */
ipfull = ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3];
addr.sin_addr.s_addr = htonl(ipfull);
if (connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {
closesocket(sock);
return IFALSE;
}
sockets[sock] = 1;
return make_immediate(sock, TPORT);
}
word prim_less(word a, word b) {
if (immediatep(a))
return immediatep(b) ? BOOL(a < b) : ITRUE; /* imm < alloc */
else
return immediatep(b) ? IFALSE : BOOL(a < b); /* alloc > imm */
}
word prim_ref(word pword, hval pos) {
hval hdr;
if (immediatep(pword))
return IFALSE;
hdr = header(pword);
pos = immval(pos);
if (rawp(hdr)) { /* raw data is #[hdrbyte{W} b0 .. bn 0{0,W-1}] */
if (payl_len(hdr) <= pos)
return IFALSE;
return F(((byte *)pword)[W + pos]);
}
if (!pos || objsize(hdr) <= pos) /* tuples are indexed from 1 (probably later 0-255) */
return IFALSE;
return G(pword, pos);
}
int64_t cnum(word a) {
uint64_t x;
if (allocp(a)) {
word *p = (word *)a;
uint shift = 0;
x = 0;
do {
x |= (uint64_t)immval(p[1]) << shift;
shift += FBITS;
p = (word *)p[2];
} while (shift < 64 && allocp(p));
return header(a) == NUMNHDR ? -x : x;
}
x = immval(a);
return is_type(a, TNUMN) ? -x : x;
}
word onum(int64_t n, uint s) {
word h = NUMHDR, t = TNUM;
if (s && n < 0) {
h = NUMNHDR;
t = TNUMN;
n = -n;
}
if (n > FMAX) {
word p = mkint(n);
header(p) = h;
return p;
}
return make_immediate(n, t);
}
word prim_set(word wptr, hval pos, word val) {
word *ob = (word *)wptr;
hval hdr, p;
word *new;
pos = immval(pos);
if (immediatep(ob))
return IFALSE;
hdr = *ob;
if (rawp(hdr) || (hdr = objsize(hdr)) < pos)
return IFALSE;
allocate(hdr, new);
for (p = 0; p <= hdr; ++p)
new[p] = (pos == p && p) ? val : ob[p];
return (word) new;
}
void setdown() {
not_implemented("setdown", "no termios");
}
word do_poll(word, word, word);
/* system- and io primops */
word prim_sys(word op, word a, word b, word c) {
switch (immval(op)) {
case 0: { /* clock_gettime clock_id → nanoseconds */
LARGE_INTEGER frequency, currentTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(¤tTime);
double ns = (double)currentTime.QuadPart / (double)frequency.QuadPart * 1e9;
return onum(ns, 1);
}
case 1: /* open path flags mode → port | #f */
if (stringp(a)) {
int fd = _open((const char *)a + W, cnum(b)|_O_BINARY, immval(c));
if (fd != -1)
return make_immediate(fd, TPORT);
}
return IFALSE;
case 2:
return BOOL(w32close(immval(a)) == 0);
case 3: { /* 3 = sopen port 0=tcp|1=udp -> False | fd */
int port = immval(a);
int type = immval(b);
int s;
int opt = 1; /* TRUE */
char udp = (type == 1);
struct sockaddr_in myaddr;
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(port);
myaddr.sin_addr.s_addr = INADDR_ANY;
s = socket(AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM), (udp ? IPPROTO_UDP : 0));
fcntl(s, F_SETFL, O_NONBLOCK);
if (s < 0)
return IFALSE;
if (type != 1) {
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) \
|| bind(s, (struct sockaddr *) &myaddr, sizeof(myaddr)) != 0 \
|| listen(s, SOMAXCONN) != 0) {
close(s);
return IFALSE;
}
} else {
if (bind(s, (struct sockaddr *) &myaddr, sizeof(myaddr)) != 0) {
close(s);
return IFALSE;
}
}
sockets[s] = 1;
return make_immediate(s, TPORT); }
case 4: { /* 4 = accept port -> rval=False|(ip . fd) */
int sock = immval(a);
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SOCKET fd;
word ipa;
fd = accept(sock, (struct sockaddr *)&addr, &len);
if (fd == INVALID_SOCKET) return IFALSE;
sockets[fd] = 1;
ipa = mkraw(TBVEC, 4);
memcpy((word *)ipa + 1, &addr.sin_addr, 4);
return cons(ipa, make_immediate(fd, TPORT)); }
case 5: /* read fd len -> bvec | EOF | #f */
if (is_type(a, TPORT)) {
long long int len = memend - fp;
const size_t max = len > MAXOBJ ? MAXPAYL : (len - 1) * W;
len = cnum(b);
len = w32read(immval(a), (void*)(fp + 1), len < max ? len : max);
if (len < 0) {
wsaerrno = WSAGetLastError();
return IFALSE;
}
if (len == 0)
return IEOF;
return mkraw(TBVEC, len);
} return IFALSE;
case 6:
setdown();
exit(immval(a)); /* stop the press */
case 7: /* set memory limit (in mb) */
max_heap_mb = immval(a);
return a;
case 8: { /* return system constants */
const word sysconst[] = {
S_IFMT, W, S_IFBLK, S_IFCHR, S_IFIFO, S_IFREG, S_IFDIR, 0,
0, E2BIG, EACCES, EADDRINUSE, EADDRNOTAVAIL, EAFNOSUPPORT, EAGAIN, EALREADY,
EBADF, EBADMSG, EBUSY, ECANCELED, ECHILD, ECONNABORTED, ECONNREFUSED, ECONNRESET,
EDEADLK, EDESTADDRREQ, EDOM, WSAEDQUOT, EEXIST, EFAULT, EFBIG, EHOSTUNREACH,
EIDRM, EILSEQ, EINPROGRESS, EINTR, EINVAL, EIO, EISCONN, EISDIR,
ELOOP, EMFILE, EMLINK, EMSGSIZE, EMULTIHOP, ENAMETOOLONG, ENETDOWN, ENETRESET,
ENETUNREACH, ENFILE, ENOBUFS, ENODATA, ENODEV, ENOENT, ENOEXEC, ENOLCK,
ENOLINK, ENOMEM, ENOMSG, ENOPROTOOPT, ENOSPC, ENOSR, ENOSTR, ENOSYS,
ENOTCONN, ENOTDIR, ENOTEMPTY, ENOTRECOVERABLE, ENOTSOCK, ENOTSUP, ENOTTY, ENXIO,
EOPNOTSUPP, EOVERFLOW, EOWNERDEAD, EPERM, EPIPE, EPROTO, EPROTONOSUPPORT, EPROTOTYPE,
ERANGE, EROFS, ESPIPE, ESRCH, WSAESTALE, ETIME, ETIMEDOUT, ETXTBSY,
WSAEWOULDBLOCK, EXDEV, SEEK_SET, SEEK_CUR, SEEK_END, O_EXEC, O_RDONLY, O_RDWR,
O_SEARCH, O_WRONLY, O_APPEND, O_CLOEXEC, O_CREAT, O_DIRECTORY, O_DSYNC, O_EXCL,
O_NOCTTY, O_NOFOLLOW, O_NONBLOCK, O_RSYNC, O_SYNC, O_TRUNC, O_TTY_INIT, O_ACCMODE,
FD_CLOEXEC, F_DUPFD, F_DUPFD_CLOEXEC, F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_GETOWN,
F_SETOWN, F_GETLK, F_SETLK, F_SETLKW, F_RDLCK, F_UNLCK, F_WRLCK, CLOCK_MONOTONIC,
CLOCK_PROCESS_CPUTIME_ID, CLOCK_REALTIME, CLOCK_THREAD_CPUTIME_ID
};
return onum(sysconst[immval(a) % (sizeof sysconst / W)], 0); }
case 9: /* return process variables */
return onum(
a == F(0) ? (wsaerrno >= 0 ? wsaerrno : errno) :
a == F(1) ? (uintptr_t)environ :
a == F(8) ? nalloc + fp - memstart : /* total allocated objects so far */
a == F(9) ? maxheap : /* maximum heap size in a major gc */
max_heap_mb, 0);
case 10: { /* receive-udp-packet sock → (ip-bvec . payload-bvec)| #false */
struct sockaddr_in si_other;
socklen_t slen = sizeof(si_other);
word bvec, ipa;
int recvd;
recvd = recvfrom(immval(a), (void*)(fp + 1), 65528, 0, (struct sockaddr *)&si_other, &slen);
if (recvd < 0)
return IFALSE;
bvec = mkraw(TBVEC, recvd);
ipa = mkraw(TBVEC, 4);
memcpy((word *)ipa + 1, &si_other.sin_addr, 4);
return cons(ipa, bvec); }
case 11: /* open-dir path → dirobjptr | #false */
if (stringp(a)) {
DIR *dirp = opendir((const char *)a + W);
if (dirp != NULL)
return onum((intptr_t)dirp, 1);
}
return IFALSE;
case 12: { /* read-dir dirp → pointer */
struct dirent *ent;
errno = 0;
ent = readdir((DIR *)(intptr_t)cnum(a));
return onum(ent != NULL ? (uintptr_t)&ent->d_name : 0, 0); }
case 13: /* close-dir dirp → bool */
return BOOL(closedir((DIR *)(intptr_t)cnum(a)) == 0);
case 14: /* strerror errnum → pointer */
return onum((uintptr_t)strerror(immval(a)), 0);
case 15: /* fcntl port cmd arg → integer | #f */
if (is_type(a, TPORT)) {
int res = fcntl(immval(a), cnum(b), (intptr_t)cnum(c));
if (res != -1)
return onum(res, 1);
}
return IFALSE;
case 16: /* getenv key → pointer */
return onum(stringp(a) ? (uintptr_t)getenv((const char *)a + W) : 0, 0);
case 17: { /* exec[v] path argl ret */
char *path = (char *)a + W;
int nargs = llen((word *)b);
char **argp, **args = realloc(NULL, (nargs + 1) * sizeof(char *));
if (args == NULL)
return IFALSE;
for (argp = args; nargs--; ++argp) {
*argp = (char *)G(b, 1) + W;
b = G(b, 2);
}
*argp = NULL;
execv(path, args); /* may return -1 and set errno */
free(args);
return IFALSE; }
case 18: { /* fork → #f: failed, 0: we're in child process, integer: we're in parent process */
not_implemented("fork", "thank you winapi");
return IFALSE;
}
case 19: { /* wait <pid> <respair> _ */
not_implemented("wait", "i'm too lazy sorry");
return IFALSE;
/* pid_t pid = a != IFALSE ? cnum(a) : -1; */
/* int status; */
/* word *r = (word *)b; */
/* pid = waitpid(pid, &status, WNOHANG|WUNTRACED); /\* |WCONTINUED *\/ */
/* if (pid == -1) */
/* return IFALSE; /\* error *\/ */
/* if (pid == 0) */
/* return ITRUE; /\* no changes, would block *\/ */
/* if (WIFEXITED(status)) { */
/* r[1] = F(1); */
/* r[2] = F(WEXITSTATUS(status)); */
/* } else if (WIFSIGNALED(status)) { */
/* r[1] = F(2); */
/* r[2] = F(WTERMSIG(status)); */
/* } else if (WIFSTOPPED(status)) { */
/* r[1] = F(3); */
/* r[2] = F(WSTOPSIG(status)); */
/* /\*} else if (WIFCONTINUED(status)) { */
/* r[1] = F(4); */
/* r[2] = F(1); *\/ */
/* } else { */
/* r = (word *)IFALSE; */
/* } */
/* return (word)r; */
}
case 20: /* chdir path → bool */
return BOOL(stringp(a) && chdir((char *)a + W) == 0);
case 21: /* kill pid signal → bool */
not_implemented("kill", "i'm too lazy");
return IFALSE;
/* return BOOL(kill(cnum(a), immval(b)) == 0); */
case 22: /* unlink path → bool */
return BOOL(stringp(a) && unlink((char *)a + W) == 0);
case 23: /* rmdir path → bool */
return BOOL(stringp(a) && rmdir((char *)a + W) == 0);
case 24: /* mknod path (type . mode) dev → bool */
if (stringp(a) && pairp(b)) {
const char *path = (const char *)a + W;
mkdir(path);
return ITRUE;
}
return IFALSE;
case 25: /* lseek port offset whence → offset | #f */
if (is_type(a, TPORT)) {
off_t o = lseek(immval(a), cnum(b), cnum(c));
if (o != -1)
return onum(o, 1);
}
return IFALSE;
case 26:
not_implemented("termios", "no termios");
return IFALSE;
case 27: { /* sendmsg sock (port . ipv4) bvec */
int sock = immval(a);
int port;
struct sockaddr_in peer;
byte *ip, *data = (byte *)c + W;
size_t len = payl_len(header(c));
port = immval(G(b, 1));
ip = (byte *)G(b, 2) + W;
peer.sin_family = AF_INET;
peer.sin_port = htons(port);
peer.sin_addr.s_addr = htonl(ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]);
return BOOL(sendto(sock, (void*)data, len, 0, (struct sockaddr *)&peer, sizeof(peer)) != -1); }
case 28: /* setenv <owl-raw-bvec-or-ascii-leaf-string> <owl-raw-bvec-or-ascii-leaf-string-or-#f> */
if (stringp(a) && (b == IFALSE || stringp(b))) {
const char *name = (const char *)a + W;
return ((b != IFALSE ?
(SetEnvironmentVariable(name, (const char *)b + W) ? ITRUE : IFALSE)
: (SetEnvironmentVariable(name, "") ? ITRUE : IFALSE)));
} return IFALSE;
case 29:
return prim_connect((word *) a, b, c);
case 30: /* dup2 old-port new-fd → new-port | #f */
if (is_type(a, TPORT)) {
int fd = dup2(immval(a), immval(b));
if (fd != -1)
return make_immediate(fd, TPORT);
}
return IFALSE;
case 31: { /* pipe → '(read-port . write-port) | #f */
int fd[2];
CreatePipe((PHANDLE)&fd[0], (PHANDLE)&fd[1], NULL, 0);
return cons(make_immediate(fd[0], TPORT), make_immediate(fd[1], TPORT)); }
case 32: /* rename src dst → bool */
return BOOL(stringp(a) && stringp(b) && rename((char *)a + W, (char *)b + W) == 0);
case 33: /* link src dst → bool */
not_implemented("link", "balls");
return IFALSE;
/* return BOOL(stringp(a) && stringp(b) && link((char *)a + W, (char *)b + W) == 0); */
case 34: /* symlink src dst → bool */
not_implemented("symlink", "too alpha");
return IFALSE;
/* return BOOL(stringp(a) && stringp(b) && symlink((char *)a + W, (char *)b + W) == 0); */
case 35: /* readlink path → raw-sting | #false */
/* if (stringp(a)) { */
/* size_t len = memend - fp; */
/* size_t max = len > MAXOBJ ? MAXPAYL + 1 : (len - 1) * W; */
/* /\* the last byte is temporarily used to check, if the string fits *\/ */
/* len = readlink((const char *)a + W, (char *)fp + W, max); */
/* if (len != (size_t)-1 && len != max) */
/* return mkraw(TSTRING, len); */
/* } */
not_implemented("readlink", "i'm too lazy");
return IFALSE;
case 36: /* getcwd → raw-sting | #false */
{
size_t len = memend - fp;
size_t max = len > MAXOBJ ? MAXPAYL + 1 : (len - 1) * W;
/* the last byte is temporarily used for the terminating '\0' */
if (getcwd((char *)fp + W, max) != NULL)
return mkraw(TSTRING, strnlen((char *)fp + W, max - 1));
}
return IFALSE;
case 37: /* umask mask → mask */
return F(umask(immval(a)));
case 38: /* stat fd|path follow → list */
if (immediatep(a) || stringp(a)) {
struct stat st;
int fd;
if (b != IFALSE)
fd = _open((char*)a + W, O_BINARY, O_RDONLY);
else
fd = immval(a);
if (fstat(fd, &st) == 0) {
word lst = INULL;
lst = cons(onum(0, 1), lst);
lst = cons(onum(0, 1), lst);
lst = cons(onum(st.st_ctime, 1), lst);
lst = cons(onum(st.st_mtime, 1), lst);
lst = cons(onum(st.st_atime, 1), lst);
lst = cons(onum(st.st_size, 1), lst);
lst = cons(onum(st.st_rdev, 0), lst);
lst = cons(onum(st.st_gid, 0), lst);
lst = cons(onum(st.st_uid, 0), lst);
lst = cons(onum(st.st_nlink, 0), lst);
lst = cons(onum(st.st_mode, 0), lst);
lst = cons(onum(st.st_ino, 0), lst);
lst = cons(onum(st.st_dev, 1), lst);
if (b != IFALSE)
close(fd);
return lst;
}
}
return INULL;
case 39: /* chmod fd|path mode follow → bool */
/* if ((immediatep(a) || stringp(a)) && fixnump(b)) { */
/* mode_t mod = immval(b); */