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