6d1db284536556a87efa4caee90c04d3fe0b8607
[libfirm] / ir / debug / debugger.c
1 /*
2  * Copyright (C) 1995-2010 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief     Helper function for integrated debug support
23  * @author    Michael Beck
24  * @date      2005
25  */
26 #include "config.h"
27
28 #ifdef DEBUG_libfirm
29
30 #ifdef _WIN32
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33 #endif
34
35 #include "debugger.h"
36
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <signal.h>
40 #include <string.h>
41 #include <strings.h>
42
43 #include <ctype.h>
44
45 #include "set.h"
46 #include "ident.h"
47 #include "irhooks.h"
48 #include "irgraph_t.h"
49 #include "entity_t.h"
50 #include "irprintf.h"
51 #include "irdump.h"
52 #include "iredges_t.h"
53 #include "debug.h"
54 #include "error.h"
55 #include "util.h"
56
57 #ifdef _WIN32
58 /* Break into the debugger. The Win32 way. */
59 void firm_debug_break(void)
60 {
61         DebugBreak();
62 }
63 #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64))
64 /* Break into the debugger. The ia32/x86_64 way under GCC. */
65 void firm_debug_break(void)
66 {
67         __asm__ __volatile__("int3");
68 }
69 #else
70 /* Break into the debugger. Poor Unix way. */
71 void firm_debug_break(void)
72 {
73         raise(SIGINT);
74 }
75 #endif /* _WIN32 */
76
77 /** supported breakpoint kinds */
78 typedef enum {
79         BP_NR    = 'n',   /**< break on node number. */
80         BP_IDENT = 'i'    /**< break on ident. */
81 } bp_kind;
82
83 /**
84  * Reasons for node number breakpoints.
85  */
86 typedef enum bp_reasons_t {
87         BP_ON_NEW_THING,   /**< break if node, entity or type with number is created */
88         BP_ON_REPLACE,     /**< break if node with number is replaced */
89         BP_ON_LOWER,       /**< break if node with number is lowered */
90         BP_ON_REMIRG,      /**< break if an IRG is removed */
91         BP_ON_NEW_ENT,     /**< break if a new entity is created */
92         BP_MAX_REASON
93 } bp_reasons_t;
94
95 /** A breakpoint. */
96 typedef struct breakpoint {
97         bp_kind      kind;        /**< the kind of this break point */
98         unsigned     bpnr;        /**< break point number */
99         int          active;      /**< non-zero, if this break point is active */
100         bp_reasons_t reason;      /**< reason for the breakpoint */
101         struct breakpoint *next; /**< link to the next one */
102 } breakpoint;
103
104 /** A number breakpoint. */
105 typedef struct {
106         breakpoint   bp;       /**< the breakpoint data */
107         long         nr;       /**< the node number */
108 } bp_nr_t;
109
110 /** Calculate the hash value for a node breakpoint. */
111 #define HASH_NR_BP(key) (((key).nr << 2) ^ (key).bp.reason)
112
113 /** An ident breakpoint. */
114 typedef struct {
115         breakpoint   bp;       /**< the breakpoint data */
116         ident        *id;      /**< the ident */
117 } bp_ident_t;
118
119 /** Calculate the hash value for an ident breakpoint. */
120 #define HASH_IDENT_BP(key) (hash_ptr((key).id) ^ (key).bp.reason)
121
122 /** The set containing the breakpoints on node numbers. */
123 static set *bp_numbers;
124
125 /** The set containing the breakpoints on idents. */
126 static set *bp_idents;
127
128 /**< the list of all breakpoints */
129 static breakpoint *bp_list;
130
131 /** number of the current break point */
132 static unsigned bp_num = 0;
133
134 /** set if break on init command was issued. */
135 static int break_on_init = 0;
136
137 /** the hook entries for the Firm debugger module. */
138 static hook_entry_t debugger_hooks[hook_last];
139
140 /** number of active breakpoints to maintain hooks. */
141 static unsigned num_active_bp[BP_MAX_REASON];
142
143 /**
144  * The debug message buffer
145  */
146 static char firm_dbg_msg_buf[2048];
147
148 /**
149  * If set, the debug extension writes all output to the
150  * firm_dbg_msg_buf buffer
151  */
152 static int redir_output = 0;
153
154 /**
155  * Is set to one, if the debug extension is active
156  */
157 static int is_active = 0;
158
159 /** hook the hook h with function fkt. */
160 #define HOOK(h, fkt) \
161 do {                                      \
162         debugger_hooks[h].hook._##h = fkt;    \
163         register_hook(h, &debugger_hooks[h]); \
164 } while (0)
165
166 /** unhook the hook h */
167 #define UNHOOK(h) \
168 do {                                        \
169         unregister_hook(h, &debugger_hooks[h]); \
170         debugger_hooks[h].hook._##h = NULL;     \
171 } while (0)
172
173 /** returns non-zero if a entry hook h is used */
174 #define IS_HOOKED(h) (debugger_hooks[h].hook._##h != NULL)
175
176 /* some macros needed to create the info string */
177 #define _DBG_VERSION(major, minor)  #major "." #minor
178 #define DBG_VERSION(major, minor)   _DBG_VERSION(major, minor)
179 #define API_VERSION(major, minor)   "API:" DBG_VERSION(major, minor)
180
181 /* the API version: change if needed */
182 #define FIRM_DBG_MAJOR  1
183 #define FIRM_DBG_MINOR  0
184
185 /** for automatic detection of the debug extension */
186 static const char __attribute__((used)) firm_debug_info_string[] =
187         API_VERSION(FIRM_DBG_MAJOR, FIRM_DBG_MINOR);
188
189 int firm_debug_active(void)
190 {
191         return is_active;
192 }
193
194 /**
195  * Reset the debug text buffer.
196  */
197 static void reset_dbg_buf(void)
198 {
199         firm_dbg_msg_buf[0] = '\0';
200 }
201
202 static void add_to_dbg_buf(const char *buf)
203 {
204         strncat(firm_dbg_msg_buf, buf, sizeof(firm_dbg_msg_buf));
205 }
206
207 const char *firm_debug_text(void)
208 {
209         firm_dbg_msg_buf[sizeof(firm_dbg_msg_buf) - 1] = '\0';
210         return firm_dbg_msg_buf;
211 }
212
213 /**
214  * debug output
215  */
216 static void dbg_printf(const char *fmt, ...)
217 {
218         static char buf[2048];
219
220         va_list args;
221         va_start(args, fmt);
222
223         if (fmt[0] != '+')
224                 reset_dbg_buf();
225         else
226                 ++fmt;
227
228         ir_vsnprintf(buf, sizeof(buf), fmt, args);
229         va_end(args);
230
231         if (redir_output)
232                 add_to_dbg_buf(buf);
233         else
234                 puts(buf);
235 }
236
237 /**
238  * A new node is created.
239  *
240  * @param ctx   the hook context
241  * @param irg   the IR graph on which the node is created
242  * @param node  the new IR node that was created
243  */
244 static void dbg_new_node(void *ctx, ir_graph *irg, ir_node *node)
245 {
246         bp_nr_t key, *elem;
247         (void) ctx;
248         (void) irg;
249
250         key.nr        = get_irn_node_nr(node);
251         key.bp.reason = BP_ON_NEW_THING;
252
253         elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
254         if (elem && elem->bp.active) {
255                 dbg_printf("Firm BP %u reached, %+F created\n", elem->bp.bpnr, node);
256                 firm_debug_break();
257         }
258 }
259
260 /**
261  * A node is replaced.
262  *
263  * @param ctx   the hook context
264  * @param old   the IR node the is replaced
265  * @param nw    the new IR node that will replace old
266  */
267 static void dbg_replace(void *ctx, ir_node *old, ir_node *nw)
268 {
269         bp_nr_t key, *elem;
270         (void) ctx;
271
272         key.nr        = get_irn_node_nr(old);
273         key.bp.reason = BP_ON_REPLACE;
274
275         elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
276         if (elem && elem->bp.active) {
277                 dbg_printf("Firm BP %u reached, %+F will be replaced by %+F\n", elem->bp.bpnr, old, nw);
278                 firm_debug_break();
279         }
280 }
281
282 /**
283  * A new node is lowered.
284  *
285  * @param ctx   the hook context
286  * @param node  the new IR node that will be lowered
287  */
288 static void dbg_lower(void *ctx, ir_node *node)
289 {
290         bp_nr_t key, *elem;
291         (void) ctx;
292
293         key.nr        = get_irn_node_nr(node);
294         key.bp.reason = BP_ON_LOWER;
295
296         elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
297         if (elem && elem->bp.active) {
298                 dbg_printf("Firm BP %u reached, %+F will be lowered\n", elem->bp.bpnr, node);
299                 firm_debug_break();
300         }
301 }
302
303 /**
304  * A graph will be deleted.
305  *
306  * @param ctx   the hook context
307  * @param irg   the IR graph that will be deleted
308  */
309 static void dbg_free_graph(void *ctx, ir_graph *irg)
310 {
311         (void) ctx;
312         {
313                 bp_nr_t key, *elem;
314                 key.nr        = get_irg_graph_nr(irg);
315                 key.bp.reason = BP_ON_REMIRG;
316
317                 elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
318                 if (elem && elem->bp.active) {
319                         ir_printf("Firm BP %u reached, %+F will be deleted\n", elem->bp.bpnr, irg);
320                         firm_debug_break();
321                 }
322         }
323         {
324                 bp_ident_t key, *elem;
325                 ir_entity *ent = get_irg_entity(irg);
326
327                 if (! ent)
328                         return;
329
330                 key.id        = get_entity_ident(ent);
331                 key.bp.reason = BP_ON_REMIRG;
332
333                 elem = (bp_ident_t*)set_find(bp_idents, &key, sizeof(key), HASH_IDENT_BP(key));
334                 if (elem && elem->bp.active) {
335                         dbg_printf("Firm BP %u reached, %+F will be deleted\n", elem->bp.bpnr, ent);
336                         firm_debug_break();
337                 }
338         }
339 }
340
341 /**
342  * An entity was created.
343  *
344  * @param ctx   the hook context
345  * @param ent   the newly created entity
346  */
347 static void dbg_new_entity(void *ctx, ir_entity *ent)
348 {
349         (void) ctx;
350         {
351                 bp_ident_t key, *elem;
352
353                 key.id        = get_entity_ident(ent);
354                 key.bp.reason = BP_ON_NEW_ENT;
355
356                 elem = (bp_ident_t*)set_find(bp_idents, &key, sizeof(key), HASH_IDENT_BP(key));
357                 if (elem && elem->bp.active) {
358                         ir_printf("Firm BP %u reached, %+F was created\n", elem->bp.bpnr, ent);
359                         firm_debug_break();
360                 }
361         }
362         {
363                 bp_nr_t key, *elem;
364
365                 key.nr        = get_entity_nr(ent);
366                 key.bp.reason = BP_ON_NEW_THING;
367
368                 elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
369                 if (elem && elem->bp.active) {
370                         dbg_printf("Firm BP %u reached, %+F was created\n", elem->bp.bpnr, ent);
371                         firm_debug_break();
372                 }
373         }
374 }
375
376 /**
377  * A type was created.
378  *
379  * @param ctx   the hook context
380  * @param tp    the newly created type
381  */
382 static void dbg_new_type(void *ctx, ir_type *tp)
383 {
384         (void) ctx;
385         {
386                 bp_nr_t key, *elem;
387
388                 key.nr        = get_type_nr(tp);
389                 key.bp.reason = BP_ON_NEW_THING;
390
391                 elem = (bp_nr_t*)set_find(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
392                 if (elem && elem->bp.active) {
393                         ir_printf("Firm BP %u reached, %+F was created\n", elem->bp.bpnr, tp);
394                         firm_debug_break();
395                 }
396         }
397 }
398
399 /**
400  * Return the reason string.
401  */
402 static const char *reason_str(bp_reasons_t reason)
403 {
404         switch (reason) {
405         case BP_ON_NEW_THING: return "node, entity or type creation";
406         case BP_ON_REPLACE:   return "node replace";
407         case BP_ON_LOWER:     return "node lowering";
408         case BP_ON_REMIRG:    return "removing IRG";
409         case BP_ON_NEW_ENT:   return "entity creation";
410         case BP_MAX_REASON:   break;
411         }
412         panic("unsupported reason");
413 }
414
415 /**
416  * Compare two number breakpoints.
417  */
418 static int cmp_nr_bp(const void *elt, const void *key, size_t size)
419 {
420         const bp_nr_t *e1 = (const bp_nr_t*)elt;
421         const bp_nr_t *e2 = (const bp_nr_t*)key;
422         (void) size;
423
424         return (e1->nr - e2->nr) | (e1->bp.reason - e2->bp.reason);
425 }
426
427 /**
428  * Compare two ident breakpoints.
429  */
430 static int cmp_ident_bp(const void *elt, const void *key, size_t size)
431 {
432         const bp_ident_t *e1 = (const bp_ident_t*)elt;
433         const bp_ident_t *e2 = (const bp_ident_t*)key;
434         (void) size;
435
436         return (e1->id != e2->id) | (e1->bp.reason - e2->bp.reason);
437 }
438
439 /**
440  * Update the hooks.
441  */
442 static void update_hooks(breakpoint *bp)
443 {
444 #define CASE_ON(a, hook, handler)  case a: if (! IS_HOOKED(hook)) HOOK(hook, handler); break
445 #define CASE_OFF(a, hook) case a: if (IS_HOOKED(hook)) UNHOOK(hook); break
446
447         if (bp->active)
448                 ++num_active_bp[bp->reason];
449         else
450                 --num_active_bp[bp->reason];
451
452         if (num_active_bp[bp->reason] > 0) {
453                 /* register the hooks on demand */
454                 switch (bp->reason) {
455                 CASE_ON(BP_ON_REPLACE, hook_replace,    dbg_replace);
456                 CASE_ON(BP_ON_LOWER,   hook_lower,      dbg_lower);
457                 CASE_ON(BP_ON_REMIRG,  hook_free_graph, dbg_free_graph);
458                 CASE_ON(BP_ON_NEW_ENT, hook_new_entity, dbg_new_entity);
459                 case BP_ON_NEW_THING:
460                         if (!IS_HOOKED(hook_new_node))
461                                 HOOK(hook_new_node, dbg_new_node);
462                         if (!IS_HOOKED(hook_new_type))
463                                 HOOK(hook_new_type, dbg_new_type);
464                         if (!IS_HOOKED(hook_new_entity))
465                                 HOOK(hook_new_entity, dbg_new_entity);
466                         break;
467                 default:
468                         break;
469                 }
470         }
471         else {
472                 /* unregister the hook on demand */
473                 switch (bp->reason) {
474                 CASE_OFF(BP_ON_REPLACE,  hook_replace);
475                 CASE_OFF(BP_ON_LOWER,    hook_lower);
476                 CASE_OFF(BP_ON_REMIRG,   hook_free_graph);
477                 CASE_OFF(BP_ON_NEW_ENT,  hook_new_entity);
478                 case BP_ON_NEW_THING:
479                         if (IS_HOOKED(hook_new_node))
480                                 UNHOOK(hook_new_node);
481                         if (IS_HOOKED(hook_new_type))
482                                 UNHOOK(hook_new_type);
483                         if (IS_HOOKED(hook_new_entity))
484                                 UNHOOK(hook_new_entity);
485                         break;
486                 default:
487                         break;
488                 }
489         }
490 #undef CASE_ON
491 #undef CASE_OFF
492 }
493
494 /**
495  * Break if nr is reached.
496  */
497 static void break_on_nr(long nr, bp_reasons_t reason)
498 {
499         bp_nr_t key, *elem;
500
501         key.bp.kind   = BP_NR;
502         key.bp.bpnr   = 0;
503         key.bp.active = 1;
504         key.bp.reason = reason;
505         key.nr        = nr;
506
507         elem = (bp_nr_t*)set_insert(bp_numbers, &key, sizeof(key), HASH_NR_BP(key));
508
509         if (elem->bp.bpnr == 0) {
510                 /* new break point */
511                 elem->bp.bpnr = ++bp_num;
512                 elem->bp.next = bp_list;
513                 bp_list = &elem->bp;
514
515                 dbg_printf("Firm BP %u: %s of Nr %ld\n", elem->bp.bpnr, reason_str(reason), nr);
516
517                 update_hooks(&elem->bp);
518         }
519 }
520
521 /**
522  * Break if ident name is reached.
523  */
524 static void break_on_ident(const char *name, bp_reasons_t reason)
525 {
526         bp_ident_t key, *elem;
527
528         key.bp.kind   = BP_IDENT;
529         key.bp.bpnr   = 0;
530         key.bp.active = 1;
531         key.bp.reason = reason;
532         key.id        = new_id_from_str(name);
533
534         elem = (bp_ident_t*)set_insert(bp_idents, &key, sizeof(key), HASH_IDENT_BP(key));
535
536         if (elem->bp.bpnr == 0) {
537                 /* new break point */
538                 elem->bp.bpnr = ++bp_num;
539                 elem->bp.next = bp_list;
540                 bp_list = &elem->bp;
541
542                 dbg_printf("Firm BP %u: %s of ident \"%s\"\n", elem->bp.bpnr, reason_str(reason), name);
543
544                 update_hooks(&elem->bp);
545         }
546 }
547
548 /**
549  * Sets/resets the active flag of breakpoint bp.
550  */
551 static void bp_activate(unsigned bp, int active)
552 {
553         breakpoint *p;
554
555         for (p = bp_list; p; p = p->next) {
556                 if (p->bpnr == bp) {
557                         if (p->active != active) {
558                                 p->active = active;
559                                 update_hooks(p);
560                         }
561
562                         dbg_printf("Firm BP %u is now %s\n", bp, active ? "enabled" : "disabled");
563                         return;
564                 }
565         }
566         dbg_printf("Error: Firm BP %u not exists.\n", bp);
567 }
568
569
570 /**
571  * Show a list of supported commands
572  */
573 static void show_commands(void)
574 {
575         dbg_printf("Internal Firm debugger extension commands:\n"
576                 "init                  break after initialization\n"
577                 "create nr             break if node nr was created\n"
578                 "replace nr            break if node nr is replaced by another node\n"
579                 "lower nr              break before node nr is lowered\n"
580                 "remirg nr|name        break if the irg of nr or entity name is deleted\n"
581                 "newent nr|name        break if the entity nr or name was created\n"
582                 "newtype nr|name       break if the type nr or name was created\n"
583                 "bp                    show all breakpoints\n"
584                 "enable nr             enable breakpoint nr\n"
585                 "disable nr            disable breakpoint nr\n"
586                 "showtype nr|name      show content of the type nr or name\n"
587                 "showent nr|name       show content of the entity nr or name\n"
588                 "setmask name msk      sets the debug module name to mask msk\n"
589                 "setlvl  name lvl      sets the debug module name to level lvl\n"
590                 "setoutfile name file  redirects debug output of module name to file\n"
591                 "irgname name          prints address and graph number of a method given by its name\n"
592                 "irgldname ldname      prints address and graph number of a method given by its ldname\n"
593                 "help                  list all commands\n"
594                 );
595 }
596
597 /**
598  * Shows all Firm breakpoints.
599  */
600 static void show_bp(void)
601 {
602         breakpoint *p;
603         bp_nr_t  *node_p;
604         bp_ident_t *ident_p;
605         int have_one = 0;
606
607         dbg_printf("Firm Breakpoints:");
608         for (p = bp_list; p; p = p->next) {
609                 have_one = 1;
610                 dbg_printf("+\n  BP %u: ", p->bpnr);
611
612                 switch (p->kind) {
613                 case BP_NR:
614                         node_p = (bp_nr_t *)p;
615                         dbg_printf("%s of Nr %ld ", reason_str(p->reason), node_p->nr);
616                         break;
617
618                 case BP_IDENT:
619                         ident_p = (bp_ident_t *)p;
620                         dbg_printf("+%s of ident \"%s\" ", reason_str(p->reason), get_id_str(ident_p->id));
621                         break;
622                 }
623
624                 dbg_printf(p->active ? "+enabled" : "+disabled");
625         }
626         dbg_printf(have_one ? "+\n" : "+ NONE\n");
627 }
628
629 /**
630  * firm_dbg_register() expects that the name is stored persistent.
631  * So we need this little helper function
632  */
633 static firm_dbg_module_t *dbg_register(const char *name)
634 {
635         ident *id = new_id_from_str(name);
636
637         return firm_dbg_register(get_id_str(id));
638 }
639
640 /**
641  * Sets the debug mask of module name to lvl
642  */
643 static void set_dbg_level(const char *name, unsigned lvl)
644 {
645         firm_dbg_module_t *module = dbg_register(name);
646
647         if (firm_dbg_get_mask(module) != lvl) {
648                 firm_dbg_set_mask(module, lvl);
649
650                 dbg_printf("Setting debug mask of module %s to %u\n", name, lvl);
651         }
652 }
653
654 /**
655  * Redirects the debug output of module name to fname
656  */
657 static void set_dbg_outfile(const char *name, const char *fname)
658 {
659         firm_dbg_module_t *module = dbg_register(name);
660         FILE *f = fopen(fname, "w");
661
662         if (! f) {
663                 perror(fname);
664                 return;
665         }
666
667         firm_dbg_set_file(module, f);
668         dbg_printf("Redirecting debug output of module %s to file %s\n", name, fname);
669 }
670
671 /**
672  * Show info about a firm thing.
673  */
674 static void show_firm_object(void *firm_thing)
675 {
676         FILE *f = stdout;
677
678         if (firm_thing == NULL) {
679                 fprintf(f, "<NULL>\n");
680                 return;
681         }
682         switch (get_kind(firm_thing)) {
683         case k_BAD:
684                 fprintf(f, "BAD: (%p)\n", firm_thing);
685                 break;
686         case k_entity:
687                 dump_entity_to_file(f, (ir_entity*)firm_thing);
688                 break;
689         case k_type:
690                 dump_type_to_file(f, (ir_type*)firm_thing);
691                 break;
692         case k_ir_graph:
693         case k_ir_node:
694         case k_ir_mode:
695         case k_ir_op:
696         case k_tarval:
697         case k_ir_loop:
698         case k_ir_compound_graph_path:
699         case k_ir_extblk:
700         case k_ir_prog:
701                 fprintf(f, "NIY\n");
702                 break;
703         default:
704                 fprintf(f, "Cannot identify thing at (%p).\n", firm_thing);
705         }
706 }
707
708 /**
709  * Find a firm type by its number.
710  */
711 static ir_type *find_type_nr(long nr)
712 {
713         int i, n = get_irp_n_types();
714         ir_type *tp;
715
716         for (i = 0; i < n; ++i) {
717                 tp = get_irp_type(i);
718                 if (get_type_nr(tp) == nr)
719                         return tp;
720         }
721         tp = get_glob_type();
722         if (get_type_nr(tp) == nr)
723                 return tp;
724         return NULL;
725 }
726
727 /**
728  * Find a firm type by its name.
729  */
730 static ir_type *find_type_name(const char *name)
731 {
732         int i, n = get_irp_n_types();
733         ir_type *tp;
734
735         for (i = 0; i < n; ++i) {
736                 tp = get_irp_type(i);
737                 if (!is_compound_type(tp))
738                         continue;
739
740                 if (strcmp(get_compound_name(tp), name) == 0)
741                         return tp;
742         }
743         tp = get_glob_type();
744         if (strcmp(get_compound_name(tp), name) == 0)
745                 return tp;
746         return NULL;
747 }
748
749 /** The environment for the entity search functions. */
750 typedef struct find_env {
751         union {
752                 long        nr;   /**< the number that is searched for */
753                 const char *name; /**< the name that is searched for */
754         } u;
755         ir_entity *res;     /**< the result */
756 } find_env_t;
757
758 /**
759  * Type-walker: Find an entity with given number.
760  */
761 static void check_ent_nr(type_or_ent tore, void *ctx)
762 {
763         find_env_t *env = (find_env_t*)ctx;
764
765         if (is_entity(tore.ent)) {
766                 if (get_entity_nr(tore.ent) == env->u.nr) {
767                         env->res = tore.ent;
768                 }
769         }
770 }
771
772 /**
773  * Type-walker: Find an entity with given name.
774  */
775 static void check_ent_name(type_or_ent tore, void *ctx)
776 {
777         find_env_t *env = (find_env_t*)ctx;
778
779         if (is_entity(tore.ent))
780                 if (strcmp(get_entity_name(tore.ent), env->u.name) == 0) {
781                         env->res = tore.ent;
782                 }
783 }
784
785 /**
786  * Find a firm entity by its number.
787  */
788 static ir_entity *find_entity_nr(long nr)
789 {
790         find_env_t env;
791
792         env.u.nr = nr;
793         env.res  = NULL;
794         type_walk(check_ent_nr, NULL, &env);
795         return env.res;
796 }
797
798 /**
799  * Find a firm entity by its name.
800  */
801 static ir_entity *find_entity_name(const char *name)
802 {
803         find_env_t env;
804
805         env.u.name = name;
806         env.res    = NULL;
807         type_walk(check_ent_name, NULL, &env);
808         return env.res;
809 }
810
811 /**
812  * Search methods for a name.
813  */
814 static void show_by_name(type_or_ent tore, void *env)
815 {
816         ident *id = (ident *)env;
817
818         if (is_entity(tore.ent)) {
819                 ir_entity *ent = tore.ent;
820
821                 if (is_method_entity(ent)) {
822                         if (get_entity_ident(ent) == id) {
823                                 ir_type *owner = get_entity_owner(ent);
824                                 ir_graph *irg = get_entity_irg(ent);
825
826                                 if (owner != get_glob_type()) {
827                                         printf("%s::%s", get_compound_name(owner), get_id_str(id));
828                                 } else {
829                                         printf("%s", get_id_str(id));
830                                 }
831                                 if (irg)
832                                         printf("[%ld] (%p)\n", get_irg_graph_nr(irg), irg);
833                                 else
834                                         printf(" NULL\n");
835                         }
836                 }
837         }
838 }
839
840 /**
841  * Search methods for a ldname.
842  */
843 static void show_by_ldname(type_or_ent tore, void *env)
844 {
845         ident *id = (ident *)env;
846
847         if (is_entity(tore.ent)) {
848                 ir_entity *ent = tore.ent;
849
850                 if (is_method_entity(ent)) {
851                         if (get_entity_ld_ident(ent) == id) {
852                                 ir_type *owner = get_entity_owner(ent);
853                                 ir_graph *irg = get_entity_irg(ent);
854
855                                 if (owner != get_glob_type()) {
856                                         printf("%s::%s", get_compound_name(owner), get_id_str(id));
857                                 } else {
858                                         printf("%s", get_id_str(id));
859                                 }
860                                 if (irg)
861                                         printf("[%ld] (%p)\n", get_irg_graph_nr(irg), irg);
862                                 else
863                                         printf(" NULL\n");
864                         }
865                 }
866         }
867 }
868
869 /**
870  * prints the address and graph number of all irgs with given name
871  */
872 static void irg_name(const char *name)
873 {
874         ident *id = new_id_from_str(name);
875
876         type_walk(show_by_name, NULL, (void *)id);
877 }
878
879 /**
880  * prints the address and graph number of all irgs with given ld_name
881  */
882 static void irg_ld_name(const char *name)
883 {
884         ident *id = new_id_from_str(name);
885
886         type_walk(show_by_ldname, NULL, (void *)id);
887 }
888
889 enum tokens {
890         first_token = 256,
891         tok_bp = first_token,
892         tok_create,
893         tok_disable,
894         tok_dumpfilter,
895         tok_enable,
896         tok_help,
897         tok_init,
898         tok_irgldname,
899         tok_irgname,
900         tok_lower,
901         tok_newent,
902         tok_remirg,
903         tok_replace,
904         tok_setlvl,
905         tok_setmask,
906         tok_setoutfile,
907         tok_showent,
908         tok_showtype,
909         tok_identifier,
910         tok_number,
911         tok_eof,
912         tok_error
913 };
914
915 static const char *reserved[] = {
916         "bp",
917         "create",
918         "disable",
919         "dumpfilter",
920         "enable",
921         "help"
922         "init",
923         "irgldname",
924         "irgname",
925         "lower",
926         "newent",
927         "remirg",
928         "replace",
929         "setlvl",
930         "setmask",
931         "setoutfile",
932         "showent",
933         "showtype",
934 };
935
936 /**
937  * The Lexer data.
938  */
939 static struct lexer {
940         int has_token;        /**< set if a token is cached. */
941         unsigned cur_token;   /**< current token. */
942         unsigned number;      /**< current token attribute. */
943         const char *s;        /**< current token attribute. */
944         size_t len;           /**< current token attribute. */
945
946         const char *curr_pos;
947         const char *end_pos;
948         const char *tok_start;
949 } lexer;
950
951 /**
952  * Initialize the lexer.
953  */
954 static void init_lexer(const char *input)
955 {
956         lexer.has_token = 0;
957         lexer.curr_pos  = input;
958         lexer.end_pos   = input + strlen(input);
959 }
960
961
962 /**
963  * Get the next char from the input.
964  */
965 static char next_char(void)
966 {
967         if (lexer.curr_pos >= lexer.end_pos)
968                 return '\0';
969         return *lexer.curr_pos++;
970 }
971
972 #define unput()    if (lexer.curr_pos < lexer.end_pos) --lexer.curr_pos
973
974 #undef MIN
975 #define MIN(a, b) (a) < (b) ? (a) : (b)
976
977 /**
978  * The lexer.
979  */
980 static unsigned get_token(void)
981 {
982         char c;
983         size_t i;
984
985         /* skip white space */
986         do {
987                 c = next_char();
988         } while (c != '\0' && isspace((unsigned char)c));
989
990         lexer.tok_start = lexer.curr_pos - 1;
991         if (c == '.' || isalpha((unsigned char)c)) {
992                 /* command begins here */
993                 int         len = 0;
994                 const char* tok_start;
995
996                 do {
997                         c = next_char();
998                         ++len;
999                 } while (isgraph((unsigned char)c));
1000                 unput();
1001
1002                 tok_start = lexer.tok_start;
1003                 if (*tok_start == '.') {
1004                         ++tok_start;
1005                         --len;
1006                 }
1007                 for (i = ARRAY_SIZE(reserved); i-- != 0;) {
1008                         if (strncasecmp(tok_start, reserved[i], len) == 0 && reserved[i][len] == '\0')
1009                                 return first_token + i;
1010                 }
1011
1012                 /* identifier */
1013                 lexer.s   = lexer.tok_start;
1014                 lexer.len = lexer.curr_pos - lexer.s;
1015                 return tok_identifier;
1016         } else if (isdigit((unsigned char)c) || c == '-') {
1017                 unsigned number = 0;
1018                 unsigned sign   = 0;
1019
1020                 /* we support negative numbers as well, so one can easily set all bits with -1 */
1021                 if (c == '-') {
1022                         sign = 1;
1023                         c    = next_char();
1024                 }
1025
1026                 if (c == '0') {
1027                         c = next_char();
1028
1029                         if (c == 'x' || c == 'X') {
1030                                 for (;;) {
1031                                         c = next_char();
1032
1033                                         if (! isxdigit((unsigned char)c))
1034                                                 break;
1035                                         if (isdigit((unsigned char)c))
1036                                                 number = (number << 4) | (c - '0');
1037                                         else
1038                                                 number = (number << 4) | (toupper((unsigned char)c) - 'A' + 10);
1039                                 }
1040                                 unput();
1041                                 lexer.number = number;
1042                                 return tok_number;
1043                         }
1044                 }
1045                 for (;;) {
1046                         if (! isdigit((unsigned char)c))
1047                                 break;
1048                         number = number * 10 + (c - '0');
1049                         c = next_char();
1050                 }
1051                 unput();
1052                 lexer.number = sign ? 0 - number : number;
1053                 return tok_number;
1054         }
1055         else if (c == '\0')
1056                 return tok_eof;
1057         return c;
1058 }
1059
1060 void firm_debug(const char *cmd)
1061 {
1062         char name[1024], fname[1024];
1063         size_t len;
1064
1065         init_lexer(cmd);
1066
1067         for (;;) {
1068                 unsigned token;
1069
1070                 token = get_token();
1071
1072                 switch (token) {
1073                 case tok_eof:
1074                         goto leave;
1075
1076                 case tok_create:
1077                         token = get_token();
1078                         if (token != tok_number)
1079                                 goto error;
1080                         break_on_nr(lexer.number, BP_ON_NEW_THING);
1081                         break;
1082
1083                 case tok_replace:
1084                         token = get_token();
1085                         if (token != tok_number)
1086                                 goto error;
1087                         break_on_nr(lexer.number, BP_ON_REPLACE);
1088                         break;
1089
1090                 case tok_lower:
1091                         token = get_token();
1092                         if (token != tok_number)
1093                                 goto error;
1094                         break_on_nr(lexer.number, BP_ON_LOWER);
1095                         break;
1096
1097                 case tok_remirg:
1098                         token = get_token();
1099
1100                         if (token == tok_number)
1101                                 break_on_nr(lexer.number, BP_ON_REMIRG);
1102                         else if (token == tok_identifier) {
1103                                 len = MIN(lexer.len, 1023);
1104                                 strncpy(name, lexer.s, len);
1105                                 name[len] = '\0';
1106                                 break_on_ident(name, BP_ON_REMIRG);
1107                         } else
1108                                 goto error;
1109                         break;
1110
1111                 case tok_newent:
1112                         token = get_token();
1113
1114                         if (token == tok_number)
1115                                 break_on_nr(lexer.number, BP_ON_NEW_THING);
1116                         else if (token == tok_identifier) {
1117                                 len = MIN(lexer.len, 1023);
1118                                 strncpy(name, lexer.s, len);
1119                                 name[len] = '\0';
1120                                 break_on_ident(name, BP_ON_NEW_ENT);
1121                         } else
1122                                 goto error;
1123                         break;
1124
1125                 case tok_showtype:
1126                         token = get_token();
1127
1128                         if (token == tok_number)
1129                                 show_firm_object(find_type_nr(lexer.number));
1130                         else if (token == tok_identifier) {
1131                                 len = MIN(lexer.len, 1023);
1132                                 strncpy(name, lexer.s, len);
1133                                 name[len] = '\0';
1134                                 show_firm_object(find_type_name(name));
1135                         } else
1136                                 goto error;
1137                         break;
1138
1139                 case tok_showent:
1140                         token = get_token();
1141
1142                         if (token == tok_number)
1143                                 show_firm_object(find_entity_nr(lexer.number));
1144                         else if (token == tok_identifier) {
1145                                 len = MIN(lexer.len, 1023);
1146                                 strncpy(name, lexer.s, len);
1147                                 name[len] = '\0';
1148                                 show_firm_object(find_entity_name(name));
1149                         } else
1150                                 goto error;
1151                         break;
1152
1153                 case tok_init:
1154                         break_on_init = 1;
1155                         break;
1156
1157                 case tok_bp:
1158                         show_bp();
1159                         break;
1160
1161                 case tok_enable:
1162                         token = get_token();
1163                         if (token != tok_number)
1164                                 goto error;
1165                         bp_activate(lexer.number, 1);
1166                         break;
1167
1168                 case tok_disable:
1169                         token = get_token();
1170                         if (token != tok_number)
1171                                 goto error;
1172                         bp_activate(lexer.number, 0);
1173                         break;
1174
1175                 case tok_setmask:
1176                         token = get_token();
1177                         if (token != tok_identifier)
1178                                 goto error;
1179                         len = MIN(lexer.len, 1023);
1180                         strncpy(name, lexer.s, len);
1181                         name[len] = '\0';
1182
1183                         token = get_token();
1184                         if (token != tok_number)
1185                                 goto error;
1186                         set_dbg_level(name, lexer.number);
1187                         break;
1188
1189                 case tok_setlvl:
1190                         token = get_token();
1191                         if (token != tok_identifier)
1192                                 goto error;
1193                         len = MIN(lexer.len, 1023);
1194                         strncpy(name, lexer.s, len);
1195                         name[len] = '\0';
1196
1197                         token = get_token();
1198                         if (token != tok_number)
1199                                 goto error;
1200                         set_dbg_level(name, (1 << lexer.number) - 1);
1201                         break;
1202
1203                 case tok_setoutfile:
1204                         token = get_token();
1205                         if (token != tok_identifier)
1206                                 goto error;
1207                         len = MIN(lexer.len, 1023);
1208                         strncpy(name, lexer.s, len);
1209                         name[len] = '\0';
1210
1211                         token = get_token();
1212                         if (token != tok_identifier)
1213                                 goto error;
1214                         len = MIN(lexer.len, 1023);
1215                         strncpy(fname, lexer.s, len);
1216                         fname[len] = '\0';
1217                         set_dbg_outfile(name, fname);
1218                         break;
1219
1220                 case tok_irgname:
1221                         token = get_token();
1222                         if (token != tok_identifier)
1223                                 goto error;
1224                         len = MIN(lexer.len, 1023);
1225                         strncpy(name, lexer.s, len);
1226                         name[len] = '\0';
1227                         irg_name(name);
1228                         break;
1229
1230                 case tok_irgldname:
1231                         token = get_token();
1232                         if (token != tok_identifier)
1233                                 goto error;
1234                         len = MIN(lexer.len, 1023);
1235                         strncpy(name, lexer.s, len);
1236                         name[len] = '\0';
1237                         irg_ld_name(name);
1238                         break;
1239
1240                 case tok_dumpfilter:
1241                         token = get_token();
1242                         if (token != tok_identifier)
1243                                 goto error;
1244                         len = MIN(lexer.len, 1023);
1245                         strncpy(name, lexer.s, len);
1246                         name[len] = '\0';
1247                         ir_set_dump_filter(name);
1248                         break;
1249
1250                 case tok_help:
1251                         show_commands();
1252                         break;
1253
1254                 case tok_error:
1255                 default:
1256 error:
1257                         printf("Error: before %s\n", lexer.tok_start);
1258                         show_commands();
1259                         goto leave;
1260                 }
1261
1262                 token = get_token();
1263                 if (token == tok_eof)
1264                         break;
1265                 if (token != ';')
1266                         goto error;
1267         }
1268 leave:
1269         ;
1270 }
1271
1272 void firm_init_debugger(void)
1273 {
1274         char *env;
1275
1276         bp_numbers = new_set(cmp_nr_bp, 8);
1277         bp_idents  = new_set(cmp_ident_bp, 8);
1278
1279         env = getenv("FIRMDBG");
1280
1281         is_active = 1;
1282
1283         if (env)
1284                 firm_debug(env);
1285
1286         if (break_on_init)
1287                 firm_debug_break();
1288 }
1289
1290 void firm_finish_debugger(void)
1291 {
1292         del_set(bp_numbers);
1293         del_set(bp_idents);
1294 }
1295
1296 /**
1297  * A gdb helper function to print firm objects.
1298  */
1299 const char *gdb_node_helper(void *firm_object)
1300 {
1301         static char buf[1024];
1302         ir_snprintf(buf, sizeof(buf), "%+F", firm_object);
1303         return buf;
1304 }
1305
1306 const char *gdb_tarval_helper(void *tv_object)
1307 {
1308         static char buf[1024];
1309         ir_snprintf(buf, sizeof(buf), "%+T", tv_object);
1310         return buf;
1311 }
1312
1313 const char *gdb_out_edge_helper(const ir_node *node)
1314 {
1315         static char buf[4*1024];
1316         char *b = buf;
1317         size_t l;
1318         size_t len = sizeof(buf);
1319         const ir_edge_t *edge;
1320         foreach_out_edge(node, edge) {
1321                 ir_node *n = get_edge_src_irn(edge);
1322
1323                 ir_snprintf(b, len, "%+F  ", n);
1324                 l = strlen(b);
1325                 len -= l;
1326                 b += l;
1327         }
1328
1329         return buf;
1330 }
1331
1332 #else
1333
1334 /* some picky compiler do not allow empty files */
1335 static int __attribute__((unused)) _firm_only_that_you_can_compile_with_NDEBUG_defined;
1336
1337 #endif /* NDEBUG */
1338
1339 /**
1340  * @page debugger   The Firm debugger extension
1341  *
1342  * Firm contains a debugger extension. This allows to set debugger breakpoints
1343  * an various events.
1344  * The extension uses a text interface which can be accessed from most debuggers.
1345  * More than one command can be given separated by ';'.
1346  *
1347  * @section sec_cmd Supported commands
1348  *
1349  * Historically all debugger commands start with a dot.  This isn't needed in newer
1350  * versions, but still supported, ie the commands ".init" and "init" are equal.
1351  * The following commands are currently supported:
1352  *
1353  * @b init
1354  *
1355  * Break immediately after the debugger extension was initialized.
1356  * Typically this command is used in the environment to stop the execution
1357  * of a Firm compiler right after the initialization, like this:
1358  *
1359  * $export FIRMDBG=".init"
1360  *
1361  * @b create nr
1362  *
1363  * Break if a new IR-node with node number nr was created.
1364  * Typically used to find the place where wrong nodes are created.
1365  *
1366  * @b replace nr
1367  *
1368  * Break before IR-node with node number nr is replaced by another node.
1369  *
1370  * @b lower nr
1371  *
1372  * Break before IR-node with node number nr is lowered.
1373  *
1374  * @b remirg nr
1375  *
1376  * Break if the irg with graph number nr is deleted.
1377  *
1378  * @b remirg name
1379  *
1380  * Break if the irg of entity name is deleted.
1381  *
1382  * @b newent nr
1383  *
1384  * Break if the entity with number nr was created.
1385  *
1386  * @b newent name
1387  *
1388  * Break if the entity name was created.
1389  *
1390  * @b newtype nr
1391  *
1392  * Break if the type with number nr was created.
1393  *
1394  * @b newtype name
1395  *
1396  * Break if the type name was created.
1397  *
1398  * @b bp
1399  *
1400  * Show all Firm internal breakpoints.
1401  *
1402  * @b enable nr
1403  *
1404  * Enables breakpoint nr.
1405  *
1406  * @b disable nr
1407  *
1408  * Disables breakpoint nr.
1409  *
1410  * @b showent nr
1411  *
1412  * Show the content of entity nr.
1413  *
1414  * @b showent name
1415  *
1416  * Show the content of entity name.
1417  *
1418  * @b showtype nr
1419  *
1420  * Show the content of type nr.
1421  *
1422  * @b showtype name
1423  *
1424  * Show the content of type name.
1425  *
1426  * @b setmask name msk
1427  *
1428  * Sets the debug module name to mask msk.
1429  *
1430  * @b setlvl name lvl
1431  *
1432  * Sets the debug module name to level lvl.
1433  *
1434  * @b setoutfile name file
1435  *
1436  * Redirects debug output of module name to file.
1437  *
1438  * @b irgname name
1439  *
1440  * Prints address and graph number of a method given by its name.
1441  *
1442  * @b irgldname name
1443  *
1444  * Prints address and graph number of a method given by its linker name.
1445  *
1446  * @b help
1447  *
1448  * List all commands.
1449  *
1450  *
1451  * The Firm debugger extension can be accessed using the function firm_debug().
1452  * The following example shows how to set a creation breakpoint in GDB when
1453  * node 2101 is created.
1454  *
1455  * -# set FIRMDBG="init"
1456  * -# start gdb with your compiler
1457  * -# after gdb breaks, issue
1458  *
1459  * call firm_debug("create 2101")
1460  *
1461  * On the console the following text should be issued:
1462  *
1463  * Firm BP 1: creation of Node 2101
1464  *
1465  *
1466  * @section gdb_macro GDB macro
1467  *
1468  * Add the following to your .gdbinit file:
1469  * @code
1470  #
1471  # define firm "cmd"  Firm debugger extension
1472  #
1473  define firm
1474  call firm_debug($arg0)
1475  end
1476  * @endcode
1477  *
1478  * Then, all Firm debugger extension commands can be accessed in the gdb
1479  * console using the firm prefix, eg.:
1480  *
1481  * firm "create 2101"
1482  *
1483  * firm "help"
1484  */