Debian Codegraph @

terps/git/glkop.c

raw symbols SCIP
1 // $Id: glkop.c,v 1.4 2004/12/22 14:33:40 iain Exp $
2
3 // glkop.c: Glulxe code for Glk API dispatching.
4 // Designed by Andrew Plotkin <[email protected]>
5 // http://www.eblong.com/zarf/glulx/index.html
6
7 /* This code is actually very general; it could work for almost any
8 32-bit VM which remotely resembles Glulxe or the Z-machine in design.
9
10 To be precise, we make the following assumptions:
11
12 - An argument list is an array of 32-bit values, which can represent
13 either integers or addresses.
14 - We can read or write to a 32-bit integer in VM memory using the macros
15 ReadMemory(addr) and WriteMemory(addr), where addr is an address
16 taken from the argument list.
17 - A character array is a sequence of bytes somewhere in VM memory.
18 The array can be turned into a C char array by the macro
19 CaptureCArray(addr, len), and released by ReleaseCArray().
20 The passin, passout hints may be used to avoid unnecessary copying.
21 - An integer array is a sequence of integers somewhere in VM memory.
22 The array can be turned into a C integer array by the macro
23 CaptureIArray(addr, len), and released by ReleaseIArray().
24 These macros are responsible for fixing byte-order and alignment
25 (if the C ABI does not match the VM's). The passin, passout hints
26 may be used to avoid unnecessary copying.
27 - A Glk object array is a sequence of integers in VM memory. It is
28 turned into a C pointer array (remember that C pointers may be more
29 than 4 bytes!) The pointer array is allocated by
30 CapturePtrArray(addr, len, objclass) and released by ReleasePtrArray().
31 Again, the macros handle the conversion.
32 - A Glk structure (such as event_t) is a set of integers somewhere
33 in VM memory, which can be read and written with the macros
34 ReadStructField(addr, fieldnum) and WriteStructField(addr, fieldnum).
35 The fieldnum is an integer (from 0 to 3, for event_t.)
36 - A VM string can be turned into a C-style string with the macro
37 ptr = DecodeVMString(addr). After the string is used, this code
38 calls ReleaseVMString(ptr), which should free any memory that
39 DecodeVMString allocates.
40 - A VM Unicode string can be turned into a zero-terminated array
41 of 32-bit integers, in the same way, with DecodeVMUstring
42 and ReleaseVMUstring.
43
44 To work this code over for a new VM, just diddle the macros.
45 */
46
47 #define Stk1(sp) \
48 (*((unsigned char *)(sp)))
49 #define Stk2(sp) \
50 (*((glui16 *)(sp)))
51 #define Stk4(sp) \
52 (*((glui32 *)(sp)))
53
54 #define StkW1(sp, vl) \
55 (*((unsigned char *)(sp)) = (unsigned char)(vl))
56 #define StkW2(sp, vl) \
57 (*((glui16 *)(sp)) = (glui16)(vl))
58 #define StkW4(sp, vl) \
59 (*((glui32 *)(sp)) = (glui32)(vl))
60
61
62 #define ReadMemory(addr) \
63 (((addr) == 0xffffffff) \
64 ? (gStackPointer -= 1, Stk4(gStackPointer)) \
65 : (memRead32(addr)))
66 #define WriteMemory(addr, val) \
67 do { \
68 if ((addr) == 0xffffffff) { \
69 StkW4(gStackPointer, (val)); \
70 gStackPointer += 1; \
71 } else { \
72 memWrite32((addr), (val)); \
73 } \
74 } while (0)
75 #define CaptureCArray(addr, len, passin) \
76 (grab_temp_c_array(addr, len, passin))
77 #define ReleaseCArray(ptr, addr, len, passout) \
78 (release_temp_c_array(ptr, addr, len, passout))
79 #define CaptureIArray(addr, len, passin) \
80 (grab_temp_i_array(addr, len, passin))
81 #define ReleaseIArray(ptr, addr, len, passout) \
82 (release_temp_i_array(ptr, addr, len, passout))
83 #define CapturePtrArray(addr, len, objclass, passin) \
84 (grab_temp_ptr_array(addr, len, objclass, passin))
85 #define ReleasePtrArray(ptr, addr, len, objclass, passout) \
86 (release_temp_ptr_array(ptr, addr, len, objclass, passout))
87 #define ReadStructField(addr, fieldnum) \
88 (((addr) == 0xffffffff) \
89 ? (gStackPointer -= 1, Stk4(gStackPointer)) \
90 : (memRead32((addr)+(fieldnum)*4)))
91 #define WriteStructField(addr, fieldnum, val) \
92 do { \
93 if ((addr) == 0xffffffff) { \
94 StkW4(gStackPointer, (val)); \
95 gStackPointer += 1; \
96 } else { \
97 memWrite32((addr)+(fieldnum)*4, (val)); \
98 } \
99 } while (0)
100
101 #define glulx_malloc malloc
102 #define glulx_free free
103
104 #ifndef TRUE
105 #define TRUE 1
106 #endif
107 #ifndef FALSE
108 #define FALSE 0
109 #endif
110
111 #include <time.h>
112 #include "glk.h"
113 #include "git.h"
114 #include "gi_dispa.h"
115
116 static char * DecodeVMString (git_uint32 addr)
117 {
118 glui32 end;
119 char * data;
120 char * c;
121
122 // The string must be a C string.
123 if (memRead8(addr) != 0xE0)
124 {
125 fatalError ("Illegal string type passed to Glk function");
126 }
127 addr += 1;
128
129 end = addr;
130 while (memRead8(end) != 0)
131 ++end;
132
133 data = glulx_malloc (end - addr + 1);
134 if (data == NULL)
135 fatalError ("Couldn't allocate string");
136
137 c = data;
138 while (addr < end)
139 *c++ = memRead8(addr++);
140 *c = 0;
141
142 return data;
143 }
144
145 static glui32 * DecodeVMUstring (git_uint32 addr)
146 {
147 glui32 end;
148 glui32 * data;
149 glui32 * c;
150
151 // The string must be a Unicode string.
152 if (memRead8(addr) != 0xE2)
153 {
154 fatalError ("Illegal string type passed to Glk function");
155 }
156 addr += 4;
157
158 end = addr;
159 while (memRead32(end) != 0)
160 end += 4;
161
162 data = glulx_malloc (end - addr + 4);
163 if (data == NULL)
164 fatalError ("Couldn't allocate string");
165
166 c = data;
167 while (addr < end)
168 {
169 *c++ = memRead32(addr);
170 addr += 4;
171 }
172 *c = 0;
173
174 return data;
175 }
176
177 static void ReleaseVMString (char * ptr)
178 {
179 glulx_free (ptr);
180 }
181
182 static void ReleaseVMUstring (glui32 * ptr)
183 {
184 glulx_free (ptr);
185 }
186
187 typedef struct dispatch_splot_struct {
188 int numwanted;
189 int maxargs;
190 gluniversal_t *garglist;
191 glui32 *varglist;
192 int numvargs;
193 glui32 *retval;
194 } dispatch_splot_t;
195
196 /* We maintain a linked list of arrays being used for Glk calls. It is
197 only used for integer (glui32) arrays -- char arrays are handled in
198 place. It's not worth bothering with a hash table, since most
199 arrays appear here only momentarily. */
200
201 typedef struct arrayref_struct arrayref_t;
202 struct arrayref_struct {
203 void *array;
204 glui32 addr;
205 glui32 elemsize;
206 glui32 len; /* elements */
207 int retained;
208 arrayref_t *next;
209 };
210
211 static arrayref_t *arrays = NULL;
212
213 /* We maintain a hash table for each opaque Glk class. classref_t are the
214 nodes of the table, and classtable_t are the tables themselves. */
215
216 typedef struct classref_struct classref_t;
217 struct classref_struct {
218 void *obj;
219 glui32 id;
220 int bucknum;
221 classref_t *next;
222 };
223
224 #define CLASSHASH_SIZE (31)
225 typedef struct classtable_struct {
226 glui32 lastid;
227 classref_t *bucket[CLASSHASH_SIZE];
228 } classtable_t;
229
230 /* The list of hash tables, for the git_classes. */
231 static int num_classes = 0;
232 classtable_t **git_classes = NULL;
233
234 static classtable_t *new_classtable(glui32 firstid);
235 static void *classes_get(int classid, glui32 objid);
236 static classref_t *classes_put(int classid, void *obj, glui32 origid);
237 static void classes_remove(int classid, void *obj);
238
239 static gidispatch_rock_t glulxe_classtable_register(void *obj,
240 glui32 objclass);
241 static void glulxe_classtable_unregister(void *obj, glui32 objclass,
242 gidispatch_rock_t objrock);
243 static gidispatch_rock_t glulxe_retained_register(void *array,
244 glui32 len, char *typecode);
245 static void glulxe_retained_unregister(void *array, glui32 len,
246 char *typecode, gidispatch_rock_t objrock);
247
248 /* The library_select_hook is called every time the VM blocks for input.
249 The app might take this opportunity to autosave, for example. */
250 static void (*library_select_hook)(glui32) = NULL;
251
252 static char *grab_temp_c_array(glui32 addr, glui32 len, int passin);
253 static void release_temp_c_array(char *arr, glui32 addr, glui32 len, int passout);
254 static glui32 *grab_temp_i_array(glui32 addr, glui32 len, int passin);
255 static void release_temp_i_array(glui32 *arr, glui32 addr, glui32 len, int passout);
256 static void **grab_temp_ptr_array(glui32 addr, glui32 len, int objclass, int passin);
257 static void release_temp_ptr_array(void **arr, glui32 addr, glui32 len, int objclass, int passout);
258
259 static void prepare_glk_args(char *proto, dispatch_splot_t *splot);
260 static void parse_glk_args(dispatch_splot_t *splot, char **proto, int depth,
261 int *argnumptr, glui32 subaddress, int subpassin);
262 static void unparse_glk_args(dispatch_splot_t *splot, char **proto, int depth,
263 int *argnumptr, glui32 subaddress, int subpassout);
264
265 static maybe_unused char *get_game_id(void);
266
267 /* git_init_dispatch():
268 Set up the class hash tables and other startup-time stuff.
269 */
270 int git_init_dispatch()
271 {
272 int ix;
273 int randish;
274
275 /* What with one thing and another, this *could* be called more than
276 once. We only need to allocate the tables once. */
277 if (git_classes)
278 return TRUE;
279
280 /* Set up the game-ID hook. (This is ifdeffed because not all Glk
281 libraries have this call.) */
282 #ifdef GI_DISPA_GAME_ID_AVAILABLE
283 gidispatch_set_game_id_hook(&get_game_id);
284 #endif /* GI_DISPA_GAME_ID_AVAILABLE */
285
286 /* Allocate the class hash tables. */
287 num_classes = gidispatch_count_classes();
288 git_classes = (classtable_t **)glulx_malloc(num_classes
289 * sizeof(classtable_t *));
290 if (!git_classes)
291 return FALSE;
292
293 randish = time(NULL) % 101;
294 for (ix=0; ix<num_classes; ix++) {
295 git_classes[ix] = new_classtable(1+120*ix+randish);
296 if (!git_classes[ix])
297 return FALSE;
298 }
299
300 /* Set up the two callbacks. */
301 gidispatch_set_object_registry(&glulxe_classtable_register,
302 &glulxe_classtable_unregister);
303 gidispatch_set_retained_registry(&glulxe_retained_register,
304 &glulxe_retained_unregister);
305
306 return TRUE;
307 }
308
309 /* git_perform_glk():
310 Turn a list of Glulx arguments into a list of Glk arguments,
311 dispatch the function call, and return the result.
312 */
313 glui32 git_perform_glk(glui32 funcnum, glui32 numargs, glui32 *arglist)
314 {
315 glui32 retval = 0;
316
317 switch (funcnum) {
318 /* To speed life up, we implement commonly-used Glk functions
319 directly -- instead of bothering with the whole prototype
320 mess. */
321
322 case 0x0047: /* stream_set_current */
323 if (numargs != 1)
324 goto WrongArgNum;
325 glk_stream_set_current(git_find_stream_by_id(arglist[0]));
326 break;
327 case 0x0048: /* stream_get_current */
328 if (numargs != 0)
329 goto WrongArgNum;
330 retval = git_find_id_for_stream(glk_stream_get_current());
331 break;
332 case 0x0080: /* put_char */
333 if (numargs != 1)
334 goto WrongArgNum;
335 glk_put_char(arglist[0] & 0xFF);
336 break;
337 case 0x0081: /* put_char_stream */
338 if (numargs != 2)
339 goto WrongArgNum;
340 glk_put_char_stream(git_find_stream_by_id(arglist[0]), arglist[1] & 0xFF);
341 break;
342 case 0x00C0: /* select */
343 /* call a library hook on every glk_select() */
344 if (library_select_hook)
345 library_select_hook(arglist[0]);
346 /* but then fall through to full dispatcher, because there's no real
347 need for speed here */
348 goto FullDispatcher;
349 case 0x00A0: /* char_to_lower */
350 if (numargs != 1)
351 goto WrongArgNum;
352 retval = glk_char_to_lower(arglist[0] & 0xFF);
353 break;
354 case 0x00A1: /* char_to_upper */
355 if (numargs != 1)
356 goto WrongArgNum;
357 retval = glk_char_to_upper(arglist[0] & 0xFF);
358 break;
359 case 0x0128: /* put_char_uni */
360 if (numargs != 1)
361 goto WrongArgNum;
362 glk_put_char_uni(arglist[0]);
363 break;
364 case 0x012B: /* put_char_stream_uni */
365 if (numargs != 2)
366 goto WrongArgNum;
367 glk_put_char_stream_uni(git_find_stream_by_id(arglist[0]), arglist[1]);
368 break;
369
370 WrongArgNum:
371 fatalError("Wrong number of arguments to Glk function.");
372 break;
373
374 FullDispatcher:
375 default: {
376 /* Go through the full dispatcher prototype foo. */
377 char *proto, *cx;
378 dispatch_splot_t splot;
379 int argnum, argnum2;
380
381 /* Grab the string. */
382 proto = gidispatch_prototype(funcnum);
383 if (!proto)
384 fatalError("Unknown Glk function.");
385
386 splot.varglist = arglist;
387 splot.numvargs = numargs;
388 splot.retval = &retval;
389
390 /* The work goes in four phases. First, we figure out how many
391 arguments we want, and allocate space for the Glk argument
392 list. Then we go through the Glulxe arguments and load them
393 into the Glk list. Then we call. Then we go through the
394 arguments again, unloading the data back into Glulx memory. */
395
396 /* Phase 0. */
397 prepare_glk_args(proto, &splot);
398
399 /* Phase 1. */
400 argnum = 0;
401 cx = proto;
402 parse_glk_args(&splot, &cx, 0, &argnum, 0, 0);
403
404 /* Phase 2. */
405 gidispatch_call(funcnum, argnum, splot.garglist);
406
407 /* Phase 3. */
408 argnum2 = 0;
409 cx = proto;
410 unparse_glk_args(&splot, &cx, 0, &argnum2, 0, 0);
411 if (argnum != argnum2)
412 fatalError("Argument counts did not match.");
413
414 break;
415 }
416 }
417
418 return retval;
419 }
420
421 /* read_prefix():
422 Read the prefixes of an argument string -- the "<>&+:#!" chars.
423 */
424 static char *read_prefix(char *cx, int *isref, int *isarray,
425 int *passin, int *passout, int *nullok, int *isretained,
426 int *isreturn)
427 {
428 *isref = FALSE;
429 *passin = FALSE;
430 *passout = FALSE;
431 *nullok = TRUE;
432 *isarray = FALSE;
433 *isretained = FALSE;
434 *isreturn = FALSE;
435 while (1) {
436 if (*cx == '<') {
437 *isref = TRUE;
438 *passout = TRUE;
439 }
440 else if (*cx == '>') {
441 *isref = TRUE;
442 *passin = TRUE;
443 }
444 else if (*cx == '&') {
445 *isref = TRUE;
446 *passout = TRUE;
447 *passin = TRUE;
448 }
449 else if (*cx == '+') {
450 *nullok = FALSE;
451 }
452 else if (*cx == ':') {
453 *isref = TRUE;
454 *passout = TRUE;
455 *nullok = FALSE;
456 *isreturn = TRUE;
457 }
458 else if (*cx == '#') {
459 *isarray = TRUE;
460 }
461 else if (*cx == '!') {
462 *isretained = TRUE;
463 }
464 else {
465 break;
466 }
467 cx++;
468 }
469 return cx;
470 }
471
472 /* prepare_glk_args():
473 This reads through the prototype string, and pulls Floo objects off the
474 stack. It also works out the maximal number of gluniversal_t objects
475 which could be used by the Glk call in question. It then allocates
476 space for them.
477 */
478 static void prepare_glk_args(char *proto, dispatch_splot_t *splot)
479 {
480 static gluniversal_t *garglist = NULL;
481 static int garglist_size = 0;
482
483 int ix;
484 int numwanted, numvargswanted, maxargs;
485 char *cx;
486
487 cx = proto;
488 numwanted = 0;
489 while (*cx >= '0' && *cx <= '9') {
490 numwanted = 10 * numwanted + (*cx - '0');
491 cx++;
492 }
493 splot->numwanted = numwanted;
494
495 maxargs = 0;
496 numvargswanted = 0;
497 for (ix = 0; ix < numwanted; ix++) {
498 int isref, passin, passout, nullok, isarray, isretained, isreturn;
499 cx = read_prefix(cx, &isref, &isarray, &passin, &passout, &nullok,
500 &isretained, &isreturn);
501 if (isref) {
502 maxargs += 2;
503 }
504 else {
505 maxargs += 1;
506 }
507 if (!isreturn) {
508 if (isarray) {
509 numvargswanted += 2;
510 }
511 else {
512 numvargswanted += 1;
513 }
514 }
515
516 if (*cx == 'I' || *cx == 'C') {
517 cx += 2;
518 }
519 else if (*cx == 'Q') {
520 cx += 2;
521 }
522 else if (*cx == 'S' || *cx == 'U') {
523 cx += 1;
524 }
525 else if (*cx == '[') {
526 int refdepth, nwx;
527 cx++;
528 nwx = 0;
529 while (*cx >= '0' && *cx <= '9') {
530 nwx = 10 * nwx + (*cx - '0');
531 cx++;
532 }
533 maxargs += nwx; /* This is *only* correct because all structs contain
534 plain values. */
535 refdepth = 1;
536 while (refdepth > 0) {
537 if (*cx == '[')
538 refdepth++;
539 else if (*cx == ']')
540 refdepth--;
541 cx++;
542 }
543 }
544 else {
545 fatalError("Illegal format string.");
546 }
547 }
548
549 if (*cx != ':' && *cx != '\0')
550 fatalError("Illegal format string.");
551
552 splot->maxargs = maxargs;
553
554 if (splot->numvargs != numvargswanted)
555 fatalError("Wrong number of arguments to Glk function.");
556
557 if (garglist && garglist_size < maxargs) {
558 glulx_free(garglist);
559 garglist = NULL;
560 garglist_size = 0;
561 }
562 if (!garglist) {
563 garglist_size = maxargs + 16;
564 garglist = (gluniversal_t *)glulx_malloc(garglist_size
565 * sizeof(gluniversal_t));
566 }
567 if (!garglist)
568 fatalError("Unable to allocate storage for Glk arguments.");
569
570 splot->garglist = garglist;
571 }
572
573 /* parse_glk_args():
574 This long and unpleasant function translates a set of Floo objects into
575 a gluniversal_t array. It's recursive, too, to deal with structures.
576 */
577 static void parse_glk_args(dispatch_splot_t *splot, char **proto, int depth,
578 int *argnumptr, glui32 subaddress, int subpassin)
579 {
580 char *cx;
581 int ix, argx;
582 int gargnum, numwanted;
583 void *opref;
584 gluniversal_t *garglist;
585 glui32 *varglist;
586
587 garglist = splot->garglist;
588 varglist = splot->varglist;
589 gargnum = *argnumptr;
590 cx = *proto;
591
592 numwanted = 0;
593 while (*cx >= '0' && *cx <= '9') {
594 numwanted = 10 * numwanted + (*cx - '0');
595 cx++;
596 }
597
598 for (argx = 0, ix = 0; argx < numwanted; argx++, ix++) {
599 char typeclass;
600 int skipval;
601 int isref, passin, passout, nullok, isarray, isretained, isreturn;
602 cx = read_prefix(cx, &isref, &isarray, &passin, &passout, &nullok,
603 &isretained, &isreturn);
604
605 typeclass = *cx;
606 cx++;
607
608 skipval = FALSE;
609 if (isref) {
610 if (!isreturn && varglist[ix] == 0) {
611 if (!nullok)
612 fatalError("Zero passed invalidly to Glk function.");
613 garglist[gargnum].ptrflag = FALSE;
614 gargnum++;
615 skipval = TRUE;
616 }
617 else {
618 garglist[gargnum].ptrflag = TRUE;
619 gargnum++;
620 }
621 }
622 if (!skipval) {
623 glui32 thisval;
624
625 if (typeclass == '[') {
626
627 parse_glk_args(splot, &cx, depth+1, &gargnum, varglist[ix], passin);
628
629 }
630 else if (isarray) {
631 /* definitely isref */
632
633 switch (typeclass) {
634 case 'C':
635 /* This test checks for a giant array length, and cuts it down to
636 something reasonable. Future releases of this interpreter may
637 treat this case as a fatal error. */
638 if (varglist[ix+1] > gEndMem || varglist[ix]+varglist[ix+1] > gEndMem)
639 varglist[ix+1] = gEndMem - varglist[ix];
640
641 garglist[gargnum].array = (void*) CaptureCArray(varglist[ix], varglist[ix+1], passin);
642 gargnum++;
643 ix++;
644 garglist[gargnum].uint = varglist[ix];
645 gargnum++;
646 cx++;
647 break;
648 case 'I':
649 /* See comment above. */
650 if (varglist[ix+1] > gEndMem/4 || varglist[ix+1] > (gEndMem-varglist[ix])/4)
651 varglist[ix+1] = (gEndMem - varglist[ix]) / 4;
652
653 garglist[gargnum].array = CaptureIArray(varglist[ix], varglist[ix+1], passin);
654 gargnum++;
655 ix++;
656 garglist[gargnum].uint = varglist[ix];
657 gargnum++;
658 cx++;
659 break;
660 case 'Q':
661 garglist[gargnum].array = CapturePtrArray(varglist[ix], varglist[ix+1], (*cx-'a'), passin);
662 gargnum++;
663 ix++;
664 garglist[gargnum].uint = varglist[ix];
665 gargnum++;
666 cx++;
667 break;
668 default:
669 fatalError("Illegal format string.");
670 break;
671 }
672 }
673 else {
674 /* a plain value or a reference to one. */
675
676 if (isreturn) {
677 thisval = 0;
678 }
679 else if (depth > 0) {
680 /* Definitely not isref or isarray. */
681 if (subpassin)
682 thisval = ReadStructField(subaddress, ix);
683 else
684 thisval = 0;
685 }
686 else if (isref) {
687 if (passin)
688 thisval = ReadMemory(varglist[ix]);
689 else
690 thisval = 0;
691 }
692 else {
693 thisval = varglist[ix];
694 }
695
696 switch (typeclass) {
697 case 'I':
698 if (*cx == 'u')
699 garglist[gargnum].uint = (glui32)(thisval);
700 else if (*cx == 's')
701 garglist[gargnum].sint = (glsi32)(thisval);
702 else
703 fatalError("Illegal format string.");
704 gargnum++;
705 cx++;
706 break;
707 case 'Q':
708 if (thisval) {
709 opref = classes_get(*cx-'a', thisval);
710 if (!opref) {
711 fatalError("Reference to nonexistent Glk object.");
712 }
713 }
714 else {
715 opref = NULL;
716 }
717 garglist[gargnum].opaqueref = opref;
718 gargnum++;
719 cx++;
720 break;
721 case 'C':
722 if (*cx == 'u')
723 garglist[gargnum].uch = (unsigned char)(thisval);
724 else if (*cx == 's')
725 garglist[gargnum].sch = (signed char)(thisval);
726 else if (*cx == 'n')
727 garglist[gargnum].ch = (char)(thisval);
728 else
729 fatalError("Illegal format string.");
730 gargnum++;
731 cx++;
732 break;
733 case 'S':
734 garglist[gargnum].charstr = DecodeVMString(thisval);
735 gargnum++;
736 break;
737 #ifdef GLK_MODULE_UNICODE
738 case 'U':
739 garglist[gargnum].unicharstr = DecodeVMUstring(thisval);
740 gargnum++;
741 break;
742 #endif /* GLK_MODULE_UNICODE */
743 default:
744 fatalError("Illegal format string.");
745 break;
746 }
747 }
748 }
749 else {
750 /* We got a null reference, so we have to skip the format element. */
751 if (typeclass == '[') {
752 int numsubwanted, refdepth;
753 numsubwanted = 0;
754 while (*cx >= '0' && *cx <= '9') {
755 numsubwanted = 10 * numsubwanted + (*cx - '0');
756 cx++;
757 }
758 refdepth = 1;
759 while (refdepth > 0) {
760 if (*cx == '[')
761 refdepth++;
762 else if (*cx == ']')
763 refdepth--;
764 cx++;
765 }
766 }
767 else if (typeclass == 'S' || typeclass == 'U') {
768 /* leave it */
769 }
770 else {
771 cx++;
772 if (isarray)
773 ix++;
774 }
775 }
776 }
777
778 if (depth > 0) {
779 if (*cx != ']')
780 fatalError("Illegal format string.");
781 cx++;
782 }
783 else {
784 if (*cx != ':' && *cx != '\0')
785 fatalError("Illegal format string.");
786 }
787
788 *proto = cx;
789 *argnumptr = gargnum;
790 }
791
792 /* unparse_glk_args():
793 This is about the reverse of parse_glk_args().
794 */
795 static void unparse_glk_args(dispatch_splot_t *splot, char **proto, int depth,
796 int *argnumptr, glui32 subaddress, int subpassout)
797 {
798 char *cx;
799 int ix, argx;
800 int gargnum, numwanted;
801 void *opref;
802 gluniversal_t *garglist;
803 glui32 *varglist;
804
805 garglist = splot->garglist;
806 varglist = splot->varglist;
807 gargnum = *argnumptr;
808 cx = *proto;
809
810 numwanted = 0;
811 while (*cx >= '0' && *cx <= '9') {
812 numwanted = 10 * numwanted + (*cx - '0');
813 cx++;
814 }
815
816 for (argx = 0, ix = 0; argx < numwanted; argx++, ix++) {
817 char typeclass;
818 int skipval;
819 int isref, passin, passout, nullok, isarray, isretained, isreturn;
820 cx = read_prefix(cx, &isref, &isarray, &passin, &passout, &nullok,
821 &isretained, &isreturn);
822
823 typeclass = *cx;
824 cx++;
825
826 skipval = FALSE;
827 if (isref) {
828 if (!isreturn && varglist[ix] == 0) {
829 if (!nullok)
830 fatalError("Zero passed invalidly to Glk function.");
831 garglist[gargnum].ptrflag = FALSE;
832 gargnum++;
833 skipval = TRUE;
834 }
835 else {
836 garglist[gargnum].ptrflag = TRUE;
837 gargnum++;
838 }
839 }
840 if (!skipval) {
841 glui32 thisval = 0;
842
843 if (typeclass == '[') {
844
845 unparse_glk_args(splot, &cx, depth+1, &gargnum, varglist[ix], passout);
846
847 }
848 else if (isarray) {
849 /* definitely isref */
850
851 switch (typeclass) {
852 case 'C':
853 ReleaseCArray(garglist[gargnum].array, varglist[ix], varglist[ix+1], passout);
854 gargnum++;
855 ix++;
856 gargnum++;
857 cx++;
858 break;
859 case 'I':
860 ReleaseIArray(garglist[gargnum].array, varglist[ix], varglist[ix+1], passout);
861 gargnum++;
862 ix++;
863 gargnum++;
864 cx++;
865 break;
866 case 'Q':
867 ReleasePtrArray(garglist[gargnum].array, varglist[ix], varglist[ix+1], (*cx-'a'), passout);
868 gargnum++;
869 ix++;
870 gargnum++;
871 cx++;
872 break;
873 default:
874 fatalError("Illegal format string.");
875 break;
876 }
877 }
878 else {
879 /* a plain value or a reference to one. */
880
881 if (isreturn || (depth > 0 && subpassout) || (isref && passout)) {
882 skipval = FALSE;
883 }
884 else {
885 skipval = TRUE;
886 }
887
888 switch (typeclass) {
889 case 'I':
890 if (!skipval) {
891 if (*cx == 'u')
892 thisval = (glui32)garglist[gargnum].uint;
893 else if (*cx == 's')
894 thisval = (glui32)garglist[gargnum].sint;
895 else
896 fatalError("Illegal format string.");
897 }
898 gargnum++;
899 cx++;
900 break;
901 case 'Q':
902 if (!skipval) {
903 opref = garglist[gargnum].opaqueref;
904 if (opref) {
905 gidispatch_rock_t objrock =
906 gidispatch_get_objrock(opref, *cx-'a');
907 thisval = ((classref_t *)objrock.ptr)->id;
908 }
909 else {
910 thisval = 0;
911 }
912 }
913 gargnum++;
914 cx++;
915 break;
916 case 'C':
917 if (!skipval) {
918 if (*cx == 'u')
919 thisval = (glui32)garglist[gargnum].uch;
920 else if (*cx == 's')
921 thisval = (glui32)garglist[gargnum].sch;
922 else if (*cx == 'n')
923 thisval = (glui32)garglist[gargnum].ch;
924 else
925 fatalError("Illegal format string.");
926 }
927 gargnum++;
928 cx++;
929 break;
930 case 'S':
931 if (garglist[gargnum].charstr)
932 ReleaseVMString(garglist[gargnum].charstr);
933 gargnum++;
934 break;
935 #ifdef GLK_MODULE_UNICODE
936 case 'U':
937 if (garglist[gargnum].unicharstr)
938 ReleaseVMUstring(garglist[gargnum].unicharstr);
939 gargnum++;
940 break;
941 #endif /* GLK_MODULE_UNICODE */
942 default:
943 fatalError("Illegal format string.");
944 break;
945 }
946
947 if (isreturn) {
948 *(splot->retval) = thisval;
949 }
950 else if (depth > 0) {
951 /* Definitely not isref or isarray. */
952 if (subpassout)
953 WriteStructField(subaddress, ix, thisval);
954 }
955 else if (isref) {
956 if (passout)
957 WriteMemory(varglist[ix], thisval);
958 }
959 }
960 }
961 else {
962 /* We got a null reference, so we have to skip the format element. */
963 if (typeclass == '[') {
964 int numsubwanted, refdepth;
965 numsubwanted = 0;
966 while (*cx >= '0' && *cx <= '9') {
967 numsubwanted = 10 * numsubwanted + (*cx - '0');
968 cx++;
969 }
970 refdepth = 1;
971 while (refdepth > 0) {
972 if (*cx == '[')
973 refdepth++;
974 else if (*cx == ']')
975 refdepth--;
976 cx++;
977 }
978 }
979 else if (typeclass == 'S' || typeclass == 'U') {
980 /* leave it */
981 }
982 else {
983 cx++;
984 if (isarray)
985 ix++;
986 }
987 }
988 }
989
990 if (depth > 0) {
991 if (*cx != ']')
992 fatalError("Illegal format string.");
993 cx++;
994 }
995 else {
996 if (*cx != ':' && *cx != '\0')
997 fatalError("Illegal format string.");
998 }
999
1000 *proto = cx;
1001 *argnumptr = gargnum;
1002 }
1003
1004 /* git_find_stream_by_id():
1005 This is used by some interpreter code which has to, well, find a Glk
1006 stream given its ID.
1007 */
1008 strid_t git_find_stream_by_id(glui32 objid)
1009 {
1010 if (!objid)
1011 return NULL;
1012
1013 /* Recall that class 1 ("b") is streams. */
1014 return classes_get(gidisp_Class_Stream, objid);
1015 }
1016
1017 /* git_find_id_for_window():
1018 Return the ID of a given Glk window.
1019 */
1020 glui32 git_find_id_for_window(winid_t win)
1021 {
1022 gidispatch_rock_t objrock;
1023
1024 if (!win)
1025 return 0;
1026
1027 objrock = gidispatch_get_objrock(win, gidisp_Class_Window);
1028 return ((classref_t *)objrock.ptr)->id;
1029 }
1030
1031 /* git_find_id_for_stream():
1032 Return the ID of a given Glk stream.
1033 */
1034 glui32 git_find_id_for_stream(strid_t str)
1035 {
1036 gidispatch_rock_t objrock;
1037
1038 if (!str)
1039 return 0;
1040
1041 objrock = gidispatch_get_objrock(str, gidisp_Class_Stream);
1042 return ((classref_t *)objrock.ptr)->id;
1043 }
1044
1045 /* git_find_id_for_fileref():
1046 Return the ID of a given Glk fileref.
1047 */
1048 glui32 git_find_id_for_fileref(frefid_t fref)
1049 {
1050 gidispatch_rock_t objrock;
1051
1052 if (!fref)
1053 return 0;
1054
1055 objrock = gidispatch_get_objrock(fref, gidisp_Class_Fileref);
1056 return ((classref_t *)objrock.ptr)->id;
1057 }
1058
1059 /* git_find_id_for_schannel():
1060 Return the ID of a given Glk schannel.
1061 */
1062 glui32 git_find_id_for_schannel(schanid_t schan)
1063 {
1064 gidispatch_rock_t objrock;
1065
1066 if (!schan)
1067 return 0;
1068
1069 objrock = gidispatch_get_objrock(schan, gidisp_Class_Schannel);
1070 return ((classref_t *)objrock.ptr)->id;
1071 }
1072
1073 /* Build a hash table to hold a set of Glk objects. */
1074 static classtable_t *new_classtable(glui32 firstid)
1075 {
1076 int ix;
1077 classtable_t *ctab = (classtable_t *)glulx_malloc(sizeof(classtable_t));
1078 if (!ctab)
1079 return NULL;
1080
1081 for (ix=0; ix<CLASSHASH_SIZE; ix++)
1082 ctab->bucket[ix] = NULL;
1083
1084 ctab->lastid = firstid;
1085
1086 return ctab;
1087 }
1088
1089 /* Find a Glk object in the appropriate hash table. */
1090 static void *classes_get(int classid, glui32 objid)
1091 {
1092 classtable_t *ctab;
1093 classref_t *cref;
1094 if (classid < 0 || classid >= num_classes)
1095 return NULL;
1096 ctab = git_classes[classid];
1097 cref = ctab->bucket[objid % CLASSHASH_SIZE];
1098 for (; cref; cref = cref->next) {
1099 if (cref->id == objid)
1100 return cref->obj;
1101 }
1102 return NULL;
1103 }
1104
1105 /* Put a Glk object in the appropriate hash table. If origid is zero,
1106 invent a new unique ID for it. */
1107 static classref_t *classes_put(int classid, void *obj, glui32 origid)
1108 {
1109 int bucknum;
1110 classtable_t *ctab;
1111 classref_t *cref;
1112 if (classid < 0 || classid >= num_classes)
1113 return NULL;
1114 ctab = git_classes[classid];
1115 cref = (classref_t *)glulx_malloc(sizeof(classref_t));
1116 if (!cref)
1117 return NULL;
1118 cref->obj = obj;
1119 if (!origid) {
1120 cref->id = ctab->lastid;
1121 ctab->lastid++;
1122 }
1123 else {
1124 cref->id = origid;
1125 if (ctab->lastid <= origid)
1126 ctab->lastid = origid+1;
1127 }
1128 bucknum = cref->id % CLASSHASH_SIZE;
1129 cref->bucknum = bucknum;
1130 cref->next = ctab->bucket[bucknum];
1131 ctab->bucket[bucknum] = cref;
1132 return cref;
1133 }
1134
1135 /* Delete a Glk object from the appropriate hash table. */
1136 static void classes_remove(int classid, void *obj)
1137 {
1138 classtable_t *ctab;
1139 classref_t *cref;
1140 classref_t **crefp;
1141 gidispatch_rock_t objrock;
1142 if (classid < 0 || classid >= num_classes)
1143 return;
1144 ctab = git_classes[classid];
1145 objrock = gidispatch_get_objrock(obj, classid);
1146 cref = objrock.ptr;
1147 if (!cref)
1148 return;
1149 crefp = &(ctab->bucket[cref->bucknum]);
1150 for (; *crefp; crefp = &((*crefp)->next)) {
1151 if ((*crefp) == cref) {
1152 *crefp = cref->next;
1153 cref->obj = NULL;
1154 cref->id = 0;
1155 cref->next = NULL;
1156 glulx_free(cref);
1157 return;
1158 }
1159 }
1160 return;
1161 }
1162
1163 /* The object registration/unregistration callbacks that the library calls
1164 to keep the hash tables up to date. */
1165
1166 static gidispatch_rock_t glulxe_classtable_register(void *obj,
1167 glui32 objclass)
1168 {
1169 classref_t *cref;
1170 gidispatch_rock_t objrock;
1171 cref = classes_put(objclass, obj, 0);
1172 objrock.ptr = cref;
1173 return objrock;
1174 }
1175
1176 static void glulxe_classtable_unregister(void *obj, glui32 objclass,
1177 gidispatch_rock_t objrock)
1178 {
1179 classes_remove(objclass, obj);
1180 }
1181
1182 static char *grab_temp_c_array(glui32 addr, glui32 len, int passin)
1183 {
1184 arrayref_t *arref = NULL;
1185 char *arr = NULL;
1186 glui32 ix, addr2;
1187
1188 if (len) {
1189 arr = (char *)glulx_malloc(len * sizeof(char));
1190 arref = (arrayref_t *)glulx_malloc(sizeof(arrayref_t));
1191 if (!arr || !arref)
1192 fatalError("Unable to allocate space for array argument to Glk call.");
1193
1194 arref->array = arr;
1195 arref->addr = addr;
1196 arref->elemsize = 1;
1197 arref->retained = FALSE;
1198 arref->len = len;
1199 arref->next = arrays;
1200 arrays = arref;
1201
1202 if (passin) {
1203 for (ix=0, addr2=addr; ix<len; ix++, addr2+=1) {
1204 arr[ix] = memRead8(addr2);
1205 }
1206 }
1207 }
1208
1209 return arr;
1210 }
1211
1212 static void release_temp_c_array(char *arr, glui32 addr, glui32 len, int passout)
1213 {
1214 arrayref_t *arref = NULL;
1215 arrayref_t **aptr;
1216 glui32 ix, val, addr2;
1217
1218 if (arr) {
1219 for (aptr=(&arrays); (*aptr); aptr=(&((*aptr)->next))) {
1220 if ((*aptr)->array == arr)
1221 break;
1222 }
1223 arref = *aptr;
1224 if (!arref)
1225 fatalError("Unable to re-find array argument in Glk call.");
1226 if (arref->addr != addr || arref->len != len)
1227 fatalError("Mismatched array argument in Glk call.");
1228
1229 if (arref->retained) {
1230 return;
1231 }
1232
1233 *aptr = arref->next;
1234 arref->next = NULL;
1235
1236 if (passout) {
1237 for (ix=0, addr2=addr; ix<len; ix++, addr2+=1) {
1238 val = arr[ix];
1239 memWrite8(addr2, val);
1240 }
1241 }
1242 glulx_free(arr);
1243 glulx_free(arref);
1244 }
1245 }
1246
1247 static glui32 *grab_temp_i_array(glui32 addr, glui32 len, int passin)
1248 {
1249 arrayref_t *arref = NULL;
1250 glui32 *arr = NULL;
1251 glui32 ix, addr2;
1252
1253 if (len) {
1254 arr = (glui32 *)glulx_malloc(len * sizeof(glui32));
1255 arref = (arrayref_t *)glulx_malloc(sizeof(arrayref_t));
1256 if (!arr || !arref)
1257 fatalError("Unable to allocate space for array argument to Glk call.");
1258
1259 arref->array = arr;
1260 arref->addr = addr;
1261 arref->elemsize = 4;
1262 arref->retained = FALSE;
1263 arref->len = len;
1264 arref->next = arrays;
1265 arrays = arref;
1266
1267 if (passin) {
1268 for (ix=0, addr2=addr; ix<len; ix++, addr2+=4) {
1269 arr[ix] = memRead32(addr2);
1270 }
1271 }
1272 }
1273
1274 return arr;
1275 }
1276
1277 static void release_temp_i_array(glui32 *arr, glui32 addr, glui32 len, int passout)
1278 {
1279 arrayref_t *arref = NULL;
1280 arrayref_t **aptr;
1281 glui32 ix, val, addr2;
1282
1283 if (arr) {
1284 for (aptr=(&arrays); (*aptr); aptr=(&((*aptr)->next))) {
1285 if ((*aptr)->array == arr)
1286 break;
1287 }
1288 arref = *aptr;
1289 if (!arref)
1290 fatalError("Unable to re-find array argument in Glk call.");
1291 if (arref->addr != addr || arref->len != len)
1292 fatalError("Mismatched array argument in Glk call.");
1293
1294 if (arref->retained) {
1295 return;
1296 }
1297
1298 *aptr = arref->next;
1299 arref->next = NULL;
1300
1301 if (passout) {
1302 for (ix=0, addr2=addr; ix<len; ix++, addr2+=4) {
1303 val = arr[ix];
1304 memWrite32(addr2, val);
1305 }
1306 }
1307 glulx_free(arr);
1308 glulx_free(arref);
1309 }
1310 }
1311
1312 static void **grab_temp_ptr_array(glui32 addr, glui32 len, int objclass, int passin)
1313 {
1314 arrayref_t *arref = NULL;
1315 void **arr = NULL;
1316 glui32 ix, addr2;
1317
1318 if (len) {
1319 arr = (void **)glulx_malloc(len * sizeof(void *));
1320 arref = (arrayref_t *)glulx_malloc(sizeof(arrayref_t));
1321 if (!arr || !arref)
1322 fatalError("Unable to allocate space for array argument to Glk call.");
1323
1324 arref->array = arr;
1325 arref->addr = addr;
1326 arref->elemsize = sizeof(void *);
1327 arref->retained = FALSE;
1328 arref->len = len;
1329 arref->next = arrays;
1330 arrays = arref;
1331
1332 if (passin) {
1333 for (ix=0, addr2=addr; ix<len; ix++, addr2+=4) {
1334 glui32 thisval = memRead32(addr2);
1335 if (thisval)
1336 arr[ix] = classes_get(objclass, thisval);
1337 else
1338 arr[ix] = NULL;
1339 }
1340 }
1341 }
1342
1343 return arr;
1344 }
1345
1346 static void release_temp_ptr_array(void **arr, glui32 addr, glui32 len, int objclass, int passout)
1347 {
1348 arrayref_t *arref = NULL;
1349 arrayref_t **aptr;
1350 glui32 ix, val, addr2;
1351
1352 if (arr) {
1353 for (aptr=(&arrays); (*aptr); aptr=(&((*aptr)->next))) {
1354 if ((*aptr)->array == arr)
1355 break;
1356 }
1357 arref = *aptr;
1358 if (!arref)
1359 fatalError("Unable to re-find array argument in Glk call.");
1360 if (arref->addr != addr || arref->len != len)
1361 fatalError("Mismatched array argument in Glk call.");
1362
1363 if (arref->retained) {
1364 return;
1365 }
1366
1367 *aptr = arref->next;
1368 arref->next = NULL;
1369
1370 if (passout) {
1371 for (ix=0, addr2=addr; ix<len; ix++, addr2+=4) {
1372 void *opref = arr[ix];
1373 if (opref) {
1374 gidispatch_rock_t objrock =
1375 gidispatch_get_objrock(opref, objclass);
1376 val = ((classref_t *)objrock.ptr)->id;
1377 }
1378 else {
1379 val = 0;
1380 }
1381 memWrite32(addr2, val);
1382 }
1383 }
1384 glulx_free(arr);
1385 glulx_free(arref);
1386 }
1387 }
1388
1389 static gidispatch_rock_t glulxe_retained_register(void *array,
1390 glui32 len, char *typecode)
1391 {
1392 gidispatch_rock_t rock;
1393 arrayref_t *arref = NULL;
1394 arrayref_t **aptr;
1395 int elemsize = 0;
1396
1397 if (typecode[4] == 'C')
1398 elemsize = 1;
1399 else if (typecode[4] == 'I')
1400 elemsize = 4;
1401
1402 if (!elemsize || array == NULL) {
1403 rock.ptr = NULL;
1404 return rock;
1405 }
1406
1407 for (aptr=(&arrays); (*aptr); aptr=(&((*aptr)->next))) {
1408 if ((*aptr)->array == array)
1409 break;
1410 }
1411 arref = *aptr;
1412 if (!arref)
1413 fatalError("Unable to re-find array argument in Glk call.");
1414 if (arref->elemsize != elemsize || arref->len != len)
1415 fatalError("Mismatched array argument in Glk call.");
1416
1417 arref->retained = TRUE;
1418
1419 rock.ptr = arref;
1420 return rock;
1421 }
1422
1423 static void glulxe_retained_unregister(void *array, glui32 len,
1424 char *typecode, gidispatch_rock_t objrock)
1425 {
1426 arrayref_t *arref = NULL;
1427 arrayref_t **aptr;
1428 glui32 ix, addr2, val;
1429 int elemsize = 0;
1430
1431 if (typecode[4] == 'C')
1432 elemsize = 1;
1433 else if (typecode[4] == 'I')
1434 elemsize = 4;
1435
1436 if (!elemsize || array == NULL) {
1437 return;
1438 }
1439
1440 for (aptr=(&arrays); (*aptr); aptr=(&((*aptr)->next))) {
1441 if ((*aptr)->array == array)
1442 break;
1443 }
1444 arref = *aptr;
1445 if (!arref) {
1446 if (objrock.num == 0)
1447 return;
1448 fatalError("Unable to re-find array argument in Glk call.");
1449 }
1450 if (arref != objrock.ptr)
1451 fatalError("Mismatched array reference in Glk call.");
1452 if (!arref->retained)
1453 fatalError("Unretained array reference in Glk call.");
1454 if (arref->elemsize != elemsize || arref->len != len)
1455 fatalError("Mismatched array argument in Glk call.");
1456
1457 *aptr = arref->next;
1458 arref->next = NULL;
1459
1460 if (elemsize == 1) {
1461 for (ix=0, addr2=arref->addr; ix<arref->len; ix++, addr2+=1) {
1462 val = ((char *)array)[ix];
1463 memWrite8(addr2, val);
1464 }
1465 }
1466 else if (elemsize == 4) {
1467 for (ix=0, addr2=arref->addr; ix<arref->len; ix++, addr2+=4) {
1468 val = ((glui32 *)array)[ix];
1469 memWrite32(addr2, val);
1470 }
1471 }
1472
1473 glulx_free(array);
1474 glulx_free(arref);
1475 }
1476
1477 void set_library_select_hook(void (*func)(glui32))
1478 {
1479 library_select_hook = func;
1480 }
1481
1482 /* Create a string identifying this game. We use the first 64 bytes of the
1483 memory map, encoded as hex,
1484 */
1485 static char *get_game_id()
1486 {
1487 /* This buffer gets rewritten on every call, but that's okay -- the caller
1488 is supposed to copy out the result. */
1489 static char buf[2*64+2];
1490 int ix, jx;
1491
1492 if (!gInitMem)
1493 return NULL;
1494
1495 for (ix=0, jx=0; ix<64; ix++) {
1496 char ch = gInitMem[ix];
1497 int val = ((ch >> 4) & 0x0F);
1498 buf[jx++] = ((val < 10) ? (val + '0') : (val + 'A' - 10));
1499 val = (ch & 0x0F);
1500 buf[jx++] = ((val < 10) ? (val + '0') : (val + 'A' - 10));
1501 }
1502 buf[jx++] = '\0';
1503
1504 return buf;
1505 }
1506