Make stap-probe.c:stap_parse_register_operand's "regname" an std::string
[external/binutils.git] / gdb / stap-probe.c
1 /* SystemTap probe support for GDB.
2
3    Copyright (C) 2012-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "stap-probe.h"
22 #include "probe.h"
23 #include "common/vec.h"
24 #include "ui-out.h"
25 #include "objfiles.h"
26 #include "arch-utils.h"
27 #include "command.h"
28 #include "gdbcmd.h"
29 #include "filenames.h"
30 #include "value.h"
31 #include "ax.h"
32 #include "ax-gdb.h"
33 #include "complaints.h"
34 #include "cli/cli-utils.h"
35 #include "linespec.h"
36 #include "user-regs.h"
37 #include "parser-defs.h"
38 #include "language.h"
39 #include "elf-bfd.h"
40
41 #include <ctype.h>
42
43 /* The name of the SystemTap section where we will find information about
44    the probes.  */
45
46 #define STAP_BASE_SECTION_NAME ".stapsdt.base"
47
48 /* Should we display debug information for the probe's argument expression
49    parsing?  */
50
51 static unsigned int stap_expression_debug = 0;
52
53 /* The various possibilities of bitness defined for a probe's argument.
54
55    The relationship is:
56
57    - STAP_ARG_BITNESS_UNDEFINED:  The user hasn't specified the bitness.
58    - STAP_ARG_BITNESS_8BIT_UNSIGNED:  argument string starts with `1@'.
59    - STAP_ARG_BITNESS_8BIT_SIGNED:  argument string starts with `-1@'.
60    - STAP_ARG_BITNESS_16BIT_UNSIGNED:  argument string starts with `2@'.
61    - STAP_ARG_BITNESS_16BIT_SIGNED:  argument string starts with `-2@'.
62    - STAP_ARG_BITNESS_32BIT_UNSIGNED:  argument string starts with `4@'.
63    - STAP_ARG_BITNESS_32BIT_SIGNED:  argument string starts with `-4@'.
64    - STAP_ARG_BITNESS_64BIT_UNSIGNED:  argument string starts with `8@'.
65    - STAP_ARG_BITNESS_64BIT_SIGNED:  argument string starts with `-8@'.  */
66
67 enum stap_arg_bitness
68 {
69   STAP_ARG_BITNESS_UNDEFINED,
70   STAP_ARG_BITNESS_8BIT_UNSIGNED,
71   STAP_ARG_BITNESS_8BIT_SIGNED,
72   STAP_ARG_BITNESS_16BIT_UNSIGNED,
73   STAP_ARG_BITNESS_16BIT_SIGNED,
74   STAP_ARG_BITNESS_32BIT_UNSIGNED,
75   STAP_ARG_BITNESS_32BIT_SIGNED,
76   STAP_ARG_BITNESS_64BIT_UNSIGNED,
77   STAP_ARG_BITNESS_64BIT_SIGNED,
78 };
79
80 /* The following structure represents a single argument for the probe.  */
81
82 struct stap_probe_arg
83 {
84   /* Constructor for stap_probe_arg.  */
85   stap_probe_arg (enum stap_arg_bitness bitness_, struct type *atype_,
86                   expression_up &&aexpr_)
87   : bitness (bitness_), atype (atype_), aexpr (std::move (aexpr_))
88   {}
89
90   /* The bitness of this argument.  */
91   enum stap_arg_bitness bitness;
92
93   /* The corresponding `struct type *' to the bitness.  */
94   struct type *atype;
95
96   /* The argument converted to an internal GDB expression.  */
97   expression_up aexpr;
98 };
99
100 /* Class that implements the static probe methods for "stap" probes.  */
101
102 class stap_static_probe_ops : public static_probe_ops
103 {
104 public:
105   /* See probe.h.  */
106   bool is_linespec (const char **linespecp) const override;
107
108   /* See probe.h.  */
109   void get_probes (std::vector<std::unique_ptr<probe>> *probesp,
110                    struct objfile *objfile) const override;
111
112   /* See probe.h.  */
113   const char *type_name () const override;
114
115   /* See probe.h.  */
116   std::vector<struct info_probe_column> gen_info_probes_table_header
117     () const override;
118 };
119
120 /* SystemTap static_probe_ops.  */
121
122 const stap_static_probe_ops stap_static_probe_ops {};
123
124 class stap_probe : public probe
125 {
126 public:
127   /* Constructor for stap_probe.  */
128   stap_probe (std::string &&name_, std::string &&provider_, CORE_ADDR address_,
129               struct gdbarch *arch_, CORE_ADDR sem_addr, const char *args_text)
130     : probe (std::move (name_), std::move (provider_), address_, arch_),
131       m_sem_addr (sem_addr),
132       m_have_parsed_args (false), m_unparsed_args_text (args_text)
133   {}
134
135   /* See probe.h.  */
136   CORE_ADDR get_relocated_address (struct objfile *objfile) override;
137
138   /* See probe.h.  */
139   unsigned get_argument_count (struct frame_info *frame) override;
140
141   /* See probe.h.  */
142   bool can_evaluate_arguments () const override;
143
144   /* See probe.h.  */
145   struct value *evaluate_argument (unsigned n,
146                                    struct frame_info *frame) override;
147
148   /* See probe.h.  */
149   void compile_to_ax (struct agent_expr *aexpr,
150                       struct axs_value *axs_value,
151                       unsigned n) override;
152
153   /* See probe.h.  */
154   void set_semaphore (struct objfile *objfile,
155                       struct gdbarch *gdbarch) override;
156
157   /* See probe.h.  */
158   void clear_semaphore (struct objfile *objfile,
159                         struct gdbarch *gdbarch) override;
160
161   /* See probe.h.  */
162   const static_probe_ops *get_static_ops () const override;
163
164   /* See probe.h.  */
165   std::vector<const char *> gen_info_probes_table_values () const override;
166
167   /* Return argument N of probe.
168
169      If the probe's arguments have not been parsed yet, parse them.  If
170      there are no arguments, throw an exception (error).  Otherwise,
171      return the requested argument.  */
172   struct stap_probe_arg *get_arg_by_number (unsigned n,
173                                             struct gdbarch *gdbarch)
174   {
175     if (!m_have_parsed_args)
176       this->parse_arguments (gdbarch);
177
178     gdb_assert (m_have_parsed_args);
179     if (m_parsed_args.empty ())
180       internal_error (__FILE__, __LINE__,
181                       _("Probe '%s' apparently does not have arguments, but \n"
182                         "GDB is requesting its argument number %u anyway.  "
183                         "This should not happen.  Please report this bug."),
184                       this->get_name ().c_str (), n);
185
186     if (n > m_parsed_args.size ())
187       internal_error (__FILE__, __LINE__,
188                       _("Probe '%s' has %d arguments, but GDB is requesting\n"
189                         "argument %u.  This should not happen.  Please\n"
190                         "report this bug."),
191                       this->get_name ().c_str (),
192                       (int) m_parsed_args.size (), n);
193
194     return &m_parsed_args[n];
195   }
196
197   /* Function which parses an argument string from the probe,
198      correctly splitting the arguments and storing their information
199      in properly ways.
200
201      Consider the following argument string (x86 syntax):
202
203      `4@%eax 4@$10'
204
205      We have two arguments, `%eax' and `$10', both with 32-bit
206      unsigned bitness.  This function basically handles them, properly
207      filling some structures with this information.  */
208   void parse_arguments (struct gdbarch *gdbarch);
209
210 private:
211   /* If the probe has a semaphore associated, then this is the value of
212      it, relative to SECT_OFF_DATA.  */
213   CORE_ADDR m_sem_addr;
214
215   /* True if the arguments have been parsed.  */
216   bool m_have_parsed_args;
217
218   /* The text version of the probe's arguments, unparsed.  */
219   const char *m_unparsed_args_text;
220
221   /* Information about each argument.  This is an array of `stap_probe_arg',
222      with each entry representing one argument.  This is only valid if
223      M_ARGS_PARSED is true.  */
224   std::vector<struct stap_probe_arg> m_parsed_args;
225 };
226
227 /* When parsing the arguments, we have to establish different precedences
228    for the various kinds of asm operators.  This enumeration represents those
229    precedences.
230
231    This logic behind this is available at
232    <http://sourceware.org/binutils/docs/as/Infix-Ops.html#Infix-Ops>, or using
233    the command "info '(as)Infix Ops'".  */
234
235 enum stap_operand_prec
236 {
237   /* Lowest precedence, used for non-recognized operands or for the beginning
238      of the parsing process.  */
239   STAP_OPERAND_PREC_NONE = 0,
240
241   /* Precedence of logical OR.  */
242   STAP_OPERAND_PREC_LOGICAL_OR,
243
244   /* Precedence of logical AND.  */
245   STAP_OPERAND_PREC_LOGICAL_AND,
246
247   /* Precedence of additive (plus, minus) and comparative (equal, less,
248      greater-than, etc) operands.  */
249   STAP_OPERAND_PREC_ADD_CMP,
250
251   /* Precedence of bitwise operands (bitwise OR, XOR, bitwise AND,
252      logical NOT).  */
253   STAP_OPERAND_PREC_BITWISE,
254
255   /* Precedence of multiplicative operands (multiplication, division,
256      remainder, left shift and right shift).  */
257   STAP_OPERAND_PREC_MUL
258 };
259
260 static void stap_parse_argument_1 (struct stap_parse_info *p, bool has_lhs,
261                                    enum stap_operand_prec prec);
262
263 static void stap_parse_argument_conditionally (struct stap_parse_info *p);
264
265 /* Returns true if *S is an operator, false otherwise.  */
266
267 static bool stap_is_operator (const char *op);
268
269 static void
270 show_stapexpressiondebug (struct ui_file *file, int from_tty,
271                           struct cmd_list_element *c, const char *value)
272 {
273   fprintf_filtered (file, _("SystemTap Probe expression debugging is %s.\n"),
274                     value);
275 }
276
277 /* Returns the operator precedence level of OP, or STAP_OPERAND_PREC_NONE
278    if the operator code was not recognized.  */
279
280 static enum stap_operand_prec
281 stap_get_operator_prec (enum exp_opcode op)
282 {
283   switch (op)
284     {
285     case BINOP_LOGICAL_OR:
286       return STAP_OPERAND_PREC_LOGICAL_OR;
287
288     case BINOP_LOGICAL_AND:
289       return STAP_OPERAND_PREC_LOGICAL_AND;
290
291     case BINOP_ADD:
292     case BINOP_SUB:
293     case BINOP_EQUAL:
294     case BINOP_NOTEQUAL:
295     case BINOP_LESS:
296     case BINOP_LEQ:
297     case BINOP_GTR:
298     case BINOP_GEQ:
299       return STAP_OPERAND_PREC_ADD_CMP;
300
301     case BINOP_BITWISE_IOR:
302     case BINOP_BITWISE_AND:
303     case BINOP_BITWISE_XOR:
304     case UNOP_LOGICAL_NOT:
305       return STAP_OPERAND_PREC_BITWISE;
306
307     case BINOP_MUL:
308     case BINOP_DIV:
309     case BINOP_REM:
310     case BINOP_LSH:
311     case BINOP_RSH:
312       return STAP_OPERAND_PREC_MUL;
313
314     default:
315       return STAP_OPERAND_PREC_NONE;
316     }
317 }
318
319 /* Given S, read the operator in it.  Return the EXP_OPCODE which
320    represents the operator detected, or throw an error if no operator
321    was found.  */
322
323 static enum exp_opcode
324 stap_get_opcode (const char **s)
325 {
326   const char c = **s;
327   enum exp_opcode op;
328
329   *s += 1;
330
331   switch (c)
332     {
333     case '*':
334       op = BINOP_MUL;
335       break;
336
337     case '/':
338       op = BINOP_DIV;
339       break;
340
341     case '%':
342       op = BINOP_REM;
343     break;
344
345     case '<':
346       op = BINOP_LESS;
347       if (**s == '<')
348         {
349           *s += 1;
350           op = BINOP_LSH;
351         }
352       else if (**s == '=')
353         {
354           *s += 1;
355           op = BINOP_LEQ;
356         }
357       else if (**s == '>')
358         {
359           *s += 1;
360           op = BINOP_NOTEQUAL;
361         }
362     break;
363
364     case '>':
365       op = BINOP_GTR;
366       if (**s == '>')
367         {
368           *s += 1;
369           op = BINOP_RSH;
370         }
371       else if (**s == '=')
372         {
373           *s += 1;
374           op = BINOP_GEQ;
375         }
376     break;
377
378     case '|':
379       op = BINOP_BITWISE_IOR;
380       if (**s == '|')
381         {
382           *s += 1;
383           op = BINOP_LOGICAL_OR;
384         }
385     break;
386
387     case '&':
388       op = BINOP_BITWISE_AND;
389       if (**s == '&')
390         {
391           *s += 1;
392           op = BINOP_LOGICAL_AND;
393         }
394     break;
395
396     case '^':
397       op = BINOP_BITWISE_XOR;
398       break;
399
400     case '!':
401       op = UNOP_LOGICAL_NOT;
402       break;
403
404     case '+':
405       op = BINOP_ADD;
406       break;
407
408     case '-':
409       op = BINOP_SUB;
410       break;
411
412     case '=':
413       gdb_assert (**s == '=');
414       op = BINOP_EQUAL;
415       break;
416
417     default:
418       error (_("Invalid opcode in expression `%s' for SystemTap"
419                "probe"), *s);
420     }
421
422   return op;
423 }
424
425 /* Given the bitness of the argument, represented by B, return the
426    corresponding `struct type *', or throw an error if B is
427    unknown.  */
428
429 static struct type *
430 stap_get_expected_argument_type (struct gdbarch *gdbarch,
431                                  enum stap_arg_bitness b,
432                                  const char *probe_name)
433 {
434   switch (b)
435     {
436     case STAP_ARG_BITNESS_UNDEFINED:
437       if (gdbarch_addr_bit (gdbarch) == 32)
438         return builtin_type (gdbarch)->builtin_uint32;
439       else
440         return builtin_type (gdbarch)->builtin_uint64;
441
442     case STAP_ARG_BITNESS_8BIT_UNSIGNED:
443       return builtin_type (gdbarch)->builtin_uint8;
444
445     case STAP_ARG_BITNESS_8BIT_SIGNED:
446       return builtin_type (gdbarch)->builtin_int8;
447
448     case STAP_ARG_BITNESS_16BIT_UNSIGNED:
449       return builtin_type (gdbarch)->builtin_uint16;
450
451     case STAP_ARG_BITNESS_16BIT_SIGNED:
452       return builtin_type (gdbarch)->builtin_int16;
453
454     case STAP_ARG_BITNESS_32BIT_SIGNED:
455       return builtin_type (gdbarch)->builtin_int32;
456
457     case STAP_ARG_BITNESS_32BIT_UNSIGNED:
458       return builtin_type (gdbarch)->builtin_uint32;
459
460     case STAP_ARG_BITNESS_64BIT_SIGNED:
461       return builtin_type (gdbarch)->builtin_int64;
462
463     case STAP_ARG_BITNESS_64BIT_UNSIGNED:
464       return builtin_type (gdbarch)->builtin_uint64;
465
466     default:
467       error (_("Undefined bitness for probe '%s'."), probe_name);
468       break;
469     }
470 }
471
472 /* Helper function to check for a generic list of prefixes.  GDBARCH
473    is the current gdbarch being used.  S is the expression being
474    analyzed.  If R is not NULL, it will be used to return the found
475    prefix.  PREFIXES is the list of expected prefixes.
476
477    This function does a case-insensitive match.
478
479    Return true if any prefix has been found, false otherwise.  */
480
481 static bool
482 stap_is_generic_prefix (struct gdbarch *gdbarch, const char *s,
483                         const char **r, const char *const *prefixes)
484 {
485   const char *const *p;
486
487   if (prefixes == NULL)
488     {
489       if (r != NULL)
490         *r = "";
491
492       return true;
493     }
494
495   for (p = prefixes; *p != NULL; ++p)
496     if (strncasecmp (s, *p, strlen (*p)) == 0)
497       {
498         if (r != NULL)
499           *r = *p;
500
501         return true;
502       }
503
504   return false;
505 }
506
507 /* Return true if S points to a register prefix, false otherwise.  For
508    a description of the arguments, look at stap_is_generic_prefix.  */
509
510 static bool
511 stap_is_register_prefix (struct gdbarch *gdbarch, const char *s,
512                          const char **r)
513 {
514   const char *const *t = gdbarch_stap_register_prefixes (gdbarch);
515
516   return stap_is_generic_prefix (gdbarch, s, r, t);
517 }
518
519 /* Return true if S points to a register indirection prefix, false
520    otherwise.  For a description of the arguments, look at
521    stap_is_generic_prefix.  */
522
523 static bool
524 stap_is_register_indirection_prefix (struct gdbarch *gdbarch, const char *s,
525                                      const char **r)
526 {
527   const char *const *t = gdbarch_stap_register_indirection_prefixes (gdbarch);
528
529   return stap_is_generic_prefix (gdbarch, s, r, t);
530 }
531
532 /* Return true if S points to an integer prefix, false otherwise.  For
533    a description of the arguments, look at stap_is_generic_prefix.
534
535    This function takes care of analyzing whether we are dealing with
536    an expected integer prefix, or, if there is no integer prefix to be
537    expected, whether we are dealing with a digit.  It does a
538    case-insensitive match.  */
539
540 static bool
541 stap_is_integer_prefix (struct gdbarch *gdbarch, const char *s,
542                         const char **r)
543 {
544   const char *const *t = gdbarch_stap_integer_prefixes (gdbarch);
545   const char *const *p;
546
547   if (t == NULL)
548     {
549       /* A NULL value here means that integers do not have a prefix.
550          We just check for a digit then.  */
551       if (r != NULL)
552         *r = "";
553
554       return isdigit (*s) > 0;
555     }
556
557   for (p = t; *p != NULL; ++p)
558     {
559       size_t len = strlen (*p);
560
561       if ((len == 0 && isdigit (*s))
562           || (len > 0 && strncasecmp (s, *p, len) == 0))
563         {
564           /* Integers may or may not have a prefix.  The "len == 0"
565              check covers the case when integers do not have a prefix
566              (therefore, we just check if we have a digit).  The call
567              to "strncasecmp" covers the case when they have a
568              prefix.  */
569           if (r != NULL)
570             *r = *p;
571
572           return true;
573         }
574     }
575
576   return false;
577 }
578
579 /* Helper function to check for a generic list of suffixes.  If we are
580    not expecting any suffixes, then it just returns 1.  If we are
581    expecting at least one suffix, then it returns true if a suffix has
582    been found, false otherwise.  GDBARCH is the current gdbarch being
583    used.  S is the expression being analyzed.  If R is not NULL, it
584    will be used to return the found suffix.  SUFFIXES is the list of
585    expected suffixes.  This function does a case-insensitive
586    match.  */
587
588 static bool
589 stap_generic_check_suffix (struct gdbarch *gdbarch, const char *s,
590                            const char **r, const char *const *suffixes)
591 {
592   const char *const *p;
593   bool found = false;
594
595   if (suffixes == NULL)
596     {
597       if (r != NULL)
598         *r = "";
599
600       return true;
601     }
602
603   for (p = suffixes; *p != NULL; ++p)
604     if (strncasecmp (s, *p, strlen (*p)) == 0)
605       {
606         if (r != NULL)
607           *r = *p;
608
609         found = true;
610         break;
611       }
612
613   return found;
614 }
615
616 /* Return true if S points to an integer suffix, false otherwise.  For
617    a description of the arguments, look at
618    stap_generic_check_suffix.  */
619
620 static bool
621 stap_check_integer_suffix (struct gdbarch *gdbarch, const char *s,
622                            const char **r)
623 {
624   const char *const *p = gdbarch_stap_integer_suffixes (gdbarch);
625
626   return stap_generic_check_suffix (gdbarch, s, r, p);
627 }
628
629 /* Return true if S points to a register suffix, false otherwise.  For
630    a description of the arguments, look at
631    stap_generic_check_suffix.  */
632
633 static bool
634 stap_check_register_suffix (struct gdbarch *gdbarch, const char *s,
635                             const char **r)
636 {
637   const char *const *p = gdbarch_stap_register_suffixes (gdbarch);
638
639   return stap_generic_check_suffix (gdbarch, s, r, p);
640 }
641
642 /* Return true if S points to a register indirection suffix, false
643    otherwise.  For a description of the arguments, look at
644    stap_generic_check_suffix.  */
645
646 static bool
647 stap_check_register_indirection_suffix (struct gdbarch *gdbarch, const char *s,
648                                         const char **r)
649 {
650   const char *const *p = gdbarch_stap_register_indirection_suffixes (gdbarch);
651
652   return stap_generic_check_suffix (gdbarch, s, r, p);
653 }
654
655 /* Function responsible for parsing a register operand according to
656    SystemTap parlance.  Assuming:
657
658    RP  = register prefix
659    RS  = register suffix
660    RIP = register indirection prefix
661    RIS = register indirection suffix
662    
663    Then a register operand can be:
664    
665    [RIP] [RP] REGISTER [RS] [RIS]
666
667    This function takes care of a register's indirection, displacement and
668    direct access.  It also takes into consideration the fact that some
669    registers are named differently inside and outside GDB, e.g., PPC's
670    general-purpose registers are represented by integers in the assembly
671    language (e.g., `15' is the 15th general-purpose register), but inside
672    GDB they have a prefix (the letter `r') appended.  */
673
674 static void
675 stap_parse_register_operand (struct stap_parse_info *p)
676 {
677   /* Simple flag to indicate whether we have seen a minus signal before
678      certain number.  */
679   bool got_minus = false;
680   /* Flags to indicate whether this register access is being displaced and/or
681      indirected.  */
682   bool disp_p = false;
683   bool indirect_p = false;
684   struct gdbarch *gdbarch = p->gdbarch;
685   /* Needed to generate the register name as a part of an expression.  */
686   struct stoken str;
687   /* Variables used to extract the register name from the probe's
688      argument.  */
689   const char *start;
690   const char *gdb_reg_prefix = gdbarch_stap_gdb_register_prefix (gdbarch);
691   const char *gdb_reg_suffix = gdbarch_stap_gdb_register_suffix (gdbarch);
692   const char *reg_prefix;
693   const char *reg_ind_prefix;
694   const char *reg_suffix;
695   const char *reg_ind_suffix;
696
697   /* Checking for a displacement argument.  */
698   if (*p->arg == '+')
699     {
700       /* If it's a plus sign, we don't need to do anything, just advance the
701          pointer.  */
702       ++p->arg;
703     }
704   else if (*p->arg == '-')
705     {
706       got_minus = true;
707       ++p->arg;
708     }
709
710   if (isdigit (*p->arg))
711     {
712       /* The value of the displacement.  */
713       long displacement;
714       char *endp;
715
716       disp_p = true;
717       displacement = strtol (p->arg, &endp, 10);
718       p->arg = endp;
719
720       /* Generating the expression for the displacement.  */
721       write_exp_elt_opcode (&p->pstate, OP_LONG);
722       write_exp_elt_type (&p->pstate, builtin_type (gdbarch)->builtin_long);
723       write_exp_elt_longcst (&p->pstate, displacement);
724       write_exp_elt_opcode (&p->pstate, OP_LONG);
725       if (got_minus)
726         write_exp_elt_opcode (&p->pstate, UNOP_NEG);
727     }
728
729   /* Getting rid of register indirection prefix.  */
730   if (stap_is_register_indirection_prefix (gdbarch, p->arg, &reg_ind_prefix))
731     {
732       indirect_p = true;
733       p->arg += strlen (reg_ind_prefix);
734     }
735
736   if (disp_p && !indirect_p)
737     error (_("Invalid register displacement syntax on expression `%s'."),
738            p->saved_arg);
739
740   /* Getting rid of register prefix.  */
741   if (stap_is_register_prefix (gdbarch, p->arg, &reg_prefix))
742     p->arg += strlen (reg_prefix);
743
744   /* Now we should have only the register name.  Let's extract it and get
745      the associated number.  */
746   start = p->arg;
747
748   /* We assume the register name is composed by letters and numbers.  */
749   while (isalnum (*p->arg))
750     ++p->arg;
751
752   std::string regname (start, p->arg - start);
753
754   /* We only add the GDB's register prefix/suffix if we are dealing with
755      a numeric register.  */
756   if (isdigit (*start))
757     {
758       if (gdb_reg_prefix != NULL)
759         regname = gdb_reg_prefix + regname;
760
761       if (gdb_reg_suffix != NULL)
762         regname += gdb_reg_suffix;
763     }
764
765   /* Is this a valid register name?  */
766   if (user_reg_map_name_to_regnum (gdbarch,
767                                    regname.c_str (),
768                                    regname.size ()) == -1)
769     error (_("Invalid register name `%s' on expression `%s'."),
770            regname.c_str (), p->saved_arg);
771
772   write_exp_elt_opcode (&p->pstate, OP_REGISTER);
773   str.ptr = regname.c_str ();
774   str.length = regname.size ();
775   write_exp_string (&p->pstate, str);
776   write_exp_elt_opcode (&p->pstate, OP_REGISTER);
777
778   if (indirect_p)
779     {
780       if (disp_p)
781         write_exp_elt_opcode (&p->pstate, BINOP_ADD);
782
783       /* Casting to the expected type.  */
784       write_exp_elt_opcode (&p->pstate, UNOP_CAST);
785       write_exp_elt_type (&p->pstate, lookup_pointer_type (p->arg_type));
786       write_exp_elt_opcode (&p->pstate, UNOP_CAST);
787
788       write_exp_elt_opcode (&p->pstate, UNOP_IND);
789     }
790
791   /* Getting rid of the register name suffix.  */
792   if (stap_check_register_suffix (gdbarch, p->arg, &reg_suffix))
793     p->arg += strlen (reg_suffix);
794   else
795     error (_("Missing register name suffix on expression `%s'."),
796            p->saved_arg);
797
798   /* Getting rid of the register indirection suffix.  */
799   if (indirect_p)
800     {
801       if (stap_check_register_indirection_suffix (gdbarch, p->arg,
802                                                   &reg_ind_suffix))
803         p->arg += strlen (reg_ind_suffix);
804       else
805         error (_("Missing indirection suffix on expression `%s'."),
806                p->saved_arg);
807     }
808 }
809
810 /* This function is responsible for parsing a single operand.
811
812    A single operand can be:
813
814       - an unary operation (e.g., `-5', `~2', or even with subexpressions
815         like `-(2 + 1)')
816       - a register displacement, which will be treated as a register
817         operand (e.g., `-4(%eax)' on x86)
818       - a numeric constant, or
819       - a register operand (see function `stap_parse_register_operand')
820
821    The function also calls special-handling functions to deal with
822    unrecognized operands, allowing arch-specific parsers to be
823    created.  */
824
825 static void
826 stap_parse_single_operand (struct stap_parse_info *p)
827 {
828   struct gdbarch *gdbarch = p->gdbarch;
829   const char *int_prefix = NULL;
830
831   /* We first try to parse this token as a "special token".  */
832   if (gdbarch_stap_parse_special_token_p (gdbarch)
833       && (gdbarch_stap_parse_special_token (gdbarch, p) != 0))
834     {
835       /* If the return value of the above function is not zero,
836          it means it successfully parsed the special token.
837
838          If it is NULL, we try to parse it using our method.  */
839       return;
840     }
841
842   if (*p->arg == '-' || *p->arg == '~' || *p->arg == '+')
843     {
844       char c = *p->arg;
845       /* We use this variable to do a lookahead.  */
846       const char *tmp = p->arg;
847       bool has_digit = false;
848
849       /* Skipping signal.  */
850       ++tmp;
851
852       /* This is an unary operation.  Here is a list of allowed tokens
853          here:
854
855          - numeric literal;
856          - number (from register displacement)
857          - subexpression (beginning with `(')
858
859          We handle the register displacement here, and the other cases
860          recursively.  */
861       if (p->inside_paren_p)
862         tmp = skip_spaces (tmp);
863
864       while (isdigit (*tmp))
865         {
866           /* We skip the digit here because we are only interested in
867              knowing what kind of unary operation this is.  The digit
868              will be handled by one of the functions that will be
869              called below ('stap_parse_argument_conditionally' or
870              'stap_parse_register_operand').  */
871           ++tmp;
872           has_digit = true;
873         }
874
875       if (has_digit && stap_is_register_indirection_prefix (gdbarch, tmp,
876                                                             NULL))
877         {
878           /* If we are here, it means it is a displacement.  The only
879              operations allowed here are `-' and `+'.  */
880           if (c != '-' && c != '+')
881             error (_("Invalid operator `%c' for register displacement "
882                      "on expression `%s'."), c, p->saved_arg);
883
884           stap_parse_register_operand (p);
885         }
886       else
887         {
888           /* This is not a displacement.  We skip the operator, and
889              deal with it when the recursion returns.  */
890           ++p->arg;
891           stap_parse_argument_conditionally (p);
892           if (c == '-')
893             write_exp_elt_opcode (&p->pstate, UNOP_NEG);
894           else if (c == '~')
895             write_exp_elt_opcode (&p->pstate, UNOP_COMPLEMENT);
896         }
897     }
898   else if (isdigit (*p->arg))
899     {
900       /* A temporary variable, needed for lookahead.  */
901       const char *tmp = p->arg;
902       char *endp;
903       long number;
904
905       /* We can be dealing with a numeric constant, or with a register
906          displacement.  */
907       number = strtol (tmp, &endp, 10);
908       tmp = endp;
909
910       if (p->inside_paren_p)
911         tmp = skip_spaces (tmp);
912
913       /* If "stap_is_integer_prefix" returns true, it means we can
914          accept integers without a prefix here.  But we also need to
915          check whether the next token (i.e., "tmp") is not a register
916          indirection prefix.  */
917       if (stap_is_integer_prefix (gdbarch, p->arg, NULL)
918           && !stap_is_register_indirection_prefix (gdbarch, tmp, NULL))
919         {
920           const char *int_suffix;
921
922           /* We are dealing with a numeric constant.  */
923           write_exp_elt_opcode (&p->pstate, OP_LONG);
924           write_exp_elt_type (&p->pstate,
925                               builtin_type (gdbarch)->builtin_long);
926           write_exp_elt_longcst (&p->pstate, number);
927           write_exp_elt_opcode (&p->pstate, OP_LONG);
928
929           p->arg = tmp;
930
931           if (stap_check_integer_suffix (gdbarch, p->arg, &int_suffix))
932             p->arg += strlen (int_suffix);
933           else
934             error (_("Invalid constant suffix on expression `%s'."),
935                    p->saved_arg);
936         }
937       else if (stap_is_register_indirection_prefix (gdbarch, tmp, NULL))
938         stap_parse_register_operand (p);
939       else
940         error (_("Unknown numeric token on expression `%s'."),
941                p->saved_arg);
942     }
943   else if (stap_is_integer_prefix (gdbarch, p->arg, &int_prefix))
944     {
945       /* We are dealing with a numeric constant.  */
946       long number;
947       char *endp;
948       const char *int_suffix;
949
950       p->arg += strlen (int_prefix);
951       number = strtol (p->arg, &endp, 10);
952       p->arg = endp;
953
954       write_exp_elt_opcode (&p->pstate, OP_LONG);
955       write_exp_elt_type (&p->pstate, builtin_type (gdbarch)->builtin_long);
956       write_exp_elt_longcst (&p->pstate, number);
957       write_exp_elt_opcode (&p->pstate, OP_LONG);
958
959       if (stap_check_integer_suffix (gdbarch, p->arg, &int_suffix))
960         p->arg += strlen (int_suffix);
961       else
962         error (_("Invalid constant suffix on expression `%s'."),
963                p->saved_arg);
964     }
965   else if (stap_is_register_prefix (gdbarch, p->arg, NULL)
966            || stap_is_register_indirection_prefix (gdbarch, p->arg, NULL))
967     stap_parse_register_operand (p);
968   else
969     error (_("Operator `%c' not recognized on expression `%s'."),
970            *p->arg, p->saved_arg);
971 }
972
973 /* This function parses an argument conditionally, based on single or
974    non-single operands.  A non-single operand would be a parenthesized
975    expression (e.g., `(2 + 1)'), and a single operand is anything that
976    starts with `-', `~', `+' (i.e., unary operators), a digit, or
977    something recognized by `gdbarch_stap_is_single_operand'.  */
978
979 static void
980 stap_parse_argument_conditionally (struct stap_parse_info *p)
981 {
982   gdb_assert (gdbarch_stap_is_single_operand_p (p->gdbarch));
983
984   if (*p->arg == '-' || *p->arg == '~' || *p->arg == '+' /* Unary.  */
985       || isdigit (*p->arg)
986       || gdbarch_stap_is_single_operand (p->gdbarch, p->arg))
987     stap_parse_single_operand (p);
988   else if (*p->arg == '(')
989     {
990       /* We are dealing with a parenthesized operand.  It means we
991          have to parse it as it was a separate expression, without
992          left-side or precedence.  */
993       ++p->arg;
994       p->arg = skip_spaces (p->arg);
995       ++p->inside_paren_p;
996
997       stap_parse_argument_1 (p, 0, STAP_OPERAND_PREC_NONE);
998
999       --p->inside_paren_p;
1000       if (*p->arg != ')')
1001         error (_("Missign close-paren on expression `%s'."),
1002                p->saved_arg);
1003
1004       ++p->arg;
1005       if (p->inside_paren_p)
1006         p->arg = skip_spaces (p->arg);
1007     }
1008   else
1009     error (_("Cannot parse expression `%s'."), p->saved_arg);
1010 }
1011
1012 /* Helper function for `stap_parse_argument'.  Please, see its comments to
1013    better understand what this function does.  */
1014
1015 static void
1016 stap_parse_argument_1 (struct stap_parse_info *p, bool has_lhs,
1017                        enum stap_operand_prec prec)
1018 {
1019   /* This is an operator-precedence parser.
1020
1021      We work with left- and right-sides of expressions, and
1022      parse them depending on the precedence of the operators
1023      we find.  */
1024
1025   gdb_assert (p->arg != NULL);
1026
1027   if (p->inside_paren_p)
1028     p->arg = skip_spaces (p->arg);
1029
1030   if (!has_lhs)
1031     {
1032       /* We were called without a left-side, either because this is the
1033          first call, or because we were called to parse a parenthesized
1034          expression.  It doesn't really matter; we have to parse the
1035          left-side in order to continue the process.  */
1036       stap_parse_argument_conditionally (p);
1037     }
1038
1039   /* Start to parse the right-side, and to "join" left and right sides
1040      depending on the operation specified.
1041
1042      This loop shall continue until we run out of characters in the input,
1043      or until we find a close-parenthesis, which means that we've reached
1044      the end of a sub-expression.  */
1045   while (*p->arg != '\0' && *p->arg != ')' && !isspace (*p->arg))
1046     {
1047       const char *tmp_exp_buf;
1048       enum exp_opcode opcode;
1049       enum stap_operand_prec cur_prec;
1050
1051       if (!stap_is_operator (p->arg))
1052         error (_("Invalid operator `%c' on expression `%s'."), *p->arg,
1053                p->saved_arg);
1054
1055       /* We have to save the current value of the expression buffer because
1056          the `stap_get_opcode' modifies it in order to get the current
1057          operator.  If this operator's precedence is lower than PREC, we
1058          should return and not advance the expression buffer pointer.  */
1059       tmp_exp_buf = p->arg;
1060       opcode = stap_get_opcode (&tmp_exp_buf);
1061
1062       cur_prec = stap_get_operator_prec (opcode);
1063       if (cur_prec < prec)
1064         {
1065           /* If the precedence of the operator that we are seeing now is
1066              lower than the precedence of the first operator seen before
1067              this parsing process began, it means we should stop parsing
1068              and return.  */
1069           break;
1070         }
1071
1072       p->arg = tmp_exp_buf;
1073       if (p->inside_paren_p)
1074         p->arg = skip_spaces (p->arg);
1075
1076       /* Parse the right-side of the expression.  */
1077       stap_parse_argument_conditionally (p);
1078
1079       /* While we still have operators, try to parse another
1080          right-side, but using the current right-side as a left-side.  */
1081       while (*p->arg != '\0' && stap_is_operator (p->arg))
1082         {
1083           enum exp_opcode lookahead_opcode;
1084           enum stap_operand_prec lookahead_prec;
1085
1086           /* Saving the current expression buffer position.  The explanation
1087              is the same as above.  */
1088           tmp_exp_buf = p->arg;
1089           lookahead_opcode = stap_get_opcode (&tmp_exp_buf);
1090           lookahead_prec = stap_get_operator_prec (lookahead_opcode);
1091
1092           if (lookahead_prec <= prec)
1093             {
1094               /* If we are dealing with an operator whose precedence is lower
1095                  than the first one, just abandon the attempt.  */
1096               break;
1097             }
1098
1099           /* Parse the right-side of the expression, but since we already
1100              have a left-side at this point, set `has_lhs' to 1.  */
1101           stap_parse_argument_1 (p, 1, lookahead_prec);
1102         }
1103
1104       write_exp_elt_opcode (&p->pstate, opcode);
1105     }
1106 }
1107
1108 /* Parse a probe's argument.
1109
1110    Assuming that:
1111
1112    LP = literal integer prefix
1113    LS = literal integer suffix
1114
1115    RP = register prefix
1116    RS = register suffix
1117
1118    RIP = register indirection prefix
1119    RIS = register indirection suffix
1120
1121    This routine assumes that arguments' tokens are of the form:
1122
1123    - [LP] NUMBER [LS]
1124    - [RP] REGISTER [RS]
1125    - [RIP] [RP] REGISTER [RS] [RIS]
1126    - If we find a number without LP, we try to parse it as a literal integer
1127    constant (if LP == NULL), or as a register displacement.
1128    - We count parenthesis, and only skip whitespaces if we are inside them.
1129    - If we find an operator, we skip it.
1130
1131    This function can also call a special function that will try to match
1132    unknown tokens.  It will return the expression_up generated from
1133    parsing the argument.  */
1134
1135 static expression_up
1136 stap_parse_argument (const char **arg, struct type *atype,
1137                      struct gdbarch *gdbarch)
1138 {
1139   /* We need to initialize the expression buffer, in order to begin
1140      our parsing efforts.  We use language_c here because we may need
1141      to do pointer arithmetics.  */
1142   struct stap_parse_info p (*arg, atype, language_def (language_c),
1143                             gdbarch);
1144
1145   stap_parse_argument_1 (&p, 0, STAP_OPERAND_PREC_NONE);
1146
1147   gdb_assert (p.inside_paren_p == 0);
1148
1149   /* Casting the final expression to the appropriate type.  */
1150   write_exp_elt_opcode (&p.pstate, UNOP_CAST);
1151   write_exp_elt_type (&p.pstate, atype);
1152   write_exp_elt_opcode (&p.pstate, UNOP_CAST);
1153
1154   p.arg = skip_spaces (p.arg);
1155   *arg = p.arg;
1156
1157   return p.pstate.release ();
1158 }
1159
1160 /* Implementation of 'parse_arguments' method.  */
1161
1162 void
1163 stap_probe::parse_arguments (struct gdbarch *gdbarch)
1164 {
1165   const char *cur;
1166
1167   gdb_assert (!m_have_parsed_args);
1168   cur = m_unparsed_args_text;
1169   m_have_parsed_args = true;
1170
1171   if (cur == NULL || *cur == '\0' || *cur == ':')
1172     return;
1173
1174   while (*cur != '\0')
1175     {
1176       enum stap_arg_bitness bitness;
1177       bool got_minus = false;
1178
1179       /* We expect to find something like:
1180
1181          N@OP
1182
1183          Where `N' can be [+,-][1,2,4,8].  This is not mandatory, so
1184          we check it here.  If we don't find it, go to the next
1185          state.  */
1186       if ((cur[0] == '-' && isdigit (cur[1]) && cur[2] == '@')
1187           || (isdigit (cur[0]) && cur[1] == '@'))
1188         {
1189           if (*cur == '-')
1190             {
1191               /* Discard the `-'.  */
1192               ++cur;
1193               got_minus = true;
1194             }
1195
1196           /* Defining the bitness.  */
1197           switch (*cur)
1198             {
1199             case '1':
1200               bitness = (got_minus ? STAP_ARG_BITNESS_8BIT_SIGNED
1201                          : STAP_ARG_BITNESS_8BIT_UNSIGNED);
1202               break;
1203
1204             case '2':
1205               bitness = (got_minus ? STAP_ARG_BITNESS_16BIT_SIGNED
1206                          : STAP_ARG_BITNESS_16BIT_UNSIGNED);
1207               break;
1208
1209             case '4':
1210               bitness = (got_minus ? STAP_ARG_BITNESS_32BIT_SIGNED
1211                          : STAP_ARG_BITNESS_32BIT_UNSIGNED);
1212               break;
1213
1214             case '8':
1215               bitness = (got_minus ? STAP_ARG_BITNESS_64BIT_SIGNED
1216                          : STAP_ARG_BITNESS_64BIT_UNSIGNED);
1217               break;
1218
1219             default:
1220               {
1221                 /* We have an error, because we don't expect anything
1222                    except 1, 2, 4 and 8.  */
1223                 warning (_("unrecognized bitness %s%c' for probe `%s'"),
1224                          got_minus ? "`-" : "`", *cur,
1225                          this->get_name ().c_str ());
1226                 return;
1227               }
1228             }
1229           /* Discard the number and the `@' sign.  */
1230           cur += 2;
1231         }
1232       else
1233         bitness = STAP_ARG_BITNESS_UNDEFINED;
1234
1235       struct type *atype
1236         = stap_get_expected_argument_type (gdbarch, bitness,
1237                                            this->get_name ().c_str ());
1238
1239       expression_up expr = stap_parse_argument (&cur, atype, gdbarch);
1240
1241       if (stap_expression_debug)
1242         dump_raw_expression (expr.get (), gdb_stdlog,
1243                              "before conversion to prefix form");
1244
1245       prefixify_expression (expr.get ());
1246
1247       if (stap_expression_debug)
1248         dump_prefix_expression (expr.get (), gdb_stdlog);
1249
1250       m_parsed_args.emplace_back (bitness, atype, std::move (expr));
1251
1252       /* Start it over again.  */
1253       cur = skip_spaces (cur);
1254     }
1255 }
1256
1257 /* Helper function to relocate an address.  */
1258
1259 static CORE_ADDR
1260 relocate_address (CORE_ADDR address, struct objfile *objfile)
1261 {
1262   return address + ANOFFSET (objfile->section_offsets,
1263                              SECT_OFF_DATA (objfile));
1264 }
1265
1266 /* Implementation of the get_relocated_address method.  */
1267
1268 CORE_ADDR
1269 stap_probe::get_relocated_address (struct objfile *objfile)
1270 {
1271   return relocate_address (this->get_address (), objfile);
1272 }
1273
1274 /* Given PROBE, returns the number of arguments present in that probe's
1275    argument string.  */
1276
1277 unsigned
1278 stap_probe::get_argument_count (struct frame_info *frame)
1279 {
1280   struct gdbarch *gdbarch = get_frame_arch (frame);
1281
1282   if (!m_have_parsed_args)
1283     {
1284       if (this->can_evaluate_arguments ())
1285         this->parse_arguments (gdbarch);
1286       else
1287         {
1288           static bool have_warned_stap_incomplete = false;
1289
1290           if (!have_warned_stap_incomplete)
1291             {
1292               warning (_(
1293 "The SystemTap SDT probe support is not fully implemented on this target;\n"
1294 "you will not be able to inspect the arguments of the probes.\n"
1295 "Please report a bug against GDB requesting a port to this target."));
1296               have_warned_stap_incomplete = true;
1297             }
1298
1299           /* Marking the arguments as "already parsed".  */
1300           m_have_parsed_args = true;
1301         }
1302     }
1303
1304   gdb_assert (m_have_parsed_args);
1305   return m_parsed_args.size ();
1306 }
1307
1308 /* Return true if OP is a valid operator inside a probe argument, or
1309    false otherwise.  */
1310
1311 static bool
1312 stap_is_operator (const char *op)
1313 {
1314   bool ret = true;
1315
1316   switch (*op)
1317     {
1318     case '*':
1319     case '/':
1320     case '%':
1321     case '^':
1322     case '!':
1323     case '+':
1324     case '-':
1325     case '<':
1326     case '>':
1327     case '|':
1328     case '&':
1329       break;
1330
1331     case '=':
1332       if (op[1] != '=')
1333         ret = false;
1334       break;
1335
1336     default:
1337       /* We didn't find any operator.  */
1338       ret = false;
1339     }
1340
1341   return ret;
1342 }
1343
1344 /* Implement the `can_evaluate_arguments' method.  */
1345
1346 bool
1347 stap_probe::can_evaluate_arguments () const
1348 {
1349   struct gdbarch *gdbarch = this->get_gdbarch ();
1350
1351   /* For SystemTap probes, we have to guarantee that the method
1352      stap_is_single_operand is defined on gdbarch.  If it is not, then it
1353      means that argument evaluation is not implemented on this target.  */
1354   return gdbarch_stap_is_single_operand_p (gdbarch);
1355 }
1356
1357 /* Evaluate the probe's argument N (indexed from 0), returning a value
1358    corresponding to it.  Assertion is thrown if N does not exist.  */
1359
1360 struct value *
1361 stap_probe::evaluate_argument (unsigned n, struct frame_info *frame)
1362 {
1363   struct stap_probe_arg *arg;
1364   int pos = 0;
1365   struct gdbarch *gdbarch = get_frame_arch (frame);
1366
1367   arg = this->get_arg_by_number (n, gdbarch);
1368   return evaluate_subexp_standard (arg->atype, arg->aexpr.get (), &pos,
1369                                    EVAL_NORMAL);
1370 }
1371
1372 /* Compile the probe's argument N (indexed from 0) to agent expression.
1373    Assertion is thrown if N does not exist.  */
1374
1375 void
1376 stap_probe::compile_to_ax (struct agent_expr *expr, struct axs_value *value,
1377                            unsigned n)
1378 {
1379   struct stap_probe_arg *arg;
1380   union exp_element *pc;
1381
1382   arg = this->get_arg_by_number (n, expr->gdbarch);
1383
1384   pc = arg->aexpr->elts;
1385   gen_expr (arg->aexpr.get (), &pc, expr, value);
1386
1387   require_rvalue (expr, value);
1388   value->type = arg->atype;
1389 }
1390 \f
1391
1392 /* Set or clear a SystemTap semaphore.  ADDRESS is the semaphore's
1393    address.  SET is zero if the semaphore should be cleared, or one if
1394    it should be set.  This is a helper function for
1395    'stap_probe::set_semaphore' and 'stap_probe::clear_semaphore'.  */
1396
1397 static void
1398 stap_modify_semaphore (CORE_ADDR address, int set, struct gdbarch *gdbarch)
1399 {
1400   gdb_byte bytes[sizeof (LONGEST)];
1401   /* The ABI specifies "unsigned short".  */
1402   struct type *type = builtin_type (gdbarch)->builtin_unsigned_short;
1403   ULONGEST value;
1404
1405   if (address == 0)
1406     return;
1407
1408   /* Swallow errors.  */
1409   if (target_read_memory (address, bytes, TYPE_LENGTH (type)) != 0)
1410     {
1411       warning (_("Could not read the value of a SystemTap semaphore."));
1412       return;
1413     }
1414
1415   value = extract_unsigned_integer (bytes, TYPE_LENGTH (type),
1416                                     gdbarch_byte_order (gdbarch));
1417   /* Note that we explicitly don't worry about overflow or
1418      underflow.  */
1419   if (set)
1420     ++value;
1421   else
1422     --value;
1423
1424   store_unsigned_integer (bytes, TYPE_LENGTH (type),
1425                           gdbarch_byte_order (gdbarch), value);
1426
1427   if (target_write_memory (address, bytes, TYPE_LENGTH (type)) != 0)
1428     warning (_("Could not write the value of a SystemTap semaphore."));
1429 }
1430
1431 /* Implementation of the 'set_semaphore' method.
1432
1433    SystemTap semaphores act as reference counters, so calls to this
1434    function must be paired with calls to 'clear_semaphore'.
1435
1436    This function and 'clear_semaphore' race with another tool
1437    changing the probes, but that is too rare to care.  */
1438
1439 void
1440 stap_probe::set_semaphore (struct objfile *objfile, struct gdbarch *gdbarch)
1441 {
1442   stap_modify_semaphore (relocate_address (m_sem_addr, objfile), 1, gdbarch);
1443 }
1444
1445 /* Implementation of the 'clear_semaphore' method.  */
1446
1447 void
1448 stap_probe::clear_semaphore (struct objfile *objfile, struct gdbarch *gdbarch)
1449 {
1450   stap_modify_semaphore (relocate_address (m_sem_addr, objfile), 0, gdbarch);
1451 }
1452
1453 /* Implementation of the 'get_static_ops' method.  */
1454
1455 const static_probe_ops *
1456 stap_probe::get_static_ops () const
1457 {
1458   return &stap_static_probe_ops;
1459 }
1460
1461 /* Implementation of the 'gen_info_probes_table_values' method.  */
1462
1463 std::vector<const char *>
1464 stap_probe::gen_info_probes_table_values () const
1465 {
1466   const char *val = NULL;
1467
1468   if (m_sem_addr != 0)
1469     val = print_core_address (this->get_gdbarch (), m_sem_addr);
1470
1471   return std::vector<const char *> { val };
1472 }
1473
1474 /* Helper function that parses the information contained in a
1475    SystemTap's probe.  Basically, the information consists in:
1476
1477    - Probe's PC address;
1478    - Link-time section address of `.stapsdt.base' section;
1479    - Link-time address of the semaphore variable, or ZERO if the
1480      probe doesn't have an associated semaphore;
1481    - Probe's provider name;
1482    - Probe's name;
1483    - Probe's argument format.  */
1484
1485 static void
1486 handle_stap_probe (struct objfile *objfile, struct sdt_note *el,
1487                    std::vector<std::unique_ptr<probe>> *probesp,
1488                    CORE_ADDR base)
1489 {
1490   bfd *abfd = objfile->obfd;
1491   int size = bfd_get_arch_size (abfd) / 8;
1492   struct gdbarch *gdbarch = get_objfile_arch (objfile);
1493   struct type *ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
1494
1495   /* Provider and the name of the probe.  */
1496   const char *provider = (const char *) &el->data[3 * size];
1497   const char *name = ((const char *)
1498                       memchr (provider, '\0',
1499                               (char *) el->data + el->size - provider));
1500   /* Making sure there is a name.  */
1501   if (name == NULL)
1502     {
1503       complaint (_("corrupt probe name when reading `%s'"),
1504                  objfile_name (objfile));
1505
1506       /* There is no way to use a probe without a name or a provider, so
1507          returning here makes sense.  */
1508       return;
1509     }
1510   else
1511     ++name;
1512
1513   /* Retrieving the probe's address.  */
1514   CORE_ADDR address = extract_typed_address (&el->data[0], ptr_type);
1515
1516   /* Link-time sh_addr of `.stapsdt.base' section.  */
1517   CORE_ADDR base_ref = extract_typed_address (&el->data[size], ptr_type);
1518
1519   /* Semaphore address.  */
1520   CORE_ADDR sem_addr = extract_typed_address (&el->data[2 * size], ptr_type);
1521
1522   address += base - base_ref;
1523   if (sem_addr != 0)
1524     sem_addr += base - base_ref;
1525
1526   /* Arguments.  We can only extract the argument format if there is a valid
1527      name for this probe.  */
1528   const char *probe_args = ((const char*)
1529                             memchr (name, '\0',
1530                                     (char *) el->data + el->size - name));
1531
1532   if (probe_args != NULL)
1533     ++probe_args;
1534
1535   if (probe_args == NULL
1536       || (memchr (probe_args, '\0', (char *) el->data + el->size - name)
1537           != el->data + el->size - 1))
1538     {
1539       complaint (_("corrupt probe argument when reading `%s'"),
1540                  objfile_name (objfile));
1541       /* If the argument string is NULL, it means some problem happened with
1542          it.  So we return.  */
1543       return;
1544     }
1545
1546   stap_probe *ret = new stap_probe (std::string (name), std::string (provider),
1547                                     address, gdbarch, sem_addr, probe_args);
1548
1549   /* Successfully created probe.  */
1550   probesp->emplace_back (ret);
1551 }
1552
1553 /* Helper function which tries to find the base address of the SystemTap
1554    base section named STAP_BASE_SECTION_NAME.  */
1555
1556 static void
1557 get_stap_base_address_1 (bfd *abfd, asection *sect, void *obj)
1558 {
1559   asection **ret = (asection **) obj;
1560
1561   if ((sect->flags & (SEC_DATA | SEC_ALLOC | SEC_HAS_CONTENTS))
1562       && sect->name && !strcmp (sect->name, STAP_BASE_SECTION_NAME))
1563     *ret = sect;
1564 }
1565
1566 /* Helper function which iterates over every section in the BFD file,
1567    trying to find the base address of the SystemTap base section.
1568    Returns 1 if found (setting BASE to the proper value), zero otherwise.  */
1569
1570 static int
1571 get_stap_base_address (bfd *obfd, bfd_vma *base)
1572 {
1573   asection *ret = NULL;
1574
1575   bfd_map_over_sections (obfd, get_stap_base_address_1, (void *) &ret);
1576
1577   if (ret == NULL)
1578     {
1579       complaint (_("could not obtain base address for "
1580                                         "SystemTap section on objfile `%s'."),
1581                  obfd->filename);
1582       return 0;
1583     }
1584
1585   if (base != NULL)
1586     *base = ret->vma;
1587
1588   return 1;
1589 }
1590
1591 /* Implementation of the 'is_linespec' method.  */
1592
1593 bool
1594 stap_static_probe_ops::is_linespec (const char **linespecp) const
1595 {
1596   static const char *const keywords[] = { "-pstap", "-probe-stap", NULL };
1597
1598   return probe_is_linespec_by_keyword (linespecp, keywords);
1599 }
1600
1601 /* Implementation of the 'get_probes' method.  */
1602
1603 void
1604 stap_static_probe_ops::get_probes
1605   (std::vector<std::unique_ptr<probe>> *probesp,
1606    struct objfile *objfile) const
1607 {
1608   /* If we are here, then this is the first time we are parsing the
1609      SystemTap probe's information.  We basically have to count how many
1610      probes the objfile has, and then fill in the necessary information
1611      for each one.  */
1612   bfd *obfd = objfile->obfd;
1613   bfd_vma base;
1614   struct sdt_note *iter;
1615   unsigned save_probesp_len = probesp->size ();
1616
1617   if (objfile->separate_debug_objfile_backlink != NULL)
1618     {
1619       /* This is a .debug file, not the objfile itself.  */
1620       return;
1621     }
1622
1623   if (elf_tdata (obfd)->sdt_note_head == NULL)
1624     {
1625       /* There isn't any probe here.  */
1626       return;
1627     }
1628
1629   if (!get_stap_base_address (obfd, &base))
1630     {
1631       /* There was an error finding the base address for the section.
1632          Just return NULL.  */
1633       return;
1634     }
1635
1636   /* Parsing each probe's information.  */
1637   for (iter = elf_tdata (obfd)->sdt_note_head;
1638        iter != NULL;
1639        iter = iter->next)
1640     {
1641       /* We first have to handle all the information about the
1642          probe which is present in the section.  */
1643       handle_stap_probe (objfile, iter, probesp, base);
1644     }
1645
1646   if (save_probesp_len == probesp->size ())
1647     {
1648       /* If we are here, it means we have failed to parse every known
1649          probe.  */
1650       complaint (_("could not parse SystemTap probe(s) from inferior"));
1651       return;
1652     }
1653 }
1654
1655 /* Implementation of the type_name method.  */
1656
1657 const char *
1658 stap_static_probe_ops::type_name () const
1659 {
1660   return "stap";
1661 }
1662
1663 /* Implementation of the 'gen_info_probes_table_header' method.  */
1664
1665 std::vector<struct info_probe_column>
1666 stap_static_probe_ops::gen_info_probes_table_header () const
1667 {
1668   struct info_probe_column stap_probe_column;
1669
1670   stap_probe_column.field_name = "semaphore";
1671   stap_probe_column.print_name = _("Semaphore");
1672
1673   return std::vector<struct info_probe_column> { stap_probe_column };
1674 }
1675
1676 /* Implementation of the `info probes stap' command.  */
1677
1678 static void
1679 info_probes_stap_command (const char *arg, int from_tty)
1680 {
1681   info_probes_for_spops (arg, from_tty, &stap_static_probe_ops);
1682 }
1683
1684 void
1685 _initialize_stap_probe (void)
1686 {
1687   all_static_probe_ops.push_back (&stap_static_probe_ops);
1688
1689   add_setshow_zuinteger_cmd ("stap-expression", class_maintenance,
1690                              &stap_expression_debug,
1691                              _("Set SystemTap expression debugging."),
1692                              _("Show SystemTap expression debugging."),
1693                              _("When non-zero, the internal representation "
1694                                "of SystemTap expressions will be printed."),
1695                              NULL,
1696                              show_stapexpressiondebug,
1697                              &setdebuglist, &showdebuglist);
1698
1699   add_cmd ("stap", class_info, info_probes_stap_command,
1700            _("\
1701 Show information about SystemTap static probes.\n\
1702 Usage: info probes stap [PROVIDER [NAME [OBJECT]]]\n\
1703 Each argument is a regular expression, used to select probes.\n\
1704 PROVIDER matches probe provider names.\n\
1705 NAME matches the probe names.\n\
1706 OBJECT matches the executable or shared library name."),
1707            info_probes_cmdlist_get ());
1708
1709 }