style changes
[platform/upstream/ltrace.git] / dwarf_prototypes.c
1 /* Most of this is Copyright Dima Kogan <dima@secretsauce.net>
2  *
3  * Pieces of this were taken from dwarf_prototypes.c in the dwarves project.
4  * Those are Copyright (C) 2008 Arnaldo Carvalho de Melo <acme@redhat.com>.
5  *
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of version 2 of the GNU General Public License as published by the
8  * Free Software Foundation.
9  *
10  */
11 #include <stdio.h>
12 #include <elfutils/libdwfl.h>
13 #include <dwarf.h>
14 #include <stdlib.h>
15 #include <errno.h>
16 #include <string.h>
17
18 #include "config.h"
19 #include "prototype.h"
20 #include "type.h"
21 #include "param.h"
22 #include "dict.h"
23 #include "lens.h"
24 #include "lens_enum.h"
25 #include "value.h"
26 #include "expr.h"
27 #include "library.h"
28 #include "options.h"
29 #include "filter.h"
30
31
32 //#define DUMP_PROTOTYPES
33
34 #if 1
35 #define complain( die, format, ... )                                                    \
36         fprintf(stderr, "%s() die '%s' @ 0x%lx: " format "\n",          \
37                         __func__, dwarf_diename(die), dwarf_dieoffset(die),     \
38                         ##__VA_ARGS__ )
39 #else
40 #define complain( die, format, ... )
41 #endif
42
43 // A map from DIE addresses (Dwarf_Off) to type structures (struct
44 // arg_type_info*). This is created and filled in at the start of each import,
45 // and deleted when the import is complete
46 static struct dict type_hash;
47
48
49 static bool get_type(struct arg_type_info** info, Dwarf_Die* type_die);
50
51
52 #if 0
53 static bool _dump_dwarf_tree(Dwarf_Die* die, int indent)
54 {
55     while (1) {
56         fprintf(stderr, "%*sprocessing unit: 0x%02x/'%s'\n", indent*4, "",
57                dwarf_tag(die), dwarf_diename(die));
58
59         Dwarf_Die child;
60         if (dwarf_child(die, &child) == 0) {
61                         if (!_dump_dwarf_tree(&child, indent+1))
62                                 return false;
63         }
64
65         int res = dwarf_siblingof(die, die);
66         if (res == 0 ) continue;     // sibling exists
67         if (res < 0 )  return false; // error
68         break;                       // no sibling exists
69     }
70
71     return true;
72 }
73
74 static bool dump_dwarf_tree(Dwarf_Die* die)
75 {
76     return _dump_dwarf_tree( die, 0 );
77 }
78 #endif
79
80 #ifdef DUMP_PROTOTYPES
81 static bool _dump_ltrace_tree(const struct arg_type_info* info, int indent)
82 {
83         if (indent > 7) {
84                 fprintf(stderr, "%*s%p ...\n", indent*4, "", (void*)info);
85                 return true;
86         }
87
88         if (info == NULL) {
89                 fprintf(stderr, "%*s%p NULL\n", indent*4, "", (void*)info);
90                 return true;
91         }
92
93         switch (info->type) {
94         case ARGTYPE_VOID:
95                 fprintf(stderr, "%*s%p void\n", indent*4, "", (void*)info);
96                 break;
97
98         case ARGTYPE_INT:
99         case ARGTYPE_UINT:
100         case ARGTYPE_LONG:
101         case ARGTYPE_ULONG:
102         case ARGTYPE_CHAR:
103         case ARGTYPE_SHORT:
104         case ARGTYPE_USHORT:
105         case ARGTYPE_FLOAT:
106         case ARGTYPE_DOUBLE:
107                 fprintf(stderr, "%*s%p base\n", indent*4, "", (void*)info);
108                 break;
109
110         case ARGTYPE_ARRAY:
111                 fprintf(stderr, "%*s%p array. elements not printed\n", indent*4, "",
112                                 (void*)info);
113                 break;
114
115         case ARGTYPE_POINTER:
116                 fprintf(stderr, "%*s%p pointer to...\n", indent*4, "", (void*)info);
117                 _dump_ltrace_tree( info->u.ptr_info.info, indent+1 );
118                 break;
119
120         case ARGTYPE_STRUCT:
121                 fprintf(stderr, "%*s%p struct...\n", indent*4, "", (void*)info);
122                 struct struct_field
123                 {
124                         struct arg_type_info *info;
125                         int own_info;
126                 }* elements = (struct struct_field*)info->u.entries.data;
127                 unsigned int i;
128                 for(i=0; i<info->u.entries.size; i++)
129                         _dump_ltrace_tree( elements[i].info, indent+1 );
130                 break;
131
132         default:
133                 fprintf(stderr, "%*s%p unknown type\n", indent*4, "", (void*)info);
134                 return false;;
135         }
136
137         return true;
138 }
139
140 static bool dump_ltrace_tree(const struct arg_type_info* info)
141 {
142         return _dump_ltrace_tree( info, 0 );
143 }
144 #endif
145
146
147
148 static uint64_t attr_numeric(Dwarf_Die *die, uint32_t name)
149 {
150         Dwarf_Attribute attr;
151         uint32_t form;
152
153         if (dwarf_attr(die, name, &attr) == NULL)
154                 return 0;
155
156         form = dwarf_whatform(&attr);
157
158         switch (form) {
159         case DW_FORM_addr: {
160                 Dwarf_Addr addr;
161                 if (dwarf_formaddr(&attr, &addr) == 0)
162                         return addr;
163         }
164                 break;
165         case DW_FORM_data1:
166         case DW_FORM_data2:
167         case DW_FORM_data4:
168         case DW_FORM_data8:
169         case DW_FORM_sdata:
170         case DW_FORM_udata: {
171                 Dwarf_Word value;
172                 if (dwarf_formudata(&attr, &value) == 0)
173                         return value;
174         }
175                 break;
176         case DW_FORM_flag:
177         case DW_FORM_flag_present: {
178                 bool value;
179                 if (dwarf_formflag(&attr, &value) == 0)
180                         return value;
181         }
182                 break;
183         default:
184                 complain(die, "DW_AT_<0x%x>=0x%x", name, form);
185                 break;
186         }
187
188         return 0;
189 }
190
191 static enum arg_type get_base_type(Dwarf_Die* die)
192 {
193         int encoding = attr_numeric(die, DW_AT_encoding);
194
195         if (encoding == DW_ATE_void )
196                 return ARGTYPE_VOID;
197
198         if (encoding == DW_ATE_signed_char || encoding == DW_ATE_unsigned_char )
199                 return ARGTYPE_CHAR;
200
201         if (encoding == DW_ATE_signed   ||
202                 encoding == DW_ATE_unsigned ||
203                 encoding == DW_ATE_boolean) {
204                 bool is_signed = (encoding == DW_ATE_signed);
205                 switch (attr_numeric(die, DW_AT_byte_size)) {
206                 case sizeof(char):
207                         return ARGTYPE_CHAR;
208
209                 case sizeof(short):
210                         return is_signed ? ARGTYPE_SHORT : ARGTYPE_USHORT;
211
212                 case sizeof(int):
213                         return is_signed ? ARGTYPE_INT : ARGTYPE_UINT;
214
215                 case sizeof(long):
216                         return is_signed ? ARGTYPE_LONG : ARGTYPE_ULONG;
217
218                 default:
219                         complain(die, "");
220                         exit(1);
221                 }
222         }
223
224         if (encoding == DW_ATE_float) {
225                 switch (attr_numeric(die, DW_AT_byte_size)) {
226                 case sizeof(float):
227                         return ARGTYPE_FLOAT;
228
229                 case sizeof(double):
230                         return ARGTYPE_DOUBLE;
231
232                 default:
233                         // things like long doubles. ltrace has no support yet, so I just
234                         // say "void"
235                         return ARGTYPE_VOID;
236                 }
237         }
238
239         // Unknown encoding. I just say void
240         return ARGTYPE_VOID;
241 }
242
243 static bool get_type_die(Dwarf_Die* type_die, Dwarf_Die* die)
244 {
245         Dwarf_Attribute attr;
246         return
247                 dwarf_attr(die, DW_AT_type, &attr) != NULL &&
248                 dwarf_formref_die(&attr, type_die) != NULL;
249 }
250
251 static size_t dwarf_die_hash(const void* x)
252 {
253         return *(const Dwarf_Off*)x;
254 }
255 static int dwarf_die_eq(const void* a, const void* b)
256 {
257         return *(const Dwarf_Off*)a == *(const Dwarf_Off*)b;
258 }
259
260 static bool get_enum(struct arg_type_info* enum_info, Dwarf_Die* parent)
261 {
262         enum_info->type = ARGTYPE_INT;
263
264         struct enum_lens *lens = calloc(1, sizeof(struct enum_lens));
265         if (lens == NULL) {
266                 complain(parent, "alloc error");
267                 return false;
268         }
269         lens_init_enum(lens);
270         enum_info->lens = &lens->super;
271
272         Dwarf_Die die;
273         if (dwarf_child(parent, &die) != 0) {
274                 // empty enum. we're done
275                 return true;
276         }
277
278         while(1) {
279                 complain(&die, "enum element: 0x%02x/'%s'", dwarf_tag(&die),
280                                  dwarf_diename(&die));
281
282                 if (dwarf_tag(&die) != DW_TAG_enumerator) {
283                         complain(&die, "Enums can have ONLY DW_TAG_enumerator elements");
284                         return false;
285                 }
286
287                 if (!dwarf_hasattr(&die, DW_AT_const_value)) {
288                         complain(&die, "Enums MUST have DW_AT_const_value values");
289                         return false;
290                 }
291
292                 const char* key = dwarf_diename(&die);
293                 if (key == NULL) {
294                         complain(&die, "Enums must have a DW_AT_name key");
295                         return false;
296                 }
297                 const char* dupkey = strdup(key);
298                 if (dupkey == NULL) {
299                         complain(&die, "Couldn't duplicate enum key");
300                         return false;
301                 }
302
303                 struct value* value = calloc( 1, sizeof(struct value));
304                 if (value == NULL) {
305                         complain(&die, "Couldn't alloc enum value");
306                         return false;
307                 }
308
309                 value_init_detached(value, NULL, type_get_simple( ARGTYPE_INT ), 0);
310                 value_set_word(value, attr_numeric(&die, DW_AT_const_value));
311
312                 if (lens_enum_add( lens, dupkey, 0, value, 0 )) {
313                         complain(&die, "Couldn't add enum element");
314                         return false;
315                 }
316
317                 int res = dwarf_siblingof(&die, &die);
318                 if (res == 0) continue;     /* sibling exists    */
319                 if (res < 0)  return false; /* error             */
320                 break;                      /* no sibling exists */
321         }
322
323         return true;
324 }
325
326 static bool get_array(struct arg_type_info* array_info, Dwarf_Die* parent)
327 {
328         Dwarf_Die type_die;
329         if (!get_type_die( &type_die, parent )) {
330                 complain( parent, "Array has unknown type" );
331                 return false;
332         }
333
334         struct arg_type_info* info;
335         if (!get_type( &info, &type_die )) {
336                 complain( parent, "Couldn't figure out array's type" );
337                 return false;
338         }
339
340         Dwarf_Die subrange;
341         if (dwarf_child(parent, &subrange) != 0) {
342                 complain(parent,
343                                  "Array must have a DW_TAG_subrange_type child, but has none");
344                 return false;
345         }
346
347         Dwarf_Die next_subrange;
348         if (dwarf_siblingof(&subrange, &next_subrange) <= 0) {
349                 complain(parent,
350                                  "Array must have exactly one DW_TAG_subrange_type child");
351                 return false;
352         }
353
354         if (dwarf_hasattr(&subrange, DW_AT_lower_bound)) {
355                 if (attr_numeric(&subrange, DW_AT_lower_bound) != 0) {
356                         complain( parent,
357                                           "Array subrange has a nonzero lower bound. Don't know what to do");
358                         return false;
359                 }
360         }
361
362         int N;
363         if (!dwarf_hasattr(&subrange, DW_AT_upper_bound)) {
364                 // no upper bound is defined. This is probably a variable-width array,
365                 // and I don't know how long it is. Let's say 0 to be safe
366                 N = 0;
367         }
368         else
369                 N = attr_numeric(&subrange, DW_AT_upper_bound)+1;
370
371         // I'm not checking the subrange type. It should be some sort of integer,
372         // and I don't know what it would mean for it to be something else
373
374         struct value* value = calloc( 1, sizeof(struct value));
375         if (value == NULL) {
376                 complain(&subrange, "Couldn't alloc length value");
377                 return false;
378         }
379         value_init_detached(value, NULL, type_get_simple( ARGTYPE_INT ), 0);
380         value_set_word(value, N );
381
382         struct expr_node* length = calloc( 1, sizeof(struct expr_node));
383         if (length == NULL) {
384                 complain(&subrange, "Couldn't alloc length expr");
385                 return false;
386         }
387         expr_init_const(length, value);
388
389         type_init_array(array_info, info, 0, length, 0 );
390
391         return true;
392 }
393
394 static bool get_structure(struct arg_type_info* struct_info, Dwarf_Die* parent)
395 {
396         type_init_struct(struct_info);
397
398         Dwarf_Die die;
399         if (dwarf_child(parent, &die) != 0) {
400                 // no elements; we're done
401                 return true;
402         }
403
404         while(1) {
405                 complain(&die, "member: 0x%02x", dwarf_tag(&die));
406
407                 if (dwarf_tag(&die) != DW_TAG_member) {
408                         complain(&die, "Structure can have ONLY DW_TAG_member");
409                         return false;
410                 }
411
412                 Dwarf_Die type_die;
413                 if (!get_type_die( &type_die, &die )) {
414                         complain( &die, "Couldn't get type of element");
415                         return false;
416                 }
417
418                 struct arg_type_info* member_info = NULL;
419                 if (!get_type( &member_info, &type_die )) {
420                         complain(&die, "Couldn't parse type from DWARF data");
421                         return false;
422                 }
423                 type_struct_add( struct_info, member_info, 0 );
424
425                 int res = dwarf_siblingof(&die, &die);
426                 if (res == 0) continue;     /* sibling exists    */
427                 if (res < 0)  return false; /* error             */
428                 break;                      /* no sibling exists */
429         }
430
431         return true;
432 }
433
434 // Reads the type in the die into the given structure
435 // Returns true on sucess
436 static bool get_type(struct arg_type_info** info, Dwarf_Die* type_die)
437 {
438         Dwarf_Off die_offset = dwarf_dieoffset(type_die);
439         struct arg_type_info** found_type = dict_find(&type_hash, &die_offset );
440         if (found_type != NULL) {
441                 *info = *found_type;
442                 complain(type_die, "Read pre-computed type: %p", *info);
443                 return true;
444         }
445
446         Dwarf_Die next_die;
447
448         switch (dwarf_tag(type_die)) {
449         case DW_TAG_base_type:
450                 *info = type_get_simple( get_base_type( type_die ));
451                 complain(type_die, "Storing base type: %p", *info);
452                 dict_insert( &type_hash, &die_offset, info );
453                 return true;
454
455         case DW_TAG_subroutine_type:
456         case DW_TAG_inlined_subroutine:
457                 // function pointers are stored as void*. If ltrace tries to dereference
458                 // these, it'll get a segfault
459                 *info = type_get_simple( ARGTYPE_VOID );
460                 complain(type_die, "Storing subroutine type: %p", *info);
461                 dict_insert( &type_hash, &die_offset, info );
462                 return true;
463
464         case DW_TAG_pointer_type:
465
466                 if (!get_type_die(&next_die, type_die )) {
467                         // the pointed-to type isn't defined, so I report a void*
468                         *info = type_get_simple( ARGTYPE_VOID );
469                         complain(type_die, "Storing void-pointer type: %p", *info);
470                         dict_insert( &type_hash, &die_offset, info );
471                         return true;
472                 }
473
474                 *info = calloc( 1, sizeof(struct arg_type_info));
475                 if (*info == NULL) {
476                         complain(type_die, "alloc error");
477                         return false;
478                 }
479                 type_init_pointer(*info, NULL, 0);
480
481                 complain(type_die, "Storing pointer type: %p", *info);
482                 dict_insert( &type_hash, &die_offset, info );
483                 return get_type( &(*info)->u.ptr_info.info, &next_die );
484
485         case DW_TAG_structure_type:
486                 *info = calloc( 1, sizeof(struct arg_type_info));
487                 if (*info == NULL) {
488                         complain(type_die, "alloc error");
489                         return false;
490                 }
491
492                 complain(type_die, "Storing struct type: %p", *info);
493                 dict_insert( &type_hash, &die_offset, info );
494                 return get_structure( *info, type_die );
495
496
497         case DW_TAG_typedef: ;
498         case DW_TAG_const_type: ;
499         case DW_TAG_volatile_type: ;
500                 // Various tags are simply pass-through, so I just keep going
501                 bool res = true;
502                 if (get_type_die(&next_die, type_die )) {
503                         complain(type_die, "Storing const/typedef type: %p", *info);
504                         res = get_type( info, &next_die );
505                 } else {
506                         // no type. Use 'void'. Normally I'd think this is bogus, but stdio
507                         // typedefs something to void
508                         *info = type_get_simple( ARGTYPE_VOID );
509                         complain(type_die, "Storing void type: %p", *info);
510                 }
511                 if (res )
512                         dict_insert( &type_hash, &die_offset, info );
513                 return res;
514
515         case DW_TAG_enumeration_type:
516                 // We have an enumeration. This has type "int", but has a particular
517                 // lens to handle the enum
518                 *info = calloc( 1, sizeof(struct arg_type_info));
519                 if (*info == NULL) {
520                         complain(type_die, "alloc error");
521                         return false;
522                 }
523
524                 complain(type_die, "Storing enum int: %p", *info);
525                 dict_insert( &type_hash, &die_offset, info );
526                 return get_enum( *info, type_die );
527
528         case DW_TAG_array_type:
529                 *info = calloc( 1, sizeof(struct arg_type_info));
530                 if (*info == NULL) {
531                         complain(type_die, "alloc error");
532                         return false;
533                 }
534
535                 complain(type_die, "Storing array: %p", *info);
536                 dict_insert( &type_hash, &die_offset, info );
537                 return get_array( *info, type_die );
538
539         case DW_TAG_union_type:
540                 *info = type_get_simple( ARGTYPE_VOID );
541                 complain(type_die, "Storing union-as-void type: %p", *info);
542                 return true;
543
544         default:
545                 complain(type_die, "Unknown type tag 0x%x", dwarf_tag(type_die));
546                 break;
547         }
548
549         return false;
550 }
551
552 static bool get_prototype(struct prototype* proto, Dwarf_Die* subroutine)
553 {
554         // First, look at the return type. This is stored in a DW_AT_type tag in the
555         // subroutine DIE. If there is no such tag, this function returns void
556         Dwarf_Die return_type_die;
557         if (!get_type_die(&return_type_die, subroutine )) {
558                 proto->return_info = type_get_simple( ARGTYPE_VOID );
559                 proto->own_return_info = 0;
560         } else {
561                 proto->return_info = calloc( 1, sizeof( struct arg_type_info ));
562                 if (proto->return_info == NULL) {
563                         complain(subroutine, "Couldn't alloc return type");
564                         return false;
565                 }
566                 proto->own_return_info = 0;
567
568                 if (!get_type( &proto->return_info, &return_type_die )) {
569                         complain(subroutine, "Couldn't get return type");
570                         return false;
571                 }
572         }
573
574
575         // Now look at the arguments
576         Dwarf_Die arg_die;
577         if (dwarf_child(subroutine, &arg_die) != 0) {
578                 // no args. We're done
579                 return true;
580         }
581
582         while(1) {
583                 if (dwarf_tag(&arg_die) != DW_TAG_formal_parameter )
584                         goto next_prototype_argument;
585
586                 complain(&arg_die, "arg: 0x%02x", dwarf_tag(&arg_die));
587
588                 Dwarf_Die type_die;
589                 if (!get_type_die(&type_die, &arg_die )) {
590                         complain(&arg_die, "Couldn't get the argument type die");
591                         return false;
592                 }
593
594                 struct arg_type_info* arg_type_info = NULL;
595                 if (!get_type( &arg_type_info, &type_die )) {
596                         complain(&arg_die, "Couldn't parse arg type from DWARF data");
597                         return false;
598                 }
599
600                 struct param param;
601                 param_init_type(&param, arg_type_info, 0);
602                 if (prototype_push_param(proto, &param) <0) {
603                         complain(&arg_die, "couldn't add argument to the prototype");
604                         return false;
605                 }
606
607 #ifdef DUMP_PROTOTYPES
608                 fprintf(stderr, "Adding argument:\n");
609                 dump_ltrace_tree(arg_type_info);
610 #endif
611
612         next_prototype_argument: ;
613                 int res = dwarf_siblingof(&arg_die, &arg_die);
614                 if (res == 0) continue;     /* sibling exists    */
615                 if (res < 0)  return false; /* error             */
616                 break;                      /* no sibling exists */
617         }
618
619         return true;
620 }
621
622 static bool process_die_compileunit(struct protolib* plib, struct library* lib,
623                                                                         Dwarf_Die* parent)
624 {
625         Dwarf_Die die;
626         if (dwarf_child(parent, &die) != 0) {
627                 // no child nodes, so nothing to do
628                 return true;
629         }
630
631         while (1) {
632                 if (dwarf_tag(&die) == DW_TAG_subprogram) {
633                         const char* function_name = dwarf_diename(&die);
634
635                         complain(&die, "subroutine_type: 0x%02x; function '%s'",
636                                          dwarf_tag(&die), function_name);
637
638                         struct prototype* proto =
639                                 protolib_lookup_prototype(plib, function_name, true );
640
641                         if (proto != NULL) {
642                                 complain(&die, "Prototype already exists. Skipping");
643                                 goto next_prototype;
644                         }
645
646                         if (!filter_matches_symbol(options.plt_filter,    function_name, lib) &&
647                                 !filter_matches_symbol(options.static_filter, function_name, lib) &&
648                                 !filter_matches_symbol(options.export_filter, function_name, lib)) {
649                                 complain(&die, "Prototype not requested by any filter");
650                                 goto next_prototype;
651                         }
652
653                         proto = malloc(sizeof(struct prototype));
654                         if (proto == NULL) {
655                                 complain(&die, "couldn't alloc prototype");
656                                 return false;
657                         }
658                         prototype_init( proto );
659
660                         if (!get_prototype(proto, &die )) {
661                                 complain(&die, "couldn't get prototype");
662                                 return false;
663                         }
664
665                         protolib_add_prototype(plib, function_name, 0, proto);
666                 }
667
668                 next_prototype:;
669                 int res = dwarf_siblingof(&die, &die);
670                 if (res == 0) continue;     /* sibling exists    */
671                 if (res < 0)  return false; /* error             */
672                 break;                      /* no sibling exists */
673         }
674
675         return true;
676 }
677
678 static bool import(struct protolib* plib, struct library* lib, Dwfl* dwfl)
679 {
680         dict_init(&type_hash, sizeof(Dwarf_Off), sizeof(struct arg_type_info*),
681                           dwarf_die_hash, dwarf_die_eq, NULL );
682
683         Dwarf_Addr bias;
684     Dwarf_Die* die = NULL;
685     while ((die = dwfl_nextcu(dwfl, die, &bias)) != NULL) {
686         if (dwarf_tag(die) == DW_TAG_compile_unit) {
687             if (!process_die_compileunit(plib, lib, die)) {
688                 complain(die, "Error reading compile unit");
689                                 exit(1);
690                                 return false;
691             }
692         } else {
693             complain(die, "DW_TAG_compile_unit expected");
694                         exit(1);
695             return false;
696         }
697     }
698
699         dict_destroy( &type_hash, NULL, NULL, NULL );
700         return true;
701 }
702
703 bool import_DWARF_prototypes(struct protolib* plib, struct library* lib,
704                                                          Dwfl *dwfl)
705 {
706         if (plib == NULL) {
707                 plib = protolib_cache_default(&g_protocache, lib->soname, 0);
708                 if (plib == NULL) {
709                         fprintf(stderr, "Error loading protolib %s: %s.\n",
710                                         lib->soname, strerror(errno));
711                 }
712         }
713
714         return import(plib, lib, dwfl);
715 }
716
717 /*
718 - I handle static functions now. Should I? Those do not have DW_AT_external==1
719
720 - should process existing prototypes to make sure they match
721
722 - what do function pointers look like? I'm doing void*
723
724 - unions
725
726 - all my *allocs leak
727
728 - protolib_lookup_prototype should look for imports?
729
730 */