Debian Codegraph @

terps/glulxe/debugger.c

raw symbols SCIP
1 /* debugger.c: Glulxe debugger functions.
2 Designed by Andrew Plotkin <[email protected]>
3 http://eblong.com/zarf/glulx/index.html
4 */
5
6 /* This module is a low-level debugger for Inform 6 (and 7) games.
7
8 This code is only compiled in if the "#define VM_DEBUGGER" line in
9 glulxe.h is uncommented. You will then have to compile with a Glk
10 library that supports the debug feature. (See gi_debug.h as distributed
11 with CheapGlk.) You will also need to link the libxml2 library.
12
13 When debugging is compiled in, glulxe looks for a "Dbug" chunk in the
14 Blorb file. This should contain the "gameinfo.dbg" file generated by
15 the I6 compiler. (Must be the new XML-based debug format.) It also
16 offers a bunch of new command-line options:
17
18 --gameinfo filename: Read the "gameinfo.dbg" from an external file.
19 (If you're not using Blorb or have not pulled the debug info
20 into it.)
21 --cpu: Display time and VM CPU cycles used for each input.
22 --starttrap: Enter debug mode as soon as the game starts up. (Before
23 any code has executed.)
24 --quittrap: Enter debug mode when the game quits.
25 --crashtrap: Enter debug mode if any fatal error occurs (including
26 Glk library fatal errors).
27
28 You do not need "gameinfo.dbg" data to use the debugger. However, that
29 file contains the I6-level names of all functions and variables. So
30 without it, you'll see a lot of "???" in the debug output.
31
32 The debug model assumes that you have a "debug console" available, which
33 can accept debug commands and display responses. (The implementation
34 of this depends on the Glk library.) You can enter commands whenever
35 the game is awaiting input, or if it pauses because of the --starttrap
36 flag, the --crashtrap flag, a breakpoint, or a @debugtrap opcode.
37
38 The debugger is currently pretty minimal. You can display the stack
39 (including local variables), display global variables, and set
40 breakpoints (only at the beginning of a function). Type "help" into
41 the debug console for the command list.
42
43 (If you've compiled with CheapGlk, then the "debug console" is just
44 standard output. Enter a line beginning with "/" to send a debug
45 command -- "/help", etc.) (This "/" convention is *only* used in
46 CheapGlk. Other libraries will have debug interfaces that don't
47 suck.)
48 */
49
50 #include "glk.h"
51 #include "glulxe.h"
52
53 #if VM_DEBUGGER
54
55 #include <string.h>
56 #include <sys/time.h>
57 #include "gi_debug.h"
58 #include <libxml/xmlreader.h>
59
60 /* Data structures to store the debug info in memory. */
61
62 typedef enum grouptype_enum {
63 grp_None = 0,
64 grp_Constant = 1,
65 grp_Attribute = 2,
66 grp_Property = 3,
67 grp_Routine = 4,
68 grp_Global = 5,
69 grp_Object = 6,
70 grp_Array = 7,
71 } grouptype;
72
73 /* Used for constants, globals, locals, objects -- the meaning of the value
74 field varies. */
75 typedef struct infoconstant_struct {
76 const xmlChar *identifier;
77 int32_t value;
78 } infoconstant;
79
80 typedef struct inforoutine_struct {
81 const xmlChar *identifier;
82 int32_t address;
83 int32_t length;
84
85 /* Address of the next higher function. May be beyond length if there
86 are gaps. */
87 int32_t nextaddress;
88
89 /* The locals is a block of infoconstants where the value is
90 frame-offset. We adopt Inform's assumption that locals are
91 always 4 bytes long. */
92 int32_t numlocals;
93 infoconstant *locals;
94 } inforoutine;
95
96 typedef struct infoobject_struct {
97 const xmlChar *identifier;
98 int32_t address;
99
100 /* Address of the next higher function. May be beyond length if there
101 are gaps. */
102 int32_t nextaddress;
103 } infoobject;
104
105 typedef struct infoarray_struct {
106 const xmlChar *identifier;
107 int32_t address;
108 int32_t bytelength;
109 int32_t bytesize; /* per element */
110 int32_t count;
111 int lengthfield; /* true if the zeroth element is the length */
112
113 /* Address of the next higher function. May be beyond length if there
114 are gaps. */
115 int32_t nextaddress;
116 } infoarray;
117
118 typedef struct breakpoint_struct {
119 inforoutine *func;
120 int32_t address;
121 struct breakpoint_struct *next; /* linked list of breakpoints */
122 } breakpoint;
123
124 typedef struct debuginfofile_struct {
125 strid_t str;
126 int32_t strread;
127 int32_t strreadmax;
128 int failed;
129
130 grouptype curgrouptype;
131
132 int tempcounter;
133 infoconstant *tempconstant;
134 inforoutine *temproutine;
135 infoarray *temparray;
136 infoobject *tempobject;
137 int tempnumlocals;
138 int templocalssize;
139 infoconstant *templocals;
140
141 const xmlChar *storyfileprefix;
142 xmlHashTablePtr constants;
143 xmlHashTablePtr attributes;
144 xmlHashTablePtr properties;
145 xmlHashTablePtr globals;
146 xmlHashTablePtr objects;
147 int numobjects;
148 infoobject **objectlist; /* array, ordered by address */
149 xmlHashTablePtr arrays;
150 int numarrays;
151 infoarray **arraylist; /* array, ordered by address */
152 xmlHashTablePtr routines;
153 int numroutines;
154 inforoutine **routinelist; /* array, ordered by address */
155 } debuginfofile;
156
157 /* This global holds the loaded debug info, if we have any. */
158 static debuginfofile *debuginfo = NULL;
159
160 /* Lists of breakpoints. */
161 static breakpoint *funcbreakpoints = NULL; /* linked list */
162
163 /* Internal functions used while loading the debug info. */
164
165 static int xmlreadstreamfunc(void *rock, char *buffer, int len);
166 static int xmlreadchunkfunc(void *rock, char *buffer, int len);
167 static int xmlclosefunc(void *rock);
168 static void xmlhandlenode(xmlTextReaderPtr reader, debuginfofile *context);
169 static int finalize_debuginfo(debuginfofile *context);
170
171 static debuginfofile *create_debuginfofile(void)
172 {
173 debuginfofile *context = (debuginfofile *)malloc(sizeof(debuginfofile));
174 context->str = NULL;
175 context->failed = 0;
176 context->tempconstant = NULL;
177 context->temparray = NULL;
178 context->tempobject = NULL;
179 context->temproutine = NULL;
180 context->tempnumlocals = 0;
181 context->templocals = NULL;
182 context->templocalssize = 0;
183 context->curgrouptype = grp_None;
184 context->constants = xmlHashCreate(16);
185 context->attributes = xmlHashCreate(16);
186 context->properties = xmlHashCreate(16);
187 context->globals = xmlHashCreate(16);
188 context->objects = xmlHashCreate(16);
189 context->numobjects = 0;
190 context->objectlist = NULL;
191 context->arrays = xmlHashCreate(16);
192 context->numarrays = 0;
193 context->arraylist = NULL;
194 context->routines = xmlHashCreate(16);
195 context->numroutines = 0;
196 context->routinelist = NULL;
197 context->storyfileprefix = NULL;
198
199 return context;
200 }
201
202 static void free_debuginfofile(debuginfofile *context)
203 {
204 if (!context)
205 return;
206
207 context->str = NULL;
208 context->tempconstant = NULL;
209 context->temparray = NULL;
210 context->tempobject = NULL;
211 context->temproutine = NULL;
212
213 /* We don't bother to free the member structures, because this
214 only happens once at startup and then only on error
215 conditions. */
216
217 if (context->constants) {
218 xmlHashFree(context->constants, NULL);
219 context->constants = NULL;
220 }
221
222 if (context->attributes) {
223 xmlHashFree(context->attributes, NULL);
224 context->attributes = NULL;
225 }
226
227 if (context->properties) {
228 xmlHashFree(context->properties, NULL);
229 context->properties = NULL;
230 }
231
232 if (context->globals) {
233 xmlHashFree(context->globals, NULL);
234 context->globals = NULL;
235 }
236
237 if (context->objects) {
238 xmlHashFree(context->objects, NULL);
239 context->objects = NULL;
240 }
241
242 if (context->objectlist) {
243 free(context->objectlist);
244 context->objectlist = NULL;
245 }
246
247 if (context->arrays) {
248 xmlHashFree(context->arrays, NULL);
249 context->arrays = NULL;
250 }
251
252 if (context->arraylist) {
253 free(context->arraylist);
254 context->arraylist = NULL;
255 }
256
257 if (context->routines) {
258 xmlHashFree(context->routines, NULL);
259 context->routines = NULL;
260 }
261
262 if (context->routinelist) {
263 free(context->routinelist);
264 context->routinelist = NULL;
265 }
266
267 free(context);
268 }
269
270 static infoconstant *create_infoconstant(void)
271 {
272 infoconstant *cons = (infoconstant *)malloc(sizeof(infoconstant));
273 cons->identifier = NULL;
274 cons->value = 0;
275 return cons;
276 }
277
278 static infoobject *create_infoobject(void)
279 {
280 infoobject *object = (infoobject *)malloc(sizeof(infoobject));
281 object->identifier = NULL;
282 object->address = 0;
283 object->nextaddress = 0;
284 return object;
285 }
286
287 static infoarray *create_infoarray(void)
288 {
289 infoarray *arr = (infoarray *)malloc(sizeof(infoarray));
290 arr->identifier = NULL;
291 arr->address = 0;
292 arr->bytelength = 0;
293 arr->bytesize = 1;
294 arr->count = 0;
295 arr->lengthfield = 0;
296 arr->nextaddress = 0;
297 return arr;
298 }
299
300 static inforoutine *create_inforoutine(void)
301 {
302 inforoutine *func = (inforoutine *)malloc(sizeof(inforoutine));
303 func->identifier = NULL;
304 func->address = 0;
305 func->length = 0;
306 func->nextaddress = 0;
307 func->numlocals = 0;
308 func->locals = NULL;
309 return func;
310 }
311
312 static breakpoint *create_breakpoint(glui32 addr)
313 {
314 breakpoint *bp = (breakpoint *)malloc(sizeof(breakpoint));
315 bp->func = NULL; /* useful? */
316 bp->address = addr;
317 bp->next = NULL;
318 return bp;
319 }
320
321 static void add_object_to_table(void *obj, void *rock, const xmlChar *name)
322 {
323 debuginfofile *context = rock;
324 infoobject *object = obj;
325
326 if (context->tempcounter >= context->numobjects) {
327 printf("### object overflow!\n"); /*###*/
328 return;
329 }
330
331 context->objectlist[context->tempcounter++] = object;
332 }
333
334 static int sort_objects_table(const void *obj1, const void *obj2)
335 {
336 infoobject **object1 = (infoobject **)obj1;
337 infoobject **object2 = (infoobject **)obj2;
338
339 return ((*object1)->address - (*object2)->address);
340 }
341
342 static int find_object_in_table(const void *keyptr, const void *obj)
343 {
344 /* Binary-search callback. We rely on address and nextaddress so
345 that there are no gaps. */
346
347 glui32 addr = *(glui32 *)(keyptr);
348 infoobject **object = (infoobject **)obj;
349
350 if (addr < (*object)->address)
351 return -1;
352 if (addr >= (*object)->nextaddress)
353 return 1;
354 return 0;
355 }
356
357 static void add_array_to_table(void *obj, void *rock, const xmlChar *name)
358 {
359 debuginfofile *context = rock;
360 infoarray *array = obj;
361
362 if (context->tempcounter >= context->numarrays) {
363 printf("### array overflow!\n"); /*###*/
364 return;
365 }
366
367 context->arraylist[context->tempcounter++] = array;
368 }
369
370 static int sort_arrays_table(const void *obj1, const void *obj2)
371 {
372 infoarray **array1 = (infoarray **)obj1;
373 infoarray **array2 = (infoarray **)obj2;
374
375 return ((*array1)->address - (*array2)->address);
376 }
377
378 static int find_array_in_table(const void *keyptr, const void *obj)
379 {
380 /* Binary-search callback. We rely on address and nextaddress so
381 that there are no gaps. */
382
383 glui32 addr = *(glui32 *)(keyptr);
384 infoarray **array = (infoarray **)obj;
385
386 if (addr < (*array)->address)
387 return -1;
388 if (addr >= (*array)->nextaddress)
389 return 1;
390 return 0;
391 }
392
393 static void add_routine_to_table(void *obj, void *rock, const xmlChar *name)
394 {
395 debuginfofile *context = rock;
396 inforoutine *routine = obj;
397
398 if (context->tempcounter >= context->numroutines) {
399 printf("### array overflow!\n"); /*###*/
400 return;
401 }
402
403 context->routinelist[context->tempcounter++] = routine;
404 }
405
406 static int sort_routines_table(const void *obj1, const void *obj2)
407 {
408 inforoutine **routine1 = (inforoutine **)obj1;
409 inforoutine **routine2 = (inforoutine **)obj2;
410
411 return ((*routine1)->address - (*routine2)->address);
412 }
413
414 static int find_routine_in_table(const void *keyptr, const void *obj)
415 {
416 /* Binary-search callback. We rely on address and nextaddress so
417 that there are no gaps. */
418
419 glui32 addr = *(glui32 *)(keyptr);
420 inforoutine **routine = (inforoutine **)obj;
421
422 if (addr < (*routine)->address)
423 return -1;
424 if (addr >= (*routine)->nextaddress)
425 return 1;
426 return 0;
427 }
428
429 /* Top-level function for loading debug info from a Glk stream.
430 The debug data must take up the entire file; this will read until EOF.
431 If successful, fills out the debuginfo global and returns true.
432 If not, reports an error and returns false.
433 (The stream will not be closed.)
434 */
435 int debugger_load_info_stream(strid_t stream)
436 {
437 xmlTextReaderPtr reader;
438 debuginfofile *context = create_debuginfofile();
439 context->str = stream;
440 context->strread = 0; /* not used */
441 context->strreadmax = 0; /* not used */
442
443 reader = xmlReaderForIO(xmlreadstreamfunc, xmlclosefunc, context,
444 NULL, NULL,
445 XML_PARSE_RECOVER|XML_PARSE_NOENT|XML_PARSE_NONET|XML_PARSE_NOCDATA|XML_PARSE_COMPACT);
446 if (!reader) {
447 printf("Error: Unable to create XML reader.\n"); /*###*/
448 free_debuginfofile(context);
449 return 0;
450 }
451
452 while (1) {
453 int res = xmlTextReaderRead(reader);
454 if (res < 0) {
455 context->failed = 1;
456 break; /* error */
457 }
458 if (res == 0) {
459 break; /* EOF */
460 }
461 xmlhandlenode(reader, context);
462 }
463
464 xmlFreeTextReader(reader);
465 context->str = NULL; /* the reader didn't close it, but we're done with it. */
466
467 if (context->failed) {
468 printf("Error: Unable to load debug info.\n"); /*###*/
469 free_debuginfofile(context);
470 return 0;
471 }
472
473 /* Now that all the data is loaded in, we go through and create some
474 indexes that will be handy. */
475 return finalize_debuginfo(context);
476 }
477
478 /* Top-level function for loading debug info from a segment of a Glk stream.
479 This starts at position pos in the file and reads len bytes.
480 If successful, fills out the debuginfo global and returns true.
481 If not, reports an error and returns false.
482 (The stream will not be closed.)
483 */
484 int debugger_load_info_chunk(strid_t stream, glui32 pos, glui32 len)
485 {
486 xmlTextReaderPtr reader;
487 debuginfofile *context = create_debuginfofile();
488 context->str = stream;
489 context->strread = 0;
490 context->strreadmax = len;
491
492 glk_stream_set_position(stream, pos, seekmode_Start);
493
494 reader = xmlReaderForIO(xmlreadchunkfunc, xmlclosefunc, context,
495 NULL, NULL,
496 XML_PARSE_RECOVER|XML_PARSE_NOENT|XML_PARSE_NONET|XML_PARSE_NOCDATA|XML_PARSE_COMPACT);
497 if (!reader) {
498 printf("Error: Unable to create XML reader.\n"); /*###*/
499 free_debuginfofile(context);
500 return 0;
501 }
502
503 while (1) {
504 int res = xmlTextReaderRead(reader);
505 if (res < 0) {
506 context->failed = 1;
507 break; /* error */
508 }
509 if (res == 0) {
510 break; /* EOF */
511 }
512 xmlhandlenode(reader, context);
513 }
514
515 xmlFreeTextReader(reader);
516 context->str = NULL; /* the reader didn't close it, but we're done with it. */
517
518 if (context->failed) {
519 printf("Error: Unable to load debug info.\n"); /*###*/
520 free_debuginfofile(context);
521 return 0;
522 }
523
524 /* Now that all the data is loaded in, we go through and create some
525 indexes that will be handy. */
526 return finalize_debuginfo(context);
527 }
528
529 /* xmlReader callback to read from a stream (until EOF). */
530 static int xmlreadstreamfunc(void *rock, char *buffer, int len)
531 {
532 debuginfofile *context = rock;
533 int res = glk_get_buffer_stream(context->str, buffer, len);
534 if (res < 0)
535 return -1;
536 return res;
537 }
538
539 /* xmlReader callback to read from a stream (until a given position). */
540 static int xmlreadchunkfunc(void *rock, char *buffer, int len)
541 {
542 int res;
543 debuginfofile *context = rock;
544 if (context->strread >= context->strreadmax)
545 return 0;
546
547 if (len > context->strreadmax - context->strread)
548 len = context->strreadmax - context->strread;
549 res = glk_get_buffer_stream(context->str, buffer, len);
550 if (res < 0)
551 return -1;
552 context->strread += res;
553 return res;
554 }
555
556 /* xmlReader callback to stop reading a stream. We don't actually close
557 the stream here, just discard the reference. */
558 static int xmlclosefunc(void *rock)
559 {
560 debuginfofile *context = rock;
561 context->str = NULL;
562 return 0;
563 }
564
565 /* xmlReader callback: an XML node has arrived. (Might be the beginning of
566 a tag, the end of a tag, or a block of text.)
567
568 All the work of parsing the debug format happens here, which is why this
569 function is big and ugly.
570 */
571 static void xmlhandlenode(xmlTextReaderPtr reader, debuginfofile *context)
572 {
573 int depth = xmlTextReaderDepth(reader);
574 int nodetype = xmlTextReaderNodeType(reader);
575
576 if (depth == 0) {
577 if (nodetype == XML_ELEMENT_NODE) {
578 const xmlChar *name = xmlTextReaderConstName(reader);
579 if (xmlStrcmp(name, BAD_CAST "inform-story-file")) {
580 printf("Error: This is not an Inform debug info file.\n"); /*###*/
581 context->failed = 1;
582 }
583 }
584 else if (nodetype == XML_ELEMENT_DECL) {
585 /* End of document */
586 context->curgrouptype = grp_None;
587 context->tempconstant = NULL;
588 context->temparray = NULL;
589 context->tempobject = NULL;
590 context->temproutine = NULL;
591 }
592 }
593 else if (depth == 1) {
594 if (nodetype == XML_ELEMENT_NODE) {
595 const xmlChar *name = xmlTextReaderConstName(reader);
596 if (!xmlStrcmp(name, BAD_CAST "constant")) {
597 context->curgrouptype = grp_Constant;
598 context->tempconstant = create_infoconstant();
599 }
600 else if (!xmlStrcmp(name, BAD_CAST "attribute")) {
601 context->curgrouptype = grp_Attribute;
602 context->tempconstant = create_infoconstant();
603 }
604 else if (!xmlStrcmp(name, BAD_CAST "property")) {
605 context->curgrouptype = grp_Property;
606 context->tempconstant = create_infoconstant();
607 }
608 else if (!xmlStrcmp(name, BAD_CAST "routine")) {
609 context->curgrouptype = grp_Routine;
610 context->temproutine = create_inforoutine();
611 context->tempnumlocals = 0;
612 }
613 else if (!xmlStrcmp(name, BAD_CAST "global-variable")) {
614 context->curgrouptype = grp_Global;
615 context->tempconstant = create_infoconstant();
616 }
617 else if (!xmlStrcmp(name, BAD_CAST "object")) {
618 context->curgrouptype = grp_Object;
619 context->tempobject = create_infoobject();
620 }
621 else if (!xmlStrcmp(name, BAD_CAST "array")) {
622 context->curgrouptype = grp_Array;
623 context->temparray = create_infoarray();
624 }
625 else if (!xmlStrcmp(name, BAD_CAST "story-file-prefix")) {
626 xmlNodePtr nod = xmlTextReaderExpand(reader);
627 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
628 context->storyfileprefix = xmlStrdup(nod->children->content);
629 }
630 }
631 else {
632 context->curgrouptype = grp_None;
633 }
634 }
635 else if (nodetype == XML_ELEMENT_DECL) {
636 /* End of group */
637 switch (context->curgrouptype) {
638 case grp_Constant:
639 if (context->tempconstant) {
640 infoconstant *dat = context->tempconstant;
641 context->tempconstant = NULL;
642 xmlHashAddEntry(context->constants, dat->identifier, dat);
643 }
644 break;
645 case grp_Attribute:
646 if (context->tempconstant) {
647 infoconstant *dat = context->tempconstant;
648 context->tempconstant = NULL;
649 xmlHashAddEntry(context->attributes, dat->identifier, dat);
650 }
651 break;
652 case grp_Property:
653 if (context->tempconstant) {
654 infoconstant *dat = context->tempconstant;
655 context->tempconstant = NULL;
656 xmlHashAddEntry(context->properties, dat->identifier, dat);
657 }
658 break;
659 case grp_Global:
660 if (context->tempconstant) {
661 infoconstant *dat = context->tempconstant;
662 context->tempconstant = NULL;
663 xmlHashAddEntry(context->globals, dat->identifier, dat);
664 }
665 break;
666 case grp_Object:
667 if (context->tempobject) {
668 infoobject *dat = context->tempobject;
669 context->tempobject = NULL;
670 xmlHashAddEntry(context->objects, dat->identifier, dat);
671 }
672 break;
673 case grp_Array:
674 if (context->temparray) {
675 infoarray *dat = context->temparray;
676 context->temparray = NULL;
677 dat->count = dat->bytelength / dat->bytesize;
678 xmlHashAddEntry(context->arrays, dat->identifier, dat);
679 }
680 break;
681 case grp_Routine:
682 if (context->temproutine) {
683 inforoutine *dat = context->temproutine;
684 context->temproutine = NULL;
685 /* Copy the list of locals into the inforoutine structure.
686 This loop totally assumes that locals are found
687 in order in the debug file! */
688 if (context->tempnumlocals && context->templocals) {
689 int ix;
690 dat->numlocals = context->tempnumlocals;
691 dat->locals = (infoconstant *)malloc(context->tempnumlocals * sizeof(infoconstant));
692 for (ix=0; ix<context->tempnumlocals; ix++) {
693 dat->locals[ix].identifier = context->templocals[ix].identifier;
694 dat->locals[ix].value = context->templocals[ix].value;
695 context->templocals[ix].identifier = NULL;
696 context->templocals[ix].value = 0;
697 }
698 }
699 context->tempnumlocals = 0;
700 /* An address of 0 is impossible. Inform uses this to
701 indicate a routine that was eliminated because it was
702 never called. */
703 if (dat->address != 0) {
704 xmlHashAddEntry(context->routines, dat->identifier, dat);
705 }
706 }
707 break;
708 default:
709 break;
710 }
711 context->curgrouptype = grp_None;
712 }
713 }
714 else {
715 if (nodetype == XML_ELEMENT_NODE) {
716 const xmlChar *name = xmlTextReaderConstName(reader);
717 /* These fields are always simple text nodes. */
718 if (!xmlStrcmp(name, BAD_CAST "identifier")) {
719 xmlNodePtr nod = xmlTextReaderExpand(reader);
720 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
721 xmlChar *text = nod->children->content;
722 if (context->curgrouptype == grp_Constant
723 || context->curgrouptype == grp_Attribute
724 || context->curgrouptype == grp_Property
725 || context->curgrouptype == grp_Global) {
726 if (context->tempconstant) {
727 if (depth == 2)
728 context->tempconstant->identifier = xmlStrdup(text);
729 }
730 }
731 else if (context->curgrouptype == grp_Object) {
732 if (context->tempobject) {
733 if (depth == 2)
734 context->tempobject->identifier = xmlStrdup(text);
735 }
736 }
737 else if (context->curgrouptype == grp_Array) {
738 if (context->temparray) {
739 if (depth == 2)
740 context->temparray->identifier = xmlStrdup(text);
741 }
742 }
743 else if (context->curgrouptype == grp_Routine) {
744 if (context->temproutine) {
745 if (depth == 2)
746 context->temproutine->identifier = xmlStrdup(text);
747 }
748 }
749 }
750 }
751 else if (!xmlStrcmp(name, BAD_CAST "value")) {
752 xmlNodePtr nod = xmlTextReaderExpand(reader);
753 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
754 if (context->curgrouptype == grp_Constant
755 || context->curgrouptype == grp_Attribute
756 || context->curgrouptype == grp_Property) {
757 if (context->tempconstant) {
758 if (depth == 2)
759 context->tempconstant->value = strtol((char *)nod->children->content, NULL, 10);
760 }
761 }
762 else if (context->curgrouptype == grp_Object) {
763 if (context->tempobject) {
764 if (depth == 2)
765 context->tempobject->address = strtol((char *)nod->children->content, NULL, 10);
766 }
767 }
768 else if (context->curgrouptype == grp_Array) {
769 if (context->temparray) {
770 if (depth == 2)
771 context->temparray->address = strtol((char *)nod->children->content, NULL, 10);
772 }
773 }
774 else if (context->curgrouptype == grp_Routine) {
775 if (context->temproutine) {
776 if (depth == 2)
777 context->temproutine->address = strtol((char *)nod->children->content, NULL, 10);
778 }
779 }
780 }
781 }
782 else if (!xmlStrcmp(name, BAD_CAST "address")) {
783 xmlNodePtr nod = xmlTextReaderExpand(reader);
784 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
785 if (context->curgrouptype == grp_Global) {
786 if (context->tempconstant) {
787 if (depth == 2)
788 context->tempconstant->value = strtol((char *)nod->children->content, NULL, 10);
789 }
790 }
791 }
792 }
793 else if (!xmlStrcmp(name, BAD_CAST "byte-count")) {
794 xmlNodePtr nod = xmlTextReaderExpand(reader);
795 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
796 if (context->curgrouptype == grp_Routine) {
797 if (context->temproutine) {
798 if (depth == 2)
799 context->temproutine->length = strtol((char *)nod->children->content, NULL, 10);
800 }
801 }
802 else if (context->curgrouptype == grp_Array) {
803 if (context->temparray) {
804 if (depth == 2)
805 context->temparray->bytelength = strtol((char *)nod->children->content, NULL, 10);
806 }
807 }
808 }
809 }
810 else if (!xmlStrcmp(name, BAD_CAST "bytes-per-element")) {
811 xmlNodePtr nod = xmlTextReaderExpand(reader);
812 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
813 if (context->curgrouptype == grp_Array) {
814 if (context->temparray) {
815 if (depth == 2)
816 context->temparray->bytesize = strtol((char *)nod->children->content, NULL, 10);
817 }
818 }
819 }
820 }
821 else if (!xmlStrcmp(name, BAD_CAST "zeroth-element-holds-length")) {
822 xmlNodePtr nod = xmlTextReaderExpand(reader);
823 if (nod && nod->children && nod->children->type == XML_TEXT_NODE) {
824 if (context->curgrouptype == grp_Array) {
825 if (context->temparray) {
826 if (depth == 2)
827 if (!xmlStrcmp(nod->children->content, BAD_CAST "true"))
828 context->temparray->lengthfield = 1;
829 }
830 }
831 }
832 }
833 else if (!xmlStrcmp(name, BAD_CAST "local-variable")) {
834 xmlNodePtr nod = xmlTextReaderExpand(reader);
835 if (nod) {
836 infoconstant *templocal;
837 if (!context->templocals) {
838 context->templocalssize = 8;
839 context->templocals = (infoconstant *)malloc(context->templocalssize * sizeof(infoconstant));
840 }
841 if (context->tempnumlocals >= context->templocalssize) {
842 context->templocalssize = 2*context->tempnumlocals + 4;
843 context->templocals = (infoconstant *)realloc(context->templocals, context->templocalssize * sizeof(infoconstant));
844 }
845 templocal = &(context->templocals[context->tempnumlocals]);
846 context->tempnumlocals += 1;
847 for (nod = nod->children; nod; nod=nod->next) {
848 if (nod->type == XML_ELEMENT_NODE) {
849 if (!xmlStrcmp(nod->name, BAD_CAST "identifier") && nod->children && nod->children->type == XML_TEXT_NODE) {
850 templocal->identifier = xmlStrdup(nod->children->content);
851 }
852 if (!xmlStrcmp(nod->name, BAD_CAST "frame-offset") && nod->children && nod->children->type == XML_TEXT_NODE) {
853 templocal->value = strtol((char *)nod->children->content, NULL, 10);
854 }
855 }
856 }
857 }
858 }
859 }
860 }
861 }
862
863 /* This is called after the XML data is parsed. We wrap up what we've
864 found and store it in the debuginfo global. Returns 1 on success.
865 */
866 static int finalize_debuginfo(debuginfofile *context)
867 {
868 int ix;
869
870 context->numarrays = xmlHashSize(context->arrays);
871 context->arraylist = (infoarray **)malloc(context->numarrays * sizeof(infoarray *));
872
873 context->tempcounter = 0;
874 xmlHashScan(context->arrays, add_array_to_table, context);
875 if (context->tempcounter != context->numarrays)
876 printf("### array underflow!\n"); /*###*/
877 qsort(context->arraylist, context->numarrays, sizeof(infoarray *), sort_arrays_table);
878
879 for (ix=0; ix<context->numarrays; ix++) {
880 if (ix+1 < context->numarrays) {
881 context->arraylist[ix]->nextaddress = context->arraylist[ix+1]->address;
882 }
883 else {
884 context->arraylist[ix]->nextaddress = context->arraylist[ix]->address + context->arraylist[ix]->bytelength;
885 }
886 }
887
888 context->numobjects = xmlHashSize(context->objects);
889 context->objectlist = (infoobject **)malloc(context->numobjects * sizeof(infoobject *));
890
891 context->tempcounter = 0;
892 xmlHashScan(context->objects, add_object_to_table, context);
893 if (context->tempcounter != context->numobjects)
894 printf("### object underflow!\n"); /*###*/
895 qsort(context->objectlist, context->numobjects, sizeof(infoobject *), sort_objects_table);
896
897 for (ix=0; ix<context->numobjects; ix++) {
898 if (ix+1 < context->numobjects) {
899 context->objectlist[ix]->nextaddress = context->objectlist[ix+1]->address;
900 }
901 else {
902 context->objectlist[ix]->nextaddress = context->objectlist[ix]->address + 1;
903 }
904 }
905
906 context->numroutines = xmlHashSize(context->routines);
907 context->routinelist = (inforoutine **)malloc(context->numroutines * sizeof(inforoutine *));
908
909 context->tempcounter = 0;
910 xmlHashScan(context->routines, add_routine_to_table, context);
911 if (context->tempcounter != context->numroutines)
912 printf("### array underflow!\n"); /*###*/
913 qsort(context->routinelist, context->numroutines, sizeof(inforoutine *), sort_routines_table);
914
915 for (ix=0; ix<context->numroutines; ix++) {
916 if (ix+1 < context->numroutines) {
917 context->routinelist[ix]->nextaddress = context->routinelist[ix+1]->address;
918 }
919 else {
920 context->routinelist[ix]->nextaddress = context->routinelist[ix]->address + context->routinelist[ix]->length;
921 }
922 }
923
924 if (context->templocals) {
925 free(context->templocals);
926 context->templocals = NULL;
927 }
928 context->templocalssize = 0;
929 context->tempnumlocals = 0;
930
931 /* Install into global. */
932 debuginfo = context;
933 return 1;
934 }
935
936 /* Compare main memory to the story-file-prefix we found. If it doesn't
937 match, display a warning.
938 */
939 void debugger_check_story_file()
940 {
941 const unsigned char *cx;
942 int pos = 0;
943 int count = 0;
944 uint32_t word = 0;
945 int fail = FALSE;
946
947 if (!debuginfo || !debuginfo->storyfileprefix)
948 return;
949
950 /* Check that this looks like an Inform 6 game file. See the
951 Glulx Inform Technical Reference. */
952 if (Mem4(0x24) != 0x496E666F) { /* 'Info' */
953 gidebug_output("Warning: This game file does not look like it was generated by Inform.");
954 }
955
956 /* Decode the storyfileprefix, which is in base64. */
957
958 for (cx = debuginfo->storyfileprefix; *cx && *cx != '='; cx++) {
959 unsigned int sixbit = 0;
960 if (*cx >= 'A' && *cx <= 'Z')
961 sixbit = (*cx) - 'A';
962 else if (*cx >= 'a' && *cx <= 'z')
963 sixbit = ((*cx) - 'a') + 26;
964 else if (*cx >= '0' && *cx <= '9')
965 sixbit = ((*cx) - '0') + 52;
966 else if (*cx == '+')
967 sixbit = 62;
968 else if (*cx == '/')
969 sixbit = 63;
970 else
971 sixbit = 0;
972
973 switch (count) {
974 case 0:
975 word = (sixbit << 18);
976 break;
977 case 1:
978 word |= (sixbit << 12);
979 break;
980 case 2:
981 word |= (sixbit << 6);
982 break;
983 case 3:
984 word |= (sixbit);
985 break;
986 }
987
988 count++;
989 if (count == 4) {
990 unsigned char byte;
991 byte = (word >> 16) & 0xFF;
992 if (byte != Mem1(pos))
993 fail = TRUE;
994 byte = (word >> 8) & 0xFF;
995 if (byte != Mem1(pos+1))
996 fail = TRUE;
997 byte = (word) & 0xFF;
998 if (byte != Mem1(pos+2))
999 fail = TRUE;
1000 pos += 3;
1001 count = 0;
1002 }
1003 }
1004
1005 if (fail)
1006 gidebug_output("Warning: debug info <story-file-prefix> does not match this game file.");
1007 }
1008
1009 /* The rest of this file is the debugger itself. */
1010
1011 static char *linebuf = NULL;
1012 static int linebufsize = 0;
1013
1014 /* Expand the output line buffer to a given length, if necessary.
1015 If you want to write an N-character string, call ensure_line_buf(N).
1016 Then use snprintf() just to be safe. */
1017 static void ensure_line_buf(int len)
1018 {
1019 len += 1; /* for the closing null */
1020 if (linebuf && len <= linebufsize)
1021 return;
1022
1023 linebufsize = linebufsize*2+16;
1024 if (linebufsize < len)
1025 linebufsize = len+16;
1026
1027 if (!linebuf)
1028 linebuf = malloc(linebufsize * sizeof(char));
1029 else
1030 linebuf = realloc(linebuf, linebufsize * sizeof(char));
1031 }
1032
1033 static int track_cpu = FALSE;
1034 static int start_trap = FALSE;
1035 static int crash_trap = FALSE;
1036 static int quit_trap = FALSE;
1037 static int debugger_invoked = FALSE; /* true if cycle handler called */
1038 unsigned long debugger_opcount = 0; /* incremented in exec.c */
1039 static struct timeval debugger_timer;
1040
1041 /* Set the track-CPU flag. (In fact we always track the VM CPU usage.
1042 This flag determines whether we report it to the debug console.)
1043 */
1044 void debugger_track_cpu(int flag)
1045 {
1046 track_cpu = flag;
1047 }
1048
1049 /* Set the block-on-startup flag.
1050 */
1051 void debugger_set_start_trap(int flag)
1052 {
1053 start_trap = flag;
1054 }
1055
1056 /* Set the block-on-quit flag.
1057 */
1058 void debugger_set_quit_trap(int flag)
1059 {
1060 quit_trap = flag;
1061 }
1062
1063 /* Set the block-on-crash flag.
1064 */
1065 void debugger_set_crash_trap(int flag)
1066 {
1067 crash_trap = flag;
1068 }
1069
1070 /* Has the library activated debugger features? If not, we assume
1071 that the debug console is entirely hidden from the user.
1072 */
1073 int debugger_ever_invoked()
1074 {
1075 return debugger_invoked;
1076 }
1077
1078 /* Returns 1 if this is a (hex or decimal) numeric constant; 0 if not;
1079 -1 if it looks like a constant but is malformed.
1080
1081 On 1, the number itself is returned in res.
1082 */
1083 static int parse_numeric_constant(char *arg, glui32 *res)
1084 {
1085 if (arg[0] == '$') {
1086 char *cx;
1087 glui32 val = 0;
1088 for (cx=arg+1; *cx; cx++) {
1089 if (*cx >= '0' && *cx <= '9') {
1090 val = 16 * val + (*cx - '0');
1091 continue;
1092 }
1093 if (*cx >= 'A' && *cx <= 'F') {
1094 val = 16 * val + (*cx - 'A' + 10);
1095 continue;
1096 }
1097 if (*cx >= 'a' && *cx <= 'f') {
1098 val = 16 * val + (*cx - 'a' + 10);
1099 continue;
1100 }
1101 snprintf(linebuf, linebufsize, "Invalid hex number");
1102 gidebug_output(linebuf);
1103 return -1;
1104 }
1105 *res = val;
1106 return 1;
1107 }
1108
1109 if (arg[0] >= '0' && arg[0] <= '9') {
1110 char *cx;
1111 glui32 val = 0;
1112 for (cx=arg; *cx; cx++) {
1113 if (*cx >= '0' && *cx <= '9') {
1114 val = 10 * val + (*cx - '0');
1115 continue;
1116 }
1117 snprintf(linebuf, linebufsize, "Invalid number");
1118 gidebug_output(linebuf);
1119 return -1;
1120 }
1121 *res = val;
1122 return 1;
1123 }
1124
1125 return 0;
1126 }
1127
1128 static infoarray *find_array_for_address(glui32 addr)
1129 {
1130 infoarray **res;
1131 infoarray *arr;
1132
1133 if (!debuginfo)
1134 return NULL;
1135
1136 res = bsearch(&addr, debuginfo->arraylist, debuginfo->numarrays, sizeof(infoarray *), find_array_in_table);
1137 if (!res)
1138 return NULL;
1139
1140 arr = *res;
1141 if (addr < arr->address || addr >= arr->address + arr->bytelength)
1142 return NULL;
1143
1144 return arr;
1145 }
1146
1147 static infoobject *find_object_for_address(glui32 addr)
1148 {
1149 infoobject **res;
1150 infoobject *arr;
1151
1152 if (!debuginfo)
1153 return NULL;
1154
1155 res = bsearch(&addr, debuginfo->objectlist, debuginfo->numobjects, sizeof(infoobject *), find_object_in_table);
1156 if (!res)
1157 return NULL;
1158
1159 arr = *res;
1160 if (addr != arr->address)
1161 return NULL;
1162
1163 return arr;
1164 }
1165
1166 static inforoutine *find_routine_for_address(glui32 addr)
1167 {
1168 inforoutine **res;
1169 inforoutine *func;
1170
1171 if (!debuginfo)
1172 return NULL;
1173
1174 res = bsearch(&addr, debuginfo->routinelist, debuginfo->numroutines, sizeof(inforoutine *), find_routine_in_table);
1175 if (!res)
1176 return NULL;
1177
1178 func = *res;
1179 if (addr < func->address || addr >= func->address + func->length)
1180 return NULL;
1181
1182 return func;
1183 }
1184
1185 static void render_value_linebuf(glui32 val)
1186 {
1187 int tmplen;
1188 inforoutine *func;
1189 infoarray *arr;
1190 infoobject *object;
1191
1192 /* Special case for single-digit numbers: display the decimal
1193 digit and stop. */
1194 if (val < 10) {
1195 tmplen = strlen(linebuf);
1196 ensure_line_buf(tmplen+4);
1197 snprintf(linebuf+tmplen, linebufsize-tmplen, "%d", val);
1198 return;
1199 }
1200
1201 /* Always display the signed decimal and unsigned hex. */
1202 tmplen = strlen(linebuf);
1203 ensure_line_buf(tmplen+40);
1204 if (val <= 0x7FFFFFFF)
1205 snprintf(linebuf+tmplen, linebufsize-tmplen, "%d ($%X)", val, val);
1206 else
1207 snprintf(linebuf+tmplen, linebufsize-tmplen, "%d ($%X)", -(int)(0x100000000-val), val);
1208
1209 /* If the address of a function, display it. (But not addresses in
1210 the middle of a function.) */
1211 func = find_routine_for_address(val);
1212 if (func) {
1213 if (val == func->address) {
1214 tmplen = strlen(linebuf);
1215 ensure_line_buf(tmplen+40);
1216 snprintf(linebuf+tmplen, linebufsize-tmplen, ", %s()", func->identifier);
1217 }
1218 }
1219
1220 /* If the address of an array, display it. */
1221 arr = find_array_for_address(val);
1222 if (arr) {
1223 if (val == arr->address) {
1224 tmplen = strlen(linebuf);
1225 ensure_line_buf(tmplen+40);
1226 snprintf(linebuf+tmplen, linebufsize-tmplen, ", %s[%d]", arr->identifier, arr->count);
1227 }
1228 }
1229
1230 /* If the address of an object, display it. */
1231 object = find_object_for_address(val);
1232 if (object) {
1233 if (val == object->address) {
1234 tmplen = strlen(linebuf);
1235 ensure_line_buf(tmplen+40);
1236 snprintf(linebuf+tmplen, linebufsize-tmplen, ", %s", object->identifier);
1237 }
1238 }
1239 }
1240
1241 static void debugcmd_backtrace(int wholestack)
1242 {
1243 if (stack) {
1244 glui32 curpc = pc;
1245 glui32 curframeptr = frameptr;
1246 glui32 curstackptr = stackptr;
1247 glui32 curvalstackbase = valstackbase;
1248 glui32 curlocalsbase = localsbase;
1249
1250 ensure_line_buf(256);
1251
1252 while (1) {
1253 glui32 locptr;
1254 int locnum;
1255 glui32 newframeptr;
1256 glui32 newpc;
1257
1258 inforoutine *routine = find_routine_for_address(curpc);
1259 if (!routine)
1260 snprintf(linebuf, linebufsize, "- %s() (pc=$%.2X)", "???", curpc);
1261 else
1262 snprintf(linebuf, linebufsize, "- %s() (pc=$%.2X)", routine->identifier, curpc);
1263 gidebug_output(linebuf);
1264
1265 strcpy(linebuf, " ");
1266 /* Again, this loop assumes that all locals are 4 bytes. */
1267 for (locptr = curlocalsbase, locnum = 0; locptr < curvalstackbase; locptr += 4, locnum++) {
1268 glui32 val;
1269 int tmplen = strlen(linebuf);
1270 ensure_line_buf(tmplen+32);
1271 if (!routine || !routine->locals || locnum >= routine->numlocals)
1272 snprintf(linebuf+tmplen, linebufsize-tmplen, "%sloc#%d=", (locnum?"; ":""), locnum);
1273 else
1274 snprintf(linebuf+tmplen, linebufsize-tmplen, "%s%s=", (locnum?"; ":""), routine->locals[locnum].identifier);
1275
1276 val = Stk4(locptr);
1277 render_value_linebuf(val);
1278 }
1279 if (!locnum) {
1280 strcat(linebuf, "(no locals)");
1281 }
1282 gidebug_output(linebuf);
1283
1284 if (!wholestack)
1285 break;
1286
1287 curstackptr = curframeptr;
1288 if (curstackptr < 16)
1289 break;
1290 curstackptr -= 16;
1291 newframeptr = Stk4(curstackptr+12);
1292 newpc = Stk4(curstackptr+8);
1293 curframeptr = newframeptr;
1294 curpc = newpc;
1295 curvalstackbase = curframeptr + Stk4(curframeptr);
1296 curlocalsbase = curframeptr + Stk4(curframeptr+4);
1297 }
1298 }
1299 }
1300
1301 static void debugcmd_set_breakpoint(char *arg)
1302 {
1303 int found;
1304 glui32 addr;
1305 breakpoint *bp;
1306
1307 while (*arg == ' ')
1308 arg++;
1309
1310 if (*arg == '\0') {
1311 gidebug_output("What function do you want to set a breakpoint at?");
1312 return;
1313 }
1314
1315 found = FALSE;
1316 addr = 0;
1317
1318 if (!found) {
1319 int res = parse_numeric_constant(arg, &addr);
1320 if (res < 0)
1321 return;
1322 if (res > 0) {
1323 found = TRUE;
1324 /* If possible, check whether this looks like a function
1325 address. But if it doesn't, just print a warning. */
1326 if (debuginfo) {
1327 inforoutine *routine = find_routine_for_address(addr);
1328 if (!routine || routine->address != addr) {
1329 ensure_line_buf(128);
1330 strcpy(linebuf, "This does not look like a function address: ");
1331 render_value_linebuf(addr);
1332 gidebug_output(linebuf);
1333 }
1334 }
1335 }
1336 }
1337
1338 if (!found) {
1339 inforoutine *routine;
1340 if (!debuginfo) {
1341 gidebug_output("No debug info; cannot look up functions by name");
1342 return;
1343 }
1344 routine = xmlHashLookup(debuginfo->routines, BAD_CAST arg);
1345 if (!routine) {
1346 ensure_line_buf(128);
1347 snprintf(linebuf, linebufsize, "Not a function name: %s", arg);
1348 gidebug_output(linebuf);
1349 return;
1350 }
1351 found = TRUE;
1352 addr = routine->address;
1353 }
1354
1355 if (!found)
1356 return;
1357
1358 for (bp = funcbreakpoints; bp; bp=bp->next) {
1359 if (bp->address == addr) {
1360 ensure_line_buf(128);
1361 strcpy(linebuf, "Breakpoint is already set for function: ");
1362 render_value_linebuf(addr);
1363 gidebug_output(linebuf);
1364 return;
1365 }
1366 }
1367
1368 bp = create_breakpoint(addr);
1369 bp->next = funcbreakpoints;
1370 funcbreakpoints = bp;
1371
1372 ensure_line_buf(128);
1373 strcpy(linebuf, "Breakpoint set for function: ");
1374 render_value_linebuf(addr);
1375 gidebug_output(linebuf);
1376 }
1377
1378 static void debugcmd_clear_breakpoint(char *arg)
1379 {
1380 int found;
1381 glui32 addr;
1382 breakpoint **bpp;
1383
1384 while (*arg == ' ')
1385 arg++;
1386
1387 if (*arg == '\0') {
1388 gidebug_output("What function do you want to clear a breakpoint at?");
1389 return;
1390 }
1391
1392 found = FALSE;
1393 addr = 0;
1394
1395 if (!found) {
1396 int res = parse_numeric_constant(arg, &addr);
1397 if (res < 0)
1398 return;
1399 if (res > 0) {
1400 found = TRUE;
1401 /* If possible, check whether this looks like a function
1402 address. But if it doesn't, just print a warning. */
1403 if (debuginfo) {
1404 inforoutine *routine = find_routine_for_address(addr);
1405 if (!routine || routine->address != addr) {
1406 ensure_line_buf(128);
1407 strcpy(linebuf, "This does not look like a function address: ");
1408 render_value_linebuf(addr);
1409 gidebug_output(linebuf);
1410 }
1411 }
1412 }
1413 }
1414
1415 if (!found) {
1416 inforoutine *routine;
1417 if (!debuginfo) {
1418 gidebug_output("No debug info; cannot look up functions by name");
1419 return;
1420 }
1421 routine = xmlHashLookup(debuginfo->routines, BAD_CAST arg);
1422 if (!routine) {
1423 ensure_line_buf(128);
1424 snprintf(linebuf, linebufsize, "Not a function name: %s", arg);
1425 gidebug_output(linebuf);
1426 return;
1427 }
1428 found = TRUE;
1429 addr = routine->address;
1430 }
1431
1432 if (!found)
1433 return;
1434
1435 for (bpp = &funcbreakpoints; *bpp; bpp=&((*bpp)->next)) {
1436 if ((*bpp)->address == addr) {
1437 breakpoint *bp = *bpp;
1438 *bpp = bp->next;
1439 free(bp);
1440 ensure_line_buf(128);
1441 strcpy(linebuf, "Cleared breakpoint for function: ");
1442 render_value_linebuf(addr);
1443 gidebug_output(linebuf);
1444 return;
1445 }
1446 }
1447
1448 ensure_line_buf(128);
1449 strcpy(linebuf, "No breakpoint found for function: ");
1450 render_value_linebuf(addr);
1451 gidebug_output(linebuf);
1452 }
1453
1454 static void debugcmd_print(char *arg)
1455 {
1456 ensure_line_buf(128); /* for a start */
1457
1458 while (*arg == ' ')
1459 arg++;
1460
1461 if (*arg == '\0') {
1462 gidebug_output("What do you want to print?");
1463 return;
1464 }
1465
1466 /* For plain numbers, and $HEX numbers, we print the value directly. */
1467
1468 {
1469 glui32 val = 0;
1470 int res = parse_numeric_constant(arg, &val);
1471 if (res < 0)
1472 return;
1473 if (res > 0) {
1474 strcpy(linebuf, "");
1475 render_value_linebuf(val);
1476 gidebug_output(linebuf);
1477 return;
1478 }
1479 }
1480
1481 /* Symbol recognition should be case-insensitive */
1482
1483 /* Is it a local variable name? */
1484 if (debuginfo) {
1485 glui32 curpc = pc;
1486 glui32 curlocalsbase = localsbase;
1487 /* Should have a way to trawl up and down the stack. */
1488 inforoutine *routine = find_routine_for_address(curpc);
1489 if (routine && routine->locals) {
1490 int ix;
1491 for (ix=0; ix<routine->numlocals; ix++) {
1492 if (!xmlStrcmp(routine->locals[ix].identifier, BAD_CAST arg)) {
1493 glui32 locptr = curlocalsbase + 4*ix;
1494 glui32 val = Stk4(locptr);
1495 snprintf(linebuf, linebufsize, "local %s = ", routine->locals[ix].identifier);
1496 render_value_linebuf(val);
1497 gidebug_output(linebuf);
1498 return;
1499 }
1500 }
1501 }
1502 }
1503
1504 /* Is it a constant name? */
1505 if (debuginfo) {
1506 infoconstant *cons = xmlHashLookup(debuginfo->constants, BAD_CAST arg);
1507 if (cons) {
1508 snprintf(linebuf, linebufsize, "%d ($%X): constant", cons->value, cons->value);
1509 gidebug_output(linebuf);
1510 return;
1511 }
1512 }
1513
1514 /* Is it an attribute name? */
1515 if (debuginfo) {
1516 infoconstant *cons = xmlHashLookup(debuginfo->attributes, BAD_CAST arg);
1517 if (cons) {
1518 snprintf(linebuf, linebufsize, "%d ($%X): attribute", cons->value, cons->value);
1519 gidebug_output(linebuf);
1520 return;
1521 }
1522 }
1523
1524 /* Is it a property name? */
1525 if (debuginfo) {
1526 infoconstant *cons = xmlHashLookup(debuginfo->properties, BAD_CAST arg);
1527 if (cons) {
1528 snprintf(linebuf, linebufsize, "%d ($%X): property", cons->value, cons->value);
1529 gidebug_output(linebuf);
1530 return;
1531 }
1532 }
1533
1534 /* Is it an object name? */
1535 if (debuginfo) {
1536 infoobject *cons = xmlHashLookup(debuginfo->objects, BAD_CAST arg);
1537 if (cons) {
1538 snprintf(linebuf, linebufsize, "%d ($%X): object", cons->address, cons->address);
1539 gidebug_output(linebuf);
1540 return;
1541 }
1542 }
1543
1544 /* Is it an array name? */
1545 if (debuginfo) {
1546 infoarray *arr = xmlHashLookup(debuginfo->arrays, BAD_CAST arg);
1547 if (arr) {
1548 snprintf(linebuf, linebufsize, "%d ($%X): array[%d] of %d-byte values", arr->address, arr->address, arr->count, arr->bytesize);
1549 gidebug_output(linebuf);
1550 return;
1551 }
1552 }
1553
1554 /* Is it a global name? */
1555 if (debuginfo) {
1556 infoconstant *cons = xmlHashLookup(debuginfo->globals, BAD_CAST arg);
1557 if (cons) {
1558 glui32 val = Mem4(cons->value);
1559 snprintf(linebuf, linebufsize, "global %s = ", cons->identifier);
1560 render_value_linebuf(val);
1561 gidebug_output(linebuf);
1562 return;
1563 }
1564 }
1565
1566 /* Is it a routine name? */
1567 if (debuginfo) {
1568 inforoutine *routine = xmlHashLookup(debuginfo->routines, BAD_CAST arg);
1569 if (routine) {
1570 snprintf(linebuf, linebufsize, "%d ($%X): routine", routine->address, routine->address);
1571 gidebug_output(linebuf);
1572 return;
1573 }
1574 }
1575
1576 gidebug_output("Symbol not found");
1577 }
1578
1579 static void debugcmd_help(char *arg)
1580 {
1581 gidebug_output("Glulxe built-in debugger. Commands:");
1582 gidebug_output("- print <val>: Print a symbol or number.");
1583 gidebug_output("- bt: Display the current stack backtrace, with local variables.");
1584 gidebug_output("- break <func>: Set a breakpoint. (Must be a function name or the address of a function. Breakpoints currently only work at the start of a function.)");
1585 gidebug_output("- clear <func>: Clear a breakpoint.");
1586 gidebug_output("- cont: Continue execution. (From a breakpoint or other trap.)");
1587 gidebug_output("- help/?: This list.");
1588 }
1589
1590 /* Debug console callback: This is invoked whenever the user enters a debug
1591 command.
1592 Returns 0 for most commands, 1 if the command ends a debugger pause.
1593 */
1594 int debugger_cmd_handler(char *cmd)
1595 {
1596 int len;
1597 char *cx;
1598
1599 /* Trim spaces from start */
1600 while (*cmd == ' ')
1601 cmd++;
1602 /* Trim spaces from end */
1603 len = strlen(cmd);
1604 while (len > 0 && cmd[len-1] == ' ') {
1605 cmd[len-1] = '\0';
1606 len--;
1607 }
1608
1609 if (*cmd == '\0')
1610 return 0; /* empty command */
1611
1612 for (cx=cmd; *cx && *cx != ' '; cx++) { }
1613 len = (cx - cmd);
1614
1615 if (len == 2 && !strncmp(cmd, "bt", len)) {
1616 debugcmd_backtrace(1);
1617 return 0;
1618 }
1619
1620 if (len == 5 && !strncmp(cmd, "print", len)) {
1621 debugcmd_print(cx);
1622 return 0;
1623 }
1624
1625 if (len == 5 && !strncmp(cmd, "break", len)) {
1626 debugcmd_set_breakpoint(cx);
1627 return 0;
1628 }
1629
1630 if (len == 5 && !strncmp(cmd, "clear", len)) {
1631 debugcmd_clear_breakpoint(cx);
1632 return 0;
1633 }
1634
1635 if (len == 4 && !strncmp(cmd, "cont", len)) {
1636 gidebug_output("Continuing...");
1637 return 1;
1638 }
1639
1640 if (len == 4 && !strncmp(cmd, "help", len)) {
1641 debugcmd_help(cx);
1642 return 0;
1643 }
1644
1645 if (len == 1 && !strncmp(cmd, "?", len)) {
1646 debugcmd_help(cx);
1647 return 0;
1648 }
1649
1650 ensure_line_buf(strlen(cmd) + 64);
1651 snprintf(linebuf, linebufsize, "Unknown debug command: %s", cmd);
1652 gidebug_output(linebuf);
1653 return 0;
1654 }
1655
1656 /* Debug console callback: This is invoked when the game starts, when it
1657 ends, and when each input cycle begins and ends.
1658
1659 We take this opportunity to report CPU usage, if the track_cpu flag
1660 is set.
1661 */
1662 void debugger_cycle_handler(int cycle)
1663 {
1664 struct timeval now;
1665 double diff;
1666
1667 debugger_invoked = TRUE;
1668
1669 if (track_cpu) {
1670 switch (cycle) {
1671
1672 case gidebug_cycle_Start:
1673 debugger_opcount = 0;
1674 gettimeofday(&debugger_timer, NULL);
1675 break;
1676
1677 case gidebug_cycle_InputWait:
1678 case gidebug_cycle_DebugPause:
1679 gettimeofday(&now, NULL);
1680 diff = (now.tv_sec - debugger_timer.tv_sec) * 1000.0 + (now.tv_usec - debugger_timer.tv_usec) / 1000.0;
1681 ensure_line_buf(64);
1682 snprintf(linebuf, linebufsize, "VM: %ld cycles in %.3f ms", debugger_opcount, diff);
1683 gidebug_output(linebuf);
1684 break;
1685
1686 case gidebug_cycle_InputAccept:
1687 case gidebug_cycle_DebugUnpause:
1688 debugger_opcount = 0;
1689 gettimeofday(&debugger_timer, NULL);
1690 break;
1691
1692 }
1693 }
1694 }
1695
1696 /* Do any start-time setup. This is called after VM memory is loaded,
1697 but before execution begins.
1698 */
1699 void debugger_setup_start_state(void)
1700 {
1701 if (start_trap) {
1702 /* Block and debug right now. This doesn't install a trap, it
1703 just calls gidebug_pause() directly. */
1704 gidebug_output("Break at start:");
1705 debugcmd_backtrace(0);
1706 gidebug_pause();
1707 }
1708 }
1709
1710 /* Check whether we've set a breakpoint at this function address.
1711 If so, block and debug.
1712 */
1713 void debugger_check_func_breakpoint(glui32 addr)
1714 {
1715 int pause = FALSE;
1716 breakpoint *bp;
1717
1718 for (bp = funcbreakpoints; bp; bp=bp->next) {
1719 if (bp->address == addr) {
1720 pause = TRUE;
1721 break;
1722 }
1723 }
1724
1725 if (pause) {
1726 gidebug_output("Breakpoint:");
1727 debugcmd_backtrace(0);
1728 gidebug_pause();
1729 }
1730 }
1731
1732 /* Invoke the library's debug-block mechanism.
1733 */
1734 void debugger_block_and_debug(char *msg)
1735 {
1736 gidebug_output(msg);
1737 gidebug_pause();
1738 }
1739
1740 /* If the quit-trap preference is set, enter debug mode.
1741 */
1742 void debugger_handle_quit()
1743 {
1744 if (quit_trap) {
1745 gidebug_output("Quit trap, pausing...");
1746 debugcmd_backtrace(0);
1747 gidebug_pause();
1748 }
1749 }
1750
1751 /* Report a fatal error to the debug console, along with the current
1752 stack trace. Depending on preferences, we may then enter full-on debug mode.
1753 */
1754 void debugger_handle_crash(char *msg)
1755 {
1756 char *prefix = "Glulxe fatal error: ";
1757 ensure_line_buf(strlen(prefix) + strlen(msg));
1758 strcpy(linebuf, prefix);
1759 strcat(linebuf, msg);
1760 gidebug_output(linebuf);
1761
1762 debugcmd_backtrace(1);
1763
1764 if (crash_trap) {
1765 gidebug_pause();
1766 }
1767 }
1768
1769
1770 #endif /* VM_DEBUGGER */