1 /* GDB-specific functions for operating on agent expressions.
2 
3    Copyright (C) 1998-2021 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 "symtab.h"
22 #include "symfile.h"
23 #include "gdbtypes.h"
24 #include "language.h"
25 #include "value.h"
26 #include "expression.h"
27 #include "command.h"
28 #include "gdbcmd.h"
29 #include "frame.h"
30 #include "target.h"
31 #include "ax.h"
32 #include "ax-gdb.h"
33 #include "block.h"
34 #include "regcache.h"
35 #include "user-regs.h"
36 #include "dictionary.h"
37 #include "breakpoint.h"
38 #include "tracepoint.h"
39 #include "cp-support.h"
40 #include "arch-utils.h"
41 #include "cli/cli-utils.h"
42 #include "linespec.h"
43 #include "location.h"
44 #include "objfiles.h"
45 #include "typeprint.h"
46 #include "valprint.h"
47 #include "c-lang.h"
48 #include "expop.h"
49 
50 #include "gdbsupport/format.h"
51 
52 /* To make sense of this file, you should read doc/agentexpr.texi.
53    Then look at the types and enums in ax-gdb.h.  For the code itself,
54    look at gen_expr, towards the bottom; that's the main function that
55    looks at the GDB expressions and calls everything else to generate
56    code.
57 
58    I'm beginning to wonder whether it wouldn't be nicer to internally
59    generate trees, with types, and then spit out the bytecode in
60    linear form afterwards; we could generate fewer `swap', `ext', and
61    `zero_ext' bytecodes that way; it would make good constant folding
62    easier, too.  But at the moment, I think we should be willing to
63    pay for the simplicity of this code with less-than-optimal bytecode
64    strings.
65 
66    Remember, "GBD" stands for "Great Britain, Dammit!"  So be careful.  */
67 
68 
69 
70 /* Prototypes for local functions.  */
71 
72 /* There's a standard order to the arguments of these functions:
73    struct agent_expr * --- agent expression buffer to generate code into
74    struct axs_value * --- describes value left on top of stack  */
75 
76 static void gen_traced_pop (struct agent_expr *, struct axs_value *);
77 
78 static void gen_sign_extend (struct agent_expr *, struct type *);
79 static void gen_extend (struct agent_expr *, struct type *);
80 static void gen_fetch (struct agent_expr *, struct type *);
81 static void gen_left_shift (struct agent_expr *, int);
82 
83 
84 static void gen_frame_args_address (struct agent_expr *);
85 static void gen_frame_locals_address (struct agent_expr *);
86 static void gen_offset (struct agent_expr *ax, int offset);
87 static void gen_sym_offset (struct agent_expr *, struct symbol *);
88 static void gen_var_ref (struct agent_expr *ax, struct axs_value *value,
89 			 struct symbol *var);
90 
91 
92 static void gen_int_literal (struct agent_expr *ax,
93 			     struct axs_value *value,
94 			     LONGEST k, struct type *type);
95 
96 static void gen_usual_unary (struct agent_expr *ax, struct axs_value *value);
97 static int type_wider_than (struct type *type1, struct type *type2);
98 static struct type *max_type (struct type *type1, struct type *type2);
99 static void gen_conversion (struct agent_expr *ax,
100 			    struct type *from, struct type *to);
101 static int is_nontrivial_conversion (struct type *from, struct type *to);
102 static void gen_usual_arithmetic (struct agent_expr *ax,
103 				  struct axs_value *value1,
104 				  struct axs_value *value2);
105 static void gen_integral_promotions (struct agent_expr *ax,
106 				     struct axs_value *value);
107 static void gen_cast (struct agent_expr *ax,
108 		      struct axs_value *value, struct type *type);
109 static void gen_scale (struct agent_expr *ax,
110 		       enum agent_op op, struct type *type);
111 static void gen_ptradd (struct agent_expr *ax, struct axs_value *value,
112 			struct axs_value *value1, struct axs_value *value2);
113 static void gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
114 			struct axs_value *value1, struct axs_value *value2);
115 static void gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
116 			 struct axs_value *value1, struct axs_value *value2,
117 			 struct type *result_type);
118 static void gen_binop (struct agent_expr *ax,
119 		       struct axs_value *value,
120 		       struct axs_value *value1,
121 		       struct axs_value *value2,
122 		       enum agent_op op,
123 		       enum agent_op op_unsigned, int may_carry,
124 		       const char *name);
125 static void gen_logical_not (struct agent_expr *ax, struct axs_value *value,
126 			     struct type *result_type);
127 static void gen_complement (struct agent_expr *ax, struct axs_value *value);
128 static void gen_deref (struct axs_value *);
129 static void gen_address_of (struct axs_value *);
130 static void gen_bitfield_ref (struct agent_expr *ax, struct axs_value *value,
131 			      struct type *type, int start, int end);
132 static void gen_primitive_field (struct agent_expr *ax,
133 				 struct axs_value *value,
134 				 int offset, int fieldno, struct type *type);
135 static int gen_struct_ref_recursive (struct agent_expr *ax,
136 				     struct axs_value *value,
137 				     const char *field, int offset,
138 				     struct type *type);
139 static void gen_struct_ref (struct agent_expr *ax,
140 			    struct axs_value *value,
141 			    const char *field,
142 			    const char *operator_name,
143 			    const char *operand_name);
144 static void gen_static_field (struct agent_expr *ax, struct axs_value *value,
145 			      struct type *type, int fieldno);
146 static void gen_expr_binop_rest (struct expression *exp,
147 				 enum exp_opcode op,
148 				 struct agent_expr *ax,
149 				 struct axs_value *value,
150 				 struct axs_value *value1,
151 				 struct axs_value *value2);
152 
153 
154 
155 /* Generating bytecode from GDB expressions: general assumptions */
156 
157 /* Here are a few general assumptions made throughout the code; if you
158    want to make a change that contradicts one of these, then you'd
159    better scan things pretty thoroughly.
160 
161    - We assume that all values occupy one stack element.  For example,
162    sometimes we'll swap to get at the left argument to a binary
163    operator.  If we decide that void values should occupy no stack
164    elements, or that synthetic arrays (whose size is determined at
165    run time, created by the `@' operator) should occupy two stack
166    elements (address and length), then this will cause trouble.
167 
168    - We assume the stack elements are infinitely wide, and that we
169    don't have to worry what happens if the user requests an
170    operation that is wider than the actual interpreter's stack.
171    That is, it's up to the interpreter to handle directly all the
172    integer widths the user has access to.  (Woe betide the language
173    with bignums!)
174 
175    - We don't support side effects.  Thus, we don't have to worry about
176    GCC's generalized lvalues, function calls, etc.
177 
178    - We don't support floating point.  Many places where we switch on
179    some type don't bother to include cases for floating point; there
180    may be even more subtle ways this assumption exists.  For
181    example, the arguments to % must be integers.
182 
183    - We assume all subexpressions have a static, unchanging type.  If
184    we tried to support convenience variables, this would be a
185    problem.
186 
187    - All values on the stack should always be fully zero- or
188    sign-extended.
189 
190    (I wasn't sure whether to choose this or its opposite --- that
191    only addresses are assumed extended --- but it turns out that
192    neither convention completely eliminates spurious extend
193    operations (if everything is always extended, then you have to
194    extend after add, because it could overflow; if nothing is
195    extended, then you end up producing extends whenever you change
196    sizes), and this is simpler.)  */
197 
198 
199 /* Scan for all static fields in the given class, including any base
200    classes, and generate tracing bytecodes for each.  */
201 
202 static void
gen_trace_static_fields(struct agent_expr * ax,struct type * type)203 gen_trace_static_fields (struct agent_expr *ax,
204 			 struct type *type)
205 {
206   int i, nbases = TYPE_N_BASECLASSES (type);
207   struct axs_value value;
208 
209   type = check_typedef (type);
210 
211   for (i = type->num_fields () - 1; i >= nbases; i--)
212     {
213       if (field_is_static (&type->field (i)))
214 	{
215 	  gen_static_field (ax, &value, type, i);
216 	  if (value.optimized_out)
217 	    continue;
218 	  switch (value.kind)
219 	    {
220 	    case axs_lvalue_memory:
221 	      {
222 		/* Initialize the TYPE_LENGTH if it is a typedef.  */
223 		check_typedef (value.type);
224 		ax_const_l (ax, TYPE_LENGTH (value.type));
225 		ax_simple (ax, aop_trace);
226 	      }
227 	      break;
228 
229 	    case axs_lvalue_register:
230 	      /* We don't actually need the register's value to be pushed,
231 		 just note that we need it to be collected.  */
232 	      ax_reg_mask (ax, value.u.reg);
233 
234 	    default:
235 	      break;
236 	    }
237 	}
238     }
239 
240   /* Now scan through base classes recursively.  */
241   for (i = 0; i < nbases; i++)
242     {
243       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
244 
245       gen_trace_static_fields (ax, basetype);
246     }
247 }
248 
249 /* Trace the lvalue on the stack, if it needs it.  In either case, pop
250    the value.  Useful on the left side of a comma, and at the end of
251    an expression being used for tracing.  */
252 static void
gen_traced_pop(struct agent_expr * ax,struct axs_value * value)253 gen_traced_pop (struct agent_expr *ax, struct axs_value *value)
254 {
255   int string_trace = 0;
256   if (ax->trace_string
257       && value->type->code () == TYPE_CODE_PTR
258       && c_textual_element_type (check_typedef (TYPE_TARGET_TYPE (value->type)),
259 				 's'))
260     string_trace = 1;
261 
262   if (ax->tracing)
263     switch (value->kind)
264       {
265       case axs_rvalue:
266 	if (string_trace)
267 	  {
268 	    ax_const_l (ax, ax->trace_string);
269 	    ax_simple (ax, aop_tracenz);
270 	  }
271 	else
272 	  /* We don't trace rvalues, just the lvalues necessary to
273 	     produce them.  So just dispose of this value.  */
274 	  ax_simple (ax, aop_pop);
275 	break;
276 
277       case axs_lvalue_memory:
278 	{
279 	  /* Initialize the TYPE_LENGTH if it is a typedef.  */
280 	  check_typedef (value->type);
281 
282 	  if (string_trace)
283 	    {
284 	      gen_fetch (ax, value->type);
285 	      ax_const_l (ax, ax->trace_string);
286 	      ax_simple (ax, aop_tracenz);
287 	    }
288 	  else
289 	    {
290 	      /* There's no point in trying to use a trace_quick bytecode
291 		 here, since "trace_quick SIZE pop" is three bytes, whereas
292 		 "const8 SIZE trace" is also three bytes, does the same
293 		 thing, and the simplest code which generates that will also
294 		 work correctly for objects with large sizes.  */
295 	      ax_const_l (ax, TYPE_LENGTH (value->type));
296 	      ax_simple (ax, aop_trace);
297 	    }
298 	}
299 	break;
300 
301       case axs_lvalue_register:
302 	/* We don't actually need the register's value to be on the
303 	   stack, and the target will get heartburn if the register is
304 	   larger than will fit in a stack, so just mark it for
305 	   collection and be done with it.  */
306 	ax_reg_mask (ax, value->u.reg);
307 
308 	/* But if the register points to a string, assume the value
309 	   will fit on the stack and push it anyway.  */
310 	if (string_trace)
311 	  {
312 	    ax_reg (ax, value->u.reg);
313 	    ax_const_l (ax, ax->trace_string);
314 	    ax_simple (ax, aop_tracenz);
315 	  }
316 	break;
317       }
318   else
319     /* If we're not tracing, just pop the value.  */
320     ax_simple (ax, aop_pop);
321 
322   /* To trace C++ classes with static fields stored elsewhere.  */
323   if (ax->tracing
324       && (value->type->code () == TYPE_CODE_STRUCT
325 	  || value->type->code () == TYPE_CODE_UNION))
326     gen_trace_static_fields (ax, value->type);
327 }
328 
329 
330 
331 /* Generating bytecode from GDB expressions: helper functions */
332 
333 /* Assume that the lower bits of the top of the stack is a value of
334    type TYPE, and the upper bits are zero.  Sign-extend if necessary.  */
335 static void
gen_sign_extend(struct agent_expr * ax,struct type * type)336 gen_sign_extend (struct agent_expr *ax, struct type *type)
337 {
338   /* Do we need to sign-extend this?  */
339   if (!type->is_unsigned ())
340     ax_ext (ax, TYPE_LENGTH (type) * TARGET_CHAR_BIT);
341 }
342 
343 
344 /* Assume the lower bits of the top of the stack hold a value of type
345    TYPE, and the upper bits are garbage.  Sign-extend or truncate as
346    needed.  */
347 static void
gen_extend(struct agent_expr * ax,struct type * type)348 gen_extend (struct agent_expr *ax, struct type *type)
349 {
350   int bits = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
351 
352   /* I just had to.  */
353   ((type->is_unsigned () ? ax_zero_ext : ax_ext) (ax, bits));
354 }
355 
356 
357 /* Assume that the top of the stack contains a value of type "pointer
358    to TYPE"; generate code to fetch its value.  Note that TYPE is the
359    target type, not the pointer type.  */
360 static void
gen_fetch(struct agent_expr * ax,struct type * type)361 gen_fetch (struct agent_expr *ax, struct type *type)
362 {
363   if (ax->tracing)
364     {
365       /* Record the area of memory we're about to fetch.  */
366       ax_trace_quick (ax, TYPE_LENGTH (type));
367     }
368 
369   if (type->code () == TYPE_CODE_RANGE)
370     type = TYPE_TARGET_TYPE (type);
371 
372   switch (type->code ())
373     {
374     case TYPE_CODE_PTR:
375     case TYPE_CODE_REF:
376     case TYPE_CODE_RVALUE_REF:
377     case TYPE_CODE_ENUM:
378     case TYPE_CODE_INT:
379     case TYPE_CODE_CHAR:
380     case TYPE_CODE_BOOL:
381       /* It's a scalar value, so we know how to dereference it.  How
382 	 many bytes long is it?  */
383       switch (TYPE_LENGTH (type))
384 	{
385 	case 8 / TARGET_CHAR_BIT:
386 	  ax_simple (ax, aop_ref8);
387 	  break;
388 	case 16 / TARGET_CHAR_BIT:
389 	  ax_simple (ax, aop_ref16);
390 	  break;
391 	case 32 / TARGET_CHAR_BIT:
392 	  ax_simple (ax, aop_ref32);
393 	  break;
394 	case 64 / TARGET_CHAR_BIT:
395 	  ax_simple (ax, aop_ref64);
396 	  break;
397 
398 	  /* Either our caller shouldn't have asked us to dereference
399 	     that pointer (other code's fault), or we're not
400 	     implementing something we should be (this code's fault).
401 	     In any case, it's a bug the user shouldn't see.  */
402 	default:
403 	  internal_error (__FILE__, __LINE__,
404 			  _("gen_fetch: strange size"));
405 	}
406 
407       gen_sign_extend (ax, type);
408       break;
409 
410     default:
411       /* Our caller requested us to dereference a pointer from an unsupported
412 	 type.  Error out and give callers a chance to handle the failure
413 	 gracefully.  */
414       error (_("gen_fetch: Unsupported type code `%s'."),
415 	     type->name ());
416     }
417 }
418 
419 
420 /* Generate code to left shift the top of the stack by DISTANCE bits, or
421    right shift it by -DISTANCE bits if DISTANCE < 0.  This generates
422    unsigned (logical) right shifts.  */
423 static void
gen_left_shift(struct agent_expr * ax,int distance)424 gen_left_shift (struct agent_expr *ax, int distance)
425 {
426   if (distance > 0)
427     {
428       ax_const_l (ax, distance);
429       ax_simple (ax, aop_lsh);
430     }
431   else if (distance < 0)
432     {
433       ax_const_l (ax, -distance);
434       ax_simple (ax, aop_rsh_unsigned);
435     }
436 }
437 
438 
439 
440 /* Generating bytecode from GDB expressions: symbol references */
441 
442 /* Generate code to push the base address of the argument portion of
443    the top stack frame.  */
444 static void
gen_frame_args_address(struct agent_expr * ax)445 gen_frame_args_address (struct agent_expr *ax)
446 {
447   int frame_reg;
448   LONGEST frame_offset;
449 
450   gdbarch_virtual_frame_pointer (ax->gdbarch,
451 				 ax->scope, &frame_reg, &frame_offset);
452   ax_reg (ax, frame_reg);
453   gen_offset (ax, frame_offset);
454 }
455 
456 
457 /* Generate code to push the base address of the locals portion of the
458    top stack frame.  */
459 static void
gen_frame_locals_address(struct agent_expr * ax)460 gen_frame_locals_address (struct agent_expr *ax)
461 {
462   int frame_reg;
463   LONGEST frame_offset;
464 
465   gdbarch_virtual_frame_pointer (ax->gdbarch,
466 				 ax->scope, &frame_reg, &frame_offset);
467   ax_reg (ax, frame_reg);
468   gen_offset (ax, frame_offset);
469 }
470 
471 
472 /* Generate code to add OFFSET to the top of the stack.  Try to
473    generate short and readable code.  We use this for getting to
474    variables on the stack, and structure members.  If we were
475    programming in ML, it would be clearer why these are the same
476    thing.  */
477 static void
gen_offset(struct agent_expr * ax,int offset)478 gen_offset (struct agent_expr *ax, int offset)
479 {
480   /* It would suffice to simply push the offset and add it, but this
481      makes it easier to read positive and negative offsets in the
482      bytecode.  */
483   if (offset > 0)
484     {
485       ax_const_l (ax, offset);
486       ax_simple (ax, aop_add);
487     }
488   else if (offset < 0)
489     {
490       ax_const_l (ax, -offset);
491       ax_simple (ax, aop_sub);
492     }
493 }
494 
495 
496 /* In many cases, a symbol's value is the offset from some other
497    address (stack frame, base register, etc.)  Generate code to add
498    VAR's value to the top of the stack.  */
499 static void
gen_sym_offset(struct agent_expr * ax,struct symbol * var)500 gen_sym_offset (struct agent_expr *ax, struct symbol *var)
501 {
502   gen_offset (ax, SYMBOL_VALUE (var));
503 }
504 
505 
506 /* Generate code for a variable reference to AX.  The variable is the
507    symbol VAR.  Set VALUE to describe the result.  */
508 
509 static void
gen_var_ref(struct agent_expr * ax,struct axs_value * value,struct symbol * var)510 gen_var_ref (struct agent_expr *ax, struct axs_value *value, struct symbol *var)
511 {
512   /* Dereference any typedefs.  */
513   value->type = check_typedef (SYMBOL_TYPE (var));
514   value->optimized_out = 0;
515 
516   if (SYMBOL_COMPUTED_OPS (var) != NULL)
517     {
518       SYMBOL_COMPUTED_OPS (var)->tracepoint_var_ref (var, ax, value);
519       return;
520     }
521 
522   /* I'm imitating the code in read_var_value.  */
523   switch (SYMBOL_CLASS (var))
524     {
525     case LOC_CONST:		/* A constant, like an enum value.  */
526       ax_const_l (ax, (LONGEST) SYMBOL_VALUE (var));
527       value->kind = axs_rvalue;
528       break;
529 
530     case LOC_LABEL:		/* A goto label, being used as a value.  */
531       ax_const_l (ax, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
532       value->kind = axs_rvalue;
533       break;
534 
535     case LOC_CONST_BYTES:
536       internal_error (__FILE__, __LINE__,
537 		      _("gen_var_ref: LOC_CONST_BYTES "
538 			"symbols are not supported"));
539 
540       /* Variable at a fixed location in memory.  Easy.  */
541     case LOC_STATIC:
542       /* Push the address of the variable.  */
543       ax_const_l (ax, SYMBOL_VALUE_ADDRESS (var));
544       value->kind = axs_lvalue_memory;
545       break;
546 
547     case LOC_ARG:		/* var lives in argument area of frame */
548       gen_frame_args_address (ax);
549       gen_sym_offset (ax, var);
550       value->kind = axs_lvalue_memory;
551       break;
552 
553     case LOC_REF_ARG:		/* As above, but the frame slot really
554 				   holds the address of the variable.  */
555       gen_frame_args_address (ax);
556       gen_sym_offset (ax, var);
557       /* Don't assume any particular pointer size.  */
558       gen_fetch (ax, builtin_type (ax->gdbarch)->builtin_data_ptr);
559       value->kind = axs_lvalue_memory;
560       break;
561 
562     case LOC_LOCAL:		/* var lives in locals area of frame */
563       gen_frame_locals_address (ax);
564       gen_sym_offset (ax, var);
565       value->kind = axs_lvalue_memory;
566       break;
567 
568     case LOC_TYPEDEF:
569       error (_("Cannot compute value of typedef `%s'."),
570 	     var->print_name ());
571       break;
572 
573     case LOC_BLOCK:
574       ax_const_l (ax, BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (var)));
575       value->kind = axs_rvalue;
576       break;
577 
578     case LOC_REGISTER:
579       /* Don't generate any code at all; in the process of treating
580 	 this as an lvalue or rvalue, the caller will generate the
581 	 right code.  */
582       value->kind = axs_lvalue_register;
583       value->u.reg
584 	= SYMBOL_REGISTER_OPS (var)->register_number (var, ax->gdbarch);
585       break;
586 
587       /* A lot like LOC_REF_ARG, but the pointer lives directly in a
588 	 register, not on the stack.  Simpler than LOC_REGISTER
589 	 because it's just like any other case where the thing
590 	 has a real address.  */
591     case LOC_REGPARM_ADDR:
592       ax_reg (ax,
593 	      SYMBOL_REGISTER_OPS (var)->register_number (var, ax->gdbarch));
594       value->kind = axs_lvalue_memory;
595       break;
596 
597     case LOC_UNRESOLVED:
598       {
599 	struct bound_minimal_symbol msym
600 	  = lookup_minimal_symbol (var->linkage_name (), NULL, NULL);
601 
602 	if (!msym.minsym)
603 	  error (_("Couldn't resolve symbol `%s'."), var->print_name ());
604 
605 	/* Push the address of the variable.  */
606 	ax_const_l (ax, BMSYMBOL_VALUE_ADDRESS (msym));
607 	value->kind = axs_lvalue_memory;
608       }
609       break;
610 
611     case LOC_COMPUTED:
612       gdb_assert_not_reached (_("LOC_COMPUTED variable missing a method"));
613 
614     case LOC_OPTIMIZED_OUT:
615       /* Flag this, but don't say anything; leave it up to callers to
616 	 warn the user.  */
617       value->optimized_out = 1;
618       break;
619 
620     default:
621       error (_("Cannot find value of botched symbol `%s'."),
622 	     var->print_name ());
623       break;
624     }
625 }
626 
627 /* Generate code for a minimal symbol variable reference to AX.  The
628    variable is the symbol MINSYM, of OBJFILE.  Set VALUE to describe
629    the result.  */
630 
631 static void
gen_msym_var_ref(agent_expr * ax,axs_value * value,minimal_symbol * msymbol,objfile * objf)632 gen_msym_var_ref (agent_expr *ax, axs_value *value,
633 		  minimal_symbol *msymbol, objfile *objf)
634 {
635   CORE_ADDR address;
636   type *t = find_minsym_type_and_address (msymbol, objf, &address);
637   value->type = t;
638   value->optimized_out = false;
639   ax_const_l (ax, address);
640   value->kind = axs_lvalue_memory;
641 }
642 
643 
644 
645 
646 /* Generating bytecode from GDB expressions: literals */
647 
648 static void
gen_int_literal(struct agent_expr * ax,struct axs_value * value,LONGEST k,struct type * type)649 gen_int_literal (struct agent_expr *ax, struct axs_value *value, LONGEST k,
650 		 struct type *type)
651 {
652   ax_const_l (ax, k);
653   value->kind = axs_rvalue;
654   value->type = check_typedef (type);
655 }
656 
657 
658 
659 /* Generating bytecode from GDB expressions: unary conversions, casts */
660 
661 /* Take what's on the top of the stack (as described by VALUE), and
662    try to make an rvalue out of it.  Signal an error if we can't do
663    that.  */
664 void
require_rvalue(struct agent_expr * ax,struct axs_value * value)665 require_rvalue (struct agent_expr *ax, struct axs_value *value)
666 {
667   /* Only deal with scalars, structs and such may be too large
668      to fit in a stack entry.  */
669   value->type = check_typedef (value->type);
670   if (value->type->code () == TYPE_CODE_ARRAY
671       || value->type->code () == TYPE_CODE_STRUCT
672       || value->type->code () == TYPE_CODE_UNION
673       || value->type->code () == TYPE_CODE_FUNC)
674     error (_("Value not scalar: cannot be an rvalue."));
675 
676   switch (value->kind)
677     {
678     case axs_rvalue:
679       /* It's already an rvalue.  */
680       break;
681 
682     case axs_lvalue_memory:
683       /* The top of stack is the address of the object.  Dereference.  */
684       gen_fetch (ax, value->type);
685       break;
686 
687     case axs_lvalue_register:
688       /* There's nothing on the stack, but value->u.reg is the
689 	 register number containing the value.
690 
691 	 When we add floating-point support, this is going to have to
692 	 change.  What about SPARC register pairs, for example?  */
693       ax_reg (ax, value->u.reg);
694       gen_extend (ax, value->type);
695       break;
696     }
697 
698   value->kind = axs_rvalue;
699 }
700 
701 
702 /* Assume the top of the stack is described by VALUE, and perform the
703    usual unary conversions.  This is motivated by ANSI 6.2.2, but of
704    course GDB expressions are not ANSI; they're the mishmash union of
705    a bunch of languages.  Rah.
706 
707    NOTE!  This function promises to produce an rvalue only when the
708    incoming value is of an appropriate type.  In other words, the
709    consumer of the value this function produces may assume the value
710    is an rvalue only after checking its type.
711 
712    The immediate issue is that if the user tries to use a structure or
713    union as an operand of, say, the `+' operator, we don't want to try
714    to convert that structure to an rvalue; require_rvalue will bomb on
715    structs and unions.  Rather, we want to simply pass the struct
716    lvalue through unchanged, and let `+' raise an error.  */
717 
718 static void
gen_usual_unary(struct agent_expr * ax,struct axs_value * value)719 gen_usual_unary (struct agent_expr *ax, struct axs_value *value)
720 {
721   /* We don't have to generate any code for the usual integral
722      conversions, since values are always represented as full-width on
723      the stack.  Should we tweak the type?  */
724 
725   /* Some types require special handling.  */
726   switch (value->type->code ())
727     {
728       /* Functions get converted to a pointer to the function.  */
729     case TYPE_CODE_FUNC:
730       value->type = lookup_pointer_type (value->type);
731       value->kind = axs_rvalue;	/* Should always be true, but just in case.  */
732       break;
733 
734       /* Arrays get converted to a pointer to their first element, and
735 	 are no longer an lvalue.  */
736     case TYPE_CODE_ARRAY:
737       {
738 	struct type *elements = TYPE_TARGET_TYPE (value->type);
739 
740 	value->type = lookup_pointer_type (elements);
741 	value->kind = axs_rvalue;
742 	/* We don't need to generate any code; the address of the array
743 	   is also the address of its first element.  */
744       }
745       break;
746 
747       /* Don't try to convert structures and unions to rvalues.  Let the
748 	 consumer signal an error.  */
749     case TYPE_CODE_STRUCT:
750     case TYPE_CODE_UNION:
751       return;
752     }
753 
754   /* If the value is an lvalue, dereference it.  */
755   require_rvalue (ax, value);
756 }
757 
758 
759 /* Return non-zero iff the type TYPE1 is considered "wider" than the
760    type TYPE2, according to the rules described in gen_usual_arithmetic.  */
761 static int
type_wider_than(struct type * type1,struct type * type2)762 type_wider_than (struct type *type1, struct type *type2)
763 {
764   return (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)
765 	  || (TYPE_LENGTH (type1) == TYPE_LENGTH (type2)
766 	      && type1->is_unsigned ()
767 	      && !type2->is_unsigned ()));
768 }
769 
770 
771 /* Return the "wider" of the two types TYPE1 and TYPE2.  */
772 static struct type *
max_type(struct type * type1,struct type * type2)773 max_type (struct type *type1, struct type *type2)
774 {
775   return type_wider_than (type1, type2) ? type1 : type2;
776 }
777 
778 
779 /* Generate code to convert a scalar value of type FROM to type TO.  */
780 static void
gen_conversion(struct agent_expr * ax,struct type * from,struct type * to)781 gen_conversion (struct agent_expr *ax, struct type *from, struct type *to)
782 {
783   /* Perhaps there is a more graceful way to state these rules.  */
784 
785   /* If we're converting to a narrower type, then we need to clear out
786      the upper bits.  */
787   if (TYPE_LENGTH (to) < TYPE_LENGTH (from))
788     gen_extend (ax, to);
789 
790   /* If the two values have equal width, but different signednesses,
791      then we need to extend.  */
792   else if (TYPE_LENGTH (to) == TYPE_LENGTH (from))
793     {
794       if (from->is_unsigned () != to->is_unsigned ())
795 	gen_extend (ax, to);
796     }
797 
798   /* If we're converting to a wider type, and becoming unsigned, then
799      we need to zero out any possible sign bits.  */
800   else if (TYPE_LENGTH (to) > TYPE_LENGTH (from))
801     {
802       if (to->is_unsigned ())
803 	gen_extend (ax, to);
804     }
805 }
806 
807 
808 /* Return non-zero iff the type FROM will require any bytecodes to be
809    emitted to be converted to the type TO.  */
810 static int
is_nontrivial_conversion(struct type * from,struct type * to)811 is_nontrivial_conversion (struct type *from, struct type *to)
812 {
813   agent_expr_up ax (new agent_expr (NULL, 0));
814   int nontrivial;
815 
816   /* Actually generate the code, and see if anything came out.  At the
817      moment, it would be trivial to replicate the code in
818      gen_conversion here, but in the future, when we're supporting
819      floating point and the like, it may not be.  Doing things this
820      way allows this function to be independent of the logic in
821      gen_conversion.  */
822   gen_conversion (ax.get (), from, to);
823   nontrivial = ax->len > 0;
824   return nontrivial;
825 }
826 
827 
828 /* Generate code to perform the "usual arithmetic conversions" (ANSI C
829    6.2.1.5) for the two operands of an arithmetic operator.  This
830    effectively finds a "least upper bound" type for the two arguments,
831    and promotes each argument to that type.  *VALUE1 and *VALUE2
832    describe the values as they are passed in, and as they are left.  */
833 static void
gen_usual_arithmetic(struct agent_expr * ax,struct axs_value * value1,struct axs_value * value2)834 gen_usual_arithmetic (struct agent_expr *ax, struct axs_value *value1,
835 		      struct axs_value *value2)
836 {
837   /* Do the usual binary conversions.  */
838   if (value1->type->code () == TYPE_CODE_INT
839       && value2->type->code () == TYPE_CODE_INT)
840     {
841       /* The ANSI integral promotions seem to work this way: Order the
842 	 integer types by size, and then by signedness: an n-bit
843 	 unsigned type is considered "wider" than an n-bit signed
844 	 type.  Promote to the "wider" of the two types, and always
845 	 promote at least to int.  */
846       struct type *target = max_type (builtin_type (ax->gdbarch)->builtin_int,
847 				      max_type (value1->type, value2->type));
848 
849       /* Deal with value2, on the top of the stack.  */
850       gen_conversion (ax, value2->type, target);
851 
852       /* Deal with value1, not on the top of the stack.  Don't
853 	 generate the `swap' instructions if we're not actually going
854 	 to do anything.  */
855       if (is_nontrivial_conversion (value1->type, target))
856 	{
857 	  ax_simple (ax, aop_swap);
858 	  gen_conversion (ax, value1->type, target);
859 	  ax_simple (ax, aop_swap);
860 	}
861 
862       value1->type = value2->type = check_typedef (target);
863     }
864 }
865 
866 
867 /* Generate code to perform the integral promotions (ANSI 6.2.1.1) on
868    the value on the top of the stack, as described by VALUE.  Assume
869    the value has integral type.  */
870 static void
gen_integral_promotions(struct agent_expr * ax,struct axs_value * value)871 gen_integral_promotions (struct agent_expr *ax, struct axs_value *value)
872 {
873   const struct builtin_type *builtin = builtin_type (ax->gdbarch);
874 
875   if (!type_wider_than (value->type, builtin->builtin_int))
876     {
877       gen_conversion (ax, value->type, builtin->builtin_int);
878       value->type = builtin->builtin_int;
879     }
880   else if (!type_wider_than (value->type, builtin->builtin_unsigned_int))
881     {
882       gen_conversion (ax, value->type, builtin->builtin_unsigned_int);
883       value->type = builtin->builtin_unsigned_int;
884     }
885 }
886 
887 
888 /* Generate code for a cast to TYPE.  */
889 static void
gen_cast(struct agent_expr * ax,struct axs_value * value,struct type * type)890 gen_cast (struct agent_expr *ax, struct axs_value *value, struct type *type)
891 {
892   /* GCC does allow casts to yield lvalues, so this should be fixed
893      before merging these changes into the trunk.  */
894   require_rvalue (ax, value);
895   /* Dereference typedefs.  */
896   type = check_typedef (type);
897 
898   switch (type->code ())
899     {
900     case TYPE_CODE_PTR:
901     case TYPE_CODE_REF:
902     case TYPE_CODE_RVALUE_REF:
903       /* It's implementation-defined, and I'll bet this is what GCC
904 	 does.  */
905       break;
906 
907     case TYPE_CODE_ARRAY:
908     case TYPE_CODE_STRUCT:
909     case TYPE_CODE_UNION:
910     case TYPE_CODE_FUNC:
911       error (_("Invalid type cast: intended type must be scalar."));
912 
913     case TYPE_CODE_ENUM:
914     case TYPE_CODE_BOOL:
915       /* We don't have to worry about the size of the value, because
916 	 all our integral values are fully sign-extended, and when
917 	 casting pointers we can do anything we like.  Is there any
918 	 way for us to know what GCC actually does with a cast like
919 	 this?  */
920       break;
921 
922     case TYPE_CODE_INT:
923       gen_conversion (ax, value->type, type);
924       break;
925 
926     case TYPE_CODE_VOID:
927       /* We could pop the value, and rely on everyone else to check
928 	 the type and notice that this value doesn't occupy a stack
929 	 slot.  But for now, leave the value on the stack, and
930 	 preserve the "value == stack element" assumption.  */
931       break;
932 
933     default:
934       error (_("Casts to requested type are not yet implemented."));
935     }
936 
937   value->type = type;
938 }
939 
940 
941 
942 /* Generating bytecode from GDB expressions: arithmetic */
943 
944 /* Scale the integer on the top of the stack by the size of the target
945    of the pointer type TYPE.  */
946 static void
gen_scale(struct agent_expr * ax,enum agent_op op,struct type * type)947 gen_scale (struct agent_expr *ax, enum agent_op op, struct type *type)
948 {
949   struct type *element = TYPE_TARGET_TYPE (type);
950 
951   if (TYPE_LENGTH (element) != 1)
952     {
953       ax_const_l (ax, TYPE_LENGTH (element));
954       ax_simple (ax, op);
955     }
956 }
957 
958 
959 /* Generate code for pointer arithmetic PTR + INT.  */
960 static void
gen_ptradd(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2)961 gen_ptradd (struct agent_expr *ax, struct axs_value *value,
962 	    struct axs_value *value1, struct axs_value *value2)
963 {
964   gdb_assert (pointer_type (value1->type));
965   gdb_assert (value2->type->code () == TYPE_CODE_INT);
966 
967   gen_scale (ax, aop_mul, value1->type);
968   ax_simple (ax, aop_add);
969   gen_extend (ax, value1->type);	/* Catch overflow.  */
970   value->type = value1->type;
971   value->kind = axs_rvalue;
972 }
973 
974 
975 /* Generate code for pointer arithmetic PTR - INT.  */
976 static void
gen_ptrsub(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2)977 gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
978 	    struct axs_value *value1, struct axs_value *value2)
979 {
980   gdb_assert (pointer_type (value1->type));
981   gdb_assert (value2->type->code () == TYPE_CODE_INT);
982 
983   gen_scale (ax, aop_mul, value1->type);
984   ax_simple (ax, aop_sub);
985   gen_extend (ax, value1->type);	/* Catch overflow.  */
986   value->type = value1->type;
987   value->kind = axs_rvalue;
988 }
989 
990 
991 /* Generate code for pointer arithmetic PTR - PTR.  */
992 static void
gen_ptrdiff(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2,struct type * result_type)993 gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
994 	     struct axs_value *value1, struct axs_value *value2,
995 	     struct type *result_type)
996 {
997   gdb_assert (pointer_type (value1->type));
998   gdb_assert (pointer_type (value2->type));
999 
1000   if (TYPE_LENGTH (TYPE_TARGET_TYPE (value1->type))
1001       != TYPE_LENGTH (TYPE_TARGET_TYPE (value2->type)))
1002     error (_("\
1003 First argument of `-' is a pointer, but second argument is neither\n\
1004 an integer nor a pointer of the same type."));
1005 
1006   ax_simple (ax, aop_sub);
1007   gen_scale (ax, aop_div_unsigned, value1->type);
1008   value->type = result_type;
1009   value->kind = axs_rvalue;
1010 }
1011 
1012 static void
gen_equal(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2,struct type * result_type)1013 gen_equal (struct agent_expr *ax, struct axs_value *value,
1014 	   struct axs_value *value1, struct axs_value *value2,
1015 	   struct type *result_type)
1016 {
1017   if (pointer_type (value1->type) || pointer_type (value2->type))
1018     ax_simple (ax, aop_equal);
1019   else
1020     gen_binop (ax, value, value1, value2,
1021 	       aop_equal, aop_equal, 0, "equal");
1022   value->type = result_type;
1023   value->kind = axs_rvalue;
1024 }
1025 
1026 static void
gen_less(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2,struct type * result_type)1027 gen_less (struct agent_expr *ax, struct axs_value *value,
1028 	  struct axs_value *value1, struct axs_value *value2,
1029 	  struct type *result_type)
1030 {
1031   if (pointer_type (value1->type) || pointer_type (value2->type))
1032     ax_simple (ax, aop_less_unsigned);
1033   else
1034     gen_binop (ax, value, value1, value2,
1035 	       aop_less_signed, aop_less_unsigned, 0, "less than");
1036   value->type = result_type;
1037   value->kind = axs_rvalue;
1038 }
1039 
1040 /* Generate code for a binary operator that doesn't do pointer magic.
1041    We set VALUE to describe the result value; we assume VALUE1 and
1042    VALUE2 describe the two operands, and that they've undergone the
1043    usual binary conversions.  MAY_CARRY should be non-zero iff the
1044    result needs to be extended.  NAME is the English name of the
1045    operator, used in error messages */
1046 static void
gen_binop(struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2,enum agent_op op,enum agent_op op_unsigned,int may_carry,const char * name)1047 gen_binop (struct agent_expr *ax, struct axs_value *value,
1048 	   struct axs_value *value1, struct axs_value *value2,
1049 	   enum agent_op op, enum agent_op op_unsigned,
1050 	   int may_carry, const char *name)
1051 {
1052   /* We only handle INT op INT.  */
1053   if ((value1->type->code () != TYPE_CODE_INT)
1054       || (value2->type->code () != TYPE_CODE_INT))
1055     error (_("Invalid combination of types in %s."), name);
1056 
1057   ax_simple (ax, value1->type->is_unsigned () ? op_unsigned : op);
1058   if (may_carry)
1059     gen_extend (ax, value1->type);	/* catch overflow */
1060   value->type = value1->type;
1061   value->kind = axs_rvalue;
1062 }
1063 
1064 
1065 static void
gen_logical_not(struct agent_expr * ax,struct axs_value * value,struct type * result_type)1066 gen_logical_not (struct agent_expr *ax, struct axs_value *value,
1067 		 struct type *result_type)
1068 {
1069   if (value->type->code () != TYPE_CODE_INT
1070       && value->type->code () != TYPE_CODE_PTR)
1071     error (_("Invalid type of operand to `!'."));
1072 
1073   ax_simple (ax, aop_log_not);
1074   value->type = result_type;
1075 }
1076 
1077 
1078 static void
gen_complement(struct agent_expr * ax,struct axs_value * value)1079 gen_complement (struct agent_expr *ax, struct axs_value *value)
1080 {
1081   if (value->type->code () != TYPE_CODE_INT)
1082     error (_("Invalid type of operand to `~'."));
1083 
1084   ax_simple (ax, aop_bit_not);
1085   gen_extend (ax, value->type);
1086 }
1087 
1088 
1089 
1090 /* Generating bytecode from GDB expressions: * & . -> @ sizeof */
1091 
1092 /* Dereference the value on the top of the stack.  */
1093 static void
gen_deref(struct axs_value * value)1094 gen_deref (struct axs_value *value)
1095 {
1096   /* The caller should check the type, because several operators use
1097      this, and we don't know what error message to generate.  */
1098   if (!pointer_type (value->type))
1099     internal_error (__FILE__, __LINE__,
1100 		    _("gen_deref: expected a pointer"));
1101 
1102   /* We've got an rvalue now, which is a pointer.  We want to yield an
1103      lvalue, whose address is exactly that pointer.  So we don't
1104      actually emit any code; we just change the type from "Pointer to
1105      T" to "T", and mark the value as an lvalue in memory.  Leave it
1106      to the consumer to actually dereference it.  */
1107   value->type = check_typedef (TYPE_TARGET_TYPE (value->type));
1108   if (value->type->code () == TYPE_CODE_VOID)
1109     error (_("Attempt to dereference a generic pointer."));
1110   value->kind = ((value->type->code () == TYPE_CODE_FUNC)
1111 		 ? axs_rvalue : axs_lvalue_memory);
1112 }
1113 
1114 
1115 /* Produce the address of the lvalue on the top of the stack.  */
1116 static void
gen_address_of(struct axs_value * value)1117 gen_address_of (struct axs_value *value)
1118 {
1119   /* Special case for taking the address of a function.  The ANSI
1120      standard describes this as a special case, too, so this
1121      arrangement is not without motivation.  */
1122   if (value->type->code () == TYPE_CODE_FUNC)
1123     /* The value's already an rvalue on the stack, so we just need to
1124        change the type.  */
1125     value->type = lookup_pointer_type (value->type);
1126   else
1127     switch (value->kind)
1128       {
1129       case axs_rvalue:
1130 	error (_("Operand of `&' is an rvalue, which has no address."));
1131 
1132       case axs_lvalue_register:
1133 	error (_("Operand of `&' is in a register, and has no address."));
1134 
1135       case axs_lvalue_memory:
1136 	value->kind = axs_rvalue;
1137 	value->type = lookup_pointer_type (value->type);
1138 	break;
1139       }
1140 }
1141 
1142 /* Generate code to push the value of a bitfield of a structure whose
1143    address is on the top of the stack.  START and END give the
1144    starting and one-past-ending *bit* numbers of the field within the
1145    structure.  */
1146 static void
gen_bitfield_ref(struct agent_expr * ax,struct axs_value * value,struct type * type,int start,int end)1147 gen_bitfield_ref (struct agent_expr *ax, struct axs_value *value,
1148 		  struct type *type, int start, int end)
1149 {
1150   /* Note that ops[i] fetches 8 << i bits.  */
1151   static enum agent_op ops[]
1152     = {aop_ref8, aop_ref16, aop_ref32, aop_ref64};
1153   static int num_ops = (sizeof (ops) / sizeof (ops[0]));
1154 
1155   /* We don't want to touch any byte that the bitfield doesn't
1156      actually occupy; we shouldn't make any accesses we're not
1157      explicitly permitted to.  We rely here on the fact that the
1158      bytecode `ref' operators work on unaligned addresses.
1159 
1160      It takes some fancy footwork to get the stack to work the way
1161      we'd like.  Say we're retrieving a bitfield that requires three
1162      fetches.  Initially, the stack just contains the address:
1163      addr
1164      For the first fetch, we duplicate the address
1165      addr addr
1166      then add the byte offset, do the fetch, and shift and mask as
1167      needed, yielding a fragment of the value, properly aligned for
1168      the final bitwise or:
1169      addr frag1
1170      then we swap, and repeat the process:
1171      frag1 addr                    --- address on top
1172      frag1 addr addr               --- duplicate it
1173      frag1 addr frag2              --- get second fragment
1174      frag1 frag2 addr              --- swap again
1175      frag1 frag2 frag3             --- get third fragment
1176      Notice that, since the third fragment is the last one, we don't
1177      bother duplicating the address this time.  Now we have all the
1178      fragments on the stack, and we can simply `or' them together,
1179      yielding the final value of the bitfield.  */
1180 
1181   /* The first and one-after-last bits in the field, but rounded down
1182      and up to byte boundaries.  */
1183   int bound_start = (start / TARGET_CHAR_BIT) * TARGET_CHAR_BIT;
1184   int bound_end = (((end + TARGET_CHAR_BIT - 1)
1185 		    / TARGET_CHAR_BIT)
1186 		   * TARGET_CHAR_BIT);
1187 
1188   /* current bit offset within the structure */
1189   int offset;
1190 
1191   /* The index in ops of the opcode we're considering.  */
1192   int op;
1193 
1194   /* The number of fragments we generated in the process.  Probably
1195      equal to the number of `one' bits in bytesize, but who cares?  */
1196   int fragment_count;
1197 
1198   /* Dereference any typedefs.  */
1199   type = check_typedef (type);
1200 
1201   /* Can we fetch the number of bits requested at all?  */
1202   if ((end - start) > ((1 << num_ops) * 8))
1203     internal_error (__FILE__, __LINE__,
1204 		    _("gen_bitfield_ref: bitfield too wide"));
1205 
1206   /* Note that we know here that we only need to try each opcode once.
1207      That may not be true on machines with weird byte sizes.  */
1208   offset = bound_start;
1209   fragment_count = 0;
1210   for (op = num_ops - 1; op >= 0; op--)
1211     {
1212       /* number of bits that ops[op] would fetch */
1213       int op_size = 8 << op;
1214 
1215       /* The stack at this point, from bottom to top, contains zero or
1216 	 more fragments, then the address.  */
1217 
1218       /* Does this fetch fit within the bitfield?  */
1219       if (offset + op_size <= bound_end)
1220 	{
1221 	  /* Is this the last fragment?  */
1222 	  int last_frag = (offset + op_size == bound_end);
1223 
1224 	  if (!last_frag)
1225 	    ax_simple (ax, aop_dup);	/* keep a copy of the address */
1226 
1227 	  /* Add the offset.  */
1228 	  gen_offset (ax, offset / TARGET_CHAR_BIT);
1229 
1230 	  if (ax->tracing)
1231 	    {
1232 	      /* Record the area of memory we're about to fetch.  */
1233 	      ax_trace_quick (ax, op_size / TARGET_CHAR_BIT);
1234 	    }
1235 
1236 	  /* Perform the fetch.  */
1237 	  ax_simple (ax, ops[op]);
1238 
1239 	  /* Shift the bits we have to their proper position.
1240 	     gen_left_shift will generate right shifts when the operand
1241 	     is negative.
1242 
1243 	     A big-endian field diagram to ponder:
1244 	     byte 0  byte 1  byte 2  byte 3  byte 4  byte 5  byte 6  byte 7
1245 	     +------++------++------++------++------++------++------++------+
1246 	     xxxxAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCxxxxxxxxxxx
1247 	     ^               ^               ^    ^
1248 	     bit number      16              32              48   53
1249 	     These are bit numbers as supplied by GDB.  Note that the
1250 	     bit numbers run from right to left once you've fetched the
1251 	     value!
1252 
1253 	     A little-endian field diagram to ponder:
1254 	     byte 7  byte 6  byte 5  byte 4  byte 3  byte 2  byte 1  byte 0
1255 	     +------++------++------++------++------++------++------++------+
1256 	     xxxxxxxxxxxAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCxxxx
1257 	     ^               ^               ^           ^   ^
1258 	     bit number     48              32              16          4   0
1259 
1260 	     In both cases, the most significant end is on the left
1261 	     (i.e. normal numeric writing order), which means that you
1262 	     don't go crazy thinking about `left' and `right' shifts.
1263 
1264 	     We don't have to worry about masking yet:
1265 	     - If they contain garbage off the least significant end, then we
1266 	     must be looking at the low end of the field, and the right
1267 	     shift will wipe them out.
1268 	     - If they contain garbage off the most significant end, then we
1269 	     must be looking at the most significant end of the word, and
1270 	     the sign/zero extension will wipe them out.
1271 	     - If we're in the interior of the word, then there is no garbage
1272 	     on either end, because the ref operators zero-extend.  */
1273 	  if (gdbarch_byte_order (ax->gdbarch) == BFD_ENDIAN_BIG)
1274 	    gen_left_shift (ax, end - (offset + op_size));
1275 	  else
1276 	    gen_left_shift (ax, offset - start);
1277 
1278 	  if (!last_frag)
1279 	    /* Bring the copy of the address up to the top.  */
1280 	    ax_simple (ax, aop_swap);
1281 
1282 	  offset += op_size;
1283 	  fragment_count++;
1284 	}
1285     }
1286 
1287   /* Generate enough bitwise `or' operations to combine all the
1288      fragments we left on the stack.  */
1289   while (fragment_count-- > 1)
1290     ax_simple (ax, aop_bit_or);
1291 
1292   /* Sign- or zero-extend the value as appropriate.  */
1293   ((type->is_unsigned () ? ax_zero_ext : ax_ext) (ax, end - start));
1294 
1295   /* This is *not* an lvalue.  Ugh.  */
1296   value->kind = axs_rvalue;
1297   value->type = type;
1298 }
1299 
1300 /* Generate bytecodes for field number FIELDNO of type TYPE.  OFFSET
1301    is an accumulated offset (in bytes), will be nonzero for objects
1302    embedded in other objects, like C++ base classes.  Behavior should
1303    generally follow value_primitive_field.  */
1304 
1305 static void
gen_primitive_field(struct agent_expr * ax,struct axs_value * value,int offset,int fieldno,struct type * type)1306 gen_primitive_field (struct agent_expr *ax, struct axs_value *value,
1307 		     int offset, int fieldno, struct type *type)
1308 {
1309   /* Is this a bitfield?  */
1310   if (TYPE_FIELD_PACKED (type, fieldno))
1311     gen_bitfield_ref (ax, value, type->field (fieldno).type (),
1312 		      (offset * TARGET_CHAR_BIT
1313 		       + TYPE_FIELD_BITPOS (type, fieldno)),
1314 		      (offset * TARGET_CHAR_BIT
1315 		       + TYPE_FIELD_BITPOS (type, fieldno)
1316 		       + TYPE_FIELD_BITSIZE (type, fieldno)));
1317   else
1318     {
1319       gen_offset (ax, offset
1320 		  + TYPE_FIELD_BITPOS (type, fieldno) / TARGET_CHAR_BIT);
1321       value->kind = axs_lvalue_memory;
1322       value->type = type->field (fieldno).type ();
1323     }
1324 }
1325 
1326 /* Search for the given field in either the given type or one of its
1327    base classes.  Return 1 if found, 0 if not.  */
1328 
1329 static int
gen_struct_ref_recursive(struct agent_expr * ax,struct axs_value * value,const char * field,int offset,struct type * type)1330 gen_struct_ref_recursive (struct agent_expr *ax, struct axs_value *value,
1331 			  const char *field, int offset, struct type *type)
1332 {
1333   int i, rslt;
1334   int nbases = TYPE_N_BASECLASSES (type);
1335 
1336   type = check_typedef (type);
1337 
1338   for (i = type->num_fields () - 1; i >= nbases; i--)
1339     {
1340       const char *this_name = TYPE_FIELD_NAME (type, i);
1341 
1342       if (this_name)
1343 	{
1344 	  if (strcmp (field, this_name) == 0)
1345 	    {
1346 	      /* Note that bytecodes for the struct's base (aka
1347 		 "this") will have been generated already, which will
1348 		 be unnecessary but not harmful if the static field is
1349 		 being handled as a global.  */
1350 	      if (field_is_static (&type->field (i)))
1351 		{
1352 		  gen_static_field (ax, value, type, i);
1353 		  if (value->optimized_out)
1354 		    error (_("static field `%s' has been "
1355 			     "optimized out, cannot use"),
1356 			   field);
1357 		  return 1;
1358 		}
1359 
1360 	      gen_primitive_field (ax, value, offset, i, type);
1361 	      return 1;
1362 	    }
1363 #if 0 /* is this right? */
1364 	  if (this_name[0] == '\0')
1365 	    internal_error (__FILE__, __LINE__,
1366 			    _("find_field: anonymous unions not supported"));
1367 #endif
1368 	}
1369     }
1370 
1371   /* Now scan through base classes recursively.  */
1372   for (i = 0; i < nbases; i++)
1373     {
1374       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
1375 
1376       rslt = gen_struct_ref_recursive (ax, value, field,
1377 				       offset + TYPE_BASECLASS_BITPOS (type, i)
1378 				       / TARGET_CHAR_BIT,
1379 				       basetype);
1380       if (rslt)
1381 	return 1;
1382     }
1383 
1384   /* Not found anywhere, flag so caller can complain.  */
1385   return 0;
1386 }
1387 
1388 /* Generate code to reference the member named FIELD of a structure or
1389    union.  The top of the stack, as described by VALUE, should have
1390    type (pointer to a)* struct/union.  OPERATOR_NAME is the name of
1391    the operator being compiled, and OPERAND_NAME is the kind of thing
1392    it operates on; we use them in error messages.  */
1393 static void
gen_struct_ref(struct agent_expr * ax,struct axs_value * value,const char * field,const char * operator_name,const char * operand_name)1394 gen_struct_ref (struct agent_expr *ax, struct axs_value *value,
1395 		const char *field, const char *operator_name,
1396 		const char *operand_name)
1397 {
1398   struct type *type;
1399   int found;
1400 
1401   /* Follow pointers until we reach a non-pointer.  These aren't the C
1402      semantics, but they're what the normal GDB evaluator does, so we
1403      should at least be consistent.  */
1404   while (pointer_type (value->type))
1405     {
1406       require_rvalue (ax, value);
1407       gen_deref (value);
1408     }
1409   type = check_typedef (value->type);
1410 
1411   /* This must yield a structure or a union.  */
1412   if (type->code () != TYPE_CODE_STRUCT
1413       && type->code () != TYPE_CODE_UNION)
1414     error (_("The left operand of `%s' is not a %s."),
1415 	   operator_name, operand_name);
1416 
1417   /* And it must be in memory; we don't deal with structure rvalues,
1418      or structures living in registers.  */
1419   if (value->kind != axs_lvalue_memory)
1420     error (_("Structure does not live in memory."));
1421 
1422   /* Search through fields and base classes recursively.  */
1423   found = gen_struct_ref_recursive (ax, value, field, 0, type);
1424 
1425   if (!found)
1426     error (_("Couldn't find member named `%s' in struct/union/class `%s'"),
1427 	   field, type->name ());
1428 }
1429 
1430 static int
1431 gen_namespace_elt (struct agent_expr *ax, struct axs_value *value,
1432 		   const struct type *curtype, const char *name);
1433 static int
1434 gen_maybe_namespace_elt (struct agent_expr *ax, struct axs_value *value,
1435 			 const struct type *curtype, const char *name);
1436 
1437 static void
gen_static_field(struct agent_expr * ax,struct axs_value * value,struct type * type,int fieldno)1438 gen_static_field (struct agent_expr *ax, struct axs_value *value,
1439 		  struct type *type, int fieldno)
1440 {
1441   if (TYPE_FIELD_LOC_KIND (type, fieldno) == FIELD_LOC_KIND_PHYSADDR)
1442     {
1443       ax_const_l (ax, TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
1444       value->kind = axs_lvalue_memory;
1445       value->type = type->field (fieldno).type ();
1446       value->optimized_out = 0;
1447     }
1448   else
1449     {
1450       const char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
1451       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0).symbol;
1452 
1453       if (sym)
1454 	{
1455 	  gen_var_ref (ax, value, sym);
1456 
1457 	  /* Don't error if the value was optimized out, we may be
1458 	     scanning all static fields and just want to pass over this
1459 	     and continue with the rest.  */
1460 	}
1461       else
1462 	{
1463 	  /* Silently assume this was optimized out; class printing
1464 	     will let the user know why the data is missing.  */
1465 	  value->optimized_out = 1;
1466 	}
1467     }
1468 }
1469 
1470 static int
gen_struct_elt_for_reference(struct agent_expr * ax,struct axs_value * value,struct type * type,const char * fieldname)1471 gen_struct_elt_for_reference (struct agent_expr *ax, struct axs_value *value,
1472 			      struct type *type, const char *fieldname)
1473 {
1474   struct type *t = type;
1475   int i;
1476 
1477   if (t->code () != TYPE_CODE_STRUCT
1478       && t->code () != TYPE_CODE_UNION)
1479     internal_error (__FILE__, __LINE__,
1480 		    _("non-aggregate type to gen_struct_elt_for_reference"));
1481 
1482   for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
1483     {
1484       const char *t_field_name = TYPE_FIELD_NAME (t, i);
1485 
1486       if (t_field_name && strcmp (t_field_name, fieldname) == 0)
1487 	{
1488 	  if (field_is_static (&t->field (i)))
1489 	    {
1490 	      gen_static_field (ax, value, t, i);
1491 	      if (value->optimized_out)
1492 		error (_("static field `%s' has been "
1493 			 "optimized out, cannot use"),
1494 		       fieldname);
1495 	      return 1;
1496 	    }
1497 	  if (TYPE_FIELD_PACKED (t, i))
1498 	    error (_("pointers to bitfield members not allowed"));
1499 
1500 	  /* FIXME we need a way to do "want_address" equivalent */
1501 
1502 	  error (_("Cannot reference non-static field \"%s\""), fieldname);
1503 	}
1504     }
1505 
1506   /* FIXME add other scoped-reference cases here */
1507 
1508   /* Do a last-ditch lookup.  */
1509   return gen_maybe_namespace_elt (ax, value, type, fieldname);
1510 }
1511 
1512 /* C++: Return the member NAME of the namespace given by the type
1513    CURTYPE.  */
1514 
1515 static int
gen_namespace_elt(struct agent_expr * ax,struct axs_value * value,const struct type * curtype,const char * name)1516 gen_namespace_elt (struct agent_expr *ax, struct axs_value *value,
1517 		   const struct type *curtype, const char *name)
1518 {
1519   int found = gen_maybe_namespace_elt (ax, value, curtype, name);
1520 
1521   if (!found)
1522     error (_("No symbol \"%s\" in namespace \"%s\"."),
1523 	   name, curtype->name ());
1524 
1525   return found;
1526 }
1527 
1528 /* A helper function used by value_namespace_elt and
1529    value_struct_elt_for_reference.  It looks up NAME inside the
1530    context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
1531    is a class and NAME refers to a type in CURTYPE itself (as opposed
1532    to, say, some base class of CURTYPE).  */
1533 
1534 static int
gen_maybe_namespace_elt(struct agent_expr * ax,struct axs_value * value,const struct type * curtype,const char * name)1535 gen_maybe_namespace_elt (struct agent_expr *ax, struct axs_value *value,
1536 			 const struct type *curtype, const char *name)
1537 {
1538   const char *namespace_name = curtype->name ();
1539   struct block_symbol sym;
1540 
1541   sym = cp_lookup_symbol_namespace (namespace_name, name,
1542 				    block_for_pc (ax->scope),
1543 				    VAR_DOMAIN);
1544 
1545   if (sym.symbol == NULL)
1546     return 0;
1547 
1548   gen_var_ref (ax, value, sym.symbol);
1549 
1550   if (value->optimized_out)
1551     error (_("`%s' has been optimized out, cannot use"),
1552 	   sym.symbol->print_name ());
1553 
1554   return 1;
1555 }
1556 
1557 
1558 static int
gen_aggregate_elt_ref(struct agent_expr * ax,struct axs_value * value,struct type * type,const char * field)1559 gen_aggregate_elt_ref (struct agent_expr *ax, struct axs_value *value,
1560 		       struct type *type, const char *field)
1561 {
1562   switch (type->code ())
1563     {
1564     case TYPE_CODE_STRUCT:
1565     case TYPE_CODE_UNION:
1566       return gen_struct_elt_for_reference (ax, value, type, field);
1567       break;
1568     case TYPE_CODE_NAMESPACE:
1569       return gen_namespace_elt (ax, value, type, field);
1570       break;
1571     default:
1572       internal_error (__FILE__, __LINE__,
1573 		      _("non-aggregate type in gen_aggregate_elt_ref"));
1574     }
1575 
1576   return 0;
1577 }
1578 
1579 
1580 
1581 namespace expr
1582 {
1583 
1584 void
generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1585 operation::generate_ax (struct expression *exp,
1586 			struct agent_expr *ax,
1587 			struct axs_value *value,
1588 			struct type *cast_type)
1589 {
1590   if (constant_p ())
1591     {
1592       struct value *v = evaluate (nullptr, exp, EVAL_AVOID_SIDE_EFFECTS);
1593       ax_const_l (ax, value_as_long (v));
1594       value->kind = axs_rvalue;
1595       value->type = check_typedef (value_type (v));
1596     }
1597   else
1598     {
1599       do_generate_ax (exp, ax, value, cast_type);
1600       if (cast_type != nullptr)
1601 	gen_cast (ax, value, cast_type);
1602     }
1603 }
1604 
1605 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1606 scope_operation::do_generate_ax (struct expression *exp,
1607 				 struct agent_expr *ax,
1608 				 struct axs_value *value,
1609 				 struct type *cast_type)
1610 {
1611   struct type *type = std::get<0> (m_storage);
1612   const std::string &name = std::get<1> (m_storage);
1613   int found = gen_aggregate_elt_ref (ax, value, type, name.c_str ());
1614   if (!found)
1615     error (_("There is no field named %s"), name.c_str ());
1616 }
1617 
1618 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1619 long_const_operation::do_generate_ax (struct expression *exp,
1620 				      struct agent_expr *ax,
1621 				      struct axs_value *value,
1622 				      struct type *cast_type)
1623 {
1624   gen_int_literal (ax, value, std::get<1> (m_storage),
1625 		   std::get<0> (m_storage));
1626 }
1627 
1628 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1629 var_msym_value_operation::do_generate_ax (struct expression *exp,
1630 					  struct agent_expr *ax,
1631 					  struct axs_value *value,
1632 					  struct type *cast_type)
1633 {
1634   const bound_minimal_symbol &b = std::get<0> (m_storage);
1635   gen_msym_var_ref (ax, value, b.minsym, b.objfile);
1636 
1637   if (value->type->code () == TYPE_CODE_ERROR)
1638     {
1639       if (cast_type == nullptr)
1640 	error_unknown_type (b.minsym->linkage_name ());
1641       value->type = cast_type;
1642     }
1643 }
1644 
1645 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1646 register_operation::do_generate_ax (struct expression *exp,
1647 				    struct agent_expr *ax,
1648 				    struct axs_value *value,
1649 				    struct type *cast_type)
1650 {
1651   const char *name = std::get<0> (m_storage).c_str ();
1652   int len = std::get<0> (m_storage).size ();
1653   int reg;
1654 
1655   reg = user_reg_map_name_to_regnum (ax->gdbarch, name, len);
1656   if (reg == -1)
1657     internal_error (__FILE__, __LINE__,
1658 		    _("Register $%s not available"), name);
1659   /* No support for tracing user registers yet.  */
1660   if (reg >= gdbarch_num_cooked_regs (ax->gdbarch))
1661     error (_("'%s' is a user-register; "
1662 	     "GDB cannot yet trace user-register contents."),
1663 	   name);
1664   value->kind = axs_lvalue_register;
1665   value->u.reg = reg;
1666   value->type = register_type (ax->gdbarch, reg);
1667 }
1668 
1669 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1670 internalvar_operation::do_generate_ax (struct expression *exp,
1671 				       struct agent_expr *ax,
1672 				       struct axs_value *value,
1673 				       struct type *cast_type)
1674 {
1675   struct internalvar *var = std::get<0> (m_storage);
1676   const char *name = internalvar_name (var);
1677   struct trace_state_variable *tsv;
1678 
1679   tsv = find_trace_state_variable (name);
1680   if (tsv)
1681     {
1682       ax_tsv (ax, aop_getv, tsv->number);
1683       if (ax->tracing)
1684 	ax_tsv (ax, aop_tracev, tsv->number);
1685       /* Trace state variables are always 64-bit integers.  */
1686       value->kind = axs_rvalue;
1687       value->type = builtin_type (ax->gdbarch)->builtin_long_long;
1688     }
1689   else if (! compile_internalvar_to_ax (var, ax, value))
1690     error (_("$%s is not a trace state variable; GDB agent "
1691 	     "expressions cannot use convenience variables."), name);
1692 }
1693 
1694 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1695 ternop_cond_operation::do_generate_ax (struct expression *exp,
1696 				       struct agent_expr *ax,
1697 				       struct axs_value *value,
1698 				       struct type *cast_type)
1699 {
1700   struct axs_value value1, value2, value3;
1701   int if1, end;
1702 
1703   std::get<0> (m_storage)->generate_ax (exp, ax, &value1);
1704   gen_usual_unary (ax, &value1);
1705   /* For (A ? B : C), it's easiest to generate subexpression
1706      bytecodes in order, but if_goto jumps on true, so we invert
1707      the sense of A.  Then we can do B by dropping through, and
1708      jump to do C.  */
1709   gen_logical_not (ax, &value1, builtin_type (ax->gdbarch)->builtin_int);
1710   if1 = ax_goto (ax, aop_if_goto);
1711   std::get<1> (m_storage)->generate_ax (exp, ax, &value2);
1712   gen_usual_unary (ax, &value2);
1713   end = ax_goto (ax, aop_goto);
1714   ax_label (ax, if1, ax->len);
1715   std::get<2> (m_storage)->generate_ax (exp, ax, &value3);
1716   gen_usual_unary (ax, &value3);
1717   ax_label (ax, end, ax->len);
1718   /* This is arbitrary - what if B and C are incompatible types? */
1719   value->type = value2.type;
1720   value->kind = value2.kind;
1721 }
1722 
1723 /* Generate code for GDB's magical `repeat' operator.
1724    LVALUE @ INT creates an array INT elements long, and whose elements
1725    have the same type as LVALUE, located in memory so that LVALUE is
1726    its first element.  For example, argv[0]@argc gives you the array
1727    of command-line arguments.
1728 
1729    Unfortunately, because we have to know the types before we actually
1730    have a value for the expression, we can't implement this perfectly
1731    without changing the type system, having values that occupy two
1732    stack slots, doing weird things with sizeof, etc.  So we require
1733    the right operand to be a constant expression.  */
1734 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1735 repeat_operation::do_generate_ax (struct expression *exp,
1736 				  struct agent_expr *ax,
1737 				  struct axs_value *value,
1738 				  struct type *cast_type)
1739 {
1740   struct axs_value value1;
1741 
1742   /* We don't want to turn this into an rvalue, so no conversions
1743      here.  */
1744   std::get<0> (m_storage)->generate_ax (exp, ax, &value1);
1745   if (value1.kind != axs_lvalue_memory)
1746     error (_("Left operand of `@' must be an object in memory."));
1747 
1748   /* Evaluate the length; it had better be a constant.  */
1749   if (!std::get<1> (m_storage)->constant_p ())
1750     error (_("Right operand of `@' must be a "
1751 	     "constant, in agent expressions."));
1752 
1753   struct value *v
1754     = std::get<1> (m_storage)->evaluate (nullptr, exp,
1755 					 EVAL_AVOID_SIDE_EFFECTS);
1756   if (value_type (v)->code () != TYPE_CODE_INT)
1757     error (_("Right operand of `@' must be an integer."));
1758   int length = value_as_long (v);
1759   if (length <= 0)
1760     error (_("Right operand of `@' must be positive."));
1761 
1762   /* The top of the stack is already the address of the object, so
1763      all we need to do is frob the type of the lvalue.  */
1764   /* FIXME-type-allocation: need a way to free this type when we are
1765      done with it.  */
1766   struct type *array
1767     = lookup_array_range_type (value1.type, 0, length - 1);
1768 
1769   value->kind = axs_lvalue_memory;
1770   value->type = array;
1771 }
1772 
1773 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1774 comma_operation::do_generate_ax (struct expression *exp,
1775 				 struct agent_expr *ax,
1776 				 struct axs_value *value,
1777 				 struct type *cast_type)
1778 {
1779   /* Note that we need to be a little subtle about generating code
1780      for comma.  In C, we can do some optimizations here because
1781      we know the left operand is only being evaluated for effect.
1782      However, if the tracing kludge is in effect, then we always
1783      need to evaluate the left hand side fully, so that all the
1784      variables it mentions get traced.  */
1785   struct axs_value value1;
1786   std::get<0> (m_storage)->generate_ax (exp, ax, &value1);
1787   /* Don't just dispose of the left operand.  We might be tracing,
1788      in which case we want to emit code to trace it if it's an
1789      lvalue.  */
1790   gen_traced_pop (ax, &value1);
1791   std::get<1> (m_storage)->generate_ax (exp, ax, value);
1792   /* It's the consumer's responsibility to trace the right operand.  */
1793 }
1794 
1795 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1796 unop_sizeof_operation::do_generate_ax (struct expression *exp,
1797 				       struct agent_expr *ax,
1798 				       struct axs_value *value,
1799 				       struct type *cast_type)
1800 {
1801   /* We don't care about the value of the operand expression; we only
1802      care about its type.  However, in the current arrangement, the
1803      only way to find an expression's type is to generate code for it.
1804      So we generate code for the operand, and then throw it away,
1805      replacing it with code that simply pushes its size.  */
1806   int start = ax->len;
1807 
1808   std::get<0> (m_storage)->generate_ax (exp, ax, value);
1809 
1810   /* Throw away the code we just generated.  */
1811   ax->len = start;
1812 
1813   ax_const_l (ax, TYPE_LENGTH (value->type));
1814   value->kind = axs_rvalue;
1815   value->type = builtin_type (ax->gdbarch)->builtin_int;
1816 }
1817 
1818 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1819 unop_cast_operation::do_generate_ax (struct expression *exp,
1820 				     struct agent_expr *ax,
1821 				     struct axs_value *value,
1822 				     struct type *cast_type)
1823 {
1824   std::get<0> (m_storage)->generate_ax (exp, ax, value,
1825 					std::get<1> (m_storage));
1826 }
1827 
1828 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1829 unop_memval_operation::do_generate_ax (struct expression *exp,
1830 				       struct agent_expr *ax,
1831 				       struct axs_value *value,
1832 				       struct type *cast_type)
1833 {
1834   std::get<0> (m_storage)->generate_ax (exp, ax, value);
1835   /* If we have an axs_rvalue or an axs_lvalue_memory, then we
1836      already have the right value on the stack.  For
1837      axs_lvalue_register, we must convert.  */
1838   if (value->kind == axs_lvalue_register)
1839     require_rvalue (ax, value);
1840 
1841   value->type = std::get<1> (m_storage);
1842   value->kind = axs_lvalue_memory;
1843 }
1844 
1845 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1846 unop_memval_type_operation::do_generate_ax (struct expression *exp,
1847 					    struct agent_expr *ax,
1848 					    struct axs_value *value,
1849 					    struct type *cast_type)
1850 {
1851   struct value *val
1852     = std::get<0> (m_storage)->evaluate (nullptr, exp,
1853 					 EVAL_AVOID_SIDE_EFFECTS);
1854   struct type *type = value_type (val);
1855 
1856   std::get<1> (m_storage)->generate_ax (exp, ax, value);
1857 
1858   /* If we have an axs_rvalue or an axs_lvalue_memory, then we
1859      already have the right value on the stack.  For
1860      axs_lvalue_register, we must convert.  */
1861   if (value->kind == axs_lvalue_register)
1862     require_rvalue (ax, value);
1863 
1864   value->type = type;
1865   value->kind = axs_lvalue_memory;
1866 }
1867 
1868 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1869 op_this_operation::do_generate_ax (struct expression *exp,
1870 				   struct agent_expr *ax,
1871 				   struct axs_value *value,
1872 				   struct type *cast_type)
1873 {
1874   struct symbol *sym, *func;
1875   const struct block *b;
1876   const struct language_defn *lang;
1877 
1878   b = block_for_pc (ax->scope);
1879   func = block_linkage_function (b);
1880   lang = language_def (func->language ());
1881 
1882   sym = lookup_language_this (lang, b).symbol;
1883   if (!sym)
1884     error (_("no `%s' found"), lang->name_of_this ());
1885 
1886   gen_var_ref (ax, value, sym);
1887 
1888   if (value->optimized_out)
1889     error (_("`%s' has been optimized out, cannot use"),
1890 	   sym->print_name ());
1891 }
1892 
1893 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1894 assign_operation::do_generate_ax (struct expression *exp,
1895 				  struct agent_expr *ax,
1896 				  struct axs_value *value,
1897 				  struct type *cast_type)
1898 {
1899   operation *subop = std::get<0> (m_storage).get ();
1900   if (subop->opcode () != OP_INTERNALVAR)
1901     error (_("May only assign to trace state variables"));
1902 
1903   internalvar_operation *ivarop
1904     = dynamic_cast<internalvar_operation *> (subop);
1905   gdb_assert (ivarop != nullptr);
1906 
1907   const char *name = internalvar_name (ivarop->get_internalvar ());
1908   struct trace_state_variable *tsv;
1909 
1910   std::get<1> (m_storage)->generate_ax (exp, ax, value);
1911   tsv = find_trace_state_variable (name);
1912   if (tsv)
1913     {
1914       ax_tsv (ax, aop_setv, tsv->number);
1915       if (ax->tracing)
1916 	ax_tsv (ax, aop_tracev, tsv->number);
1917     }
1918   else
1919     error (_("$%s is not a trace state variable, "
1920 	     "may not assign to it"), name);
1921 }
1922 
1923 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1924 assign_modify_operation::do_generate_ax (struct expression *exp,
1925 					 struct agent_expr *ax,
1926 					 struct axs_value *value,
1927 					 struct type *cast_type)
1928 {
1929   operation *subop = std::get<1> (m_storage).get ();
1930   if (subop->opcode () != OP_INTERNALVAR)
1931     error (_("May only assign to trace state variables"));
1932 
1933   internalvar_operation *ivarop
1934     = dynamic_cast<internalvar_operation *> (subop);
1935   gdb_assert (ivarop != nullptr);
1936 
1937   const char *name = internalvar_name (ivarop->get_internalvar ());
1938   struct trace_state_variable *tsv;
1939 
1940   tsv = find_trace_state_variable (name);
1941   if (tsv)
1942     {
1943       /* The tsv will be the left half of the binary operation.  */
1944       ax_tsv (ax, aop_getv, tsv->number);
1945       if (ax->tracing)
1946 	ax_tsv (ax, aop_tracev, tsv->number);
1947       /* Trace state variables are always 64-bit integers.  */
1948       struct axs_value value1, value2;
1949       value1.kind = axs_rvalue;
1950       value1.type = builtin_type (ax->gdbarch)->builtin_long_long;
1951       /* Now do right half of expression.  */
1952       std::get<2> (m_storage)->generate_ax (exp, ax, &value2);
1953       gen_expr_binop_rest (exp, std::get<0> (m_storage), ax,
1954 			   value, &value1, &value2);
1955       /* We have a result of the binary op, set the tsv.  */
1956       ax_tsv (ax, aop_setv, tsv->number);
1957       if (ax->tracing)
1958 	ax_tsv (ax, aop_tracev, tsv->number);
1959     }
1960   else
1961     error (_("$%s is not a trace state variable, "
1962 	     "may not assign to it"), name);
1963 }
1964 
1965 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1966 unop_cast_type_operation::do_generate_ax (struct expression *exp,
1967 					  struct agent_expr *ax,
1968 					  struct axs_value *value,
1969 					  struct type *cast_type)
1970 {
1971   struct value *val
1972     = std::get<0> (m_storage)->evaluate (nullptr, exp,
1973 					 EVAL_AVOID_SIDE_EFFECTS);
1974   std::get<1> (m_storage)->generate_ax (exp, ax, value, value_type (val));
1975 }
1976 
1977 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1978 var_value_operation::do_generate_ax (struct expression *exp,
1979 				     struct agent_expr *ax,
1980 				     struct axs_value *value,
1981 				     struct type *cast_type)
1982 {
1983   gen_var_ref (ax, value, std::get<0> (m_storage).symbol);
1984 
1985   if (value->optimized_out)
1986     error (_("`%s' has been optimized out, cannot use"),
1987 	   std::get<0> (m_storage).symbol->print_name ());
1988 
1989   if (value->type->code () == TYPE_CODE_ERROR)
1990     {
1991       if (cast_type == nullptr)
1992 	error_unknown_type (std::get<0> (m_storage).symbol->print_name ());
1993       value->type = cast_type;
1994     }
1995 }
1996 
1997 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)1998 logical_and_operation::do_generate_ax (struct expression *exp,
1999 				       struct agent_expr *ax,
2000 				       struct axs_value *value,
2001 				       struct type *cast_type)
2002 {
2003   struct axs_value value1, value2;
2004   int if1, go1, if2, go2, end;
2005 
2006   /* Generate the obvious sequence of tests and jumps.  */
2007   std::get<0> (m_storage)->generate_ax (exp, ax, &value1);
2008   gen_usual_unary (ax, &value1);
2009   if1 = ax_goto (ax, aop_if_goto);
2010   go1 = ax_goto (ax, aop_goto);
2011   ax_label (ax, if1, ax->len);
2012   std::get<1> (m_storage)->generate_ax (exp, ax, &value2);
2013   gen_usual_unary (ax, &value2);
2014   if2 = ax_goto (ax, aop_if_goto);
2015   go2 = ax_goto (ax, aop_goto);
2016   ax_label (ax, if2, ax->len);
2017   ax_const_l (ax, 1);
2018   end = ax_goto (ax, aop_goto);
2019   ax_label (ax, go1, ax->len);
2020   ax_label (ax, go2, ax->len);
2021   ax_const_l (ax, 0);
2022   ax_label (ax, end, ax->len);
2023   value->kind = axs_rvalue;
2024   value->type = builtin_type (ax->gdbarch)->builtin_int;
2025 }
2026 
2027 void
do_generate_ax(struct expression * exp,struct agent_expr * ax,struct axs_value * value,struct type * cast_type)2028 logical_or_operation::do_generate_ax (struct expression *exp,
2029 				      struct agent_expr *ax,
2030 				      struct axs_value *value,
2031 				      struct type *cast_type)
2032 {
2033   struct axs_value value1, value2;
2034   int if1, if2, end;
2035 
2036   /* Generate the obvious sequence of tests and jumps.  */
2037   std::get<0> (m_storage)->generate_ax (exp, ax, &value1);
2038   gen_usual_unary (ax, &value1);
2039   if1 = ax_goto (ax, aop_if_goto);
2040   std::get<1> (m_storage)->generate_ax (exp, ax, &value2);
2041   gen_usual_unary (ax, &value2);
2042   if2 = ax_goto (ax, aop_if_goto);
2043   ax_const_l (ax, 0);
2044   end = ax_goto (ax, aop_goto);
2045   ax_label (ax, if1, ax->len);
2046   ax_label (ax, if2, ax->len);
2047   ax_const_l (ax, 1);
2048   ax_label (ax, end, ax->len);
2049   value->kind = axs_rvalue;
2050   value->type = builtin_type (ax->gdbarch)->builtin_int;
2051 }
2052 
2053 }
2054 
2055 /* This handles the middle-to-right-side of code generation for binary
2056    expressions, which is shared between regular binary operations and
2057    assign-modify (+= and friends) expressions.  */
2058 
2059 static void
gen_expr_binop_rest(struct expression * exp,enum exp_opcode op,struct agent_expr * ax,struct axs_value * value,struct axs_value * value1,struct axs_value * value2)2060 gen_expr_binop_rest (struct expression *exp,
2061 		     enum exp_opcode op,
2062 		     struct agent_expr *ax, struct axs_value *value,
2063 		     struct axs_value *value1, struct axs_value *value2)
2064 {
2065   struct type *int_type = builtin_type (ax->gdbarch)->builtin_int;
2066 
2067   gen_usual_unary (ax, value2);
2068   gen_usual_arithmetic (ax, value1, value2);
2069   switch (op)
2070     {
2071     case BINOP_ADD:
2072       if (value1->type->code () == TYPE_CODE_INT
2073 	  && pointer_type (value2->type))
2074 	{
2075 	  /* Swap the values and proceed normally.  */
2076 	  ax_simple (ax, aop_swap);
2077 	  gen_ptradd (ax, value, value2, value1);
2078 	}
2079       else if (pointer_type (value1->type)
2080 	       && value2->type->code () == TYPE_CODE_INT)
2081 	gen_ptradd (ax, value, value1, value2);
2082       else
2083 	gen_binop (ax, value, value1, value2,
2084 		   aop_add, aop_add, 1, "addition");
2085       break;
2086     case BINOP_SUB:
2087       if (pointer_type (value1->type)
2088 	  && value2->type->code () == TYPE_CODE_INT)
2089 	gen_ptrsub (ax,value, value1, value2);
2090       else if (pointer_type (value1->type)
2091 	       && pointer_type (value2->type))
2092 	/* FIXME --- result type should be ptrdiff_t */
2093 	gen_ptrdiff (ax, value, value1, value2,
2094 		     builtin_type (ax->gdbarch)->builtin_long);
2095       else
2096 	gen_binop (ax, value, value1, value2,
2097 		   aop_sub, aop_sub, 1, "subtraction");
2098       break;
2099     case BINOP_MUL:
2100       gen_binop (ax, value, value1, value2,
2101 		 aop_mul, aop_mul, 1, "multiplication");
2102       break;
2103     case BINOP_DIV:
2104       gen_binop (ax, value, value1, value2,
2105 		 aop_div_signed, aop_div_unsigned, 1, "division");
2106       break;
2107     case BINOP_REM:
2108       gen_binop (ax, value, value1, value2,
2109 		 aop_rem_signed, aop_rem_unsigned, 1, "remainder");
2110       break;
2111     case BINOP_LSH:
2112       gen_binop (ax, value, value1, value2,
2113 		 aop_lsh, aop_lsh, 1, "left shift");
2114       break;
2115     case BINOP_RSH:
2116       gen_binop (ax, value, value1, value2,
2117 		 aop_rsh_signed, aop_rsh_unsigned, 1, "right shift");
2118       break;
2119     case BINOP_SUBSCRIPT:
2120       {
2121 	struct type *type;
2122 
2123 	if (binop_types_user_defined_p (op, value1->type, value2->type))
2124 	  {
2125 	    error (_("cannot subscript requested type: "
2126 		     "cannot call user defined functions"));
2127 	  }
2128 	else
2129 	  {
2130 	    /* If the user attempts to subscript something that is not
2131 	       an array or pointer type (like a plain int variable for
2132 	       example), then report this as an error.  */
2133 	    type = check_typedef (value1->type);
2134 	    if (type->code () != TYPE_CODE_ARRAY
2135 		&& type->code () != TYPE_CODE_PTR)
2136 	      {
2137 		if (type->name ())
2138 		  error (_("cannot subscript something of type `%s'"),
2139 			 type->name ());
2140 		else
2141 		  error (_("cannot subscript requested type"));
2142 	      }
2143 	  }
2144 
2145 	if (!is_integral_type (value2->type))
2146 	  error (_("Argument to arithmetic operation "
2147 		   "not a number or boolean."));
2148 
2149 	gen_ptradd (ax, value, value1, value2);
2150 	gen_deref (value);
2151 	break;
2152       }
2153     case BINOP_BITWISE_AND:
2154       gen_binop (ax, value, value1, value2,
2155 		 aop_bit_and, aop_bit_and, 0, "bitwise and");
2156       break;
2157 
2158     case BINOP_BITWISE_IOR:
2159       gen_binop (ax, value, value1, value2,
2160 		 aop_bit_or, aop_bit_or, 0, "bitwise or");
2161       break;
2162 
2163     case BINOP_BITWISE_XOR:
2164       gen_binop (ax, value, value1, value2,
2165 		 aop_bit_xor, aop_bit_xor, 0, "bitwise exclusive-or");
2166       break;
2167 
2168     case BINOP_EQUAL:
2169       gen_equal (ax, value, value1, value2, int_type);
2170       break;
2171 
2172     case BINOP_NOTEQUAL:
2173       gen_equal (ax, value, value1, value2, int_type);
2174       gen_logical_not (ax, value, int_type);
2175       break;
2176 
2177     case BINOP_LESS:
2178       gen_less (ax, value, value1, value2, int_type);
2179       break;
2180 
2181     case BINOP_GTR:
2182       ax_simple (ax, aop_swap);
2183       gen_less (ax, value, value1, value2, int_type);
2184       break;
2185 
2186     case BINOP_LEQ:
2187       ax_simple (ax, aop_swap);
2188       gen_less (ax, value, value1, value2, int_type);
2189       gen_logical_not (ax, value, int_type);
2190       break;
2191 
2192     case BINOP_GEQ:
2193       gen_less (ax, value, value1, value2, int_type);
2194       gen_logical_not (ax, value, int_type);
2195       break;
2196 
2197     default:
2198       /* We should only list operators in the outer case statement
2199 	 that we actually handle in the inner case statement.  */
2200       internal_error (__FILE__, __LINE__,
2201 		      _("gen_expr: op case sets don't match"));
2202     }
2203 }
2204 
2205 /* A helper function that emits a binop based on two operations.  */
2206 
2207 void
gen_expr_binop(struct expression * exp,enum exp_opcode op,expr::operation * lhs,expr::operation * rhs,struct agent_expr * ax,struct axs_value * value)2208 gen_expr_binop (struct expression *exp,
2209 		enum exp_opcode op,
2210 		expr::operation *lhs, expr::operation *rhs,
2211 		struct agent_expr *ax, struct axs_value *value)
2212 {
2213   struct axs_value value1, value2;
2214 
2215   lhs->generate_ax (exp, ax, &value1);
2216   gen_usual_unary (ax, &value1);
2217   rhs->generate_ax (exp, ax, &value2);
2218   gen_expr_binop_rest (exp, op, ax, value, &value1, &value2);
2219 }
2220 
2221 /* A helper function that emits a structop based on an operation and a
2222    member name.  */
2223 
2224 void
gen_expr_structop(struct expression * exp,enum exp_opcode op,expr::operation * lhs,const char * name,struct agent_expr * ax,struct axs_value * value)2225 gen_expr_structop (struct expression *exp,
2226 		   enum exp_opcode op,
2227 		   expr::operation *lhs,
2228 		   const char *name,
2229 		   struct agent_expr *ax, struct axs_value *value)
2230 {
2231   lhs->generate_ax (exp, ax, value);
2232   if (op == STRUCTOP_STRUCT)
2233     gen_struct_ref (ax, value, name, ".", "structure or union");
2234   else if (op == STRUCTOP_PTR)
2235     gen_struct_ref (ax, value, name, "->",
2236 		    "pointer to a structure or union");
2237   else
2238     /* If this `if' chain doesn't handle it, then the case list
2239        shouldn't mention it, and we shouldn't be here.  */
2240     internal_error (__FILE__, __LINE__,
2241 		    _("gen_expr: unhandled struct case"));
2242 }
2243 
2244 /* A helper function that emits a unary operation.  */
2245 
2246 void
gen_expr_unop(struct expression * exp,enum exp_opcode op,expr::operation * lhs,struct agent_expr * ax,struct axs_value * value)2247 gen_expr_unop (struct expression *exp,
2248 	       enum exp_opcode op,
2249 	       expr::operation *lhs,
2250 	       struct agent_expr *ax, struct axs_value *value)
2251 {
2252   struct axs_value value1, value2;
2253 
2254   switch (op)
2255     {
2256     case UNOP_NEG:
2257       gen_int_literal (ax, &value1, 0,
2258 		       builtin_type (ax->gdbarch)->builtin_int);
2259       gen_usual_unary (ax, &value1);	/* shouldn't do much */
2260       lhs->generate_ax (exp, ax, &value2);
2261       gen_usual_unary (ax, &value2);
2262       gen_usual_arithmetic (ax, &value1, &value2);
2263       gen_binop (ax, value, &value1, &value2, aop_sub, aop_sub, 1, "negation");
2264       break;
2265 
2266     case UNOP_PLUS:
2267       /* + FOO is equivalent to 0 + FOO, which can be optimized.  */
2268       lhs->generate_ax (exp, ax, value);
2269       gen_usual_unary (ax, value);
2270       break;
2271 
2272     case UNOP_LOGICAL_NOT:
2273       lhs->generate_ax (exp, ax, value);
2274       gen_usual_unary (ax, value);
2275       gen_logical_not (ax, value,  builtin_type (ax->gdbarch)->builtin_int);
2276       break;
2277 
2278     case UNOP_COMPLEMENT:
2279       lhs->generate_ax (exp, ax, value);
2280       gen_usual_unary (ax, value);
2281       gen_integral_promotions (ax, value);
2282       gen_complement (ax, value);
2283       break;
2284 
2285     case UNOP_IND:
2286       lhs->generate_ax (exp, ax, value);
2287       gen_usual_unary (ax, value);
2288       if (!pointer_type (value->type))
2289 	error (_("Argument of unary `*' is not a pointer."));
2290       gen_deref (value);
2291       break;
2292 
2293     case UNOP_ADDR:
2294       lhs->generate_ax (exp, ax, value);
2295       gen_address_of (value);
2296       break;
2297 
2298     default:
2299       gdb_assert_not_reached ("invalid case in gen_expr_unop");
2300     }
2301 }
2302 
2303 
2304 
2305 /* Given a single variable and a scope, generate bytecodes to trace
2306    its value.  This is for use in situations where we have only a
2307    variable's name, and no parsed expression; for instance, when the
2308    name comes from a list of local variables of a function.  */
2309 
2310 agent_expr_up
gen_trace_for_var(CORE_ADDR scope,struct gdbarch * gdbarch,struct symbol * var,int trace_string)2311 gen_trace_for_var (CORE_ADDR scope, struct gdbarch *gdbarch,
2312 		   struct symbol *var, int trace_string)
2313 {
2314   agent_expr_up ax (new agent_expr (gdbarch, scope));
2315   struct axs_value value;
2316 
2317   ax->tracing = 1;
2318   ax->trace_string = trace_string;
2319   gen_var_ref (ax.get (), &value, var);
2320 
2321   /* If there is no actual variable to trace, flag it by returning
2322      an empty agent expression.  */
2323   if (value.optimized_out)
2324     return agent_expr_up ();
2325 
2326   /* Make sure we record the final object, and get rid of it.  */
2327   gen_traced_pop (ax.get (), &value);
2328 
2329   /* Oh, and terminate.  */
2330   ax_simple (ax.get (), aop_end);
2331 
2332   return ax;
2333 }
2334 
2335 /* Generating bytecode from GDB expressions: driver */
2336 
2337 /* Given a GDB expression EXPR, return bytecode to trace its value.
2338    The result will use the `trace' and `trace_quick' bytecodes to
2339    record the value of all memory touched by the expression.  The
2340    caller can then use the ax_reqs function to discover which
2341    registers it relies upon.  */
2342 
2343 agent_expr_up
gen_trace_for_expr(CORE_ADDR scope,struct expression * expr,int trace_string)2344 gen_trace_for_expr (CORE_ADDR scope, struct expression *expr,
2345 		    int trace_string)
2346 {
2347   agent_expr_up ax (new agent_expr (expr->gdbarch, scope));
2348   struct axs_value value;
2349 
2350   ax->tracing = 1;
2351   ax->trace_string = trace_string;
2352   value.optimized_out = 0;
2353   expr->op->generate_ax (expr, ax.get (), &value);
2354 
2355   /* Make sure we record the final object, and get rid of it.  */
2356   gen_traced_pop (ax.get (), &value);
2357 
2358   /* Oh, and terminate.  */
2359   ax_simple (ax.get (), aop_end);
2360 
2361   return ax;
2362 }
2363 
2364 /* Given a GDB expression EXPR, return a bytecode sequence that will
2365    evaluate and return a result.  The bytecodes will do a direct
2366    evaluation, using the current data on the target, rather than
2367    recording blocks of memory and registers for later use, as
2368    gen_trace_for_expr does.  The generated bytecode sequence leaves
2369    the result of expression evaluation on the top of the stack.  */
2370 
2371 agent_expr_up
gen_eval_for_expr(CORE_ADDR scope,struct expression * expr)2372 gen_eval_for_expr (CORE_ADDR scope, struct expression *expr)
2373 {
2374   agent_expr_up ax (new agent_expr (expr->gdbarch, scope));
2375   struct axs_value value;
2376 
2377   ax->tracing = 0;
2378   value.optimized_out = 0;
2379   expr->op->generate_ax (expr, ax.get (), &value);
2380 
2381   require_rvalue (ax.get (), &value);
2382 
2383   /* Oh, and terminate.  */
2384   ax_simple (ax.get (), aop_end);
2385 
2386   return ax;
2387 }
2388 
2389 agent_expr_up
gen_trace_for_return_address(CORE_ADDR scope,struct gdbarch * gdbarch,int trace_string)2390 gen_trace_for_return_address (CORE_ADDR scope, struct gdbarch *gdbarch,
2391 			      int trace_string)
2392 {
2393   agent_expr_up ax (new agent_expr (gdbarch, scope));
2394   struct axs_value value;
2395 
2396   ax->tracing = 1;
2397   ax->trace_string = trace_string;
2398 
2399   gdbarch_gen_return_address (gdbarch, ax.get (), &value, scope);
2400 
2401   /* Make sure we record the final object, and get rid of it.  */
2402   gen_traced_pop (ax.get (), &value);
2403 
2404   /* Oh, and terminate.  */
2405   ax_simple (ax.get (), aop_end);
2406 
2407   return ax;
2408 }
2409 
2410 /* Given a collection of printf-style arguments, generate code to
2411    evaluate the arguments and pass everything to a special
2412    bytecode.  */
2413 
2414 agent_expr_up
gen_printf(CORE_ADDR scope,struct gdbarch * gdbarch,CORE_ADDR function,LONGEST channel,const char * format,int fmtlen,int nargs,struct expression ** exprs)2415 gen_printf (CORE_ADDR scope, struct gdbarch *gdbarch,
2416 	    CORE_ADDR function, LONGEST channel,
2417 	    const char *format, int fmtlen,
2418 	    int nargs, struct expression **exprs)
2419 {
2420   agent_expr_up ax (new agent_expr (gdbarch, scope));
2421   struct axs_value value;
2422   int tem;
2423 
2424   /* We're computing values, not doing side effects.  */
2425   ax->tracing = 0;
2426 
2427   /* Evaluate and push the args on the stack in reverse order,
2428      for simplicity of collecting them on the target side.  */
2429   for (tem = nargs - 1; tem >= 0; --tem)
2430     {
2431       value.optimized_out = 0;
2432       exprs[tem]->op->generate_ax (exprs[tem], ax.get (), &value);
2433       require_rvalue (ax.get (), &value);
2434     }
2435 
2436   /* Push function and channel.  */
2437   ax_const_l (ax.get (), channel);
2438   ax_const_l (ax.get (), function);
2439 
2440   /* Issue the printf bytecode proper.  */
2441   ax_simple (ax.get (), aop_printf);
2442   ax_raw_byte (ax.get (), nargs);
2443   ax_string (ax.get (), format, fmtlen);
2444 
2445   /* And terminate.  */
2446   ax_simple (ax.get (), aop_end);
2447 
2448   return ax;
2449 }
2450 
2451 static void
agent_eval_command_one(const char * exp,int eval,CORE_ADDR pc)2452 agent_eval_command_one (const char *exp, int eval, CORE_ADDR pc)
2453 {
2454   const char *arg;
2455   int trace_string = 0;
2456 
2457   if (!eval)
2458     {
2459       if (*exp == '/')
2460 	exp = decode_agent_options (exp, &trace_string);
2461     }
2462 
2463   agent_expr_up agent;
2464 
2465   arg = exp;
2466   if (!eval && strcmp (arg, "$_ret") == 0)
2467     {
2468       agent = gen_trace_for_return_address (pc, get_current_arch (),
2469 					    trace_string);
2470     }
2471   else
2472     {
2473       expression_up expr = parse_exp_1 (&arg, pc, block_for_pc (pc), 0);
2474 
2475       if (eval)
2476 	{
2477 	  gdb_assert (trace_string == 0);
2478 	  agent = gen_eval_for_expr (pc, expr.get ());
2479 	}
2480       else
2481 	agent = gen_trace_for_expr (pc, expr.get (), trace_string);
2482     }
2483 
2484   ax_reqs (agent.get ());
2485   ax_print (gdb_stdout, agent.get ());
2486 
2487   /* It would be nice to call ax_reqs here to gather some general info
2488      about the expression, and then print out the result.  */
2489 
2490   dont_repeat ();
2491 }
2492 
2493 static void
agent_command_1(const char * exp,int eval)2494 agent_command_1 (const char *exp, int eval)
2495 {
2496   /* We don't deal with overlay debugging at the moment.  We need to
2497      think more carefully about this.  If you copy this code into
2498      another command, change the error message; the user shouldn't
2499      have to know anything about agent expressions.  */
2500   if (overlay_debugging)
2501     error (_("GDB can't do agent expression translation with overlays."));
2502 
2503   if (exp == 0)
2504     error_no_arg (_("expression to translate"));
2505 
2506   if (check_for_argument (&exp, "-at", sizeof ("-at") - 1))
2507     {
2508       struct linespec_result canonical;
2509 
2510       event_location_up location
2511 	= new_linespec_location (&exp, symbol_name_match_type::WILD);
2512       decode_line_full (location.get (), DECODE_LINE_FUNFIRSTLINE, NULL,
2513 			NULL, 0, &canonical,
2514 			NULL, NULL);
2515       exp = skip_spaces (exp);
2516       if (exp[0] == ',')
2517 	{
2518 	  exp++;
2519 	  exp = skip_spaces (exp);
2520 	}
2521       for (const auto &lsal : canonical.lsals)
2522 	for (const auto &sal : lsal.sals)
2523 	  agent_eval_command_one (exp, eval, sal.pc);
2524     }
2525   else
2526     agent_eval_command_one (exp, eval, get_frame_pc (get_current_frame ()));
2527 
2528   dont_repeat ();
2529 }
2530 
2531 static void
agent_command(const char * exp,int from_tty)2532 agent_command (const char *exp, int from_tty)
2533 {
2534   agent_command_1 (exp, 0);
2535 }
2536 
2537 /* Parse the given expression, compile it into an agent expression
2538    that does direct evaluation, and display the resulting
2539    expression.  */
2540 
2541 static void
agent_eval_command(const char * exp,int from_tty)2542 agent_eval_command (const char *exp, int from_tty)
2543 {
2544   agent_command_1 (exp, 1);
2545 }
2546 
2547 /* Parse the given expression, compile it into an agent expression
2548    that does a printf, and display the resulting expression.  */
2549 
2550 static void
maint_agent_printf_command(const char * cmdrest,int from_tty)2551 maint_agent_printf_command (const char *cmdrest, int from_tty)
2552 {
2553   struct frame_info *fi = get_current_frame ();	/* need current scope */
2554   const char *format_start, *format_end;
2555 
2556   /* We don't deal with overlay debugging at the moment.  We need to
2557      think more carefully about this.  If you copy this code into
2558      another command, change the error message; the user shouldn't
2559      have to know anything about agent expressions.  */
2560   if (overlay_debugging)
2561     error (_("GDB can't do agent expression translation with overlays."));
2562 
2563   if (cmdrest == 0)
2564     error_no_arg (_("expression to translate"));
2565 
2566   cmdrest = skip_spaces (cmdrest);
2567 
2568   if (*cmdrest++ != '"')
2569     error (_("Must start with a format string."));
2570 
2571   format_start = cmdrest;
2572 
2573   format_pieces fpieces (&cmdrest);
2574 
2575   format_end = cmdrest;
2576 
2577   if (*cmdrest++ != '"')
2578     error (_("Bad format string, non-terminated '\"'."));
2579 
2580   cmdrest = skip_spaces (cmdrest);
2581 
2582   if (*cmdrest != ',' && *cmdrest != 0)
2583     error (_("Invalid argument syntax"));
2584 
2585   if (*cmdrest == ',')
2586     cmdrest++;
2587   cmdrest = skip_spaces (cmdrest);
2588 
2589   std::vector<struct expression *> argvec;
2590   while (*cmdrest != '\0')
2591     {
2592       const char *cmd1;
2593 
2594       cmd1 = cmdrest;
2595       expression_up expr = parse_exp_1 (&cmd1, 0, (struct block *) 0, 1);
2596       argvec.push_back (expr.release ());
2597       cmdrest = cmd1;
2598       if (*cmdrest == ',')
2599 	++cmdrest;
2600       /* else complain? */
2601     }
2602 
2603 
2604   agent_expr_up agent = gen_printf (get_frame_pc (fi), get_current_arch (),
2605 				    0, 0,
2606 				    format_start, format_end - format_start,
2607 				    argvec.size (), argvec.data ());
2608   ax_reqs (agent.get ());
2609   ax_print (gdb_stdout, agent.get ());
2610 
2611   /* It would be nice to call ax_reqs here to gather some general info
2612      about the expression, and then print out the result.  */
2613 
2614   dont_repeat ();
2615 }
2616 
2617 /* Initialization code.  */
2618 
2619 void _initialize_ax_gdb ();
2620 void
_initialize_ax_gdb()2621 _initialize_ax_gdb ()
2622 {
2623   add_cmd ("agent", class_maintenance, agent_command,
2624 	   _("\
2625 Translate an expression into remote agent bytecode for tracing.\n\
2626 Usage: maint agent [-at LOCATION,] EXPRESSION\n\
2627 If -at is given, generate remote agent bytecode for this location.\n\
2628 If not, generate remote agent bytecode for current frame pc address."),
2629 	   &maintenancelist);
2630 
2631   add_cmd ("agent-eval", class_maintenance, agent_eval_command,
2632 	   _("\
2633 Translate an expression into remote agent bytecode for evaluation.\n\
2634 Usage: maint agent-eval [-at LOCATION,] EXPRESSION\n\
2635 If -at is given, generate remote agent bytecode for this location.\n\
2636 If not, generate remote agent bytecode for current frame pc address."),
2637 	   &maintenancelist);
2638 
2639   add_cmd ("agent-printf", class_maintenance, maint_agent_printf_command,
2640 	   _("Translate an expression into remote "
2641 	     "agent bytecode for evaluation and display the bytecodes."),
2642 	   &maintenancelist);
2643 }
2644