# Copyright 2010-2022 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Return true if the target supports DWARF-2 and uses gas. # For now pick a sampling of likely targets. proc dwarf2_support {} { if {[istarget *-*-linux*] || [istarget *-*-gnu*] || [istarget *-*-elf*] || [istarget *-*-openbsd*] || [istarget arm*-*-eabi*] || [istarget powerpc-*-eabi*]} { return 1 } return 0 } # Use 'objcopy --extract-dwo to extract DWO information from # OBJECT_FILE and place it into DWO_FILE. # # Return 0 on success, otherwise, return -1. proc extract_dwo_information { object_file dwo_file } { set objcopy [gdb_find_objcopy] set command "$objcopy --extract-dwo $object_file $dwo_file" verbose -log "Executing $command" set result [catch "exec $command" output] verbose -log "objcopy --extract-dwo output: $output" if { $result == 1 } { return -1 } return 0 } # Use 'objcopy --strip-dwo to remove DWO information from # FILENAME. # # Return 0 on success, otherwise, return -1. proc strip_dwo_information { filename } { set objcopy [gdb_find_objcopy] set command "$objcopy --strip-dwo $filename" verbose -log "Executing $command" set result [catch "exec $command" output] verbose -log "objcopy --strip-dwo output: $output" if { $result == 1 } { return -1 } return 0 } # Build an executable, with the debug information split out into a # separate .dwo file. # # This function is based on build_executable_from_specs in # lib/gdb.exp, but with threading support, and rust support removed. # # TESTNAME is the name of the test; this is passed to 'untested' if # something fails. # # EXECUTABLE is the executable to create, this can be an absolute # path, or a relative path, in which case the EXECUTABLE will be # created in the standard output directory. # # OPTIONS is passed to the final link, using gdb_compile. If OPTIONS # contains any option that indicates threads is required, of if the # option rust is included, then this function will return failure. # # ARGS is a series of lists. Each list is a spec for one source file # that will be compiled to make EXECUTABLE. Each spec in ARGS has the # form: # [ SOURCE OPTIONS ] # or: # [ SOURCE OPTIONS OBJFILE ] # # Where SOURCE is the path to the source file to compile. This can be # absolute, or relative to the standard global ${subdir}/${srcdir}/ # path. # # OPTIONS are the options to use when compiling SOURCE into an object # file. # # OBJFILE is optional, if present this is the name of the object file # to create for SOURCE. If this is not provided then a suitable name # will be auto-generated. # # If OPTIONS contains the option 'split-dwo' then the debug # information is extracted from the object file created by compiling # SOURCE and placed into a file with a dwo extension. The name of # this file is generated based on the name of the object file that was # created (with the .o replaced with .dwo). proc build_executable_and_dwo_files { testname executable options args } { global subdir global srcdir if { ! [regexp "^/" "$executable"] } then { set binfile [standard_output_file $executable] } else { set binfile $executable } set func gdb_compile if {[lsearch -regexp $options \ {^(pthreads|shlib|shlib_pthreads|openmp)$}] != -1} { # Currently don't support compiling thread based tests here. # If this is required then look to build_executable_from_specs # for inspiration. return -1 } if {[lsearch -exact $options rust] != -1} { # Currently don't support compiling rust tests here. If this # is required then look to build_executable_from_specs for # inspiration. return -1 } # Must be run on local host due to use of objcopy. if [is_remote host] { return -1 } set objects {} set i 0 foreach spec $args { if {[llength $spec] < 2} { error "invalid spec length" return -1 } verbose -log "APB: SPEC: $spec" set s [lindex $spec 0] set local_options [lindex $spec 1] if { ! [regexp "^/" "$s"] } then { set s "$srcdir/$subdir/$s" } if {[llength $spec] > 2} { set objfile [lindex $spec 2] } else { set objfile "${binfile}${i}.o" incr i } if { [$func "${s}" "${objfile}" object $local_options] != "" } { untested $testname return -1 } lappend objects "$objfile" if {[lsearch -exact $local_options "split-dwo"] >= 0} { # Split out the DWO file. set dwo_file "[file rootname ${objfile}].dwo" if { [extract_dwo_information $objfile $dwo_file] == -1 } { untested $testname return -1 } if { [strip_dwo_information $objfile] == -1 } { untested $testname return -1 } } } verbose -log "APB: OBJECTS = $objects" set ret [$func $objects "${binfile}" executable $options] if { $ret != "" } { untested $testname return -1 } return 0 } # Utility function for procs shared_gdb_*. proc init_shared_gdb {} { global shared_gdb_enabled global shared_gdb_started if { ! [info exists shared_gdb_enabled] } { set shared_gdb_enabled 0 set shared_gdb_started 0 } } # Cluster of four procs: # - shared_gdb_enable # - shared_gdb_disable # - shared_gdb_start_use SRC OPTIONS # - shared_gdb_end_use # # Can be used like so: # # { # if { $share } shared_gdb_enable # ... # shared_gdb_start_use $src $options # ... # shared_gdb_end_use # ... # shared_gdb_start_use $src $options # ... # shared_gdb_end_use # ... # if { $share } shared_gdb_disable # } # # to write functionalty that could share ($share == 1) or could not # share ($share == 0) a gdb session between two uses. proc shared_gdb_enable {} { set me shared_gdb_enable init_shared_gdb global shared_gdb_enabled global shared_gdb_started if { $shared_gdb_enabled } { error "$me: gdb sharing already enabled" } set shared_gdb_enabled 1 if { $shared_gdb_started } { error "$me: gdb sharing not stopped" } } # See above. proc shared_gdb_disable {} { init_shared_gdb global shared_gdb_enabled global shared_gdb_started if { ! $shared_gdb_enabled } { error "$me: gdb sharing not enabled" } set shared_gdb_enabled 0 if { $shared_gdb_started } { gdb_exit set shared_gdb_started 0 } } # Share the current gdb session. proc share_gdb { src options } { global shared_gdb_started global shared_gdb_src global shared_gdb_options set shared_gdb_started 1 set shared_gdb_src $src set shared_gdb_options $options } # See above. proc shared_gdb_start_use { src options } { set me shared_gdb_start_use init_shared_gdb global shared_gdb_enabled global shared_gdb_started global shared_gdb_src global shared_gdb_options set do_start 1 if { $shared_gdb_enabled && $shared_gdb_started } { if { $shared_gdb_src != $src || $shared_gdb_options != $options } { error "$me: gdb sharing inconsistent" } set do_start 0 } if { $do_start } { set exe [standard_temp_file func_addr[pid].x] gdb_compile $src $exe executable $options gdb_exit gdb_start gdb_load "$exe" if { $shared_gdb_enabled } { share_gdb $src $options } } } # See above. proc shared_gdb_end_use {} { init_shared_gdb global shared_gdb_enabled if { ! $shared_gdb_enabled } { gdb_exit } } # Enable gdb session sharing within BODY. proc with_shared_gdb { body } { shared_gdb_enable set code [catch { uplevel 1 $body } result] shared_gdb_disable # Return as appropriate. if { $code == 1 } { global errorInfo errorCode return -code error -errorinfo $errorInfo -errorcode $errorCode $result } elseif { $code > 1 } { return -code $code $result } return $result } # Return a list of expressions about function FUNC's address and length. # The first expression is the address of function FUNC, and the second # one is FUNC's length. SRC is the source file having function FUNC. # An internal label ${func}_label must be defined inside FUNC: # # int main (void) # { # asm ("main_label: .globl main_label"); # return 0; # } # # This label is needed to compute the start address of function FUNC. # If the compiler is gcc, we can do the following to get function start # and end address too: # # asm ("func_start: .globl func_start"); # static void func (void) {} # asm ("func_end: .globl func_end"); # # however, this isn't portable, because other compilers, such as clang, # may not guarantee the order of global asms and function. The code # becomes: # # asm ("func_start: .globl func_start"); # asm ("func_end: .globl func_end"); # static void func (void) {} # proc function_range { func src {options {debug}} } { global decimal gdb_prompt shared_gdb_start_use $src $options # Compute the label offset, and we can get the function start address # by "${func}_label - $func_label_offset". set func_label_offset "" set test "p ${func}_label - ${func}" gdb_test_multiple $test $test { -re ".* = ($decimal)\r\n$gdb_prompt $" { set func_label_offset $expect_out(1,string) } } # Compute the function length. global hex set func_length "" set test "disassemble $func" gdb_test_multiple $test $test { -re ".*$hex <\\+($decimal)>:\[^\r\n\]+\r\nEnd of assembler dump\.\r\n$gdb_prompt $" { set func_length $expect_out(1,string) } } # Compute the size of the last instruction. # For C++, GDB appends arguments to the names of functions if they don't # have a linkage name. For example, asking gdb to disassemble a C++ main # will print the function name as main() or main(int argc, char **argv). # Take this into account by optionally allowing an argument list after # the function name. set func_pattern "$func\(\?\:\\(\.\*\\)\)?" if { $func_length != 0 } { set func_pattern "$func_pattern\\+$func_length" } set test "x/2i $func+$func_length" gdb_test_multiple $test $test { -re ".*($hex) <$func_pattern>:\[^\r\n\]+\r\n\[ \]+($hex).*\.\r\n$gdb_prompt $" { set start $expect_out(1,string) set end $expect_out(2,string) set func_length [expr $func_length + $end - $start] } } shared_gdb_end_use return [list "${func}_label - $func_label_offset" $func_length] } # Extract the start, length, and end for function called NAME and # create suitable variables in the callers scope. # Return the list of created variables. proc get_func_info { name {options {debug}} } { global srcdir subdir srcfile upvar 1 "${name}_start" func_start upvar 1 "${name}_len" func_len upvar 1 "${name}_end" func_end lassign [function_range ${name} \ [list ${srcdir}/${subdir}/$srcfile] \ ${options}] \ func_start func_len set func_end "$func_start + $func_len" return [list \ "${name}_start" \ "${name}_len" \ "${name}_end"] } # A DWARF assembler. # # All the variables in this namespace are private to the # implementation. Also, any procedure whose name starts with "_" is # private as well. Do not use these. # # Exported functions are documented at their definition. # # In addition to the hand-written functions documented below, this # module automatically generates a function for each DWARF tag. For # most tags, two forms are made: a full name, and one with the # "DW_TAG_" prefix stripped. For example, you can use either # 'DW_TAG_compile_unit' or 'compile_unit' interchangeably. # # There are two exceptions to this rule: DW_TAG_variable and # DW_TAG_namespace. For these, the full name must always be used, # as the short name conflicts with Tcl builtins. (Should future # versions of Tcl or DWARF add more conflicts, this list will grow. # If you want to be safe you should always use the full names.) # # Each tag procedure is defined like: # # proc DW_TAG_mumble {{attrs {}} {children {}}} { ... } # # ATTRS is an optional list of attributes. # It is run through 'subst' in the caller's context before processing. # # Each attribute in the list has one of two forms: # 1. { NAME VALUE } # 2. { NAME VALUE FORM } # # In each case, NAME is the attribute's name. # This can either be the full name, like 'DW_AT_name', or a shortened # name, like 'name'. These are fully equivalent. # # Besides DWARF standard attributes, assembler supports 'macro' attribute # which will be substituted by one or more standard or macro attributes. # supported macro attributes are: # # - MACRO_AT_range { FUNC } # It is substituted by DW_AT_low_pc and DW_AT_high_pc with the start and # end address of function FUNC in file $srcdir/$subdir/$srcfile. # # - MACRO_AT_func { FUNC } # It is substituted by DW_AT_name with FUNC and MACRO_AT_range. # # If FORM is given, it should name a DW_FORM_ constant. # This can either be the short form, like 'DW_FORM_addr', or a # shortened version, like 'addr'. If the form is given, VALUE # is its value; see below. In some cases, additional processing # is done; for example, DW_FORM_strp manages the .debug_str # section automatically. # # If FORM is 'SPECIAL_expr', then VALUE is treated as a location # expression. The effective form is then DW_FORM_block or DW_FORM_exprloc # for DWARF version >= 4, and VALUE is passed to the (internal) # '_location' proc to be translated. # This proc implements a miniature DW_OP_ assembler. # # If FORM is not given, it is guessed: # * If VALUE starts with the "@" character, the rest of VALUE is # looked up as a DWARF constant, and DW_FORM_sdata is used. For # example, '@DW_LANG_c89' could be used. # * If VALUE starts with the ":" character, then it is a label # reference. The rest of VALUE is taken to be the name of a label, # and DW_FORM_ref4 is used. See 'new_label' and 'define_label'. # * If VALUE starts with the "%" character, then it is a label # reference too, but DW_FORM_ref_addr is used. # * Otherwise, if the attribute name has a default form (f.i. DW_FORM_addr for # DW_AT_low_pc), then that one is used. # * Otherwise, an error is reported. Either specify a form explicitly, or # add a default for the the attribute name in _default_form. # # CHILDREN is just Tcl code that can be used to define child DIEs. It # is evaluated in the caller's context. # # Currently this code is missing nice support for CFA handling, and # probably other things as well. namespace eval Dwarf { # True if the module has been initialized. variable _initialized 0 # Constants from dwarf2.h. variable _constants # DW_AT short names. variable _AT # DW_FORM short names. variable _FORM # DW_OP short names. variable _OP # The current output file. variable _output_file # Note: The _cu_ values here also apply to type units (TUs). # Think of a TU as a special kind of CU. # Current CU count. variable _cu_count # The current CU's base label. variable _cu_label # The current CU's version. variable _cu_version # The current CU's address size. variable _cu_addr_size # The current CU's offset size. variable _cu_offset_size # Label generation number. variable _label_num # The deferred output array. The index is the section name; the # contents hold the data for that section. variable _deferred_output # If empty, we should write directly to the output file. # Otherwise, this is the name of a section to write to. variable _defer # The abbrev section. Typically .debug_abbrev but can be .debug_abbrev.dwo # for Fission. variable _abbrev_section # The next available abbrev number in the current CU's abbrev # table. variable _abbrev_num # The string table for this assembly. The key is the string; the # value is the label for that string. variable _strings # Current .debug_line unit count. variable _line_count # A Label for line table header generation. variable _line_header_end_label # The address size for debug ranges section. variable _debug_ranges_64_bit # The index into the .debug_addr section (used for fission # generation). variable _debug_addr_index # Flag, true if the current CU is contains fission information, # otherwise false. variable _cu_is_fission proc _process_one_constant {name value} { variable _constants variable _AT variable _FORM variable _OP set _constants($name) $value if {![regexp "^DW_(\[A-Z\]+)_(\[A-Za-z0-9_\]+)$" $name \ ignore prefix name2]} { error "non-matching name: $name" } if {$name2 == "lo_user" || $name2 == "hi_user"} { return } # We only try to shorten some very common things. # FIXME: CFA? switch -exact -- $prefix { TAG { # Create two procedures for the tag. These call # _handle_DW_TAG with the full tag name baked in; this # does all the actual work. proc $name {{attrs {}} {children {}}} \ "_handle_DW_TAG $name \$attrs \$children" # Filter out ones that are known to clash. if {$name2 == "variable" || $name2 == "namespace"} { set name2 "tag_$name2" } if {[info commands $name2] != {}} { error "duplicate proc name: from $name" } proc $name2 {{attrs {}} {children {}}} \ "_handle_DW_TAG $name \$attrs \$children" } AT { set _AT($name2) $name } FORM { set _FORM($name2) $name } OP { set _OP($name2) $name } default { return } } } proc _read_constants {} { global srcdir hex decimal # DWARF name-matching regexp. set dwrx "DW_\[a-zA-Z0-9_\]+" # Whitespace regexp. set ws "\[ \t\]+" set fd [open [file join $srcdir .. .. include dwarf2.h]] while {![eof $fd]} { set line [gets $fd] if {[regexp -- "^${ws}($dwrx)${ws}=${ws}($hex|$decimal),?$" \ $line ignore name value ignore2]} { _process_one_constant $name $value } } close $fd set fd [open [file join $srcdir .. .. include dwarf2.def]] while {![eof $fd]} { set line [gets $fd] if {[regexp -- \ "^DW_\[A-Z_\]+${ws}\\(($dwrx),${ws}($hex|$decimal)\\)$" \ $line ignore name value ignore2]} { _process_one_constant $name $value } } close $fd } proc _quote {string} { # FIXME return "\"${string}\\0\"" } proc _nz_quote {string} { # For now, no quoting is done. return "\"${string}\"" } proc _handle_DW_FORM {form value} { switch -exact -- $form { DW_FORM_string { _op .ascii [_quote $value] } DW_FORM_flag_present { # We don't need to emit anything. } DW_FORM_data4 - DW_FORM_ref4 { _op .4byte $value } DW_FORM_ref_addr { variable _cu_offset_size variable _cu_version variable _cu_addr_size if {$_cu_version == 2} { set size $_cu_addr_size } else { set size $_cu_offset_size } _op .${size}byte $value } DW_FORM_GNU_ref_alt - DW_FORM_GNU_strp_alt - DW_FORM_sec_offset { variable _cu_offset_size _op_offset $_cu_offset_size $value } DW_FORM_ref1 - DW_FORM_flag - DW_FORM_data1 { _op .byte $value } DW_FORM_sdata { _op .sleb128 $value } DW_FORM_ref_udata - DW_FORM_udata - DW_FORM_loclistx - DW_FORM_rnglistx { _op .uleb128 $value } DW_FORM_addr { variable _cu_addr_size _op .${_cu_addr_size}byte $value } DW_FORM_GNU_addr_index { variable _debug_addr_index variable _cu_addr_size _op .uleb128 ${_debug_addr_index} incr _debug_addr_index _defer_output .debug_addr { _op .${_cu_addr_size}byte $value } } DW_FORM_data2 - DW_FORM_ref2 { _op .2byte $value } DW_FORM_data8 - DW_FORM_ref8 - DW_FORM_ref_sig8 { _op .8byte $value } DW_FORM_data16 { _op .8byte $value } DW_FORM_strp { variable _strings variable _cu_offset_size if {![info exists _strings($value)]} { set _strings($value) [new_label strp] _defer_output .debug_str { define_label $_strings($value) _op .ascii [_quote $value] } } _op_offset $_cu_offset_size $_strings($value) "strp: $value" } SPECIAL_expr { variable _cu_version variable _cu_addr_size variable _cu_offset_size set l1 [new_label "expr_start"] set l2 [new_label "expr_end"] _op .uleb128 "$l2 - $l1" "expression" define_label $l1 _location $value $_cu_version $_cu_addr_size $_cu_offset_size define_label $l2 } DW_FORM_block1 { set len [string length $value] if {$len > 255} { error "DW_FORM_block1 length too long" } _op .byte $len _op .ascii [_nz_quote $value] } DW_FORM_block2 - DW_FORM_block4 - DW_FORM_block - DW_FORM_ref2 - DW_FORM_indirect - DW_FORM_exprloc - DW_FORM_strx - DW_FORM_strx1 - DW_FORM_strx2 - DW_FORM_strx3 - DW_FORM_strx4 - DW_FORM_GNU_str_index - default { error "unhandled form $form" } } } proc _guess_form {value varname} { upvar $varname new_value switch -exact -- [string range $value 0 0] { @ { # Constant reference. variable _constants set new_value $_constants([string range $value 1 end]) # Just the simplest. return DW_FORM_sdata } : { # Label reference. variable _cu_label set new_value "[string range $value 1 end] - $_cu_label" return DW_FORM_ref4 } % { # Label reference, an offset from .debug_info. set new_value "[string range $value 1 end]" return DW_FORM_ref_addr } default { return "" } } } proc _default_form { attr } { switch -exact -- $attr { DW_AT_low_pc { return DW_FORM_addr } DW_AT_producer - DW_AT_comp_dir - DW_AT_linkage_name - DW_AT_MIPS_linkage_name - DW_AT_name { return DW_FORM_string } DW_AT_GNU_addr_base { return DW_FORM_sec_offset } } return "" } # Map NAME to its canonical form. proc _map_name {name ary} { variable $ary if {[info exists ${ary}($name)]} { set name [set ${ary}($name)] } return $name } proc _handle_attribute { attr_name attr_value attr_form } { variable _abbrev_section variable _constants variable _cu_version _handle_DW_FORM $attr_form $attr_value _defer_output $_abbrev_section { if { $attr_form eq "SPECIAL_expr" } { if { $_cu_version < 4 } { set attr_form_comment "DW_FORM_block" } else { set attr_form_comment "DW_FORM_exprloc" } } else { set attr_form_comment $attr_form } _op .uleb128 $_constants($attr_name) $attr_name _op .uleb128 $_constants($attr_form) $attr_form_comment } } # Handle macro attribute MACRO_AT_range. proc _handle_macro_at_range { attr_value } { variable _cu_is_fission if {[llength $attr_value] != 1} { error "usage: MACRO_AT_range { func }" } set func [lindex $attr_value 0] global srcdir subdir srcfile set src ${srcdir}/${subdir}/${srcfile} set result [function_range $func $src] set form DW_FORM_addr if { $_cu_is_fission } { set form DW_FORM_GNU_addr_index } _handle_attribute DW_AT_low_pc [lindex $result 0] $form _handle_attribute DW_AT_high_pc \ "[lindex $result 0] + [lindex $result 1]" $form } # Handle macro attribute MACRO_AT_func. proc _handle_macro_at_func { attr_value } { if {[llength $attr_value] != 1} { error "usage: MACRO_AT_func { func file }" } _handle_attribute DW_AT_name [lindex $attr_value 0] DW_FORM_string _handle_macro_at_range $attr_value } proc _handle_DW_TAG {tag_name {attrs {}} {children {}}} { variable _abbrev_section variable _abbrev_num variable _constants set has_children [expr {[string length $children] > 0}] set my_abbrev [incr _abbrev_num] # We somewhat wastefully emit a new abbrev entry for each tag. # There's no reason for this other than laziness. _defer_output $_abbrev_section { _op .uleb128 $my_abbrev "Abbrev start" _op .uleb128 $_constants($tag_name) $tag_name _op .byte $has_children "has_children" } _op .uleb128 $my_abbrev "Abbrev ($tag_name)" foreach attr $attrs { set attr_name [_map_name [lindex $attr 0] _AT] # When the length of ATTR is greater than 2, the last # element of the list must be a form. The second through # the penultimate elements are joined together and # evaluated using subst. This allows constructs such as # [gdb_target_symbol foo] to be used. if {[llength $attr] > 2} { set attr_value [uplevel 2 [list subst [join [lrange $attr 1 end-1]]]] } else { set attr_value [uplevel 2 [list subst [lindex $attr 1]]] } if { [string equal "MACRO_AT_func" $attr_name] } { _handle_macro_at_func $attr_value } elseif { [string equal "MACRO_AT_range" $attr_name] } { _handle_macro_at_range $attr_value } else { if {[llength $attr] > 2} { set attr_form [uplevel 2 [list subst [lindex $attr end]]] if { [string index $attr_value 0] == ":" } { # It is a label, get its value. _guess_form $attr_value attr_value } } else { set attr_form [_guess_form $attr_value attr_value] if { $attr_form eq "" } { set attr_form [_default_form $attr_name] } if { $attr_form eq "" } { error "No form for $attr_name $attr_value" } } set attr_form [_map_name $attr_form _FORM] _handle_attribute $attr_name $attr_value $attr_form } } _defer_output $_abbrev_section { # Terminator. _op .byte 0x0 "DW_AT - Terminator" _op .byte 0x0 "DW_FORM - Terminator" } if {$has_children} { uplevel 2 $children # Terminate children. _op .byte 0x0 "Terminate children" } } proc _emit {string} { variable _output_file variable _defer variable _deferred_output if {$_defer == ""} { puts $_output_file $string } else { append _deferred_output($_defer) ${string}\n } } proc _section {name {flags ""} {type ""}} { if {$flags == "" && $type == ""} { _emit " .section $name" } elseif {$type == ""} { _emit " .section $name, \"$flags\"" } else { _emit " .section $name, \"$flags\", %$type" } } # SECTION_SPEC is a list of arguments to _section. proc _defer_output {section_spec body} { variable _defer variable _deferred_output set old_defer $_defer set _defer [lindex $section_spec 0] if {![info exists _deferred_output($_defer)]} { set _deferred_output($_defer) "" eval _section $section_spec } uplevel $body set _defer $old_defer } proc _defer_to_string {body} { variable _defer variable _deferred_output set old_defer $_defer set _defer temp set _deferred_output($_defer) "" uplevel $body set result $_deferred_output($_defer) unset _deferred_output($_defer) set _defer $old_defer return $result } proc _write_deferred_output {} { variable _output_file variable _deferred_output foreach section [array names _deferred_output] { # The data already has a newline. puts -nonewline $_output_file $_deferred_output($section) } # Save some memory. unset _deferred_output } proc _op {name value {comment ""}} { set text " ${name} ${value}" if {$comment != ""} { # Try to make stuff line up nicely. while {[string length $text] < 40} { append text " " } append text "/* ${comment} */" } _emit $text } proc _op_offset { size offset {comment ""} } { if { $size == 4 } { _op .4byte $offset $comment } elseif { $size == 8 } { if {[is_64_target]} { _op .8byte $offset $comment } else { # This allows us to emit 64-bit dwarf for # 32-bit targets. if { [target_endianness] == "little" } { _op .4byte $offset "$comment (lsw)" _op .4byte 0 "$comment (msw)" } else { _op .4byte 0 "$comment (msw)" _op .4byte $offset "$comment (lsw)" } } } else { error "Don't know how to handle offset size $size" } } proc _compute_label {name} { return ".L${name}" } # Return a name suitable for use as a label. If BASE_NAME is # specified, it is incorporated into the label name; this is to # make debugging the generated assembler easier. If BASE_NAME is # not specified a generic default is used. This proc does not # define the label; see 'define_label'. 'new_label' attempts to # ensure that label names are unique. proc new_label {{base_name label}} { variable _label_num return [_compute_label ${base_name}[incr _label_num]] } # Define a label named NAME. Ordinarily, NAME comes from a call # to 'new_label', but this is not required. proc define_label {name} { _emit "${name}:" } # A higher-level interface to label handling. # # ARGS is a list of label descriptors. Each one is either a # single element, or a list of two elements -- a name and some # text. For each descriptor, 'new_label' is invoked. If the list # form is used, the second element in the list is passed as an # argument. The label name is used to define a variable in the # enclosing scope; this can be used to refer to the label later. # The label name is also used to define a new proc whose name is # the label name plus a trailing ":". This proc takes a body as # an argument and can be used to define the label at that point; # then the body, if any, is evaluated in the caller's context. # # For example: # # declare_labels int_label # something { ... $int_label } ;# refer to the label # int_label: constant { ... } ;# define the label proc declare_labels {args} { foreach arg $args { set name [lindex $arg 0] set text [lindex $arg 1] if { $text == "" } { set text $name } upvar $name label_var set label_var [new_label $text] proc ${name}: {args} [format { define_label %s uplevel $args } $label_var] } } # Assign elements from LINE to the elements of an array named # "argvec" in the caller scope. The keys used are named in ARGS. # If the wrong number of elements appear in LINE, error. proc _get_args {line op args} { if {[llength $line] != [llength $args] + 1} { error "usage: $op [string toupper $args]" } upvar argvec argvec foreach var $args value [lreplace $line 0 0] { set argvec($var) $value } } # This is a miniature assembler for location expressions. It is # suitable for use in the attributes to a DIE. Its output is # prefixed with "=" to make it automatically use DW_FORM_block. # # BODY is split by lines, and each line is taken to be a list. # # DWARF_VERSION is the DWARF version for the section where the location # description is found. # # ADDR_SIZE is the length in bytes (4 or 8) of an address on the target # machine (typically found in the header of the section where the location # description is found). # # OFFSET_SIZE is the length in bytes (4 or 8) of an offset into a DWARF # section. This typically depends on whether 32-bit or 64-bit DWARF is # used, as indicated in the header of the section where the location # description is found. # # (FIXME should use 'info complete' here.) # Each list's first element is the opcode, either short or long # forms are accepted. # FIXME argument handling # FIXME move docs proc _location { body dwarf_version addr_size offset_size } { variable _constants foreach line [split $body \n] { # Ignore blank lines, and allow embedded comments. if {[lindex $line 0] == "" || [regexp -- {^[ \t]*#} $line]} { continue } set opcode [_map_name [lindex $line 0] _OP] _op .byte $_constants($opcode) $opcode array unset argvec * switch -exact -- $opcode { DW_OP_addr { _get_args $line $opcode size _op .${addr_size}byte $argvec(size) } DW_OP_GNU_addr_index { variable _debug_addr_index variable _cu_addr_size _op .uleb128 ${_debug_addr_index} incr _debug_addr_index _defer_output .debug_addr { _op .${_cu_addr_size}byte [lindex $line 1] } } DW_OP_regx { _get_args $line $opcode register _op .uleb128 $argvec(register) } DW_OP_pick - DW_OP_const1u - DW_OP_const1s { _get_args $line $opcode const _op .byte $argvec(const) } DW_OP_const2u - DW_OP_const2s { _get_args $line $opcode const _op .2byte $argvec(const) } DW_OP_const4u - DW_OP_const4s { _get_args $line $opcode const _op .4byte $argvec(const) } DW_OP_const8u - DW_OP_const8s { _get_args $line $opcode const _op .8byte $argvec(const) } DW_OP_constu { _get_args $line $opcode const _op .uleb128 $argvec(const) } DW_OP_consts { _get_args $line $opcode const _op .sleb128 $argvec(const) } DW_OP_plus_uconst { _get_args $line $opcode const _op .uleb128 $argvec(const) } DW_OP_piece { _get_args $line $opcode size _op .uleb128 $argvec(size) } DW_OP_bit_piece { _get_args $line $opcode size offset _op .uleb128 $argvec(size) _op .uleb128 $argvec(offset) } DW_OP_skip - DW_OP_bra { _get_args $line $opcode label _op .2byte $argvec(label) } DW_OP_implicit_value { set l1 [new_label "value_start"] set l2 [new_label "value_end"] _op .uleb128 "$l2 - $l1" define_label $l1 foreach value [lrange $line 1 end] { switch -regexp -- $value { {^0x[[:xdigit:]]{1,2}$} {_op .byte $value} {^0x[[:xdigit:]]{4}$} {_op .2byte $value} {^0x[[:xdigit:]]{8}$} {_op .4byte $value} {^0x[[:xdigit:]]{16}$} {_op .8byte $value} default { error "bad value '$value' in DW_OP_implicit_value" } } } define_label $l2 } DW_OP_implicit_pointer - DW_OP_GNU_implicit_pointer { _get_args $line $opcode label offset # Here label is a section offset. if { $dwarf_version == 2 } { _op .${addr_size}byte $argvec(label) } else { _op_offset $offset_size $argvec(label) } _op .sleb128 $argvec(offset) } DW_OP_GNU_variable_value { _get_args $line $opcode label # Here label is a section offset. if { $dwarf_version == 2 } { _op .${addr_size}byte $argvec(label) } else { _op_offset $offset_size $argvec(label) } } DW_OP_deref_size { _get_args $line $opcode size _op .byte $argvec(size) } DW_OP_bregx { _get_args $line $opcode register offset _op .uleb128 $argvec(register) _op .sleb128 $argvec(offset) } DW_OP_fbreg { _get_args $line $opcode offset _op .sleb128 $argvec(offset) } DW_OP_fbreg { _op .sleb128 [lindex $line 1] } default { if {[llength $line] > 1} { error "Unimplemented: operands in location for $opcode" } } } } } # Return a label that references the current position in the # .debug_addr table. When a user is creating split DWARF they # will define two CUs, the first will be the split DWARF content, # and the second will be the non-split stub CU. The split DWARF # CU fills in the .debug_addr section, but the non-split CU # includes a reference to the start of the section. The label # returned by this proc provides that reference. proc debug_addr_label {} { variable _debug_addr_index set lbl [new_label "debug_addr_idx_${_debug_addr_index}_"] _defer_output .debug_addr { define_label $lbl } return $lbl } # Emit a DWARF CU. # OPTIONS is a list with an even number of elements containing # option-name and option-value pairs. # Current options are: # is_64 0|1 - boolean indicating if you want to emit 64-bit DWARF # default = 0 (32-bit) # version n - DWARF version number to emit # default = 4 # addr_size n - the size of addresses in bytes: 4, 8, or default # default = default # fission 0|1 - boolean indicating if generating Fission debug info # default = 0 # label