OSDN Git Service

2003-12-11 Ed Falis <falis@gnat.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / vxaddr2line.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                           V X A D D R 2 L I N E                          --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --             Copyright (C) 2002, 2003 Ada Core Technologies, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, USA.                                                      --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 --  This program is meant to be used with vxworks to compute symbolic
28 --  backtraces on the host from non-symbolic backtraces obtained on the target.
29 --
30 --  The basic idea is to automate the computation of the necessary address
31 --  adjustments prior to calling addr2line when the application has only been
32 --  partially linked on the host.
33 --
34 --  Variants for various targets are supported, and the command line should
35 --  be like :
36 --
37 --  <target>-addr2line [-a <target_arch>] <exe_file> <ref_address>
38 --                     <backtrace addresses>
39 --
40 --  Where:
41 --  <target_arch> :
42 --    selects the target architecture. In the absence of this parameter the
43 --    default variant is chosen based on the Detect_Arch result. Generally,
44 --    this parameter will only be used if vxaddr2line is recompiled manually.
45 --    Otherwise, the command name will always be of the form
46 --    <target>-vxaddr2line where there is no ambiguity on the target's
47 --    architecture.
48 --
49 --  <exe_file> :
50 --    The name of the partially linked binary file for the application.
51 --
52 --  <ref_address> :
53 --    Runtime address (on the target) of a reference symbol you choose,
54 --    which name shall match the value of the Ref_Symbol variable declared
55 --    below. A symbol with a small offset from the beginning of the text
56 --    segment is better, so "adainit" is a good choice.
57 --
58 --  <backtrace addresses> :
59 --    The call chain addresses you obtained at run time on the target and
60 --    for which you want a symbolic association.
61 --
62 --  TO ADD A NEW ARCHITECTURE add an appropriate value to Architecture type
63 --  (in a format <host>_<target>), and then an appropriate value to Config_List
64 --  array
65
66 with Text_IO;             use Text_IO;
67 with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
68 with Ada.Command_Line;    use Ada.Command_Line;
69 with Ada.Strings.Fixed;   use Ada.Strings.Fixed;
70
71 with GNAT.OS_Lib; use GNAT.OS_Lib;
72 with GNAT.Directory_Operations; use GNAT.Directory_Operations;
73 with GNAT.Expect; use GNAT.Expect;
74 with GNAT.Regpat; use GNAT.Regpat;
75
76 procedure VxAddr2Line is
77
78    Ref_Symbol : String := "adainit";
79    --  This is the name of the reference symbol which runtime address shall
80    --  be provided as the <ref_address> argument.
81
82    --  All supported architectures
83    type Architecture is
84      (WINDOWS_POWERPC,
85       WINDOWS_M68K,
86       SOLARIS_POWERPC,
87       DEC_ALPHA);
88
89    type Arch_Record is record
90       Addr2line_Binary : String_Access;
91       --  Name of the addr2line utility to use.
92
93       Nm_Binary : String_Access;
94       --  Name of the host nm utility, which will be used to find out the
95       --  offset of the reference symbol in the text segment of the partially
96       --  linked executable.
97
98       Addr_Digits_To_Skip : Integer;
99       --  When addresses such as 0xfffffc0001dfed50 are provided, for instance
100       --  on ALPHA, indicate the number of leading digits that can be ignored,
101       --  which will avoid computational overflows. Typically only useful when
102       --  64bit addresses are provided.
103
104       Bt_Offset_From_Call : Integer;
105       --  Offset from a backtrace address to the address of the corresponding
106       --  call instruction. This should always be 0, except on platforms where
107       --  the backtrace addresses actually correspond to return and not call
108       --  points. In such cases, a negative value is most likely.
109    end record;
110
111    --  Configuration for each of the architectures
112    Arch_List : array (Architecture'Range) of Arch_Record :=
113      (WINDOWS_POWERPC =>
114         (Addr2line_Binary    => null,
115          Nm_Binary           => null,
116          Addr_Digits_To_Skip => 0,
117          Bt_Offset_From_Call => -4),
118       WINDOWS_M68K =>
119         (Addr2line_Binary    => null,
120          Nm_Binary           => null,
121          Addr_Digits_To_Skip => 0,
122          Bt_Offset_From_Call => -4),
123       SOLARIS_POWERPC =>
124         (Addr2line_Binary    => null,
125          Nm_Binary           => null,
126          Addr_Digits_To_Skip => 0,
127          Bt_Offset_From_Call => 0),
128       DEC_ALPHA =>
129         (Addr2line_Binary    => null,
130          Nm_Binary           => null,
131          Addr_Digits_To_Skip => 8,
132          Bt_Offset_From_Call => 0)
133      );
134
135    --  Current architecture
136    Cur_Arch : Architecture;
137
138    --  State of architecture detection
139    Detect_Success : Boolean := False;
140
141    -----------------------
142    -- Local subprograms --
143    -----------------------
144
145    procedure Error (Msg : String);
146    pragma No_Return (Error);
147    --  Prints the message and then terminates the program
148
149    procedure Usage;
150    --  Displays the short help message and then terminates the program
151
152    function Get_Reference_Offset return Integer;
153    --  Computes the static offset of the reference symbol by calling nm
154
155    function Get_Value_From_Hex_Arg (Arg : Natural) return Integer;
156    --  Threats the argument number Arg as a C-style hexadecimal literal
157    --  and returns its integer value
158
159    function Hex_Image (Value : Integer) return String_Access;
160    --  Returns access to a string that contains hexadecimal image of Value
161
162    --  Separate functions that provide build-time customization:
163
164    procedure Detect_Arch;
165    --  Saves in Cur_Arch the current architecture, based on the name of
166    --  vxaddr2line instance and properties of the host. Detect_Success is False
167    --  if detection fails
168
169    -----------------
170    -- Detect_Arch --
171    -----------------
172
173    procedure Detect_Arch is
174       Name   : String := Base_Name (Command_Name);
175       Proc   : String := Name (Name'First .. Index (Name, "-") - 1);
176       Target : String := Name (Name'First .. Index (Name, "vxaddr2line") - 1);
177
178    begin
179       Detect_Success := False;
180
181       if Proc = "" then
182          return;
183       end if;
184
185       if Proc = "alpha" then
186          Cur_Arch := DEC_ALPHA;
187       else
188          --  Let's detect the host.
189          --  ??? A naive implementation that can't distinguish between Unixes
190          if Directory_Separator = '/' then
191             Cur_Arch := Architecture'Value ("solaris_" & Proc);
192          else
193             Cur_Arch := Architecture'Value ("windows_" & Proc);
194          end if;
195       end if;
196
197       if Arch_List (Cur_Arch).Addr2line_Binary = null then
198          Arch_List (Cur_Arch).Addr2line_Binary := new String'
199            (Target & "addr2line");
200       end if;
201       if Arch_List (Cur_Arch).Nm_Binary = null then
202          Arch_List (Cur_Arch).Nm_Binary := new String'
203            (Target & "nm");
204       end if;
205
206       Detect_Success := True;
207
208    exception
209       when others =>
210          return;
211    end Detect_Arch;
212
213
214    -----------
215    -- Error --
216    -----------
217
218    procedure Error (Msg : String) is
219    begin
220       Put_Line (Msg);
221       OS_Exit (1);
222       raise Program_Error;
223    end Error;
224
225
226    --------------------------
227    -- Get_Reference_Offset --
228    --------------------------
229
230    function Get_Reference_Offset return Integer is
231       Nm_Cmd  : constant String_Access :=
232                   Locate_Exec_On_Path (Arch_List (Cur_Arch).Nm_Binary.all);
233
234       Nm_Args : Argument_List :=
235                   (new String'("-P"),
236                    new String'(Argument (1)));
237
238       Forever   : aliased String := "^@@@@";
239       Reference : aliased String := Ref_Symbol & "\s+\S\s+([\da-fA-F]+)";
240
241       Pd     : Process_Descriptor;
242       Result : Expect_Match;
243
244    begin
245       --  If Nm is not found, abort
246
247       if Nm_Cmd = null then
248          Error ("Couldn't find " & Arch_List (Cur_Arch).Nm_Binary.all);
249       end if;
250
251       Non_Blocking_Spawn
252         (Pd, Nm_Cmd.all, Nm_Args, Buffer_Size => 0, Err_To_Out => True);
253
254       --  Expect a string containing the reference symbol
255
256       Expect (Pd, Result,
257               Regexp_Array'(1 => Reference'Unchecked_Access),
258               Timeout => -1);
259
260       --  If we are here, the pattern was matched successfully
261
262       declare
263          Match_String : String := Expect_Out_Match (Pd);
264          Matches : Match_Array (0 .. 1);
265          Value : Integer;
266
267       begin
268          Match (Reference, Match_String, Matches);
269          Value := Integer'Value
270            ("16#"
271             & Match_String (Matches (1).First .. Matches (1).Last) & "#");
272
273          --  Expect a string that will never be emitted, so that the
274          --  process can be correctly terminated (with Process_Died)
275
276          Expect (Pd, Result,
277                  Regexp_Array'(1 => Forever'Unchecked_Access),
278                  Timeout => -1);
279
280       exception
281          when Process_Died =>
282             return Value;
283       end;
284
285       --  We can not get here
286
287       raise Program_Error;
288
289    exception
290       when Invalid_Process =>
291          Error ("Could not spawn a process " & Nm_Cmd.all);
292
293       when others    =>
294
295          --  The process died without matching the reference symbol or the
296          --  format wasn't recognized.
297
298          Error ("Unexpected output from " & Nm_Cmd.all);
299    end Get_Reference_Offset;
300
301    ----------------------------
302    -- Get_Value_From_Hex_Arg --
303    ----------------------------
304
305    function Get_Value_From_Hex_Arg (Arg : Natural) return Integer is
306       Offset  : Natural;
307       Cur_Arg : String := Argument (Arg);
308
309    begin
310       --  Skip "0x" prefix if present
311
312       if Cur_Arg'Length > 2 and then Cur_Arg (1 .. 2) = "0x" then
313          Offset := 3;
314       else
315          Offset := 1;
316       end if;
317
318       --  Add architecture-specific offset
319
320       Offset := Offset + Arch_List (Cur_Arch).Addr_Digits_To_Skip;
321
322       --  Convert to value
323
324       return Integer'Value ("16#" & Cur_Arg (Offset .. Cur_Arg'Last) & "#");
325    end Get_Value_From_Hex_Arg;
326
327    ---------------
328    -- Hex_Image --
329    ---------------
330
331    function Hex_Image (Value : Integer) return String_Access is
332       Result    : String (1 .. 20);
333       Start_Pos : Natural;
334
335    begin
336       Put (Result, Value, 16);
337       Start_Pos := Index (Result, "16#") + 3;
338       return new String'(Result (Start_Pos .. Result'Last - 1));
339    end Hex_Image;
340
341    -----------
342    -- Usage --
343    -----------
344
345    procedure Usage is
346    begin
347       Put_Line ("Usage : " & Base_Name (Command_Name)
348                 & " <executable> <"
349                 & Ref_Symbol & " offset on target> <addr1> ...");
350
351       OS_Exit (1);
352    end Usage;
353
354    Ref_Static_Offset, Ref_Runtime_Address, Bt_Address : Integer;
355
356    Addr2line_Cmd : String_Access;
357
358    Addr2line_Args : Argument_List (1 .. 501);
359    --  We expect that there won't be more than 500 backtrace frames
360
361    Addr2line_Args_Count : Natural;
362
363    Success : Boolean;
364
365 --  Start of processing for VxAddr2Line
366
367 begin
368
369    Detect_Arch;
370
371    --  There should be at least two arguments
372
373    if Argument_Count < 2 then
374       Usage;
375    end if;
376
377    --  ??? HARD LIMIT! There should be at most 501 arguments
378
379    if Argument_Count > 501 then
380       Error ("Too many backtrace frames");
381    end if;
382
383    --  Do we have a valid architecture?
384
385    if not Detect_Success then
386       Put_Line ("Couldn't detect the architecture");
387       return;
388    end if;
389
390    Addr2line_Cmd :=
391      Locate_Exec_On_Path (Arch_List (Cur_Arch).Addr2line_Binary.all);
392
393    --  If Addr2line is not found, abort
394
395    if Addr2line_Cmd = null then
396       Error ("Couldn't find " & Arch_List (Cur_Arch).Addr2line_Binary.all);
397    end if;
398
399    --  The first argument specifies the image file. Check if it exists.
400
401    if not Is_Regular_File (Argument (1)) then
402       Error ("Couldn't find the executable " & Argument (1));
403    end if;
404
405    --  The second argument specifies the reference symbol runtime address.
406    --  Let's parse and store it
407
408    Ref_Runtime_Address := Get_Value_From_Hex_Arg (2);
409
410    --  Run nm command to get the reference symbol static offset
411
412    Ref_Static_Offset := Get_Reference_Offset;
413
414    --  Build addr2line parameters. First, the standard part
415
416    Addr2line_Args (1) := new String'("--exe=" & Argument (1));
417    Addr2line_Args_Count := 1;
418
419    --  Now, append to this the adjusted backtraces in arguments 4 and further
420
421    for J in 3 .. Argument_Count loop
422
423       --  Basically, for each address in the runtime backtrace ...
424
425       --  o We compute its offset relatively to the runtime address of the
426       --    reference symbol,
427
428       --  and then ...
429
430       --  o We add this offset to the static one for the reference symbol in
431       --    the executable to find the executable offset corresponding to the
432       --    backtrace address.
433
434       Bt_Address := Get_Value_From_Hex_Arg (J);
435
436       Bt_Address :=
437         Bt_Address - Ref_Runtime_Address
438                    + Ref_Static_Offset
439                    + Arch_List (Cur_Arch).Bt_Offset_From_Call;
440
441       Addr2line_Args_Count := Addr2line_Args_Count + 1;
442       Addr2line_Args (Addr2line_Args_Count) := Hex_Image (Bt_Address);
443    end loop;
444
445    --  Run the resulting command
446
447    Spawn (Addr2line_Cmd.all,
448           Addr2line_Args (1 .. Addr2line_Args_Count), Success);
449
450 exception
451    when others =>
452
453       --  Mask all exceptions
454
455       return;
456 end VxAddr2Line;