]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
tracepoints: Work with the tracequery's .o rather than .ko
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
4d0d9e8a 2// Copyright (C) 2005-2011 Red Hat Inc.
aa30ccd3 3// Copyright (C) 2005-2007 Intel Corporation.
0b8f6579 4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
56e12059
FCE
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "config.h"
12#include "staptree.h"
13#include "elaborate.h"
b55bc428 14#include "tapsets.h"
93646f4d 15#include "task_finder.h"
56e12059 16#include "translate.h"
dc38c0ae 17#include "session.h"
72dbc915 18#include "util.h"
0a6f5a3f 19#include "buildrun.h"
86bf665e 20#include "dwarf_wrappers.h"
2e67a43b 21#include "auto_free.h"
b278033a 22#include "hash.h"
440f755a 23#include "dwflpp.h"
5f8ca04f 24#include "setupdwfl.h"
6b51ee12 25#include <gelf.h>
22d737e8 26
4d0d9e8a 27#include "sdt_types.h"
bd2b1e68 28
3b579393
FCE
29#include <cstdlib>
30#include <algorithm>
bd2b1e68 31#include <deque>
56e12059 32#include <iostream>
d1bcbe71 33#include <fstream>
bd2b1e68 34#include <map>
ec4373ff 35#include <set>
56e12059 36#include <sstream>
bd2b1e68 37#include <stdexcept>
b55bc428 38#include <vector>
e36387d7 39#include <cstdarg>
29e64872 40#include <cassert>
1969b5bc 41#include <iomanip>
f781f849 42#include <cerrno>
bd2b1e68
GH
43
44extern "C" {
df8fadee 45#include <fcntl.h>
bd2b1e68 46#include <elfutils/libdwfl.h>
7a053d3b 47#include <elfutils/libdw.h>
77de5e9e
GH
48#include <dwarf.h>
49#include <elf.h>
50#include <obstack.h>
b20febf3 51#include <glob.h>
30a279be 52#include <fnmatch.h>
5f0a03a6 53#include <stdio.h>
349dc70e 54#include <sys/types.h>
37001baa 55#include <sys/stat.h>
aaf7ffe8 56#include <math.h>
aff5d390 57#include <regex.h>
37001baa 58#include <unistd.h>
6d5d594e 59#include <wordexp.h>
4b1ad75e
RM
60
61#define __STDC_FORMAT_MACROS
62#include <inttypes.h>
bd2b1e68 63}
77de5e9e 64
56e12059
FCE
65
66using namespace std;
2171f774 67using namespace __gnu_cxx;
56e12059 68
47dd066d 69
b20febf3
FCE
70
71// ------------------------------------------------------------------------
faea5e16
JS
72
73string
74common_probe_init (derived_probe* p)
75{
26e63673
JS
76 assert(p->session_index != (unsigned)-1);
77 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
78}
79
80
b20febf3 81void
a58d79d0 82common_probe_entryfn_prologue (translator_output* o, string statestr,
6eefe942
MW
83 string probe, string probe_type,
84 bool overload_processing)
b20febf3 85{
653e6a9a
JS
86 o->newline() << "#ifdef STP_ALIBI";
87 o->newline() << "atomic_inc(&(" << probe << "->alibi));";
88 o->newline() << "#else";
89
72d18b98 90 o->newline() << "struct context* __restrict__ c;";
e0a17418
JS
91 o->newline() << "#if !INTERRUPTIBLE";
92 o->newline() << "unsigned long flags;";
93 o->newline() << "#endif";
b20febf3 94
a58d79d0
DS
95 if (overload_processing)
96 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
97 else
98 o->newline() << "#ifdef STP_TIMING";
99 o->newline() << "cycles_t cycles_atstart = get_cycles ();";
b20febf3 100 o->newline() << "#endif";
b20febf3 101
994aac0e 102 o->newline() << "#ifdef STP_TIMING";
26e63673 103 o->newline() << "Stat stat = " << probe << "->timing;";
994aac0e
JS
104 o->newline() << "#endif";
105
e0a17418
JS
106 o->newline() << "#if INTERRUPTIBLE";
107 o->newline() << "preempt_disable ();";
108 o->newline() << "#else";
109 o->newline() << "local_irq_save (flags);";
110 o->newline() << "#endif";
b20febf3 111
c931ec8a 112 // Check for enough free enough stack space
d05a1d00 113 o->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
a63401b1 114 o->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
d05a1d00
FCE
115 // XXX: may need porting to platforms where task_struct is not at bottom of kernel stack
116 // NB: see also CONFIG_DEBUG_STACKOVERFLOW
b3c3ca7c
FCE
117 o->newline() << "atomic_inc (& skipped_count);";
118 o->newline() << "#ifdef STP_TIMING";
119 o->newline() << "atomic_inc (& skipped_count_lowstack);";
120 o->newline() << "#endif";
c931ec8a
FCE
121 o->newline() << "goto probe_epilogue;";
122 o->newline(-1) << "}";
123
b20febf3
FCE
124 o->newline() << "if (atomic_read (&session_state) != " << statestr << ")";
125 o->newline(1) << "goto probe_epilogue;";
126 o->indent(-1);
9a604fac 127
4a0ae64c 128 o->newline() << "c = contexts[smp_processor_id()];";
b3c3ca7c 129 o->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
9c736061
FCE
130 o->newline(1) << "#if !INTERRUPTIBLE";
131 o->newline() << "atomic_inc (& skipped_count);";
132 o->newline() << "#endif";
b3c3ca7c
FCE
133 o->newline() << "#ifdef STP_TIMING";
134 o->newline() << "atomic_inc (& skipped_count_reentrant);";
c12d974f
FCE
135 o->newline() << "#ifdef DEBUG_REENTRANCY";
136 o->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 137 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
138 // NB: There is a conceivable race condition here with reading
139 // c->probe_point, knowing that this other probe is sort of running.
140 // However, in reality, it's interrupted. Plus even if it were able
141 // to somehow start again, and stop before we read c->probe_point,
142 // at least we have that ?: "?" bit in there to avoid a NULL deref.
143 o->newline() << "#endif";
b3c3ca7c 144 o->newline() << "#endif";
9a604fac 145 o->newline() << "atomic_dec (& c->busy);";
b20febf3 146 o->newline() << "goto probe_epilogue;";
9a604fac
FCE
147 o->newline(-1) << "}";
148 o->newline();
1e00cfb1 149 o->newline() << "c->last_stmt = 0;";
9a604fac 150 o->newline() << "c->last_error = 0;";
a7ed0d3e 151 o->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
d9aed31e
MW
152 o->newline() << "c->uregs = 0;";
153 o->newline() << "c->kregs = 0;";
d4670309 154 o->newline() << "#if defined __ia64__";
b916df9c 155 o->newline() << "c->unwaddr = 0;";
d4670309 156 o->newline() << "#endif";
26e63673 157 o->newline() << "c->probe_point = " << probe << "->pp;";
d48df0cf 158 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
26e63673 159 o->newline() << "c->probe_name = " << probe << "->pn;";
2d767770 160 o->newline() << "#endif";
6eefe942 161 o->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9
MW
162 // reset Individual Probe State union
163 o->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
92c25572 164 o->newline() << "c->probe_flags = 0;";
309d67d8 165 o->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
9addf322 166 o->newline() << "c->regparm = 0;";
309d67d8 167 o->newline() << "#endif";
e0a17418
JS
168
169 o->newline() << "#if INTERRUPTIBLE";
170 o->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
171 o->newline() << "#else";
172 o->newline() << "c->actionremaining = MAXACTION;";
173 o->newline() << "#endif";
9915575b
FCE
174 // NB: The following would actually be incorrect.
175 // That's because cycles_sum/cycles_base values are supposed to survive
176 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
177 // cycles), the values will be reset.
178 /*
f0e6dc63
FCE
179 o->newline() << "#ifdef STP_OVERLOAD";
180 o->newline() << "c->cycles_sum = 0;";
181 o->newline() << "c->cycles_base = 0;";
41c262f3 182 o->newline() << "#endif";
9915575b 183 */
b20febf3 184}
9a604fac 185
a44a0785 186
b20febf3 187void
a58d79d0 188common_probe_entryfn_epilogue (translator_output* o,
912e8c59 189 bool overload_processing)
b20febf3 190{
a58d79d0
DS
191 if (overload_processing)
192 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
193 else
194 o->newline() << "#ifdef STP_TIMING";
dbb68664 195 o->newline() << "{";
a58d79d0
DS
196 o->newline(1) << "cycles_t cycles_atend = get_cycles ();";
197 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
198 // fewer, if the hardware counter rolls over really quickly. We
199 // handle 32-bit wraparound here.
200 o->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
201 o->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
202 o->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
203 o->indent(-1);
dbb68664 204
a58d79d0 205 o->newline() << "#ifdef STP_TIMING";
994aac0e 206 o->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
a58d79d0
DS
207 o->newline() << "#endif";
208
209 if (overload_processing)
210 {
211 o->newline() << "#ifdef STP_OVERLOAD";
212 o->newline() << "{";
213 // If the cycle count has wrapped (cycles_atend > cycles_base),
214 // let's go ahead and pretend the interval has been reached.
215 // This should reset cycles_base and cycles_sum.
216 o->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
217 o->newline(1) << "? (cycles_atend - c->cycles_base)";
218 o->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
219 o->newline(-1) << "c->cycles_sum += cycles_elapsed;";
220
221 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
222 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
223 // has overloaded the system and we need to quit.
224 o->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
225 o->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
226 o->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
227 o->newline() << "atomic_set (&session_state, STAP_SESSION_ERROR);";
551e9f14 228 o->newline() << "atomic_inc (&error_count);";
a58d79d0 229 o->newline(-1) << "}";
e57b735a 230
a58d79d0
DS
231 o->newline() << "c->cycles_base = cycles_atend;";
232 o->newline() << "c->cycles_sum = 0;";
233 o->newline(-1) << "}";
234 o->newline(-1) << "}";
235 o->newline() << "#endif";
236 }
e57b735a 237
440f755a
JS
238 o->newline(-1) << "}";
239 o->newline() << "#endif";
e57b735a 240
440f755a 241 o->newline() << "c->probe_point = 0;"; // vacated
dc575eac 242 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
d48df0cf 243 o->newline() << "c->probe_name = 0;";
dc575eac 244 o->newline() << "#endif";
6eefe942 245 o->newline() << "c->probe_type = 0;";
440f755a
JS
246 o->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
247 o->newline(1) << "if (c->last_stmt != NULL)";
248 o->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
249 o->newline(-1) << "else";
250 o->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
251 o->indent(-1);
252 o->newline() << "atomic_inc (& error_count);";
253 o->newline() << "if (atomic_read (& error_count) > MAXERRORS) {";
254 o->newline(1) << "atomic_set (& session_state, STAP_SESSION_ERROR);";
255 o->newline() << "_stp_exit ();";
256 o->newline(-1) << "}";
257 o->newline(-1) << "}";
258 o->newline() << "atomic_dec (&c->busy);";
e57b735a 259
440f755a
JS
260 o->newline(-1) << "probe_epilogue:"; // context is free
261 o->indent(1);
e57b735a 262
440f755a
JS
263 // Check for excessive skip counts.
264 o->newline() << "if (unlikely (atomic_read (& skipped_count) > MAXSKIPPED)) {";
079915a5 265 o->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(& session_state, STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f65166cc 266 o->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
440f755a 267 o->newline(-1) << "}";
e57b735a 268
440f755a
JS
269 o->newline() << "#if INTERRUPTIBLE";
270 o->newline() << "preempt_enable_no_resched ();";
271 o->newline() << "#else";
272 o->newline() << "local_irq_restore (flags);";
273 o->newline() << "#endif";
653e6a9a
JS
274
275 o->newline() << "#endif // STP_ALIBI";
440f755a 276}
e57b735a 277
e57b735a 278
440f755a 279// ------------------------------------------------------------------------
e57b735a 280
440f755a
JS
281// ------------------------------------------------------------------------
282// Dwarf derived probes. "We apologize for the inconvience."
283// ------------------------------------------------------------------------
e57b735a 284
4627ed58
JS
285static const string TOK_KERNEL("kernel");
286static const string TOK_MODULE("module");
287static const string TOK_FUNCTION("function");
288static const string TOK_INLINE("inline");
289static const string TOK_CALL("call");
290static const string TOK_RETURN("return");
291static const string TOK_MAXACTIVE("maxactive");
292static const string TOK_STATEMENT("statement");
293static const string TOK_ABSOLUTE("absolute");
294static const string TOK_PROCESS("process");
a794dbeb 295static const string TOK_PROVIDER("provider");
4627ed58
JS
296static const string TOK_MARK("mark");
297static const string TOK_TRACE("trace");
298static const string TOK_LABEL("label");
63b4fd14 299static const string TOK_LIBRARY("library");
576eaefe 300static const string TOK_PLT("plt");
e57b735a 301
1adf8ef1 302static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 303static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 304
440f755a
JS
305// Can we handle this query with just symbol-table info?
306enum dbinfo_reqt
307{
308 dbr_unknown,
309 dbr_none, // kernel.statement(NUM).absolute
310 dbr_need_symtab, // can get by with symbol table if there's no dwarf
311 dbr_need_dwarf
312};
e57b735a 313
20e4a32c 314
440f755a
JS
315struct base_query; // forward decls
316struct dwarf_query;
317struct dwflpp;
318struct symbol_table;
20e4a32c 319
a781f401 320
440f755a
JS
321struct
322symbol_table
323{
324 module_info *mod_info; // associated module
325 map<string, func_info*> map_by_name;
1c6b77e5
JS
326 multimap<Dwarf_Addr, func_info*> map_by_addr;
327 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
328 typedef pair<iterator_t, iterator_t> range_t;
329#ifdef __powerpc__
330 GElf_Word opd_section;
331#endif
2867a2a1
JS
332 void add_symbol(const char *name, bool weak, bool descriptor,
333 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 334 enum info_status read_symbols(FILE *f, const string& path);
83ca3872
MW
335 enum info_status read_from_elf_file(const string& path,
336 const systemtap_session &sess);
337 enum info_status read_from_text_file(const string& path,
338 const systemtap_session &sess);
440f755a
JS
339 enum info_status get_from_elf();
340 void prepare_section_rejection(Dwfl_Module *mod);
341 bool reject_section(GElf_Word section);
440f755a
JS
342 void purge_syscall_stubs();
343 func_info *lookup_symbol(const string& name);
344 Dwarf_Addr lookup_symbol_address(const string& name);
345 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 346 func_info *get_first_func();
7a053d3b 347
440f755a
JS
348 symbol_table(module_info *mi) : mod_info(mi) {}
349 ~symbol_table();
350};
77de5e9e 351
440f755a
JS
352static bool null_die(Dwarf_Die *die)
353{
822a6a3d 354 static Dwarf_Die null;
440f755a
JS
355 return (!die || !memcmp(die, &null, sizeof(null)));
356}
c4ce66a1
JS
357
358
7a053d3b 359enum
bd2b1e68 360function_spec_type
7a053d3b 361 {
bd2b1e68
GH
362 function_alone,
363 function_and_file,
7a053d3b 364 function_file_and_line
bd2b1e68
GH
365 };
366
ec4373ff 367
bd2b1e68 368struct dwarf_builder;
f10534c6 369struct dwarf_var_expanding_visitor;
77de5e9e 370
2930abc7 371
b20febf3
FCE
372// XXX: This class is a candidate for subclassing to separate
373// the relocation vs non-relocation variants. Likewise for
374// kprobe vs kretprobe variants.
375
376struct dwarf_derived_probe: public derived_probe
b55bc428 377{
b20febf3
FCE
378 dwarf_derived_probe (const string& function,
379 const string& filename,
380 int line,
381 const string& module,
382 const string& section,
383 Dwarf_Addr dwfl_addr,
2930abc7 384 Dwarf_Addr addr,
b20febf3
FCE
385 dwarf_query & q,
386 Dwarf_Die* scope_die);
20e4a32c 387
b20febf3
FCE
388 string module;
389 string section;
390 Dwarf_Addr addr;
63b4fd14 391 string path;
27dc09b1 392 bool has_process;
2930abc7 393 bool has_return;
c9bad430 394 bool has_maxactive;
63b4fd14 395 bool has_library;
c9bad430 396 long maxactive_val;
4ad95bbc 397 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
398 string user_path;
399 string user_lib;
b95e2b79 400 bool access_vars;
2930abc7 401
af234c40
JS
402 unsigned saved_longs, saved_strings;
403 dwarf_derived_probe* entry_handler;
404
b8da0ad1 405 void printsig (std::ostream &o) const;
6b66b9f7 406 virtual void join_group (systemtap_session& s);
9020300d 407 void emit_probe_local_init(translator_output * o);
d0bfd2ac 408 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 409
27dc09b1
DB
410 void emit_unprivileged_assertion (translator_output*);
411 void print_dupe_stamp(ostream& o);
412
bd2b1e68 413 // Pattern registration helpers.
7a053d3b 414 static void register_statement_variants(match_node * root,
27dc09b1 415 dwarf_builder * dw,
1e035395 416 bool bind_unprivileged_p);
fd6602a0 417 static void register_function_variants(match_node * root,
27dc09b1 418 dwarf_builder * dw,
1e035395 419 bool bind_unprivileged_p);
440d9b00
DB
420 static void register_function_and_statement_variants(systemtap_session& s,
421 match_node * root,
27dc09b1 422 dwarf_builder * dw,
1e035395 423 bool bind_unprivileged_p);
c4ce66a1 424 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
425
426protected:
427 dwarf_derived_probe(probe *base,
428 probe_point *location,
429 Dwarf_Addr addr,
430 bool has_return):
74fe61bc
LB
431 derived_probe(base, location), addr(addr), has_process(0),
432 has_return(has_return), has_maxactive(0), has_library(0),
433 maxactive_val(0), access_vars(false), saved_longs(0),
434 saved_strings(0), entry_handler(0)
6b66b9f7
JS
435 {}
436
437private:
d0bfd2ac 438 list<string> args;
8c67c337 439 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
440};
441
dc38c0ae 442
6b66b9f7 443struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 444{
6d0f3f0c 445 int pid; // 0 => unrestricted
0973d815 446
6d0f3f0c
FCE
447 uprobe_derived_probe (const string& function,
448 const string& filename,
449 int line,
450 const string& module,
6d0f3f0c
FCE
451 const string& section,
452 Dwarf_Addr dwfl_addr,
453 Dwarf_Addr addr,
454 dwarf_query & q,
6b66b9f7
JS
455 Dwarf_Die* scope_die):
456 dwarf_derived_probe(function, filename, line, module, section,
457 dwfl_addr, addr, q, scope_die), pid(0)
458 {}
6d0f3f0c 459
0973d815
FCE
460 // alternate constructor for process(PID).statement(ADDR).absolute
461 uprobe_derived_probe (probe *base,
462 probe_point *location,
463 int pid,
464 Dwarf_Addr addr,
6b66b9f7
JS
465 bool has_return):
466 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
467 {}
9ace370f 468
6d0f3f0c 469 void join_group (systemtap_session& s);
2865d17a
DB
470
471 void emit_unprivileged_assertion (translator_output*);
8f6d8c2b 472 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
473 void getargs(std::list<std::string> &arg_set) const;
474 void saveargs(int nargs);
475private:
476 list<string> args;
6d0f3f0c
FCE
477};
478
dc38c0ae
DS
479struct dwarf_derived_probe_group: public derived_probe_group
480{
481private:
62f52bb0 482 bool has_semaphores;
b20febf3
FCE
483 multimap<string,dwarf_derived_probe*> probes_by_module;
484 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
485
486public:
62f52bb0 487 dwarf_derived_probe_group(): has_semaphores(false) {}
b20febf3
FCE
488 void enroll (dwarf_derived_probe* probe);
489 void emit_module_decls (systemtap_session& s);
490 void emit_module_init (systemtap_session& s);
b4be7cbc 491 void emit_module_refresh (systemtap_session& s);
b20febf3 492 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
493};
494
495
20c6c071 496// Helper struct to thread through the dwfl callbacks.
2c384610 497struct base_query
20c6c071 498{
c4ce66a1
JS
499 base_query(dwflpp & dw, literal_map_t const & params);
500 base_query(dwflpp & dw, const string & module_val);
2c384610 501 virtual ~base_query() {}
bd2b1e68 502
5227f1ea 503 systemtap_session & sess;
2c384610 504 dwflpp & dw;
5227f1ea 505
bd2b1e68 506 // Parameter extractors.
86bf665e 507 static bool has_null_param(literal_map_t const & params,
888af770 508 string const & k);
86bf665e 509 static bool get_string_param(literal_map_t const & params,
bd2b1e68 510 string const & k, string & v);
86bf665e 511 static bool get_number_param(literal_map_t const & params,
bd2b1e68 512 string const & k, long & v);
86bf665e 513 static bool get_number_param(literal_map_t const & params,
c239d28c 514 string const & k, Dwarf_Addr & v);
f301a9ff 515 static void query_library_callback (void *object, const char *data);
576eaefe 516 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 517 virtual void query_library (const char *data) = 0;
576eaefe 518 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 519
b55bc428 520
2c384610
DS
521 // Extracted parameters.
522 bool has_kernel;
91af0778
FCE
523 bool has_module;
524 bool has_process;
63b4fd14 525 bool has_library;
576eaefe
SC
526 bool has_plt;
527 bool has_statement;
2c384610 528 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 529 string path; // executable path if module is a .so
576eaefe 530 string plt_val; // has_plt => plt wildcard
2c384610
DS
531
532 virtual void handle_query_module() = 0;
533};
534
535
c4ce66a1 536base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 537 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 538{
91af0778 539 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
540 if (has_kernel)
541 module_val = "kernel";
91af0778
FCE
542
543 has_module = get_string_param (params, TOK_MODULE, module_val);
544 if (has_module)
545 has_process = false;
4baf0e53 546 else
d0a7f5a9 547 {
63b4fd14 548 string library_name;
576eaefe 549 long statement_num_val;
d0a7f5a9 550 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 551 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
552 if ((has_plt = has_null_param (params, TOK_PLT)))
553 plt_val = "*";
554 else has_plt = get_string_param (params, TOK_PLT, plt_val);
18418d34
SC
555 if (has_plt)
556 sess.consult_symtab = true;
576eaefe
SC
557 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
558
84c84ac4 559 if (has_process)
d0a7f5a9 560 module_val = find_executable (module_val);
84c84ac4
SC
561 if (has_library)
562 {
563 if (! contains_glob_chars (library_name))
564 {
565 path = module_val;
566 module_val = find_executable (library_name, "LD_LIBRARY_PATH");
567 }
568 else
569 path = library_name;
570 }
d0a7f5a9 571 }
91af0778
FCE
572
573 assert (has_kernel || has_process || has_module);
2c384610
DS
574}
575
c4ce66a1 576base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
577 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
578 module_val(module_val)
c4ce66a1
JS
579{
580 // NB: This uses '/' to distinguish between kernel modules and userspace,
581 // which means that userspace modules won't get any PATH searching.
582 if (module_val.find('/') == string::npos)
583 {
584 has_kernel = (module_val == TOK_KERNEL);
585 has_module = !has_kernel;
586 has_process = false;
587 }
588 else
589 {
590 has_kernel = has_module = false;
591 has_process = true;
592 }
593}
594
2c384610 595bool
86bf665e 596base_query::has_null_param(literal_map_t const & params,
2c384610
DS
597 string const & k)
598{
888af770 599 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
600}
601
602
603bool
86bf665e 604base_query::get_string_param(literal_map_t const & params,
2c384610
DS
605 string const & k, string & v)
606{
607 return derived_probe_builder::get_param (params, k, v);
608}
609
610
611bool
86bf665e 612base_query::get_number_param(literal_map_t const & params,
2c384610
DS
613 string const & k, long & v)
614{
615 int64_t value;
616 bool present = derived_probe_builder::get_param (params, k, value);
617 v = (long) value;
618 return present;
619}
620
621
622bool
86bf665e 623base_query::get_number_param(literal_map_t const & params,
2c384610
DS
624 string const & k, Dwarf_Addr & v)
625{
626 int64_t value;
627 bool present = derived_probe_builder::get_param (params, k, value);
628 v = (Dwarf_Addr) value;
629 return present;
630}
631
2c384610
DS
632struct dwarf_query : public base_query
633{
e1278bd4 634 dwarf_query(probe * base_probe,
2c384610
DS
635 probe_point * base_loc,
636 dwflpp & dw,
86bf665e 637 literal_map_t const & params,
b642c901
SC
638 vector<derived_probe *> & results,
639 const string user_path,
640 const string user_lib);
2c384610 641
c4ce66a1 642 vector<derived_probe *> & results;
8f14e444 643 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
644 probe * base_probe;
645 probe_point * base_loc;
b642c901
SC
646 string user_path;
647 string user_lib;
c4ce66a1 648
2c384610 649 virtual void handle_query_module();
5f0a03a6
JK
650 void query_module_dwarf();
651 void query_module_symtab();
5d5bd369 652 void query_library (const char *data);
576eaefe 653 void query_plt (const char *entry, size_t addr);
2c384610 654
2930abc7
FCE
655 void add_probe_point(string const & funcname,
656 char const * filename,
657 int line,
658 Dwarf_Die *scope_die,
659 Dwarf_Addr addr);
36f9dd1d 660
857bdfd1
JS
661 // Track addresses we've already seen in a given module
662 set<Dwarf_Addr> alias_dupes;
663
7fdd3e2c
JS
664 // Track inlines we've already seen as well
665 // NB: this can't be compared just by entrypc, as inlines can overlap
666 set<inline_instance_info> inline_dupes;
667
2930abc7 668 // Extracted parameters.
7a053d3b 669 string function_val;
20c6c071
GH
670
671 bool has_function_str;
672 bool has_statement_str;
673 bool has_function_num;
674 bool has_statement_num;
7a053d3b
RM
675 string statement_str_val;
676 string function_str_val;
c239d28c
GH
677 Dwarf_Addr statement_num_val;
678 Dwarf_Addr function_num_val;
20c6c071 679
b8da0ad1
FCE
680 bool has_call;
681 bool has_inline;
20c6c071
GH
682 bool has_return;
683
c9bad430
DS
684 bool has_maxactive;
685 long maxactive_val;
686
20c6c071
GH
687 bool has_label;
688 string label_val;
689
690 bool has_relative;
691 long relative_val;
692
37ebca01
FCE
693 bool has_absolute;
694
467bea43
SC
695 bool has_mark;
696
5f0a03a6
JK
697 enum dbinfo_reqt dbinfo_reqt;
698 enum dbinfo_reqt assess_dbinfo_reqt();
699
7d6d0afc 700 void parse_function_spec(const string & spec);
20c6c071 701 function_spec_type spec_type;
7d6d0afc 702 vector<string> scopes;
20c6c071
GH
703 string function;
704 string file;
0c8b7d37 705 line_t line_type;
879eb9e9 706 int line[2];
5f0a03a6 707 bool query_done; // Found exact match
20c6c071 708
bd25380d 709 set<string> filtered_srcfiles;
7e1279ea
FCE
710
711 // Map official entrypc -> func_info object
86bf665e
TM
712 inline_instance_map_t filtered_inlines;
713 func_info_map_t filtered_functions;
7e1279ea
FCE
714 bool choose_next_line;
715 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
716
717 void query_module_functions ();
b55bc428
FCE
718};
719
98afd80e 720
435f53a7
FCE
721static void delete_session_module_cache (systemtap_session& s); // forward decl
722
723
98afd80e 724struct dwarf_builder: public derived_probe_builder
b55bc428 725{
665e1256 726 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 727 map <string,dwflpp*> user_dw;
b642c901
SC
728 string user_path;
729 string user_lib;
ae2552da 730 dwarf_builder() {}
aa30ccd3 731
ae2552da 732 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 733 {
ea14cf67
FCE
734 if (kern_dw[module] == 0)
735 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 736 return kern_dw[module];
707bf35e
JS
737 }
738
739 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
740 {
ea14cf67
FCE
741 if (user_dw[module] == 0)
742 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
743 return user_dw[module];
744 }
7a24d422
FCE
745
746 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 747 void dwarf_build_no_more (bool)
aa30ccd3 748 {
435f53a7
FCE
749 delete_map(kern_dw);
750 delete_map(user_dw);
7a24d422
FCE
751 }
752
753 void build_no_more (systemtap_session &s)
754 {
755 dwarf_build_no_more (s.verbose > 3);
435f53a7 756 delete_session_module_cache (s);
aa30ccd3
FCE
757 }
758
e38d6504
RM
759 ~dwarf_builder()
760 {
7a24d422 761 dwarf_build_no_more (false);
c8959a29 762 }
aa30ccd3 763
5227f1ea 764 virtual void build(systemtap_session & sess,
7a053d3b 765 probe * base,
20c6c071 766 probe_point * location,
86bf665e 767 literal_map_t const & parameters,
20c6c071 768 vector<derived_probe *> & finished_results);
b55bc428
FCE
769};
770
5111fc3e 771
e1278bd4 772dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
773 probe_point * base_loc,
774 dwflpp & dw,
86bf665e 775 literal_map_t const & params,
b642c901
SC
776 vector<derived_probe *> & results,
777 const string user_path,
778 const string user_lib)
c4ce66a1 779 : base_query(dw, params), results(results),
b642c901 780 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
781 user_path(user_path), user_lib(user_lib), has_relative(false),
782 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
783{
784 // Reduce the query to more reasonable semantic values (booleans,
785 // extracted strings, numbers, etc).
bd2b1e68
GH
786 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
787 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
788
789 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
790 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
791
0f336e95
SC
792 has_label = get_string_param(params, TOK_LABEL, label_val);
793
b8da0ad1
FCE
794 has_call = has_null_param(params, TOK_CALL);
795 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 796 has_return = has_null_param(params, TOK_RETURN);
c9bad430 797 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 798 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 799 has_mark = false;
37ebca01 800
bd2b1e68 801 if (has_function_str)
7d6d0afc 802 parse_function_spec(function_str_val);
bd2b1e68 803 else if (has_statement_str)
7d6d0afc 804 parse_function_spec(statement_str_val);
0daad364 805
5f0a03a6
JK
806 dbinfo_reqt = assess_dbinfo_reqt();
807 query_done = false;
0daad364
JS
808}
809
810
440f755a
JS
811func_info_map_t *
812get_filtered_functions(dwarf_query *q)
813{
814 return &q->filtered_functions;
815}
816
817
818inline_instance_map_t *
819get_filtered_inlines(dwarf_query *q)
820{
821 return &q->filtered_inlines;
822}
823
824
2c384610 825void
5f0a03a6 826dwarf_query::query_module_dwarf()
2c384610
DS
827{
828 if (has_function_num || has_statement_num)
829 {
830 // If we have module("foo").function(0xbeef) or
831 // module("foo").statement(0xbeef), the address is relative
832 // to the start of the module, so we seek the function
833 // number plus the module's bias.
6b517475
JS
834 Dwarf_Addr addr = has_function_num ?
835 function_num_val : statement_num_val;
08d1d520
MW
836
837 // These are raw addresses, we need to know what the elf_bias
838 // is to feed it to libdwfl based functions.
839 Dwarf_Addr elf_bias;
840 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
841 assert(elf);
842 addr += elf_bias;
6b517475 843 query_addr(addr, this);
2c384610
DS
844 }
845 else
846 {
847 // Otherwise if we have a function("foo") or statement("foo")
848 // specifier, we have to scan over all the CUs looking for
849 // the function(s) in question
850 assert(has_function_str || has_statement_str);
4df79aaf
JS
851
852 // For simple cases, no wildcard and no source:line, we can do a very
853 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
854 if (spec_type == function_alone &&
855 !dw.name_has_wildcard(function) &&
856 !startswith(function, "_Z"))
4df79aaf
JS
857 query_module_functions();
858 else
859 dw.iterate_over_cus(&query_cu, this);
2c384610
DS
860 }
861}
862
5f0a03a6
JK
863static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
864 dwarf_query * q);
865
866void
867dwarf_query::query_module_symtab()
868{
869 // Get the symbol table if it's necessary, sufficient, and not already got.
870 if (dbinfo_reqt == dbr_need_dwarf)
871 return;
872
873 module_info *mi = dw.mod_info;
874 if (dbinfo_reqt == dbr_need_symtab)
875 {
876 if (mi->symtab_status == info_unknown)
877 mi->get_symtab(this);
878 if (mi->symtab_status == info_absent)
879 return;
880 }
881
882 func_info *fi = NULL;
883 symbol_table *sym_table = mi->sym_table;
884
885 if (has_function_str)
886 {
887 // Per dwarf_query::assess_dbinfo_reqt()...
888 assert(spec_type == function_alone);
889 if (dw.name_has_wildcard(function_str_val))
890 {
891 // Until we augment the blacklist sufficently...
892 if (function_str_val.find_first_not_of("*?") == string::npos)
893 {
894 // e.g., kernel.function("*")
b530b5b3
LB
895 cerr << _F("Error: Pattern '%s' matches every single "
896 "instruction address in the symbol table,\n"
897 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
898 return;
899 }
2e67a43b 900 symbol_table::iterator_t iter;
1c6b77e5
JS
901 for (iter = sym_table->map_by_addr.begin();
902 iter != sym_table->map_by_addr.end();
2e67a43b 903 ++iter)
5f0a03a6 904 {
1c6b77e5 905 fi = iter->second;
5f0a03a6
JK
906 if (!null_die(&fi->die))
907 continue; // already handled in query_module_dwarf()
908 if (dw.function_name_matches_pattern(fi->name, function_str_val))
909 query_func_info(fi->addr, *fi, this);
910 }
911 }
912 else
913 {
914 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 915 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
916 query_func_info(fi->addr, *fi, this);
917 }
918 }
919 else
920 {
921 assert(has_function_num || has_statement_num);
922 // Find the "function" in which the indicated address resides.
923 Dwarf_Addr addr =
924 (has_function_num ? function_num_val : statement_num_val);
576eaefe 925 if (has_plt)
3d372d6b
SC
926 {
927 // Use the raw address from the .plt
928 fi = sym_table->get_first_func();
929 fi->addr = addr;
930 }
931 else
932 fi = sym_table->get_func_containing_address(addr);
933
5f0a03a6
JK
934 if (!fi)
935 {
3d372d6b
SC
936 if (! sess.suppress_warnings)
937 cerr << _F("Warning: address %#" PRIx64 " out of range for module %s\n",
938 addr, dw.module_name.c_str());
939 return;
5f0a03a6
JK
940 }
941 if (!null_die(&fi->die))
942 {
943 // addr looks like it's in the compilation unit containing
944 // the indicated function, but query_module_dwarf() didn't
945 // match addr to any compilation unit, so addr must be
946 // above that cu's address range.
83ca3872 947 if (! sess.suppress_warnings)
3d372d6b 948 cerr << _F("Warning: address %#" PRIx64 " maps to no known compilation unit in module %s\n",
b530b5b3 949 addr, dw.module_name.c_str());
5f0a03a6
JK
950 return;
951 }
952 query_func_info(fi->addr, *fi, this);
953 }
954}
955
956void
957dwarf_query::handle_query_module()
958{
1c6b77e5
JS
959 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
960 dw.get_module_dwarf(false, report);
961
962 // prebuild the symbol table to resolve aliases
963 dw.mod_info->get_symtab(this);
964
857bdfd1
JS
965 // reset the dupe-checking for each new module
966 alias_dupes.clear();
7fdd3e2c 967 inline_dupes.clear();
857bdfd1 968
5f0a03a6
JK
969 if (dw.mod_info->dwarf_status == info_present)
970 query_module_dwarf();
1c6b77e5 971
5f0a03a6
JK
972 // Consult the symbol table if we haven't found all we're looking for.
973 // asm functions can show up in the symbol table but not in dwarf.
974 if (sess.consult_symtab && !query_done)
975 query_module_symtab();
976}
977
2c384610 978
7d6d0afc
JS
979void
980dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 981{
1d12a9b2
JS
982 line_type = ABSOLUTE;
983 line[0] = line[1] = 0;
984
91699a70 985 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 986
7d6d0afc 987 // look for named scopes
91699a70
JS
988 scope_pos = spec.rfind("::");
989 if (scope_pos != string::npos)
bd2b1e68 990 {
91699a70
JS
991 tokenize_cxx(spec.substr(0, scope_pos), scopes);
992 scope_pos += 2;
bd2b1e68 993 }
91699a70
JS
994 else
995 scope_pos = 0;
bd2b1e68 996
7d6d0afc
JS
997 // look for a source separator
998 src_pos = spec.find('@', scope_pos);
999 if (src_pos == string::npos)
bd2b1e68 1000 {
7d6d0afc
JS
1001 function = spec.substr(scope_pos);
1002 spec_type = function_alone;
bd2b1e68 1003 }
7d6d0afc 1004 else
879eb9e9 1005 {
7d6d0afc 1006 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1007
7d6d0afc
JS
1008 // look for a line-number separator
1009 line_pos = spec.find_first_of(":+", src_pos);
1010 if (line_pos == string::npos)
1011 {
1012 file = spec.substr(src_pos + 1);
1013 spec_type = function_and_file;
1014 }
1015 else
1016 {
1017 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1018
1019 // classify the line spec
1020 spec_type = function_file_and_line;
1021 if (spec[line_pos] == '+')
1022 line_type = RELATIVE;
1023 else if (spec[line_pos + 1] == '*' &&
1024 spec.length() == line_pos + 2)
1025 line_type = WILDCARD;
1026 else
1027 line_type = ABSOLUTE;
1028
1029 if (line_type != WILDCARD)
1030 try
1031 {
1032 // try to parse either N or N-M
1033 dash_pos = spec.find('-', line_pos + 1);
1034 if (dash_pos == string::npos)
1035 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1036 else
1037 {
1038 line_type = RANGE;
1039 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1040 dash_pos - line_pos - 1));
1041 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1042 }
1043 }
1044 catch (runtime_error & exn)
1045 {
1046 goto bad;
1047 }
1048 }
bd2b1e68
GH
1049 }
1050
7d6d0afc
JS
1051 if (function.empty() ||
1052 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1053 goto bad;
1054
7d6d0afc 1055 if (sess.verbose > 2)
bd2b1e68 1056 {
b530b5b3
LB
1057 //clog << "parsed '" << spec << "'";
1058 clog << _F("parse '%s'", spec.c_str());
41c262f3 1059
7d6d0afc
JS
1060 if (!scopes.empty())
1061 clog << ", scope '" << scopes[0] << "'";
1062 for (unsigned i = 1; i < scopes.size(); ++i)
1063 clog << "::'" << scopes[i] << "'";
41c262f3 1064
7d6d0afc
JS
1065 clog << ", func '" << function << "'";
1066
1067 if (spec_type != function_alone)
1068 clog << ", file '" << file << "'";
1069
1070 if (spec_type == function_file_and_line)
1071 {
1072 clog << ", line ";
1073 switch (line_type)
1074 {
1075 case ABSOLUTE:
1076 clog << line[0];
1077 break;
1078
1079 case RELATIVE:
1080 clog << "+" << line[0];
1081 break;
1082
1083 case RANGE:
1084 clog << line[0] << " - " << line[1];
1085 break;
1086
1087 case WILDCARD:
1088 clog << "*";
1089 break;
1090 }
1091 }
1092
1093 clog << endl;
bd2b1e68
GH
1094 }
1095
7d6d0afc
JS
1096 return;
1097
1098bad:
b530b5b3 1099 throw semantic_error(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1100 base_probe->tok);
bd2b1e68
GH
1101}
1102
1103
36f9dd1d 1104void
1ffb8bd1 1105dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1106 const char* filename,
36f9dd1d 1107 int line,
b20febf3 1108 Dwarf_Die* scope_die,
36f9dd1d
FCE
1109 Dwarf_Addr addr)
1110{
b20febf3 1111 string reloc_section; // base section for relocation purposes
27646582 1112 Dwarf_Addr reloc_addr; // relocated
b20febf3 1113 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1114 string funcname = dw_funcname;
36f9dd1d 1115
37ebca01
FCE
1116 assert (! has_absolute); // already handled in dwarf_builder::build()
1117
576eaefe
SC
1118 if (!has_plt)
1119 reloc_addr = dw.relocate_address(addr, reloc_section);
1120 else
1121 {
3d372d6b 1122 // Set the reloc_section but use the plt entry for reloc_addr
576eaefe
SC
1123 dw.relocate_address(addr, reloc_section);
1124 reloc_addr = addr;
1125 }
2930abc7 1126
1ffb8bd1 1127 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1128 const char* linkage_name;
1129 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1130 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1131 funcname = linkage_name;
1132
7f9f3386
FCE
1133 if (sess.verbose > 1)
1134 {
b530b5b3 1135 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1136 if (string(module) == TOK_KERNEL)
b530b5b3 1137 clog << _(" kernel");
91af0778 1138 else if (has_module)
b530b5b3 1139 clog << _(" module=") << module;
91af0778 1140 else if (has_process)
b530b5b3 1141 clog << _(" process=") << module;
b20febf3 1142 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1143 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1144 }
4baf0e53 1145
27646582 1146 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1147 addr, has_return);
b20febf3
FCE
1148 if (sess.verbose > 1)
1149 clog << endl;
7f9f3386 1150
84048984
FCE
1151 if (module == TOK_KERNEL)
1152 {
1153 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1154 reloc_addr = addr - sess.sym_stext;
37ebca01 1155 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1156 }
1157
b20febf3
FCE
1158 if (! bad)
1159 {
1a0dbc5a 1160 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1161
1162 if (has_process)
1163 {
1164 results.push_back (new uprobe_derived_probe(funcname, filename, line,
6b66b9f7 1165 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1166 *this, scope_die));
1167 }
1168 else
1169 {
1170 assert (has_kernel || has_module);
1171 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1172 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1173 *this, scope_die));
1174 }
b20febf3 1175 }
2930abc7
FCE
1176}
1177
5f0a03a6
JK
1178enum dbinfo_reqt
1179dwarf_query::assess_dbinfo_reqt()
1180{
1181 if (has_absolute)
1182 {
1183 // kernel.statement(NUM).absolute
1184 return dbr_none;
1185 }
1186 if (has_inline)
1187 {
1188 // kernel.function("f").inline or module("m").function("f").inline
1189 return dbr_need_dwarf;
1190 }
1191 if (has_function_str && spec_type == function_alone)
1192 {
1193 // kernel.function("f") or module("m").function("f")
1194 return dbr_need_symtab;
1195 }
1196 if (has_statement_num)
1197 {
1198 // kernel.statement(NUM) or module("m").statement(NUM)
1199 // Technically, all we need is the module offset (or _stext, for
1200 // the kernel). But for that we need either the ELF file or (for
1201 // _stext) the symbol table. In either case, the symbol table
1202 // is available, and that allows us to map the NUM (address)
1203 // to a function, which is goodness.
1204 return dbr_need_symtab;
1205 }
1206 if (has_function_num)
1207 {
1208 // kernel.function(NUM) or module("m").function(NUM)
1209 // Need the symbol table so we can back up from NUM to the
1210 // start of the function.
1211 return dbr_need_symtab;
1212 }
1213 // Symbol table tells us nothing about source files or line numbers.
1214 return dbr_need_dwarf;
1215}
2930abc7
FCE
1216
1217
b8da0ad1
FCE
1218// The critical determining factor when interpreting a pattern
1219// string is, perhaps surprisingly: "presence of a lineno". The
1220// presence of a lineno changes the search strategy completely.
1221//
1222// Compare the two cases:
1223//
1224// 1. {statement,function}(foo@file.c:lineno)
1225// - find the files matching file.c
1226// - in each file, find the functions matching foo
1227// - query the file for line records matching lineno
1228// - iterate over the line records,
1229// - and iterate over the functions,
1230// - if(haspc(function.DIE, line.addr))
1231// - if looking for statements: probe(lineno.addr)
1232// - if looking for functions: probe(function.{entrypc,return,etc.})
1233//
1234// 2. {statement,function}(foo@file.c)
1235// - find the files matching file.c
1236// - in each file, find the functions matching foo
1237// - probe(function.{entrypc,return,etc.})
1238//
1239// Thus the first decision we make is based on the presence of a
1240// lineno, and we enter entirely different sets of callbacks
1241// depending on that decision.
1242//
1243// Note that the first case is a generalization fo the second, in that
1244// we could theoretically search through line records for matching
1245// file names (a "table scan" in rdbms lingo). Luckily, file names
1246// are already cached elsewhere, so we can do an "index scan" as an
1247// optimization.
7e1279ea 1248
bd2b1e68 1249static void
4cd232e4 1250query_statement (string const & func,
20e4a32c 1251 char const * file,
4cd232e4 1252 int line,
bcc12710 1253 Dwarf_Die *scope_die,
20e4a32c 1254 Dwarf_Addr stmt_addr,
4cd232e4 1255 dwarf_query * q)
bd2b1e68 1256{
39bcd429
FCE
1257 try
1258 {
cee35f73 1259 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1260 line, scope_die, stmt_addr);
39bcd429
FCE
1261 }
1262 catch (const semantic_error& e)
1263 {
1264 q->sess.print_error (e);
1265 }
bd2b1e68
GH
1266}
1267
6b517475
JS
1268static void
1269query_addr(Dwarf_Addr addr, dwarf_query *q)
1270{
1271 dwflpp &dw = q->dw;
1272
08d1d520
MW
1273 if (q->sess.verbose > 2)
1274 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1275
1276 // First pick which CU contains this address
1277 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1278 if (!cudie) // address could be wildly out of range
1279 return;
1280 dw.focus_on_cu(cudie);
1281
1282 // Now compensate for the dw bias
1283 addr -= dw.module_bias;
1284
1285 // Per PR5787, we look up the scope die even for
1286 // statement_num's, for blacklist sensitivity and $var
1287 // resolution purposes.
1288
1289 // Find the scopes containing this address
1290 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1291 if (scopes.empty())
1292 return;
1293
1294 // Look for the innermost containing function
1295 Dwarf_Die *fnscope = NULL;
1296 for (size_t i = 0; i < scopes.size(); ++i)
1297 {
1298 int tag = dwarf_tag(&scopes[i]);
1299 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1300 (tag == DW_TAG_inlined_subroutine &&
1301 !q->has_call && !q->has_return))
1302 {
1303 fnscope = &scopes[i];
1304 break;
1305 }
1306 }
1307 if (!fnscope)
1308 return;
1309 dw.focus_on_function(fnscope);
1310
1311 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1312
1313 const char *file = dwarf_decl_file(fnscope);
1314 int line;
1315 dwarf_decl_line(fnscope, &line);
1316
1317 // Function probes should reset the addr to the function entry
1318 // and possibly perform prologue searching
1319 if (q->has_function_num)
1320 {
1321 dw.die_entrypc(fnscope, &addr);
1322 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1323 (q->sess.prologue_searching || q->has_process)) // PR 6871
1324 {
1325 func_info func;
1326 func.die = *fnscope;
1327 func.name = dw.function_name;
1328 func.decl_file = file;
1329 func.decl_line = line;
1330 func.entrypc = addr;
1331
1332 func_info_map_t funcs(1, func);
1333 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1334 if (q->has_return) // PR13200
1335 {
1336 if (q->sess.verbose > 2)
1337 clog << "ignoring prologue for .return probes" << endl;
1338 }
1339 else
1340 {
1341 if (funcs[0].prologue_end)
1342 addr = funcs[0].prologue_end;
1343 }
6b517475
JS
1344 }
1345 }
1346 else
1347 {
1348 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1349 if (address_line)
1350 {
1351 file = address_line.linesrc();
1352 line = address_line.lineno();
1353 }
1354
1355 // Verify that a raw address matches the beginning of a
1356 // statement. This is a somewhat lame check that the address
1357 // is at the start of an assembly instruction. Mark probes are in the
1358 // middle of a macro and thus not strictly at a statement beginning.
1359 // Guru mode may override this check.
1360 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1361 {
1362 stringstream msg;
2a97f50b 1363 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1364 addr);
6b517475 1365 if (address_line)
2a97f50b 1366 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1367 else
b530b5b3
LB
1368 msg << _F(" (no line info found for '%s', in module '%s')",
1369 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475
JS
1370 if (! q->sess.guru_mode)
1371 throw semantic_error(msg.str());
1372 else if (! q->sess.suppress_warnings)
1373 q->sess.print_warning(msg.str());
1374 }
1375 }
1376
1377 // Build a probe at this point
1378 query_statement(dw.function_name, file, line, scope, addr, q);
1379}
1380
8096dd7d
JS
1381static void
1382query_label (string const & func,
1383 char const * label,
1384 char const * file,
1385 int line,
1386 Dwarf_Die *scope_die,
1387 Dwarf_Addr stmt_addr,
1388 dwarf_query * q)
1389{
6b517475
JS
1390 assert (q->has_statement_str || q->has_function_str);
1391
8096dd7d
JS
1392 size_t i = q->results.size();
1393
1394 // weed out functions whose decl_file isn't one of
1395 // the source files that we actually care about
6b517475 1396 if (q->spec_type != function_alone &&
8096dd7d
JS
1397 q->filtered_srcfiles.count(file) == 0)
1398 return;
1399
1400 query_statement(func, file, line, scope_die, stmt_addr, q);
1401
c72aa911
JS
1402 // after the fact, insert the label back into the derivation chain
1403 probe_point::component* ppc =
1404 new probe_point::component(TOK_LABEL, new literal_string (label));
1405 for (; i < q->results.size(); ++i)
1406 {
1407 derived_probe* p = q->results[i];
1408 probe_point* pp = new probe_point(*p->locations[0]);
1409 pp->components.push_back (ppc);
1410 p->base = p->base->create_alias(p->locations[0], pp);
1411 }
8096dd7d
JS
1412}
1413
7e1279ea 1414static void
3e961ba6 1415query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1416 dwarf_query * q)
1417{
b6581717 1418 try
7e1279ea 1419 {
8f14e444
FCE
1420 assert (! q->has_return); // checked by caller already
1421 if (q->sess.verbose>2)
b530b5b3
LB
1422 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1423 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1424 query_statement (ii.name, ii.decl_file, ii.decl_line,
1425 &ii.die, ii.entrypc, q);
7e1279ea 1426 }
b6581717 1427 catch (semantic_error &e)
7e1279ea 1428 {
b6581717 1429 q->sess.print_error (e);
7e1279ea
FCE
1430 }
1431}
1432
1433static void
1434query_func_info (Dwarf_Addr entrypc,
bcc12710 1435 func_info & fi,
7e1279ea
FCE
1436 dwarf_query * q)
1437{
b6581717 1438 try
7e1279ea 1439 {
b6581717
GH
1440 if (q->has_return)
1441 {
1442 // NB. dwarf_derived_probe::emit_registrations will emit a
1443 // kretprobe based on the entrypc in this case.
464379bb
FCE
1444 if (fi.prologue_end != 0 && q->has_return) // PR13200
1445 {
1446 if (q->sess.verbose > 2)
1447 clog << "ignoring prologue for .return probes" << endl;
1448 }
20e4a32c 1449 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1450 &fi.die, entrypc, q);
1451 }
1452 else
1453 {
35dc8b04 1454 if (fi.prologue_end != 0)
44f75386 1455 {
44f75386
FCE
1456 query_statement (fi.name, fi.decl_file, fi.decl_line,
1457 &fi.die, fi.prologue_end, q);
1458 }
1459 else
1460 {
1461 query_statement (fi.name, fi.decl_file, fi.decl_line,
1462 &fi.die, entrypc, q);
1463 }
b6581717 1464 }
7e1279ea 1465 }
b6581717 1466 catch (semantic_error &e)
7e1279ea 1467 {
b6581717 1468 q->sess.print_error (e);
7e1279ea
FCE
1469 }
1470}
1471
1472
bd4b874d
SC
1473static void
1474query_srcfile_label (const dwarf_line_t& line, void * arg)
1475{
1476 dwarf_query * q = static_cast<dwarf_query *>(arg);
1477
1478 Dwarf_Addr addr = line.addr();
1479
1480 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1481 i != q->filtered_functions.end(); ++i)
1482 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1483 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1484 q, query_label);
1485
1486 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1487 i != q->filtered_inlines.end(); ++i)
1488 if (q->dw.die_has_pc (i->die, addr))
1489 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1490 q, query_label);
bd4b874d
SC
1491}
1492
7e1279ea 1493static void
86bf665e 1494query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1495{
1496 dwarf_query * q = static_cast<dwarf_query *>(arg);
1497
86bf665e 1498 Dwarf_Addr addr = line.addr();
4cd232e4 1499
86bf665e 1500 int lineno = line.lineno();
847bf07f 1501
86bf665e 1502 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1503 i != q->filtered_functions.end(); ++i)
1504 {
3e961ba6 1505 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1506 {
b0ee93c4 1507 if (q->sess.verbose>3)
b530b5b3 1508 clog << _("function DIE lands on srcfile\n");
4cd232e4 1509 if (q->has_statement_str)
f5958c8f
JS
1510 {
1511 Dwarf_Die scope;
1512 q->dw.inner_die_containing_pc(i->die, addr, scope);
1513 query_statement (i->name, i->decl_file,
1514 lineno, // NB: not q->line !
1515 &scope, addr, q);
1516 }
4cd232e4 1517 else
3e961ba6 1518 query_func_info (i->entrypc, *i, q);
7e1279ea 1519 }
20e4a32c
RM
1520 }
1521
86bf665e 1522 for (inline_instance_map_t::iterator i
897820ca
GH
1523 = q->filtered_inlines.begin();
1524 i != q->filtered_inlines.end(); ++i)
1525 {
3e961ba6 1526 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1527 {
b0ee93c4 1528 if (q->sess.verbose>3)
b530b5b3 1529 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1530 if (q->has_statement_str)
f5958c8f
JS
1531 {
1532 Dwarf_Die scope;
1533 q->dw.inner_die_containing_pc(i->die, addr, scope);
1534 query_statement (i->name, i->decl_file,
1535 q->line[0], &scope, addr, q);
1536 }
897820ca 1537 else
3e961ba6 1538 query_inline_instance_info (*i, q);
897820ca 1539 }
20e4a32c 1540 }
7e1279ea
FCE
1541}
1542
1543
7fdd3e2c
JS
1544bool
1545inline_instance_info::operator<(const inline_instance_info& other) const
1546{
1547 if (entrypc != other.entrypc)
1548 return entrypc < other.entrypc;
1549
1550 if (decl_line != other.decl_line)
1551 return decl_line < other.decl_line;
1552
1553 int cmp = name.compare(other.name);
1554 if (!cmp)
1555 cmp = strcmp(decl_file, other.decl_file);
1556 return cmp < 0;
1557}
1558
1559
4fa7b22b 1560static int
7e1279ea 1561query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1562{
1563 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1564 assert (q->has_statement_str || q->has_function_str);
1565 assert (!q->has_call && !q->has_return);
bd2b1e68 1566
39bcd429 1567 try
7a053d3b 1568 {
b0ee93c4 1569 if (q->sess.verbose>2)
b530b5b3 1570 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1571
6b517475
JS
1572 Dwarf_Addr entrypc;
1573 if (q->dw.die_entrypc (die, &entrypc))
1574 {
1575 inline_instance_info inl;
1576 inl.die = *die;
1577 inl.name = q->dw.function_name;
1578 inl.entrypc = entrypc;
1579 q->dw.function_file (&inl.decl_file);
1580 q->dw.function_line (&inl.decl_line);
1581
1582 // make sure that this inline hasn't already
1583 // been matched from a different CU
1584 if (q->inline_dupes.insert(inl).second)
1585 q->filtered_inlines.push_back(inl);
1586 }
7e1279ea
FCE
1587 return DWARF_CB_OK;
1588 }
1589 catch (const semantic_error& e)
1590 {
1591 q->sess.print_error (e);
1592 return DWARF_CB_ABORT;
1593 }
1594}
bb788f9f 1595
7e1279ea 1596static int
2da9cedb 1597query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1598{
2da9cedb 1599 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1600 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1601
bd25380d
JS
1602 // weed out functions whose decl_file isn't one of
1603 // the source files that we actually care about
6b517475 1604 if (q->spec_type != function_alone &&
bd25380d 1605 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1606 return DWARF_CB_OK;
bd25380d 1607
7e1279ea
FCE
1608 try
1609 {
7e1279ea
FCE
1610 q->dw.focus_on_function (func);
1611
7d6d0afc
JS
1612 if (!q->dw.function_scope_matches(q->scopes))
1613 return DWARF_CB_OK;
1614
857bdfd1
JS
1615 // make sure that this function address hasn't
1616 // already been matched under an aliased name
1617 Dwarf_Addr addr;
1618 if (!q->dw.func_is_inline() &&
1619 dwarf_entrypc(func, &addr) == 0 &&
1620 !q->alias_dupes.insert(addr).second)
1621 return DWARF_CB_OK;
1622
6b517475 1623 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return))
7e1279ea 1624 {
b0ee93c4 1625 if (q->sess.verbose>3)
b530b5b3 1626 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
2da9cedb 1627 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1628 }
8f14e444
FCE
1629 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1630 {
1631 q->inlined_non_returnable.insert (q->dw.function_name);
1632 }
396afcee 1633 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1634 {
6b517475 1635 if (q->sess.verbose>2)
b530b5b3 1636 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1637
1638 func_info func;
1639 q->dw.function_die (&func.die);
1640 func.name = q->dw.function_name;
1641 q->dw.function_file (&func.decl_file);
1642 q->dw.function_line (&func.decl_line);
1643
1644 Dwarf_Addr entrypc;
1645 if (q->dw.function_entrypc (&entrypc))
1646 {
1647 func.entrypc = entrypc;
1648 q->filtered_functions.push_back (func);
1649 }
1650 /* else this function is fully inlined, just ignore it */
7e1279ea 1651 }
39bcd429 1652 return DWARF_CB_OK;
bd2b1e68 1653 }
39bcd429 1654 catch (const semantic_error& e)
bd2b1e68 1655 {
39bcd429
FCE
1656 q->sess.print_error (e);
1657 return DWARF_CB_ABORT;
bd2b1e68 1658 }
bd2b1e68
GH
1659}
1660
1661static int
1662query_cu (Dwarf_Die * cudie, void * arg)
1663{
20c6c071 1664 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1665 assert (q->has_statement_str || q->has_function_str);
1666
85007c04 1667 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1668
39bcd429 1669 try
bd2b1e68 1670 {
7e1279ea 1671 q->dw.focus_on_cu (cudie);
b5d77020 1672
b0ee93c4 1673 if (false && q->sess.verbose>2)
b530b5b3
LB
1674 clog << _F("focused on CU '%s', in module '%s'\n",
1675 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1676
6b517475
JS
1677 q->filtered_srcfiles.clear();
1678 q->filtered_functions.clear();
1679 q->filtered_inlines.clear();
1680
1681 // In this path, we find "abstract functions", record
1682 // information about them, and then (depending on lineno
1683 // matching) possibly emit one or more of the function's
1684 // associated addresses. Unfortunately the control of this
1685 // cannot easily be turned inside out.
1686
1687 if (q->spec_type != function_alone)
39bcd429 1688 {
6b517475
JS
1689 // If we have a pattern string with a filename, we need
1690 // to elaborate the srcfile mask in question first.
1691 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1692
1693 // If we have a file pattern and *no* srcfile matches, there's
1694 // no need to look further into this CU, so skip.
1695 if (q->filtered_srcfiles.empty())
1696 return DWARF_CB_OK;
1697 }
e4c58386 1698
6b517475
JS
1699 // Pick up [entrypc, name, DIE] tuples for all the functions
1700 // matching the query, and fill in the prologue endings of them
1701 // all in a single pass.
5898b6e1 1702 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1703 if (rc != DWARF_CB_OK)
1704 q->query_done = true;
1705
1706 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1707 && !q->has_statement_str) // PR 2608
1708 if (! q->filtered_functions.empty())
1709 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1710 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1711 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1712
1713 if (q->spec_type == function_file_and_line)
1714 {
58b070fb 1715 // .statement(...:NN) often gets mixed up with .function(...:NN)
af2e341f 1716 if (q->has_function_str && ! q->sess.suppress_warnings)
b530b5b3
LB
1717 q->sess.print_warning (_("For probing a particular line, use a "
1718 ".statement() probe, not .function()"),
af2e341f 1719 q->base_probe->tok);
58b070fb 1720
6b517475
JS
1721 // If we have a pattern string with target *line*, we
1722 // have to look at lines in all the matched srcfiles.
1723 void (* callback) (const dwarf_line_t&, void*) =
1724 q->has_label ? query_srcfile_label : query_srcfile_line;
1725 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1726 i != q->filtered_srcfiles.end(); ++i)
1727 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1728 q->line_type, callback, q->function, q);
1729 }
1730 else if (q->has_label)
1731 {
1732 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1733 i != q->filtered_functions.end(); ++i)
1734 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1735 q, query_label);
1736
1737 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1738 i != q->filtered_inlines.end(); ++i)
1739 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1740 q, query_label);
39bcd429 1741 }
6b517475
JS
1742 else
1743 {
1744 // Otherwise, simply probe all resolved functions.
1745 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1746 i != q->filtered_functions.end(); ++i)
1747 query_func_info (i->entrypc, *i, q);
1748
1749 // And all inline instances (if we're not excluding inlines with ".call")
1750 if (! q->has_call)
1751 for (inline_instance_map_t::iterator i
1752 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1753 query_inline_instance_info (*i, q);
1754 }
39bcd429 1755 return DWARF_CB_OK;
bd2b1e68 1756 }
39bcd429 1757 catch (const semantic_error& e)
bd2b1e68 1758 {
39bcd429
FCE
1759 q->sess.print_error (e);
1760 return DWARF_CB_ABORT;
bd2b1e68 1761 }
bd2b1e68
GH
1762}
1763
0ce64fb8 1764
4df79aaf
JS
1765void
1766dwarf_query::query_module_functions ()
1767{
1768 try
1769 {
1770 filtered_srcfiles.clear();
1771 filtered_functions.clear();
1772 filtered_inlines.clear();
1773
1774 // Collect all module functions so we know which CUs are interesting
1775 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1776 if (rc != DWARF_CB_OK)
1777 {
1778 query_done = true;
1779 return;
1780 }
1781
1782 set<void*> used_cus; // by cu->addr
1783 vector<Dwarf_Die> cus;
1784 Dwarf_Die cu_mem;
1785
1786 for (func_info_map_t::iterator i = filtered_functions.begin();
1787 i != filtered_functions.end(); ++i)
1788 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1789 used_cus.insert(cu_mem.addr).second)
1790 cus.push_back(cu_mem);
1791
1792 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1793 i != filtered_inlines.end(); ++i)
1794 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1795 used_cus.insert(cu_mem.addr).second)
1796 cus.push_back(cu_mem);
1797
1798 // Reset the dupes since we didn't actually collect them the first time
1799 alias_dupes.clear();
1800 inline_dupes.clear();
1801
1802 // Run the query again on the individual CUs
1803 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1804 query_cu(&*i, this);
1805 }
1806 catch (const semantic_error& e)
1807 {
1808 sess.print_error (e);
1809 }
1810}
1811
1812
5f0a03a6
JK
1813static void
1814validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1815{
1816 // Validate the machine code in this elf file against the
1817 // session machine. This is important, in case the wrong kind
1818 // of debuginfo is being automagically processed by elfutils.
1819 // While we can tell i686 apart from x86-64, unfortunately
1820 // we can't help confusing i586 vs i686 (both EM_386).
1821
1822 Dwarf_Addr bias;
1823 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1824 // because dwfl_module_getelf can force costly section relocations
1825 // we don't really need, while either will do for this purpose.
1826 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1827 ?: dwfl_module_getelf (mod, &bias));
1828
1829 GElf_Ehdr ehdr_mem;
1830 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1831 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
5f0a03a6
JK
1832 int elf_machine = em->e_machine;
1833 const char* debug_filename = "";
1834 const char* main_filename = "";
1835 (void) dwfl_module_info (mod, NULL, NULL,
1836 NULL, NULL, NULL,
1837 & main_filename,
1838 & debug_filename);
1839 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1840
1841 string expect_machine; // to match sess.machine (i.e., kernel machine)
1842 string expect_machine2;
5f0a03a6 1843
d27e6fd5 1844 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1845 switch (elf_machine)
1846 {
756c9462
FCE
1847 // x86 and ppc are bi-architecture; a 64-bit kernel
1848 // can normally run either 32-bit or 64-bit *userspace*.
1849 case EM_386:
1850 expect_machine = "i?86";
1851 if (! q->has_process) break; // 32-bit kernel/module
1852 /* FALLSTHROUGH */
1853 case EM_X86_64:
1854 expect_machine2 = "x86_64";
1855 break;
1856 case EM_PPC:
756c9462 1857 case EM_PPC64:
5a1c472e 1858 expect_machine = "powerpc";
756c9462 1859 break;
3fe7d888 1860 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 1861 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 1862 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
1863 // XXX: fill in some more of these
1864 default: expect_machine = "?"; break;
1865 }
1866
1867 if (! debug_filename) debug_filename = main_filename;
1868 if (! debug_filename) debug_filename = name;
1869
756c9462
FCE
1870 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
1871 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
1872 {
1873 stringstream msg;
b530b5b3
LB
1874 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
1875 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
1876 sess_machine.c_str(), debug_filename);
5f0a03a6
JK
1877 throw semantic_error(msg.str ());
1878 }
1879
1880 if (q->sess.verbose>2)
2a97f50b 1881 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
1882 " file %s ELF machine %s|%s (code %d)\n",
1883 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
1884 q->dw.module_bias, debug_filename, expect_machine.c_str(),
1885 expect_machine2.c_str(), elf_machine);
5f0a03a6 1886}
1d3a40b6 1887
91af0778
FCE
1888
1889
1890static Dwarf_Addr
1891lookup_symbol_address (Dwfl_Module *m, const char* wanted)
1892{
1893 int syments = dwfl_module_getsymtab(m);
1894 assert(syments);
1895 for (int i = 1; i < syments; ++i)
1896 {
1897 GElf_Sym sym;
1898 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
1899 if (name != NULL && strcmp(name, wanted) == 0)
1900 return sym.st_value;
1901 }
1902
1903 return 0;
1904}
1905
1906
1907
bd2b1e68 1908static int
b8da0ad1 1909query_module (Dwfl_Module *mod,
91af0778 1910 void **,
b8da0ad1 1911 const char *name,
6f4c1275 1912 Dwarf_Addr addr,
b8da0ad1 1913 void *arg)
bd2b1e68 1914{
91af0778 1915 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 1916
39bcd429 1917 try
e38d6504 1918 {
91af0778
FCE
1919 module_info* mi = q->sess.module_cache->cache[name];
1920 if (mi == 0)
1921 {
1922 mi = q->sess.module_cache->cache[name] = new module_info(name);
1923
6f4c1275
FCE
1924 mi->mod = mod;
1925 mi->addr = addr;
91af0778 1926
6f4c1275
FCE
1927 const char* debug_filename = "";
1928 const char* main_filename = "";
1929 (void) dwfl_module_info (mod, NULL, NULL,
1930 NULL, NULL, NULL,
1931 & main_filename,
1932 & debug_filename);
1933
1934 if (q->sess.ignore_vmlinux && name == TOK_KERNEL)
91af0778
FCE
1935 {
1936 // report_kernel() in elfutils found vmlinux, but pretend it didn't.
1937 // Given a non-null path, returning 1 means keep reporting modules.
1938 mi->dwarf_status = info_absent;
1939 }
6f4c1275 1940 else if (debug_filename || main_filename)
91af0778 1941 {
6f4c1275
FCE
1942 mi->elf_path = debug_filename ?: main_filename;
1943 }
1944 else if (name == TOK_KERNEL)
1945 {
1946 mi->dwarf_status = info_absent;
91af0778 1947 }
91af0778
FCE
1948 }
1949 // OK, enough of that module_info caching business.
1950
5f0a03a6 1951 q->dw.focus_on_module(mod, mi);
d9b516ca 1952
39bcd429
FCE
1953 // If we have enough information in the pattern to skip a module and
1954 // the module does not match that information, return early.
b8da0ad1 1955 if (!q->dw.module_name_matches(q->module_val))
85007c04 1956 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
1957
1958 // Don't allow module("*kernel*") type expressions to match the
1959 // elfutils module "kernel", which we refer to in the probe
1960 // point syntax exclusively as "kernel.*".
1961 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 1962 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 1963
5f0a03a6
JK
1964 if (mod)
1965 validate_module_elf(mod, name, q);
1966 else
91af0778
FCE
1967 assert(q->has_kernel); // and no vmlinux to examine
1968
1969 if (q->sess.verbose>2)
b530b5b3 1970 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
1971
1972
1973 // Collect a few kernel addresses. XXX: these belong better
1974 // to the sess.module_info["kernel"] struct.
1975 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 1976 {
91af0778
FCE
1977 if (! q->sess.sym_kprobes_text_start)
1978 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
1979 if (! q->sess.sym_kprobes_text_end)
1980 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
1981 if (! q->sess.sym_stext)
1982 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
1983 }
1984
84c84ac4
SC
1985 if (q->has_library && contains_glob_chars (q->path))
1986 // handle .library(GLOB)
1987 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
1988 // .plt is translated to .plt.statement(N). We only want to iterate for the
1989 // .plt case
1990 else if (q->has_plt && ! q->has_statement)
1991 q->dw.iterate_over_plt (q, &q->query_plt_callback);
84c84ac4
SC
1992 else
1993 // search the module for matches of the probe point.
1994 q->handle_query_module();
bb788f9f 1995
b8da0ad1 1996 // If we know that there will be no more matches, abort early.
85007c04 1997 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
1998 return DWARF_CB_ABORT;
1999 else
2000 return DWARF_CB_OK;
7a053d3b 2001 }
39bcd429 2002 catch (const semantic_error& e)
bd2b1e68 2003 {
39bcd429
FCE
2004 q->sess.print_error (e);
2005 return DWARF_CB_ABORT;
bd2b1e68 2006 }
bd2b1e68
GH
2007}
2008
35d4ab18 2009
84c84ac4 2010void
5d5bd369 2011base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2012{
2013 base_query *me = (base_query*)q;
5d5bd369 2014 me->query_library (data);
84c84ac4
SC
2015}
2016
2017
2018void
51d6bda3
SC
2019query_one_library (const char *library, dwflpp & dw,
2020 const string user_lib, probe * base_probe, probe_point *base_loc,
2021 vector<derived_probe *> & results)
84c84ac4
SC
2022{
2023 if (dw.function_name_matches_pattern(library, user_lib))
2024 {
2025 string library_path = find_executable (library, "LD_LIBRARY_PATH");
2026 probe_point* specific_loc = new probe_point(*base_loc);
2027 specific_loc->optional = true;
2028 vector<probe_point::component*> derived_comps;
2029
2030 vector<probe_point::component*>::iterator it;
2031 for (it = specific_loc->components.begin();
2032 it != specific_loc->components.end(); ++it)
2033 if ((*it)->functor == TOK_LIBRARY)
2034 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2035 new literal_string(library_path)));
2036 else
2037 derived_comps.push_back(*it);
2038 probe_point* derived_loc = new probe_point(*specific_loc);
2039 derived_loc->components = derived_comps;
2040 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
51d6bda3
SC
2041 derive_probes(dw.sess, new_base, results);
2042 if (dw.sess.verbose > 2)
84c84ac4
SC
2043 clog << _("module=") << library_path;
2044 }
2045}
2046
2047
51d6bda3
SC
2048void
2049dwarf_query::query_library (const char *library)
2050{
2051 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2052}
2053
576eaefe
SC
2054struct plt_expanding_visitor: public var_expanding_visitor
2055{
2056 plt_expanding_visitor(const string & entry):
2057 entry (entry)
2058 {
2059 }
2060 const string & entry;
2061
2062 void visit_target_symbol (target_symbol* e);
2063};
2064
2065
2066void
2067base_query::query_plt_callback (void *q, const char *entry, size_t address)
2068{
2069 base_query *me = (base_query*)q;
2070 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2071 me->query_plt (entry, address);
2072}
2073
2074
2075void
2076query_one_plt (const char *entry, long addr, dwflpp & dw,
2077 probe * base_probe, probe_point *base_loc,
2078 vector<derived_probe *> & results)
2079{
2080 probe_point* specific_loc = new probe_point(*base_loc);
2081 specific_loc->optional = true;
2082 vector<probe_point::component*> derived_comps;
2083
2084 if (dw.sess.verbose > 2)
2085 clog << _F("plt entry=%s\n", entry);
2086
2087 // query_module_symtab requires .plt to recognize that it can set the probe at
2088 // a plt entry so we convert process.plt to process.plt.statement
2089 vector<probe_point::component*>::iterator it;
2090 for (it = specific_loc->components.begin();
2091 it != specific_loc->components.end(); ++it)
2092 if ((*it)->functor == TOK_PLT)
3d372d6b
SC
2093 {
2094 derived_comps.push_back(*it);
2095 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
2096 new literal_number(addr)));
2097 }
576eaefe
SC
2098 else
2099 derived_comps.push_back(*it);
2100 probe_point* derived_loc = new probe_point(*specific_loc);
2101 derived_loc->components = derived_comps;
2102 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
2103 string e = string(entry);
2104 plt_expanding_visitor pltv (e);
2105 pltv.replace (new_base->body);
2106 derive_probes(dw.sess, new_base, results);
2107}
2108
2109
2110void
2111dwarf_query::query_plt (const char *entry, size_t address)
2112{
2113 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2114}
51d6bda3 2115
435f53a7
FCE
2116// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2117// but the needed declaration for module_cache is not available there.
2118// Nor for that matter in session.cxx. Only in this CU is that field ever
2119// set (in query_module() above), so we clean it up here too.
2120static void
2121delete_session_module_cache (systemtap_session& s)
2122{
2123 if (s.module_cache) {
2124 if (s.verbose > 3)
b530b5b3 2125 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2126 delete s.module_cache;
2127 s.module_cache = 0;
2128 }
2129}
2130
2131
de688825 2132struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2133{
77de5e9e 2134 dwarf_query & q;
bcc12710 2135 Dwarf_Die *scope_die;
77de5e9e 2136 Dwarf_Addr addr;
8c819921 2137 block *add_block;
2260f4e3 2138 block *add_call_probe; // synthesized from .return probes with saved $vars
8cc799a5 2139 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2140 unsigned saved_longs, saved_strings; // data saved within kretprobes
2141 map<std::string, expression *> return_ts_map;
729455a7 2142 vector<Dwarf_Die> scopes;
b95e2b79 2143 bool visited;
77de5e9e 2144
de688825 2145 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2146 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2147 add_block_tid(false), add_call_probe_tid(false),
af234c40 2148 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2149 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2150 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2151 void visit_target_symbol_saved_return (target_symbol* e);
2152 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2153 void visit_target_symbol (target_symbol* e);
c24447be 2154 void visit_cast_op (cast_op* e);
8cc799a5 2155 void visit_entry_op (entry_op* e);
729455a7
JS
2156private:
2157 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2158};
2159
2160
de688825 2161unsigned var_expanding_visitor::tick = 0;
77de5e9e 2162
a50de939 2163
74fe61bc 2164var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2165{
2166 // FIXME: for the time being, by default we only support plain '$foo
2167 // = bar', not '+=' or any other op= variant. This is fixable, but a
2168 // bit ugly.
2169 //
2170 // If derived classes desire to add additional operator support, add
2171 // new operators to this list in the derived class constructor.
2172 valid_ops.insert ("=");
2173}
2174
2175
87214add
JS
2176bool
2177var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2178 expression*& lvalue, expression*& rvalue)
77de5e9e 2179{
e57b735a
GH
2180 // Our job would normally be to require() the left and right sides
2181 // into a new assignment. What we're doing is slightly trickier:
2182 // we're pushing a functioncall** onto a stack, and if our left
2183 // child sets the functioncall* for that value, we're going to
2184 // assume our left child was a target symbol -- transformed into a
2185 // set_target_foo(value) call, and it wants to take our right child
2186 // as the argument "value".
2187 //
2188 // This is why some people claim that languages with
2189 // constructor-decomposing case expressions have a leg up on
2190 // visitors.
2191
2192 functioncall *fcall = NULL;
d9b516ca 2193
a50de939 2194 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2195 const string* old_op = op;
2196 op = &eop;
a50de939 2197
e57b735a 2198 target_symbol_setter_functioncalls.push (&fcall);
87214add 2199 replace (lvalue);
e57b735a 2200 target_symbol_setter_functioncalls.pop ();
87214add
JS
2201 replace (rvalue);
2202
2203 op = old_op;
e57b735a
GH
2204
2205 if (fcall != NULL)
77de5e9e 2206 {
e57b735a
GH
2207 // Our left child is informing us that it was a target variable
2208 // and it has been replaced with a set_target_foo() function
2209 // call; we are going to provide that function call -- with the
2210 // right child spliced in as sole argument -- in place of
de688825 2211 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2212
87214add 2213 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2214 {
2215 // Build up a list of supported operators.
2216 string ops;
2217 std::set<string>::iterator i;
b530b5b3 2218 int valid_ops_size = 0;
a50de939 2219 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2220 {
a50de939 2221 ops += " " + *i + ",";
b530b5b3
LB
2222 valid_ops_size++;
2223 }
a50de939
DS
2224 ops.resize(ops.size() - 1); // chop off the last ','
2225
2226 // Throw the error.
1e41115c
LB
2227 throw semantic_error (_F(ngettext("Only the following assign operator is implemented on target variables: %s",
2228 "Only the following assign operators are implemented on target variables: %s",
b530b5b3
LB
2229 valid_ops_size), ops.c_str()), tok);
2230
a50de939 2231 }
e57b735a 2232
87214add
JS
2233 assert (lvalue == fcall);
2234 if (rvalue)
2235 fcall->args.push_back (rvalue);
4ed05b15 2236 provide (fcall);
87214add 2237 return true;
77de5e9e 2238 }
e57b735a 2239 else
87214add
JS
2240 return false;
2241}
2242
2243
2244void
2245var_expanding_visitor::visit_assignment (assignment* e)
2246{
2247 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2248 provide (e);
2249}
2250
2251
2252void
2253var_expanding_visitor::visit_pre_crement (pre_crement* e)
2254{
2255 expression *dummy = NULL;
2256 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2257 provide (e);
2258}
2259
2260
2261void
2262var_expanding_visitor::visit_post_crement (post_crement* e)
2263{
2264 expression *dummy = NULL;
2265 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2266 provide (e);
2267}
2268
2269
2270void
2271var_expanding_visitor::visit_delete_statement (delete_statement* s)
2272{
2273 string fakeop = "delete";
2274 expression *dummy = NULL;
2275 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2276 provide (s);
e57b735a 2277}
d9b516ca 2278
d7f3e0c5 2279
30263a73
FCE
2280void
2281var_expanding_visitor::visit_defined_op (defined_op* e)
2282{
2283 bool resolved = true;
2284
2285 defined_ops.push (e);
2286 try {
2287 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2288 // defined with a target_symbol* operand, a subsidiary call may attempt to
2289 // rewrite it to a general expression* instead, and require<> happily
2290 // casts to/from void*, causing possible memory corruption. We use
2291 // expression* here, being the general case of rewritten $variable.
2292 expression *foo1 = e->operand;
2293 foo1 = require (foo1);
2294
c69a87e0 2295 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2296 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2297 // erroneous resolutions. Some would signal a visit_target_symbol failure
2298 // with an exception, with a set flag within the target_symbol, or nothing
2299 // at all.
30263a73 2300 //
c69a87e0
FCE
2301 // Now, failures always have to be signalled with a
2302 // saved_conversion_error being chained to the target_symbol.
2303 // Successes have to result in an attempted rewrite of the
850bfddd 2304 // target_symbol (via provide()).
780f11ff 2305 //
c69a87e0
FCE
2306 // Edna Mode: "no capes". fche: "no exceptions".
2307
30263a73
FCE
2308 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2309 //
2310 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2311 //
2312 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2313 // dwarf probe to take care of it.
2314 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2315 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2316 //
30263a73
FCE
2317 // utrace: success: rewrites to function; failure: semantic_error
2318 //
850bfddd 2319 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2320
2321 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2322 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2323 resolved = false;
a45664f4 2324 else if (foo2) // unresolved but not marked failing
b7aedf26 2325 {
780f11ff
JS
2326 // There are some visitors that won't touch certain target_symbols,
2327 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2328 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2329 e->operand = foo2;
2330 provide (e);
2331 return;
2332 }
30263a73
FCE
2333 else // resolved, rewritten to some other expression type
2334 resolved = true;
780f11ff 2335 } catch (const semantic_error& e) {
c69a87e0 2336 assert (0); // should not happen
30263a73
FCE
2337 }
2338 defined_ops.pop ();
2339
2340 literal_number* ln = new literal_number (resolved ? 1 : 0);
2341 ln->tok = e->tok;
2342 provide (ln);
2343}
2344
2345
5f36109e
JS
2346struct dwarf_pretty_print
2347{
2348 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2349 const string& local, bool userspace_p,
2350 const target_symbol& e):
d19a9a82
JS
2351 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2352 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2353 {
2354 init_ts (e);
2355 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2356 }
2357
2358 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2359 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2360 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2361 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2362 {
2363 init_ts (e);
2364 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2365 }
2366
2367 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2368 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2369 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2370 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2371 {
2372 init_ts (e);
2373 dw.type_die_for_pointer (type_die, ts, &base_type);
2374 }
2375
2376 functioncall* expand ();
ce83ff57 2377 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2378
2379private:
2380 dwflpp& dw;
2381 target_symbol* ts;
7d11d8c9 2382 bool print_full;
5f36109e
JS
2383 Dwarf_Die base_type;
2384
2385 string local;
2386 vector<Dwarf_Die> scopes;
2387 Dwarf_Addr pc;
2388
2389 expression* pointer;
2390 Dwarf_Die pointer_type;
2391
d19a9a82 2392 const bool userspace_p, deref_p;
5f36109e
JS
2393
2394 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2395 print_format* pf, bool top=false);
5f36109e 2396 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2397 print_format* pf);
5f36109e 2398 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2399 print_format* pf, bool top);
5f36109e 2400 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2401 print_format* pf, bool top);
5f36109e 2402 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2403 print_format* pf, bool top);
5f36109e 2404 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2405 print_format* pf, int& count);
bbee5bb8 2406 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2407
2408 void init_ts (const target_symbol& e);
2409 expression* deref (target_symbol* e);
c55ea10d 2410 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2411};
2412
2413
2414void
2415dwarf_pretty_print::init_ts (const target_symbol& e)
2416{
2417 // Work with a new target_symbol so we can modify arguments
2418 ts = new target_symbol (e);
2419
2420 if (ts->addressof)
b530b5b3 2421 throw semantic_error(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2422
2423 if (ts->components.empty() ||
2424 ts->components.back().type != target_symbol::comp_pretty_print)
b530b5b3 2425 throw semantic_error(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2426 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2427 ts->components.pop_back();
2428}
2429
2430
2431functioncall*
2432dwarf_pretty_print::expand ()
2433{
2434 static unsigned tick = 0;
2435
2436 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2437 // try {
2438 // return sprintf("{.foo=...}", (ts)->foo, ...)
2439 // } catch {
2440 // return "ERROR"
2441 // }
5f36109e
JS
2442 // }
2443
2444 // Create the function decl and call.
2445
2446 functiondecl *fdecl = new functiondecl;
2447 fdecl->tok = ts->tok;
2448 fdecl->synthetic = true;
2449 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2450 fdecl->type = pe_string;
2451
2452 functioncall* fcall = new functioncall;
2453 fcall->tok = ts->tok;
2454 fcall->function = fdecl->name;
140be17a 2455 fcall->type = pe_string;
5f36109e
JS
2456
2457 // If there's a <pointer>, replace it with a new var and make that
2458 // the first function argument.
2459 if (pointer)
2460 {
2461 vardecl *v = new vardecl;
2462 v->type = pe_long;
2463 v->name = "pointer";
2464 v->tok = ts->tok;
2465 fdecl->formal_args.push_back (v);
2466 fcall->args.push_back (pointer);
2467
2468 symbol* sym = new symbol;
2469 sym->tok = ts->tok;
2470 sym->name = v->name;
5f36109e
JS
2471 pointer = sym;
2472 }
2473
2474 // For each expression argument, replace it with a function argument.
2475 for (unsigned i = 0; i < ts->components.size(); ++i)
2476 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2477 {
2478 vardecl *v = new vardecl;
2479 v->type = pe_long;
2480 v->name = "index" + lex_cast(i);
2481 v->tok = ts->tok;
2482 fdecl->formal_args.push_back (v);
2483 fcall->args.push_back (ts->components[i].expr_index);
2484
2485 symbol* sym = new symbol;
2486 sym->tok = ts->tok;
2487 sym->name = v->name;
5f36109e
JS
2488 ts->components[i].expr_index = sym;
2489 }
2490
2491 // Create the return sprintf.
2492 token* pf_tok = new token(*ts->tok);
2493 pf_tok->content = "sprintf";
2494 print_format* pf = print_format::create(pf_tok);
2495 return_statement* rs = new return_statement;
2496 rs->tok = ts->tok;
2497 rs->value = pf;
5f36109e
JS
2498
2499 // Recurse into the actual values.
7d11d8c9 2500 recurse (&base_type, ts, pf, true);
5f36109e
JS
2501 pf->components = print_format::string_to_components(pf->raw_components);
2502
7d11d8c9
JS
2503 // Create the try-catch net
2504 try_block* tb = new try_block;
2505 tb->tok = ts->tok;
2506 tb->try_block = rs;
2507 tb->catch_error_var = 0;
2508 return_statement* rs2 = new return_statement;
2509 rs2->tok = ts->tok;
2510 rs2->value = new literal_string ("ERROR");
2511 rs2->value->tok = ts->tok;
2512 tb->catch_block = rs2;
2513 fdecl->body = tb;
2514
f8809d54 2515 fdecl->join (dw.sess);
5f36109e
JS
2516 return fcall;
2517}
2518
2519
2520void
2521dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2522 print_format* pf, bool top)
5f36109e
JS
2523{
2524 Dwarf_Die type;
2525 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2526
2527 switch (dwarf_tag(&type))
2528 {
2529 default:
2530 // XXX need a warning?
2531 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2532 // + ") for " + dwarf_type_name(&type), e->tok);
2533 pf->raw_components.append("?");
2534 break;
2535
2536 case DW_TAG_enumeration_type:
2537 case DW_TAG_base_type:
7d11d8c9 2538 recurse_base (&type, e, pf);
5f36109e
JS
2539 break;
2540
2541 case DW_TAG_array_type:
7d11d8c9 2542 recurse_array (&type, e, pf, top);
5f36109e
JS
2543 break;
2544
2545 case DW_TAG_pointer_type:
2546 case DW_TAG_reference_type:
2547 case DW_TAG_rvalue_reference_type:
7d11d8c9 2548 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2549 break;
2550
2551 case DW_TAG_subroutine_type:
c55ea10d 2552 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2553 break;
2554
2555 case DW_TAG_union_type:
5f36109e
JS
2556 case DW_TAG_structure_type:
2557 case DW_TAG_class_type:
7d11d8c9 2558 recurse_struct (&type, e, pf, top);
5f36109e
JS
2559 break;
2560 }
2561}
2562
2563
2564void
2565dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2566 print_format* pf)
5f36109e
JS
2567{
2568 Dwarf_Attribute attr;
2569 Dwarf_Word encoding = (Dwarf_Word) -1;
2570 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2571 &encoding);
5f36109e
JS
2572 switch (encoding)
2573 {
2574 case DW_ATE_float:
2575 case DW_ATE_complex_float:
2576 // XXX need a warning?
2577 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2578 // + ") for " + dwarf_type_name(type), e->tok);
2579 pf->raw_components.append("?");
5f36109e
JS
2580 break;
2581
2582 case DW_ATE_signed_char:
2583 case DW_ATE_unsigned_char:
c55ea10d 2584 push_deref (pf, "'%c'", e);
5f36109e
JS
2585 break;
2586
2587 case DW_ATE_unsigned:
c55ea10d 2588 push_deref (pf, "%u", e);
5f36109e
JS
2589 break;
2590
2591 default:
c55ea10d 2592 push_deref (pf, "%i", e);
5f36109e
JS
2593 break;
2594 }
5f36109e
JS
2595}
2596
2597
2598void
2599dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2600 print_format* pf, bool top)
5f36109e 2601{
7d11d8c9
JS
2602 if (!top && !print_full)
2603 {
2604 pf->raw_components.append("[...]");
2605 return;
2606 }
2607
5f36109e
JS
2608 Dwarf_Die childtype;
2609 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2610
2611 if (print_chars (&childtype, e, pf))
2612 return;
2613
5f36109e
JS
2614 pf->raw_components.append("[");
2615
2616 // We print the array up to the first 5 elements.
2617 // XXX how can we determine the array size?
2618 // ... for now, just print the first element
64cddf39 2619 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2620 unsigned i, size = 1;
64cddf39 2621 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2622 {
2623 if (i > 0)
2624 pf->raw_components.append(", ");
2625 target_symbol* e2 = new target_symbol(*e);
2626 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2627 recurse (&childtype, e2, pf);
5f36109e
JS
2628 }
2629 if (i < size || 1/*XXX until real size is known */)
2630 pf->raw_components.append(", ...");
2631 pf->raw_components.append("]");
2632}
2633
2634
2635void
2636dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2637 print_format* pf, bool top)
5f36109e 2638{
7d11d8c9 2639 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2640 bool void_p = true;
7d11d8c9 2641 Dwarf_Die pointee;
bbee5bb8 2642 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2643 {
2644 try
2645 {
2646 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2647 void_p = false;
2648 }
2649 catch (const semantic_error&) {}
2650 }
2651
2652 if (!void_p)
5f36109e 2653 {
bbee5bb8
JS
2654 if (print_chars (&pointee, e, pf))
2655 return;
2656
2657 if (top)
2658 {
2659 recurse (&pointee, e, pf, top);
2660 return;
2661 }
5f36109e 2662 }
bbee5bb8 2663
c55ea10d 2664 push_deref (pf, "%p", e);
5f36109e
JS
2665}
2666
2667
2668void
2669dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2670 print_format* pf, bool top)
5f36109e 2671{
bdec0e18
JS
2672 if (dwarf_hasattr(type, DW_AT_declaration))
2673 {
a44a7cb5 2674 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2675 if (!resolved)
2676 {
2677 // could be an error, but for now just stub it
2678 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2679 pf->raw_components.append("{...}");
2680 return;
2681 }
2682 type = resolved;
2683 }
2684
5f36109e
JS
2685 int count = 0;
2686 pf->raw_components.append("{");
7d11d8c9
JS
2687 if (top || print_full)
2688 recurse_struct_members (type, e, pf, count);
2689 else
2690 pf->raw_components.append("...");
5f36109e
JS
2691 pf->raw_components.append("}");
2692}
2693
2694
2695void
2696dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2697 print_format* pf, int& count)
5f36109e 2698{
a80f28d8
JS
2699 /* With inheritance, a subclass may mask member names of parent classes, so
2700 * our search among the inheritance tree must be breadth-first rather than
2701 * depth-first (recursive). The type die is still our starting point. When
2702 * we encounter a masked name, just skip it. */
2703 set<string> dupes;
2704 deque<Dwarf_Die> inheritees(1, *type);
2705 for (; !inheritees.empty(); inheritees.pop_front())
2706 {
2707 Dwarf_Die child, childtype;
2708 if (dwarf_child (&inheritees.front(), &child) == 0)
2709 do
2710 {
2711 target_symbol* e2 = e;
5f36109e 2712
a80f28d8
JS
2713 // skip static members
2714 if (dwarf_hasattr(&child, DW_AT_declaration))
2715 continue;
5f36109e 2716
a80f28d8 2717 int tag = dwarf_tag (&child);
5f36109e 2718
a80f28d8
JS
2719 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2720 continue;
5f36109e 2721
a80f28d8 2722 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2723
a80f28d8
JS
2724 if (tag == DW_TAG_inheritance)
2725 {
2726 inheritees.push_back(childtype);
2727 continue;
2728 }
5f36109e 2729
a80f28d8
JS
2730 int childtag = dwarf_tag (&childtype);
2731 const char *member = dwarf_diename (&child);
3a147004 2732
a80f28d8
JS
2733 // "_vptr.foo" members are C++ virtual function tables,
2734 // which (generally?) aren't interesting for users.
2735 if (member && startswith(member, "_vptr."))
2736 continue;
3a147004 2737
a80f28d8
JS
2738 // skip inheritance-masked duplicates
2739 if (member && !dupes.insert(member).second)
2740 continue;
64cddf39 2741
a80f28d8
JS
2742 if (++count > 1)
2743 pf->raw_components.append(", ");
64cddf39 2744
a80f28d8
JS
2745 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2746 if (pf->args.size() >= 32)
2747 {
2748 pf->raw_components.append("...");
2749 break;
2750 }
2751
2752 if (member)
2753 {
2754 pf->raw_components.append(".");
2755 pf->raw_components.append(member);
5f36109e 2756
a80f28d8
JS
2757 e2 = new target_symbol(*e);
2758 e2->components.push_back (target_symbol::component(e->tok, member));
2759 }
2760 else if (childtag == DW_TAG_union_type)
2761 pf->raw_components.append("<union>");
2762 else if (childtag == DW_TAG_structure_type)
2763 pf->raw_components.append("<class>");
2764 else if (childtag == DW_TAG_class_type)
2765 pf->raw_components.append("<struct>");
2766 pf->raw_components.append("=");
2767 recurse (&childtype, e2, pf);
5f36109e 2768 }
a80f28d8
JS
2769 while (dwarf_siblingof (&child, &child) == 0);
2770 }
5f36109e
JS
2771}
2772
2773
bbee5bb8
JS
2774bool
2775dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2776 print_format* pf)
2777{
2778 Dwarf_Die type;
2779 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2780 const char *name = dwarf_diename (&type);
2781 if (name && (name == string("char") || name == string("unsigned char")))
2782 {
c55ea10d
JS
2783 if (push_deref (pf, "\"%s\"", e))
2784 {
2785 // steal the last arg for a string access
2786 assert (!pf->args.empty());
2787 functioncall* fcall = new functioncall;
2788 fcall->tok = e->tok;
2789 fcall->function = userspace_p ? "user_string2" : "kernel_string2";
2790 fcall->args.push_back (pf->args.back());
2791 expression *err_msg = new literal_string ("<unknown>");
2792 err_msg->tok = e->tok;
2793 fcall->args.push_back (err_msg);
2794 pf->args.back() = fcall;
2795 }
bbee5bb8
JS
2796 return true;
2797 }
2798 return false;
2799}
2800
2801
5f36109e
JS
2802expression*
2803dwarf_pretty_print::deref (target_symbol* e)
2804{
2805 static unsigned tick = 0;
2806
d19a9a82
JS
2807 if (!deref_p)
2808 {
2809 assert (pointer && e->components.empty());
2810 return pointer;
2811 }
2812
5f36109e
JS
2813 // Synthesize a function to dereference the dwarf fields,
2814 // with a pointer parameter that is the base tracepoint variable
2815 functiondecl *fdecl = new functiondecl;
2816 fdecl->synthetic = true;
2817 fdecl->tok = e->tok;
2818 embeddedcode *ec = new embeddedcode;
2819 ec->tok = e->tok;
2820
2821 fdecl->name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
2822 fdecl->body = ec;
2823
2824 // Synthesize a functioncall.
2825 functioncall* fcall = new functioncall;
2826 fcall->tok = e->tok;
2827 fcall->function = fdecl->name;
5f36109e
JS
2828
2829 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
2830 ec->code += "\n#define fetch_register " + string(userspace_p?"u":"k") + "_fetch_register\n";
2831 ec->code += "#define store_register " + string(userspace_p?"u":"k") + "_store_register\n";
2832
2833 if (pointer)
2834 {
2835 ec->code += dw.literal_stmt_for_pointer (&pointer_type, e,
2836 false, fdecl->type);
2837
2838 vardecl *v = new vardecl;
2839 v->type = pe_long;
2840 v->name = "pointer";
2841 v->tok = e->tok;
2842 fdecl->formal_args.push_back(v);
2843 fcall->args.push_back(pointer);
2844 }
2845 else if (!local.empty())
2846 ec->code += dw.literal_stmt_for_local (scopes, pc, local, e,
2847 false, fdecl->type);
2848 else
2849 ec->code += dw.literal_stmt_for_return (&scopes[0], pc, e,
2850 false, fdecl->type);
2851
2852 // Any non-literal indexes need to be passed in too.
2853 for (unsigned i = 0; i < e->components.size(); ++i)
2854 if (e->components[i].type == target_symbol::comp_expression_array_index)
2855 {
2856 vardecl *v = new vardecl;
2857 v->type = pe_long;
2858 v->name = "index" + lex_cast(i);
2859 v->tok = e->tok;
2860 fdecl->formal_args.push_back(v);
2861 fcall->args.push_back(e->components[i].expr_index);
2862 }
2863
2864 ec->code += "/* pure */";
2865 ec->code += "/* unprivileged */";
2866
2867 // PR10601
2868 ec->code += "\n#undef fetch_register\n";
2869 ec->code += "\n#undef store_register\n";
2870
f8809d54 2871 fdecl->join (dw.sess);
5f36109e
JS
2872 return fcall;
2873}
2874
2875
c55ea10d
JS
2876bool
2877dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
2878 target_symbol* e)
2879{
2880 expression* e2 = NULL;
2881 try
2882 {
2883 e2 = deref (e);
2884 }
2885 catch (const semantic_error&)
2886 {
2887 pf->raw_components.append ("?");
2888 return false;
2889 }
2890 pf->raw_components.append (fmt);
2891 pf->args.push_back (e2);
2892 return true;
2893}
2894
2895
e57b735a 2896void
a7999c82 2897dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 2898{
a7999c82
JS
2899 // Get the full name of the target symbol.
2900 stringstream ts_name_stream;
2901 e->print(ts_name_stream);
2902 string ts_name = ts_name_stream.str();
2903
2904 // Check and make sure we haven't already seen this target
2905 // variable in this return probe. If we have, just return our
2906 // last replacement.
af234c40 2907 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 2908 if (i != return_ts_map.end())
85ecf79a 2909 {
a7999c82
JS
2910 provide (i->second);
2911 return;
2912 }
85ecf79a 2913
70208613
JS
2914 // Attempt the expansion directly first, so if there's a problem with the
2915 // variable we won't have a bogus entry probe lying around. Like in
2916 // saveargs(), we pretend for a moment that we're not in a .return.
2917 bool saved_has_return = q.has_return;
2918 q.has_return = false;
2919 expression *repl = e;
2920 replace (repl);
2921 q.has_return = saved_has_return;
2922 target_symbol* n = dynamic_cast<target_symbol*>(repl);
2923 if (n && n->saved_conversion_error)
2924 {
2925 provide (repl);
2926 return;
2927 }
2928
af234c40
JS
2929 expression *exp;
2930 if (!q.has_process &&
2931 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 2932 exp = gen_kretprobe_saved_return(repl);
af234c40 2933 else
277c21bc 2934 exp = gen_mapped_saved_return(repl, e->name);
af234c40
JS
2935
2936 // Provide the variable to our parent so it can be used as a
2937 // substitute for the target symbol.
2938 provide (exp);
2939
2940 // Remember this replacement since we might be able to reuse
2941 // it later if the same return probe references this target
2942 // symbol again.
2943 return_ts_map[ts_name] = exp;
2944}
2945
2946expression*
70208613 2947dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
277c21bc 2948 const string& name)
af234c40 2949{
a7999c82
JS
2950 // We've got to do several things here to handle target
2951 // variables in return probes.
85ecf79a 2952
a7999c82
JS
2953 // (1) Synthesize two global arrays. One is the cache of the
2954 // target variable and the other contains a thread specific
2955 // nesting level counter. The arrays will look like
2956 // this:
2957 //
2958 // _dwarf_tvar_{name}_{num}
2959 // _dwarf_tvar_{name}_{num}_ctr
2960
2961 string aname = (string("_dwarf_tvar_")
277c21bc 2962 + name.substr(1)
aca66a36 2963 + "_" + lex_cast(tick++));
a7999c82
JS
2964 vardecl* vd = new vardecl;
2965 vd->name = aname;
2966 vd->tok = e->tok;
2967 q.sess.globals.push_back (vd);
2968
2969 string ctrname = aname + "_ctr";
2970 vd = new vardecl;
2971 vd->name = ctrname;
2972 vd->tok = e->tok;
2973 q.sess.globals.push_back (vd);
2974
2975 // (2) Create a new code block we're going to insert at the
2976 // beginning of this probe to get the cached value into a
2977 // temporary variable. We'll replace the target variable
2978 // reference with the temporary variable reference. The code
2979 // will look like this:
2980 //
2981 // _dwarf_tvar_tid = tid()
2982 // _dwarf_tvar_{name}_{num}_tmp
2983 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2984 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
2985 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2986 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
2987 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
2988 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
2989
2990 // (2a) Synthesize the tid temporary expression, which will look
2991 // like this:
2992 //
2993 // _dwarf_tvar_tid = tid()
2994 symbol* tidsym = new symbol;
2995 tidsym->name = string("_dwarf_tvar_tid");
2996 tidsym->tok = e->tok;
85ecf79a 2997
a7999c82
JS
2998 if (add_block == NULL)
2999 {
3000 add_block = new block;
3001 add_block->tok = e->tok;
8cc799a5 3002 }
8c819921 3003
8cc799a5
JS
3004 if (!add_block_tid)
3005 {
a7999c82
JS
3006 // Synthesize a functioncall to grab the thread id.
3007 functioncall* fc = new functioncall;
3008 fc->tok = e->tok;
3009 fc->function = string("tid");
8c819921 3010
a7999c82 3011 // Assign the tid to '_dwarf_tvar_tid'.
8c819921
DS
3012 assignment* a = new assignment;
3013 a->tok = e->tok;
3014 a->op = "=";
a7999c82
JS
3015 a->left = tidsym;
3016 a->right = fc;
8c819921
DS
3017
3018 expr_statement* es = new expr_statement;
3019 es->tok = e->tok;
3020 es->value = a;
8c819921 3021 add_block->statements.push_back (es);
8cc799a5 3022 add_block_tid = true;
a7999c82 3023 }
8c819921 3024
a7999c82
JS
3025 // (2b) Synthesize an array reference and assign it to a
3026 // temporary variable (that we'll use as replacement for the
3027 // target variable reference). It will look like this:
3028 //
3029 // _dwarf_tvar_{name}_{num}_tmp
3030 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3031 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3032
3033 arrayindex* ai_tvar_base = new arrayindex;
3034 ai_tvar_base->tok = e->tok;
3035
3036 symbol* sym = new symbol;
3037 sym->name = aname;
3038 sym->tok = e->tok;
3039 ai_tvar_base->base = sym;
3040
3041 ai_tvar_base->indexes.push_back(tidsym);
3042
3043 // We need to create a copy of the array index in its current
3044 // state so we can have 2 variants of it (the original and one
3045 // that post-decrements the second index).
3046 arrayindex* ai_tvar = new arrayindex;
3047 arrayindex* ai_tvar_postdec = new arrayindex;
3048 *ai_tvar = *ai_tvar_base;
3049 *ai_tvar_postdec = *ai_tvar_base;
3050
3051 // Synthesize the
3052 // "_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]" used as the
3053 // second index into the array.
3054 arrayindex* ai_ctr = new arrayindex;
3055 ai_ctr->tok = e->tok;
3056
3057 sym = new symbol;
3058 sym->name = ctrname;
3059 sym->tok = e->tok;
3060 ai_ctr->base = sym;
3061 ai_ctr->indexes.push_back(tidsym);
3062 ai_tvar->indexes.push_back(ai_ctr);
3063
3064 symbol* tmpsym = new symbol;
3065 tmpsym->name = aname + "_tmp";
3066 tmpsym->tok = e->tok;
3067
3068 assignment* a = new assignment;
3069 a->tok = e->tok;
3070 a->op = "=";
3071 a->left = tmpsym;
3072 a->right = ai_tvar;
3073
3074 expr_statement* es = new expr_statement;
3075 es->tok = e->tok;
3076 es->value = a;
3077
3078 add_block->statements.push_back (es);
3079
3080 // (2c) Add a post-decrement to the second array index and
3081 // delete the array value. It will look like this:
3082 //
3083 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3084 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
3085
3086 post_crement* pc = new post_crement;
3087 pc->tok = e->tok;
3088 pc->op = "--";
3089 pc->operand = ai_ctr;
3090 ai_tvar_postdec->indexes.push_back(pc);
3091
3092 delete_statement* ds = new delete_statement;
3093 ds->tok = e->tok;
3094 ds->value = ai_tvar_postdec;
3095
3096 add_block->statements.push_back (ds);
3097
3098 // (2d) Delete the counter value if it is 0. It will look like
3099 // this:
3100 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
3101 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
3102
3103 ds = new delete_statement;
3104 ds->tok = e->tok;
3105 ds->value = ai_ctr;
3106
3107 unary_expression *ue = new unary_expression;
3108 ue->tok = e->tok;
3109 ue->op = "!";
3110 ue->operand = ai_ctr;
3111
3112 if_statement *ifs = new if_statement;
3113 ifs->tok = e->tok;
3114 ifs->condition = ue;
3115 ifs->thenblock = ds;
3116 ifs->elseblock = NULL;
3117
3118 add_block->statements.push_back (ifs);
3119
3120 // (3) We need an entry probe that saves the value for us in the
3121 // global array we created. Create the entry probe, which will
3122 // look like this:
3123 //
2260f4e3 3124 // probe kernel.function("{function}").call {
a7999c82
JS
3125 // _dwarf_tvar_tid = tid()
3126 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3127 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3128 // = ${param}
3129 // }
3130
2260f4e3 3131 if (add_call_probe == NULL)
a7999c82 3132 {
2260f4e3
FCE
3133 add_call_probe = new block;
3134 add_call_probe->tok = e->tok;
8cc799a5 3135 }
4baf0e53 3136
8cc799a5
JS
3137 if (!add_call_probe_tid)
3138 {
a7999c82
JS
3139 // Synthesize a functioncall to grab the thread id.
3140 functioncall* fc = new functioncall;
3141 fc->tok = e->tok;
3142 fc->function = string("tid");
4baf0e53 3143
a7999c82
JS
3144 // Assign the tid to '_dwarf_tvar_tid'.
3145 assignment* a = new assignment;
8fc05e57
DS
3146 a->tok = e->tok;
3147 a->op = "=";
a7999c82
JS
3148 a->left = tidsym;
3149 a->right = fc;
8fc05e57 3150
a7999c82 3151 expr_statement* es = new expr_statement;
8fc05e57
DS
3152 es->tok = e->tok;
3153 es->value = a;
2260f4e3 3154 add_call_probe = new block(add_call_probe, es);
8cc799a5 3155 add_call_probe_tid = true;
85ecf79a 3156 }
cf2a1f85 3157
a7999c82
JS
3158 // Save the value, like this:
3159 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3160 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3161 // = ${param}
3162 arrayindex* ai_tvar_preinc = new arrayindex;
3163 *ai_tvar_preinc = *ai_tvar_base;
3164
3165 pre_crement* preinc = new pre_crement;
3166 preinc->tok = e->tok;
3167 preinc->op = "++";
3168 preinc->operand = ai_ctr;
3169 ai_tvar_preinc->indexes.push_back(preinc);
3170
3171 a = new assignment;
3172 a->tok = e->tok;
3173 a->op = "=";
3174 a->left = ai_tvar_preinc;
3175 a->right = e;
3176
3177 es = new expr_statement;
3178 es->tok = e->tok;
3179 es->value = a;
3180
2260f4e3 3181 add_call_probe = new block(add_call_probe, es);
a7999c82
JS
3182
3183 // (4) Provide the '_dwarf_tvar_{name}_{num}_tmp' variable to
3184 // our parent so it can be used as a substitute for the target
3185 // symbol.
af234c40
JS
3186 return tmpsym;
3187}
a7999c82 3188
af234c40
JS
3189
3190expression*
140be17a 3191dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3192{
3193 // The code for this is simple.
3194 //
3195 // .call:
3196 // _set_kretprobe_long(index, $value)
3197 //
3198 // .return:
3199 // _get_kretprobe_long(index)
3200 //
3201 // (or s/long/string/ for things like $$parms)
3202
3203 unsigned index;
3204 string setfn, getfn;
3205
140be17a
JS
3206 // We need the caller to predetermine the type of the expression!
3207 switch (e->type)
af234c40 3208 {
140be17a 3209 case pe_string:
af234c40
JS
3210 index = saved_strings++;
3211 setfn = "_set_kretprobe_string";
3212 getfn = "_get_kretprobe_string";
140be17a
JS
3213 break;
3214 case pe_long:
af234c40
JS
3215 index = saved_longs++;
3216 setfn = "_set_kretprobe_long";
3217 getfn = "_get_kretprobe_long";
140be17a
JS
3218 break;
3219 default:
b530b5b3 3220 throw semantic_error(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3221 }
3222
3223 // Create the entry code
3224 // _set_kretprobe_{long|string}(index, $value)
3225
3226 if (add_call_probe == NULL)
3227 {
3228 add_call_probe = new block;
3229 add_call_probe->tok = e->tok;
3230 }
3231
3232 functioncall* set_fc = new functioncall;
3233 set_fc->tok = e->tok;
3234 set_fc->function = setfn;
3235 set_fc->args.push_back(new literal_number(index));
3236 set_fc->args.back()->tok = e->tok;
3237 set_fc->args.push_back(e);
3238
3239 expr_statement* set_es = new expr_statement;
3240 set_es->tok = e->tok;
3241 set_es->value = set_fc;
3242
3243 add_call_probe->statements.push_back(set_es);
3244
3245 // Create the return code
3246 // _get_kretprobe_{long|string}(index)
3247
3248 functioncall* get_fc = new functioncall;
3249 get_fc->tok = e->tok;
3250 get_fc->function = getfn;
3251 get_fc->args.push_back(new literal_number(index));
3252 get_fc->args.back()->tok = e->tok;
3253
3254 return get_fc;
a7999c82 3255}
a43ba433 3256
2cb3fe26 3257
a7999c82
JS
3258void
3259dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3260{
9aa8ffce 3261 if (null_die(scope_die))
a7999c82 3262 return;
2cb3fe26 3263
5f36109e
JS
3264 target_symbol *tsym = new target_symbol(*e);
3265
fde50242
JS
3266 bool pretty = (!e->components.empty() &&
3267 e->components[0].type == target_symbol::comp_pretty_print);
3268 string format = pretty ? "=%s" : "=%#x";
a43ba433 3269
a7999c82
JS
3270 // Convert $$parms to sprintf of a list of parms and active local vars
3271 // which we recursively evaluate
a43ba433 3272
a7999c82
JS
3273 // NB: we synthesize a new token here rather than reusing
3274 // e->tok, because print_format::print likes to use
3275 // its tok->content.
5f36109e 3276 token* pf_tok = new token(*e->tok);
a7999c82 3277 pf_tok->type = tok_identifier;
b393f6f2 3278 pf_tok->content = "sprintf";
2cb3fe26 3279
d5e178c1 3280 print_format* pf = print_format::create(pf_tok);
a7999c82 3281
277c21bc 3282 if (q.has_return && (e->name == "$$return"))
a7999c82 3283 {
277c21bc 3284 tsym->name = "$return";
a7999c82
JS
3285
3286 // Ignore any variable that isn't accessible.
3287 tsym->saved_conversion_error = 0;
3288 expression *texp = tsym;
8b095b45 3289 replace (texp); // NB: throws nothing ...
a7999c82 3290 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3291 {
2cb3fe26 3292
a43ba433
FCE
3293 }
3294 else
3295 {
a7999c82 3296 pf->raw_components += "return";
5f36109e 3297 pf->raw_components += format;
a7999c82
JS
3298 pf->args.push_back(texp);
3299 }
3300 }
3301 else
3302 {
3303 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3304 bool first = true;
a7999c82 3305 Dwarf_Die result;
d48bc7eb
JS
3306 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3307 for (unsigned i = 0; i < scopes.size(); ++i)
3308 {
3309 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3310 break; // we don't want file-level variables
3311 if (dwarf_child (&scopes[i], &result) == 0)
3312 do
00cf3709 3313 {
d48bc7eb
JS
3314 switch (dwarf_tag (&result))
3315 {
3316 case DW_TAG_variable:
3317 if (e->name == "$$parms")
3318 continue;
3319 break;
3320 case DW_TAG_formal_parameter:
3321 if (e->name == "$$locals")
3322 continue;
3323 break;
3324
3325 default:
3326 continue;
3327 }
41c262f3 3328
d48bc7eb
JS
3329 const char *diename = dwarf_diename (&result);
3330 if (! diename) continue;
f76427a2 3331
d48bc7eb
JS
3332 if (! first)
3333 pf->raw_components += " ";
3334 pf->raw_components += diename;
fde50242
JS
3335 first = false;
3336
3337 // Write a placeholder for ugly aggregates
3338 Dwarf_Die type;
3339 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3340 {
3341 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3342 switch (dwarf_tag(&type))
3343 {
3344 case DW_TAG_union_type:
3345 case DW_TAG_structure_type:
3346 case DW_TAG_class_type:
3347 pf->raw_components += "={...}";
3348 continue;
3349
3350 case DW_TAG_array_type:
3351 pf->raw_components += "=[...]";
3352 continue;
3353 }
3354 }
345bbb3d 3355
d48bc7eb
JS
3356 tsym->name = "$";
3357 tsym->name += diename;
41c262f3 3358
d48bc7eb
JS
3359 // Ignore any variable that isn't accessible.
3360 tsym->saved_conversion_error = 0;
3361 expression *texp = tsym;
3362 replace (texp); // NB: throws nothing ...
3363 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3364 {
d48bc7eb
JS
3365 if (q.sess.verbose>2)
3366 {
3367 for (semantic_error *c = tsym->saved_conversion_error;
3368 c != 0;
3369 c = c->chain) {
b530b5b3 3370 clog << _("variable location problem: ") << c->what() << endl;
d48bc7eb
JS
3371 }
3372 }
3373
3374 pf->raw_components += "=?";
a43ba433 3375 }
d48bc7eb
JS
3376 else
3377 {
3378 pf->raw_components += format;
3379 pf->args.push_back(texp);
3380 }
a7999c82 3381 }
d48bc7eb
JS
3382 while (dwarf_siblingof (&result, &result) == 0);
3383 }
a7999c82 3384 }
2cb3fe26 3385
a7999c82 3386 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3387 pf->type = pe_string;
a7999c82
JS
3388 provide (pf);
3389}
3390
2cb3fe26 3391
a7999c82
JS
3392void
3393dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3394{
277c21bc 3395 assert(e->name.size() > 0 && e->name[0] == '$');
a7999c82 3396 visited = true;
30263a73
FCE
3397 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3398 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3399
70208613 3400 try
a7999c82 3401 {
c69a87e0
FCE
3402 bool lvalue = is_active_lvalue(e);
3403 if (lvalue && !q.sess.guru_mode)
b530b5b3 3404 throw semantic_error(_("write to target variable not permitted"), e->tok);
2cb3fe26 3405
c69a87e0 3406 // XXX: process $context vars should be writeable
70208613 3407
c69a87e0
FCE
3408 // See if we need to generate a new probe to save/access function
3409 // parameters from a return probe. PR 1382.
3410 if (q.has_return
3411 && !defined_being_checked
277c21bc
JS
3412 && e->name != "$return" // not the special return-value variable handled below
3413 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3414 {
3415 if (lvalue)
b530b5b3 3416 throw semantic_error(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3417 visit_target_symbol_saved_return(e);
3418 return;
3419 }
e57b735a 3420
277c21bc
JS
3421 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3422 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3423 {
3424 if (lvalue)
b530b5b3 3425 throw semantic_error(_("cannot write to context variable"), e->tok);
70208613 3426
c69a87e0 3427 if (e->addressof)
b530b5b3 3428 throw semantic_error(_("cannot take address of context variable"), e->tok);
70208613 3429
5f36109e
JS
3430 e->assert_no_components("dwarf", true);
3431
c69a87e0
FCE
3432 visit_target_symbol_context(e);
3433 return;
3434 }
70208613 3435
5f36109e
JS
3436 if (!e->components.empty() &&
3437 e->components.back().type == target_symbol::comp_pretty_print)
3438 {
3439 if (lvalue)
b530b5b3 3440 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3441
277c21bc 3442 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3443 {
3444 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3445 q.has_process, *e);
3446 dpp.expand()->visit(this);
3447 }
3448 else
3449 {
3450 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
277c21bc 3451 e->name.substr(1),
5f36109e
JS
3452 q.has_process, *e);
3453 dpp.expand()->visit(this);
3454 }
3455 return;
3456 }
3457
c69a87e0
FCE
3458 // Synthesize a function.
3459 functiondecl *fdecl = new functiondecl;
59de45f1 3460 fdecl->synthetic = true;
c69a87e0
FCE
3461 fdecl->tok = e->tok;
3462 embeddedcode *ec = new embeddedcode;
3463 ec->tok = e->tok;
70208613 3464
c69a87e0 3465 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
277c21bc 3466 + "_" + e->name.substr(1)
c69a87e0 3467 + "_" + lex_cast(tick++));
70208613 3468
b5a0dd41
FCE
3469 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
3470 ec->code += "\n#define fetch_register " + string(q.has_process?"u":"k") + "_fetch_register\n";
3471 ec->code += "#define store_register " + string(q.has_process?"u":"k") + "_store_register\n";
70208613 3472
277c21bc 3473 if (q.has_return && (e->name == "$return"))
e19fda4e 3474 {
b5a0dd41 3475 ec->code += q.dw.literal_stmt_for_return (scope_die,
e19fda4e 3476 addr,
b4c34c26 3477 e,
e19fda4e
DS
3478 lvalue,
3479 fdecl->type);
3480 }
3481 else
3482 {
b5a0dd41 3483 ec->code += q.dw.literal_stmt_for_local (getscopes(e),
e19fda4e 3484 addr,
277c21bc 3485 e->name.substr(1),
b4c34c26 3486 e,
e19fda4e
DS
3487 lvalue,
3488 fdecl->type);
3489 }
3490
1b07c728
FCE
3491 if (! lvalue)
3492 ec->code += "/* pure */";
64211010
DB
3493
3494 ec->code += "/* unprivileged */";
b5a0dd41
FCE
3495
3496 // PR10601
3497 ec->code += "\n#undef fetch_register\n";
3498 ec->code += "\n#undef store_register\n";
c69a87e0
FCE
3499
3500 fdecl->name = fname;
3501 fdecl->body = ec;
70208613 3502
c69a87e0
FCE
3503 // Any non-literal indexes need to be passed in too.
3504 for (unsigned i = 0; i < e->components.size(); ++i)
3505 if (e->components[i].type == target_symbol::comp_expression_array_index)
3506 {
3507 vardecl *v = new vardecl;
3508 v->type = pe_long;
3509 v->name = "index" + lex_cast(i);
3510 v->tok = e->tok;
3511 fdecl->formal_args.push_back(v);
3512 }
70208613 3513
c69a87e0
FCE
3514 if (lvalue)
3515 {
3516 // Modify the fdecl so it carries a single pe_long formal
3517 // argument called "value".
70208613 3518
c69a87e0
FCE
3519 // FIXME: For the time being we only support setting target
3520 // variables which have base types; these are 'pe_long' in
3521 // stap's type vocabulary. Strings and pointers might be
3522 // reasonable, some day, but not today.
70208613 3523
c69a87e0
FCE
3524 vardecl *v = new vardecl;
3525 v->type = pe_long;
3526 v->name = "value";
3527 v->tok = e->tok;
3528 fdecl->formal_args.push_back(v);
3529 }
f8809d54 3530 fdecl->join (q.sess);
70208613 3531
c69a87e0
FCE
3532 // Synthesize a functioncall.
3533 functioncall* n = new functioncall;
3534 n->tok = e->tok;
3535 n->function = fname;
140be17a 3536 n->type = fdecl->type;
70208613 3537
c69a87e0
FCE
3538 // Any non-literal indexes need to be passed in too.
3539 for (unsigned i = 0; i < e->components.size(); ++i)
3540 if (e->components[i].type == target_symbol::comp_expression_array_index)
3541 n->args.push_back(require(e->components[i].expr_index));
70208613 3542
c69a87e0
FCE
3543 if (lvalue)
3544 {
3545 // Provide the functioncall to our parent, so that it can be
3546 // used to substitute for the assignment node immediately above
3547 // us.
3548 assert(!target_symbol_setter_functioncalls.empty());
3549 *(target_symbol_setter_functioncalls.top()) = n;
3550 }
70208613 3551
c69a87e0 3552 provide (n);
66d284f4
FCE
3553 }
3554 catch (const semantic_error& er)
3555 {
9fab2262
JS
3556 // We suppress this error message, and pass the unresolved
3557 // target_symbol to the next pass. We hope that this value ends
3558 // up not being referenced after all, so it can be optimized out
3559 // quietly.
1af1e62d 3560 e->chain (er);
9fab2262 3561 provide (e);
66d284f4 3562 }
77de5e9e
GH
3563}
3564
3565
c24447be
JS
3566void
3567dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3568{
3569 // Fill in our current module context if needed
3570 if (e->module.empty())
3571 e->module = q.dw.module_name;
3572
3573 var_expanding_visitor::visit_cast_op(e);
3574}
3575
3576
8cc799a5
JS
3577void
3578dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3579{
3580 expression *repl = e;
3581 if (q.has_return)
3582 {
3583 // expand the operand as if it weren't a return probe
3584 q.has_return = false;
3585 replace (e->operand);
3586 q.has_return = true;
3587
3588 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3589 // but it requires knowing the types already, which is problematic for
3590 // arbitrary expressons.
3591 repl = gen_mapped_saved_return (e->operand, "@entry");
3592 }
3593 provide (repl);
3594}
3595
3596
729455a7
JS
3597vector<Dwarf_Die>&
3598dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3599{
3600 if (scopes.empty())
3601 {
f5958c8f 3602 scopes = q.dw.getscopes(scope_die);
729455a7 3603 if (scopes.empty())
b530b5b3
LB
3604 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3605 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
729455a7
JS
3606 throw semantic_error ("unable to find any scopes containing "
3607 + lex_cast_hex(addr)
3608 + ((scope_die == NULL) ? ""
3609 : (string (" in ")
3610 + (dwarf_diename(scope_die) ?: "<unknown>")
3611 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3612 + ")"))
3613 + " while searching for local '"
277c21bc 3614 + e->name.substr(1) + "'",
729455a7
JS
3615 e->tok);
3616 }
3617 return scopes;
3618}
3619
3620
5f36109e
JS
3621struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3622{
3623 systemtap_session& s;
3624 dwarf_builder& db;
3625
3626 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3627 s(s), db(db) {}
3628 void visit_cast_op (cast_op* e);
3629 void filter_special_modules(string& module);
3630};
3631
3632
c4ce66a1
JS
3633struct dwarf_cast_query : public base_query
3634{
946e1a48 3635 cast_op& e;
c4ce66a1 3636 const bool lvalue;
5f36109e
JS
3637 const bool userspace_p;
3638 functioncall*& result;
c4ce66a1 3639
5f36109e
JS
3640 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3641 const bool userspace_p, functioncall*& result):
abb41d92 3642 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3643 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3644
3645 void handle_query_module();
822a6a3d 3646 void query_library (const char *) {}
576eaefe 3647 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3648};
3649
3650
c4ce66a1
JS
3651void
3652dwarf_cast_query::handle_query_module()
3653{
5f36109e
JS
3654 static unsigned tick = 0;
3655
3656 if (result)
c4ce66a1
JS
3657 return;
3658
ea1e477a 3659 // look for the type in any CU
a44a7cb5
JS
3660 Dwarf_Die* type_die = NULL;
3661 if (startswith(e.type_name, "class "))
3662 {
3663 // normalize to match dwflpp::global_alias_caching_callback
3664 string struct_name = "struct " + e.type_name.substr(6);
3665 type_die = dw.declaration_resolve_other_cus(struct_name);
3666 }
3667 else
3668 type_die = dw.declaration_resolve_other_cus(e.type_name);
3669
3670 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3671 // just "name". But since we didn't require users to be explicit before, and
3672 // actually sort of discouraged it, we must be flexible now. So if a lookup
3673 // fails with a bare name, try augmenting it.
3674 if (!type_die &&
3675 !startswith(e.type_name, "class ") &&
3676 !startswith(e.type_name, "struct ") &&
3677 !startswith(e.type_name, "union ") &&
3678 !startswith(e.type_name, "enum "))
3679 {
3680 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3681 if (!type_die)
3682 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3683 if (!type_die)
3684 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3685 }
3686
ea1e477a
JS
3687 if (!type_die)
3688 return;
c4ce66a1 3689
5f36109e
JS
3690 string code;
3691 exp_type type = pe_long;
3692
ea1e477a 3693 try
c4ce66a1 3694 {
ea1e477a
JS
3695 Dwarf_Die cu_mem;
3696 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
3697
3698 if (!e.components.empty() &&
3699 e.components.back().type == target_symbol::comp_pretty_print)
3700 {
3701 if (lvalue)
b530b5b3 3702 throw semantic_error(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 3703
d19a9a82 3704 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
3705 result = dpp.expand();
3706 return;
3707 }
3708
3709 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
3710 }
3711 catch (const semantic_error& er)
3712 {
3713 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
3714 // may be attempted using several different modules:
3715 // @cast(ptr, "type", "module1:module2:...")
3716 e.chain (er);
c4ce66a1 3717 }
c4ce66a1 3718
5f36109e
JS
3719 if (code.empty())
3720 return;
c4ce66a1 3721
5f36109e 3722 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
277c21bc 3723 + "_" + e.name.substr(1)
5f36109e 3724 + "_" + lex_cast(tick++));
c4ce66a1 3725
5f36109e
JS
3726 // Synthesize a function.
3727 functiondecl *fdecl = new functiondecl;
3728 fdecl->synthetic = true;
3729 fdecl->tok = e.tok;
3730 fdecl->type = type;
3731 fdecl->name = fname;
3732
3733 embeddedcode *ec = new embeddedcode;
3734 ec->tok = e.tok;
3735 fdecl->body = ec;
3736
3737 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
3738 ec->code += "\n#define fetch_register " + string(userspace_p?"u":"k") + "_fetch_register\n";
3739 ec->code += "#define store_register " + string(userspace_p?"u":"k") + "_store_register\n";
3740
3741 ec->code += code;
3742
3743 // Give the fdecl an argument for the pointer we're trying to cast
3744 vardecl *v1 = new vardecl;
3745 v1->type = pe_long;
3746 v1->name = "pointer";
3747 v1->tok = e.tok;
3748 fdecl->formal_args.push_back(v1);
3749
3750 // Any non-literal indexes need to be passed in too.
3751 for (unsigned i = 0; i < e.components.size(); ++i)
3752 if (e.components[i].type == target_symbol::comp_expression_array_index)
3753 {
3754 vardecl *v = new vardecl;
3755 v->type = pe_long;
3756 v->name = "index" + lex_cast(i);
3757 v->tok = e.tok;
3758 fdecl->formal_args.push_back(v);
3759 }
3760
3761 if (lvalue)
3762 {
3763 // Modify the fdecl so it carries a second pe_long formal
3764 // argument called "value".
3765
3766 // FIXME: For the time being we only support setting target
3767 // variables which have base types; these are 'pe_long' in
3768 // stap's type vocabulary. Strings and pointers might be
3769 // reasonable, some day, but not today.
3770
3771 vardecl *v2 = new vardecl;
3772 v2->type = pe_long;
3773 v2->name = "value";
3774 v2->tok = e.tok;
3775 fdecl->formal_args.push_back(v2);
3776 }
3777 else
3778 ec->code += "/* pure */";
3779
3780 ec->code += "/* unprivileged */";
3781
3782 // PR10601
3783 ec->code += "\n#undef fetch_register\n";
3784 ec->code += "\n#undef store_register\n";
3785
f8809d54 3786 fdecl->join (dw.sess);
5f36109e
JS
3787
3788 // Synthesize a functioncall.
3789 functioncall* n = new functioncall;
3790 n->tok = e.tok;
3791 n->function = fname;
5f36109e
JS
3792 n->args.push_back(e.operand);
3793
3794 // Any non-literal indexes need to be passed in too.
3795 for (unsigned i = 0; i < e.components.size(); ++i)
3796 if (e.components[i].type == target_symbol::comp_expression_array_index)
3797 n->args.push_back(e.components[i].expr_index);
3798
3799 result = n;
3800}
c4ce66a1
JS
3801
3802
fb0274bc
JS
3803void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
3804{
d90053e7 3805 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 3806 // for those cases, build a module including that header
d90053e7 3807 if (module[module.size() - 1] == '>' &&
60d98537 3808 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
3809 {
3810 string cached_module;
3811 if (s.use_cache)
3812 {
3813 // see if the cached module exists
a2639cb7 3814 cached_module = find_typequery_hash(s, module);
d105f664 3815 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
3816 {
3817 int fd = open(cached_module.c_str(), O_RDONLY);
3818 if (fd != -1)
3819 {
3820 if (s.verbose > 2)
b530b5b3
LB
3821 //TRANSLATORS: Here we're using a cached module.
3822 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
3823 module = cached_module;
3824 close(fd);
3825 return;
3826 }
3827 }
3828 }
3829
3830 // no cached module, time to make it
d90053e7 3831 if (make_typequery(s, module) == 0)
fb0274bc 3832 {
e16dc041 3833 // try to save typequery in the cache
fb0274bc 3834 if (s.use_cache)
e16dc041 3835 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
3836 }
3837 }
3838}
3839
3840
c4ce66a1
JS
3841void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
3842{
3843 bool lvalue = is_active_lvalue(e);
3844 if (lvalue && !s.guru_mode)
ce0f6648 3845 throw semantic_error(_("write to @cast context variable not permitted"), e->tok);
c4ce66a1
JS
3846
3847 if (e->module.empty())
3848 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
3849
5f36109e 3850 functioncall* result = NULL;
8b31197b
JS
3851
3852 // split the module string by ':' for alternatives
3853 vector<string> modules;
3854 tokenize(e->module, modules, ":");
b5a0dd41 3855 bool userspace_p=false; // PR10601
5f36109e 3856 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 3857 {
8b31197b 3858 string& module = modules[i];
fb0274bc 3859 filter_special_modules(module);
abb41d92 3860
c4ce66a1
JS
3861 // NB: This uses '/' to distinguish between kernel modules and userspace,
3862 // which means that userspace modules won't get any PATH searching.
3863 dwflpp* dw;
707bf35e
JS
3864 try
3865 {
b5a0dd41
FCE
3866 userspace_p=is_user_module (module);
3867 if (! userspace_p)
707bf35e
JS
3868 {
3869 // kernel or kernel module target
ae2552da 3870 dw = db.get_kern_dw(s, module);
707bf35e
JS
3871 }
3872 else
3873 {
3874 module = find_executable (module); // canonicalize it
3875 dw = db.get_user_dw(s, module);
3876 }
3877 }
3878 catch (const semantic_error& er)
3879 {
3880 /* ignore and go to the next module */
3881 continue;
3882 }
c4ce66a1 3883
5f36109e 3884 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 3885 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 3886 }
abb41d92 3887
5f36109e 3888 if (!result)
c4ce66a1 3889 {
946e1a48
JS
3890 // We pass the unresolved cast_op to the next pass, and hope
3891 // that this value ends up not being referenced after all, so
3892 // it can be optimized out quietly.
c4ce66a1
JS
3893 provide (e);
3894 return;
3895 }
3896
c4ce66a1
JS
3897 if (lvalue)
3898 {
3899 // Provide the functioncall to our parent, so that it can be
3900 // used to substitute for the assignment node immediately above
3901 // us.
3902 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 3903 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
3904 }
3905
5f36109e 3906 result->visit (this);
77de5e9e
GH
3907}
3908
3909
b8da0ad1
FCE
3910void
3911dwarf_derived_probe::printsig (ostream& o) const
3912{
3913 // Instead of just printing the plain locations, we add a PC value
3914 // as a comment as a way of telling e.g. apart multiple inlined
3915 // function instances. This is distinct from the verbose/clog
3916 // output, since this part goes into the cache hash calculations.
3917 sole_location()->print (o);
6d0f3f0c 3918 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
3919 printsig_nested (o);
3920}
3921
3922
3923
dc38c0ae 3924void
b20febf3
FCE
3925dwarf_derived_probe::join_group (systemtap_session& s)
3926{
af234c40
JS
3927 // skip probes which are paired entry-handlers
3928 if (!has_return && (saved_longs || saved_strings))
3929 return;
3930
b20febf3
FCE
3931 if (! s.dwarf_derived_probes)
3932 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
3933 s.dwarf_derived_probes->enroll (this);
b642c901 3934
62f52bb0
JS
3935 if (sdt_semaphore_addr != 0)
3936 enable_task_finder(s);
b20febf3
FCE
3937}
3938
3939
3940dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
3941 const string& filename,
3942 int line,
91af0778 3943 // module & section specify a relocation
b20febf3
FCE
3944 // base for <addr>, unless section==""
3945 // (equivalently module=="kernel")
3946 const string& module,
3947 const string& section,
3948 // NB: dwfl_addr is the virtualized
3949 // address for this symbol.
3950 Dwarf_Addr dwfl_addr,
3951 // addr is the section-offset for
3952 // actual relocation.
3953 Dwarf_Addr addr,
3954 dwarf_query& q,
37ebca01 3955 Dwarf_Die* scope_die /* may be null */)
4c5d1300 3956 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 3957 module (module), section (section), addr (addr),
63b4fd14 3958 path (q.path),
27dc09b1 3959 has_process (q.has_process),
c9bad430
DS
3960 has_return (q.has_return),
3961 has_maxactive (q.has_maxactive),
c57ea854 3962 has_library (q.has_library),
6b66b9f7 3963 maxactive_val (q.maxactive_val),
b642c901
SC
3964 user_path (q.user_path),
3965 user_lib (q.user_lib),
af234c40 3966 access_vars(false),
c57ea854 3967 saved_longs(0), saved_strings(0),
af234c40 3968 entry_handler(0)
bd2b1e68 3969{
b642c901
SC
3970 if (user_lib.size() != 0)
3971 has_library = true;
3972
6b66b9f7
JS
3973 if (q.has_process)
3974 {
3975 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
3976 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
3977 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
3978 // by the incoming section value (".absolute" vs. ".dynamic").
3979 // XXX Assert invariants here too?
3980 }
3981 else
3982 {
3983 // Assert kernel relocation invariants
3984 if (section == "" && dwfl_addr != addr) // addr should be absolute
ce0f6648 3985 throw semantic_error (_("missing relocation basis"), tok);
6b66b9f7 3986 if (section != "" && dwfl_addr == addr) // addr should be an offset
b530b5b3 3987 throw semantic_error (_("inconsistent relocation address"), tok);
6b66b9f7 3988 }
2930abc7 3989
21beacc9
FCE
3990 // XXX: hack for strange g++/gcc's
3991#ifndef USHRT_MAX
3992#define USHRT_MAX 32767
3993#endif
3994
606fd9c8 3995 // Range limit maxactive() value
6b66b9f7 3996 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
b530b5b3
LB
3997 throw semantic_error (_F("maxactive value out of range [0,%s]",
3998 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 3999
de688825 4000 // Expand target variables in the probe body
5f0a03a6 4001 if (!null_die(scope_die))
8fc05e57 4002 {
6b66b9f7 4003 // XXX: user-space deref's for q.has_process!
de688825 4004 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4005 v.replace (this->body);
6b66b9f7
JS
4006 if (!q.has_process)
4007 access_vars = v.visited;
37ebca01
FCE
4008
4009 // If during target-variable-expanding the probe, we added a new block
4010 // of code, add it to the start of the probe.
4011 if (v.add_block)
ba6f838d 4012 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4013
4014 // If when target-variable-expanding the probe, we need to synthesize a
4015 // sibling function-entry probe. We don't go through the whole probe derivation
4016 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4017 // dwarf-induced duplication.
4018 if (v.add_call_probe)
37ebca01 4019 {
2260f4e3
FCE
4020 assert (q.has_return && !q.has_call);
4021
4022 // We temporarily replace q.base_probe.
4023 statement* old_body = q.base_probe->body;
4024 q.base_probe->body = v.add_call_probe;
4025 q.has_return = false;
4026 q.has_call = true;
af234c40 4027
da23eceb 4028 if (q.has_process)
af234c40
JS
4029 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4030 module, section, dwfl_addr,
4031 addr, q, scope_die);
da23eceb 4032 else
af234c40
JS
4033 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4034 module, section, dwfl_addr,
4035 addr, q, scope_die);
4036
4037 saved_longs = entry_handler->saved_longs = v.saved_longs;
4038 saved_strings = entry_handler->saved_strings = v.saved_strings;
4039
4040 q.results.push_back (entry_handler);
2260f4e3
FCE
4041
4042 q.has_return = true;
4043 q.has_call = false;
4044 q.base_probe->body = old_body;
37ebca01 4045 }
f10534c6
WH
4046 // Save the local variables for listing mode
4047 if (q.sess.listing_mode_vars)
8c67c337 4048 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4049 }
37ebca01 4050 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4051
f10534c6 4052 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4053
5d23847d 4054 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4055 // "reverse-engineered" form of the incoming (q.base_loc) probe
4056 // point. This allows a user to see what function / file / line
4057 // number any particular match of the wildcards.
2930abc7 4058
a229fcd7 4059 vector<probe_point::component*> comps;
91af0778
FCE
4060 if (q.has_kernel)
4061 comps.push_back (new probe_point::component(TOK_KERNEL));
4062 else if(q.has_module)
4063 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4064 else if(q.has_process)
4065 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4066 else
4067 assert (0);
b5d77020 4068
db520b00
FCE
4069 string fn_or_stmt;
4070 if (q.has_function_str || q.has_function_num)
4071 fn_or_stmt = "function";
4072 else
4073 fn_or_stmt = "statement";
a229fcd7 4074
b8da0ad1 4075 if (q.has_function_str || q.has_statement_str)
db520b00 4076 {
4cd232e4 4077 string retro_name = funcname;
b20febf3 4078 if (filename != "")
cee35f73 4079 {
fb84c077 4080 retro_name += ("@" + string (filename));
cee35f73 4081 if (line > 0)
aca66a36 4082 retro_name += (":" + lex_cast (line));
cee35f73 4083 }
db520b00
FCE
4084 comps.push_back
4085 (new probe_point::component
4086 (fn_or_stmt, new literal_string (retro_name)));
4087 }
b8da0ad1 4088 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4089 {
4090 Dwarf_Addr retro_addr;
4091 if (q.has_function_num)
4092 retro_addr = q.function_num_val;
4093 else
4094 retro_addr = q.statement_num_val;
db520b00
FCE
4095 comps.push_back (new probe_point::component
4096 (fn_or_stmt,
9ea68eb9 4097 new literal_number(retro_addr, true)));
37ebca01
FCE
4098
4099 if (q.has_absolute)
4100 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4101 }
4102
b8da0ad1
FCE
4103 if (q.has_call)
4104 comps.push_back (new probe_point::component(TOK_CALL));
4105 if (q.has_inline)
4106 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4107 if (has_return)
b8da0ad1
FCE
4108 comps.push_back (new probe_point::component(TOK_RETURN));
4109 if (has_maxactive)
4110 comps.push_back (new probe_point::component
4111 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4112
5d23847d
FCE
4113 // Overwrite it.
4114 this->sole_location()->components = comps;
2930abc7
FCE
4115}
4116
bd2b1e68 4117
0a98fd42 4118void
8c67c337
JS
4119dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4120 Dwarf_Addr dwfl_addr)
0a98fd42 4121{
9aa8ffce 4122 if (null_die(scope_die))
0a98fd42 4123 return;
0a98fd42 4124
8c67c337 4125 bool verbose = q.sess.verbose > 2;
0a98fd42 4126
8c67c337 4127 if (verbose)
b530b5b3 4128 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4129
8c67c337
JS
4130 if (has_return)
4131 {
4132 /* Only save the return value if it has a type. */
4133 string type_name;
4134 Dwarf_Die type_die;
4135 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4136 dwarf_type_name(&type_die, type_name))
4137 args.push_back("$return:"+type_name);
4138
4139 else if (verbose)
b530b5b3
LB
4140 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4141 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4142 }
d87623a1 4143
0a98fd42 4144 Dwarf_Die arg;
4ef35696
JS
4145 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4146 for (unsigned i = 0; i < scopes.size(); ++i)
4147 {
4148 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4149 break; // we don't want file-level variables
4150 if (dwarf_child (&scopes[i], &arg) == 0)
4151 do
0a98fd42 4152 {
4ef35696
JS
4153 switch (dwarf_tag (&arg))
4154 {
4155 case DW_TAG_variable:
4156 case DW_TAG_formal_parameter:
4157 break;
0a98fd42 4158
4ef35696
JS
4159 default:
4160 continue;
4161 }
0a98fd42 4162
4ef35696
JS
4163 /* Ignore this local if it has no name. */
4164 const char *arg_name = dwarf_diename (&arg);
4165 if (!arg_name)
8c67c337
JS
4166 {
4167 if (verbose)
b530b5b3
LB
4168 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4169 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4170 continue;
4171 }
4ef35696
JS
4172
4173 if (verbose)
b530b5b3
LB
4174 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4175 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4176
4177 /* Ignore this local if it has no location (or not at this PC). */
4178 /* NB: It still may not be directly accessible, e.g. if it is an
4179 * aggregate type, implicit_pointer, etc., but the user can later
4180 * figure out how to access the interesting parts. */
4181 Dwarf_Attribute attr_mem;
4182 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4183 {
4184 Dwarf_Op *expr;
4185 size_t len;
4186 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4187 {
4188 if (verbose)
b530b5b3
LB
4189 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4190 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4191 continue;
4192 }
4193 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4194 &len, 1) == 1 && len > 0))
4195 {
4196 if (verbose)
b530b5b3
LB
4197 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4198 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4ef35696
JS
4199 continue;
4200 }
4201 }
4202
4203 /* Ignore this local if it has no type. */
4204 string type_name;
4205 Dwarf_Die type_die;
4206 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4207 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4208 {
4209 if (verbose)
b530b5b3
LB
4210 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4211 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4212 continue;
4213 }
8c67c337 4214
4ef35696
JS
4215 /* This local looks good -- save it! */
4216 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4217 }
4ef35696
JS
4218 while (dwarf_siblingof (&arg, &arg) == 0);
4219 }
0a98fd42
JS
4220}
4221
4222
4223void
d0bfd2ac 4224dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4225{
d0bfd2ac 4226 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4227}
4228
4229
27dc09b1
DB
4230void
4231dwarf_derived_probe::emit_unprivileged_assertion (translator_output* o)
4232{
4233 if (has_process)
4234 {
4235 // These probes are allowed for unprivileged users, but only in the
4236 // context of processes which they own.
4237 emit_process_owner_assertion (o);
4238 return;
4239 }
4240
4241 // Other probes must contain the default assertion which aborts
4242 // if executed by an unprivileged user.
4243 derived_probe::emit_unprivileged_assertion (o);
4244}
4245
4246
4247void
4248dwarf_derived_probe::print_dupe_stamp(ostream& o)
4249{
4250 if (has_process)
4251 {
4252 // These probes are allowed for unprivileged users, but only in the
4253 // context of processes which they own.
4254 print_dupe_stamp_unprivileged_process_owner (o);
4255 return;
4256 }
4257
4258 // Other probes must contain the default dupe stamp
4259 derived_probe::print_dupe_stamp (o);
4260}
4261
64211010 4262
7a053d3b 4263void
20c6c071 4264dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1
DB
4265 dwarf_builder * dw,
4266 bool bind_unprivileged_p)
bd2b1e68 4267{
27dc09b1
DB
4268 root
4269 ->bind_unprivileged(bind_unprivileged_p)
4270 ->bind(dw);
54efe513
GH
4271}
4272
7a053d3b 4273void
fd6602a0 4274dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1
DB
4275 dwarf_builder * dw,
4276 bool bind_unprivileged_p)
2865d17a 4277{
27dc09b1
DB
4278 root
4279 ->bind_unprivileged(bind_unprivileged_p)
4280 ->bind(dw);
27dc09b1
DB
4281 root->bind(TOK_CALL)
4282 ->bind_unprivileged(bind_unprivileged_p)
4283 ->bind(dw);
4284 root->bind(TOK_RETURN)
4285 ->bind_unprivileged(bind_unprivileged_p)
4286 ->bind(dw);
1e035395
FCE
4287
4288 if (! bind_unprivileged_p) /* for process probes / uprobes, .maxactive() is unused. */
4289 {
4290 root->bind(TOK_RETURN)
4291 ->bind_unprivileged(bind_unprivileged_p)
4292 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4293 }
bd2b1e68
GH
4294}
4295
7a053d3b 4296void
27dc09b1 4297dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4298 systemtap_session& s,
27dc09b1
DB
4299 match_node * root,
4300 dwarf_builder * dw,
4301 bool bind_unprivileged_p
4302)
bd2b1e68
GH
4303{
4304 // Here we match 4 forms:
4305 //
4306 // .function("foo")
4307 // .function(0xdeadbeef)
4308 // .statement("foo")
4309 // .statement(0xdeadbeef)
4310
440d9b00
DB
4311 match_node *fv_root = root->bind_str(TOK_FUNCTION);
4312 register_function_variants(fv_root, dw, bind_unprivileged_p);
4313 // ROOT.function("STRING") always gets the .inline variant.
4314 fv_root->bind(TOK_INLINE)
4315 ->bind_unprivileged(bind_unprivileged_p)
4316 ->bind(dw);
4317
4318 fv_root = root->bind_num(TOK_FUNCTION);
4319 register_function_variants(fv_root, dw, bind_unprivileged_p);
4320 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4321 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4322 {
4323 fv_root->bind(TOK_INLINE)
4324 ->bind_unprivileged(bind_unprivileged_p)
4325 ->bind(dw);
4326 }
4327
27dc09b1
DB
4328 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, bind_unprivileged_p);
4329 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, bind_unprivileged_p);
bd2b1e68
GH
4330}
4331
4332void
c4ce66a1 4333dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4334{
c4ce66a1 4335 match_node* root = s.pattern_root;
bd2b1e68
GH
4336 dwarf_builder *dw = new dwarf_builder();
4337
c4ce66a1
JS
4338 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4339 s.code_filters.push_back(filter);
4340
440d9b00
DB
4341 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, false);
4342 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, false);
27dc09b1
DB
4343
4344 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4345 ->bind(dw);
4346 root->bind(TOK_KERNEL)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4347 ->bind(dw);
d2c9ec9b 4348
2cab6244
JS
4349 root->bind_str(TOK_MODULE)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4350 ->bind(dw);
4351
440d9b00
DB
4352 register_function_and_statement_variants(s, root->bind_str(TOK_PROCESS), dw, true);
4353 register_function_and_statement_variants(s, root->bind(TOK_PROCESS), dw, true);
4354 register_function_and_statement_variants(s, root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY), dw, true);
4355 register_function_and_statement_variants(s, root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY), dw, true);
4ad95bbc 4356
d2c9ec9b 4357 root->bind_str(TOK_PROCESS)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
27dc09b1 4358 ->bind_unprivileged()
d2c9ec9b 4359 ->bind(dw);
6d5d594e
LB
4360 root->bind(TOK_PROCESS)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4361 ->bind_unprivileged()
4362 ->bind(dw);
63b4fd14 4363 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_MARK)
27dc09b1 4364 ->bind_unprivileged()
63b4fd14 4365 ->bind(dw);
6d5d594e
LB
4366 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_MARK)
4367 ->bind_unprivileged()
4368 ->bind(dw);
a794dbeb
FCE
4369 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4370 ->bind_unprivileged()
4371 ->bind(dw);
6d5d594e
LB
4372 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4373 ->bind_unprivileged()
4374 ->bind(dw);
d2c9ec9b 4375 root->bind_str(TOK_PROCESS)->bind_str(TOK_MARK)
27dc09b1 4376 ->bind_unprivileged()
d2c9ec9b 4377 ->bind(dw);
6d5d594e
LB
4378 root->bind(TOK_PROCESS)->bind_str(TOK_MARK)
4379 ->bind_unprivileged()
4380 ->bind(dw);
a794dbeb
FCE
4381 root->bind_str(TOK_PROCESS)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4382 ->bind_unprivileged()
4383 ->bind(dw);
576eaefe
SC
4384 root->bind_str(TOK_PROCESS)->bind(TOK_PLT)
4385 ->bind_unprivileged()
4386 ->bind(dw);
4387 root->bind_str(TOK_PROCESS)->bind_str(TOK_PLT)
4388 ->bind_unprivileged()
4389 ->bind(dw);
3d372d6b
SC
4390 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind(TOK_PLT)
4391 ->bind_unprivileged()
4392 ->bind(dw);
4393 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PLT)
4394 ->bind_unprivileged()
4395 ->bind(dw);
576eaefe
SC
4396 root->bind_str(TOK_PROCESS)->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
4397 ->bind_unprivileged()
4398 ->bind(dw);
4399 root->bind_str(TOK_PROCESS)->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
4400 ->bind_unprivileged()
4401 ->bind(dw);
3d372d6b
SC
4402 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
4403 ->bind_unprivileged()
4404 ->bind(dw);
4405 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
4406 ->bind_unprivileged()
4407 ->bind(dw);
bd2b1e68
GH
4408}
4409
9020300d
FCE
4410void
4411dwarf_derived_probe::emit_probe_local_init(translator_output * o)
4412{
b95e2b79
MH
4413 if (access_vars)
4414 {
4415 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4416 o->newline() << "#if defined __ia64__";
d9aed31e 4417 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4418 o->newline() << "#endif";
b95e2b79 4419 }
9020300d 4420}
2930abc7 4421
b20febf3 4422// ------------------------------------------------------------------------
46b84a80
DS
4423
4424void
b20febf3 4425dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4426{
62f52bb0
JS
4427 if (p->sdt_semaphore_addr != 0)
4428 has_semaphores = true;
b20febf3 4429 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4430
4431 // XXX: probes put at the same address should all share a
4432 // single kprobe/kretprobe, and have their handlers executed
4433 // sequentially.
b55bc428
FCE
4434}
4435
7a053d3b 4436void
775d51e5 4437dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4438{
b20febf3 4439 if (probes_by_module.empty()) return;
2930abc7 4440
775d51e5
DS
4441 s.op->newline() << "/* ---- dwarf probes ---- */";
4442
4443 // Warn of misconfigured kernels
f41595cc
FCE
4444 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4445 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4446 s.op->newline() << "#endif";
775d51e5 4447 s.op->newline();
f41595cc 4448
f07c3b68 4449 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4450 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4451 s.op->newline() << "#endif";
4452
14cf7e42
SC
4453 // Forward decls
4454 s.op->newline() << "#include \"kprobes-common.h\"";
4455
b20febf3
FCE
4456 // Forward declare the master entry functions
4457 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4458 s.op->line() << " struct pt_regs *regs);";
4459 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4460 s.op->line() << " struct pt_regs *regs);";
4461
42cb22bd
MH
4462 // Emit an array of kprobe/kretprobe pointers
4463 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4464 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4465 s.op->newline() << "#endif";
4466
b20febf3 4467 // Emit the actual probe list.
606fd9c8
FCE
4468
4469 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4470 // struct stap_dwarf_probe, but it being initialized data makes it add
4471 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4472 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4473 // NB: bss!
4474
4c2732a1 4475 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4476 s.op->newline(1) << "const unsigned return_p:1;";
4477 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4478 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4479 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4480 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4481
af234c40
JS
4482 // data saved in the kretprobe_instance packet
4483 s.op->newline() << "const unsigned short saved_longs;";
4484 s.op->newline() << "const unsigned short saved_strings;";
4485
faea5e16 4486 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
4487 // are small and uniform enough to justify putting char[MAX]'s into
4488 // the array instead of relocated char*'s.
faea5e16
JS
4489 size_t module_name_max = 0, section_name_max = 0;
4490 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
4491 size_t all_name_cnt = probes_by_module.size(); // for average
4492 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
4493 {
4494 dwarf_derived_probe* p = it->second;
4495#define DOIT(var,expr) do { \
4496 size_t var##_size = (expr) + 1; \
4497 var##_max = max (var##_max, var##_size); \
4498 var##_tot += var##_size; } while (0)
4499 DOIT(module_name, p->module.size());
4500 DOIT(section_name, p->section.size());
606fd9c8
FCE
4501#undef DOIT
4502 }
4503
4504 // Decide whether it's worthwhile to use char[] or char* by comparing
4505 // the amount of average waste (max - avg) to the relocation data size
4506 // (3 native long words).
4507#define CALCIT(var) \
4508 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
4509 { \
4510 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
4511 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
4512 << "[" << var##_name_max << "]" << endl; \
4513 } \
4514 else \
4515 { \
b0986e7a 4516 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
4517 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
4518 }
4519
4520 CALCIT(module);
4521 CALCIT(section);
e6fe60e7 4522#undef CALCIT
606fd9c8 4523
b0986e7a 4524 s.op->newline() << "const unsigned long address;";
26e63673 4525 s.op->newline() << "struct stap_probe * const probe;";
c87ae2c1 4526 s.op->newline() << "struct stap_probe * const entry_probe;";
62f52bb0
JS
4527 if (has_semaphores)
4528 {
4529 s.op->newline() << "const unsigned long sdt_sem_offset;";
4530 s.op->newline() << "unsigned long sdt_sem_address;";
4531 s.op->newline() << "struct task_struct *tsk;";
4532 s.op->newline() << "const char *pathname;";
4533 s.op->newline() << "struct stap_task_finder_target finder;";
4534 }
b20febf3
FCE
4535 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
4536 s.op->indent(1);
4537
4538 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 4539 {
b20febf3
FCE
4540 dwarf_derived_probe* p = it->second;
4541 s.op->newline() << "{";
4542 if (p->has_return)
4543 s.op->line() << " .return_p=1,";
c9bad430 4544 if (p->has_maxactive)
606fd9c8
FCE
4545 {
4546 s.op->line() << " .maxactive_p=1,";
4547 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
4548 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
4549 }
af234c40
JS
4550 if (p->saved_longs || p->saved_strings)
4551 {
4552 if (p->saved_longs)
4553 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
4554 if (p->saved_strings)
4555 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
4556 if (p->entry_handler)
c87ae2c1 4557 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 4558 }
b350f56b
JS
4559 if (p->locations[0]->optional)
4560 s.op->line() << " .optional_p=1,";
dc38c256 4561 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
4562 s.op->line() << " .module=\"" << p->module << "\",";
4563 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 4564 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b642c901
SC
4565 if (p->sdt_semaphore_addr != 0)
4566 {
4567 s.op->line() << " .sdt_sem_offset=(unsigned long)0x" << hex << p->sdt_semaphore_addr << dec << "ULL,";
4568 s.op->line() << " .sdt_sem_address=0,";
4569 if (p->has_library)
4570 {
4571 s.op->line() << " .finder={";
4572 s.op->line() << " .pid=0,";
4573 s.op->line() << " .procname=\"" << p->user_path << "\",";
4574 s.op->line() << " .mmap_callback=&stap_kprobe_mmap_found,";
4575 s.op->line() << " },";
4576 s.op->line() << " .pathname=\"" << p->user_lib << "\",";
4577 }
4578 else
4579 {
4580 s.op->line() << " .finder={";
4581 s.op->line() << " .pid=0,";
4582 s.op->line() << " .procname=\"" << p->user_path << "\",";
4583 s.op->line() << " .callback=&stap_kprobe_process_found,";
4584 s.op->line() << " },";
4585 s.op->line() << " .pathname=\"" << p->user_path << "\",";
4586 }
4587
4588 }
b642c901 4589
b20febf3 4590 s.op->line() << " },";
2930abc7 4591 }
2930abc7 4592
b20febf3
FCE
4593 s.op->newline(-1) << "};";
4594
4595 // Emit the kprobes callback function
4596 s.op->newline();
4597 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4598 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
4599 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
4600 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
4601 // Check that the index is plausible
4602 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4603 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4604 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4605 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4606 s.op->line() << "];";
6eefe942
MW
4607 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
4608 "_STP_PROBE_HANDLER_KPROBE");
d9aed31e 4609 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
4610
4611 // Make it look like the IP is set as it wouldn't have been replaced
4612 // by a breakpoint instruction when calling real probe handler. Reset
4613 // IP regs on return, so we don't confuse kprobes. PR10458
4614 s.op->newline() << "{";
4615 s.op->indent(1);
d9aed31e 4616 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 4617 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 4618 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 4619 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4620 s.op->newline(-1) << "}";
4621
b20febf3
FCE
4622 common_probe_entryfn_epilogue (s.op);
4623 s.op->newline() << "return 0;";
4624 s.op->newline(-1) << "}";
4625
4626 // Same for kretprobes
4627 s.op->newline();
af234c40
JS
4628 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
4629 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 4630 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
4631
4632 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 4633 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
4634 // Check that the index is plausible
4635 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4636 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4637 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4638 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4639 s.op->line() << "];";
4640
c87ae2c1
JS
4641 s.op->newline() << "struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
4642 s.op->newline() << "if (sp) {";
4643 s.op->indent(1);
6eefe942
MW
4644 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sp",
4645 "_STP_PROBE_HANDLER_KRETPROBE");
d9aed31e 4646 s.op->newline() << "c->kregs = regs;";
af234c40
JS
4647
4648 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
4649 s.op->newline() << "c->ips.krp.pi = inst;";
4650 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
4651
4652 // Make it look like the IP is set as it wouldn't have been replaced
4653 // by a breakpoint instruction when calling real probe handler. Reset
4654 // IP regs on return, so we don't confuse kprobes. PR10458
4655 s.op->newline() << "{";
d9aed31e 4656 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
4657 s.op->newline() << "if (entry)";
4658 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
4659 s.op->newline(-1) << "else";
4660 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
4661 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 4662 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4663 s.op->newline(-1) << "}";
4664
b20febf3 4665 common_probe_entryfn_epilogue (s.op);
c87ae2c1 4666 s.op->newline(-1) << "}";
b20febf3
FCE
4667 s.op->newline() << "return 0;";
4668 s.op->newline(-1) << "}";
af234c40
JS
4669
4670 s.op->newline();
4671 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4672 s.op->line() << " struct pt_regs *regs) {";
4673 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
4674 s.op->newline(-1) << "}";
4675
4676 s.op->newline();
4677 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
4678 s.op->line() << " struct pt_regs *regs) {";
4679 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
4680 s.op->newline(-1) << "}";
b642c901 4681
14cf7e42 4682 s.op->newline();
62f52bb0
JS
4683 if (has_semaphores)
4684 s.op->newline() << "#define KPROBES_TASK_FINDER 1";
14cf7e42
SC
4685 s.op->newline() << "#include \"kprobes-common.c\"";
4686 s.op->newline();
20c6c071 4687}
ec4373ff 4688
20c6c071 4689
dc38c0ae 4690void
b20febf3
FCE
4691dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
4692{
62f52bb0 4693 if (has_semaphores) // Ignore if there are no semaphores
b642c901
SC
4694 {
4695 s.op->newline() << "for (i=0; i<ARRAY_SIZE(stap_dwarf_probes); i++) {";
4696 s.op->newline(1) << "int rc;";
4697 s.op->newline() << "struct stap_dwarf_probe *p = &stap_dwarf_probes[i];";
26e63673 4698 s.op->newline() << "probe_point = p->probe->pp;"; // for error messages
b642c901
SC
4699 s.op->newline() << "if (p->sdt_sem_offset) {";
4700 s.op->newline(1) << "rc = stap_register_task_finder_target(&p->finder);";
4701 s.op->newline(-1) << "}";
4702 s.op->newline() << "if (rc) break;";
4703 s.op->newline(-1) << "}";
4704 }
4705
b20febf3
FCE
4706 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4707 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4708 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 4709 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 4710 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 4711 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 4712 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 4713 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 4714 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 4715 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 4716 s.op->newline(-1) << "} else {";
f07c3b68 4717 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 4718 s.op->newline(-1) << "}";
606fd9c8 4719 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 4720 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 4721 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
4722 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4723 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4724 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4725 s.op->newline(-1) << "}";
4726 s.op->newline() << "#endif";
e4cb375f
MH
4727 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4728 s.op->newline() << "#ifdef __ia64__";
4729 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4730 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4731 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4732 s.op->newline() << "if (rc == 0) {";
4733 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4734 s.op->newline() << "if (rc != 0)";
4735 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4736 s.op->newline(-2) << "}";
4737 s.op->newline() << "#else";
606fd9c8 4738 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 4739 s.op->newline() << "#endif";
b20febf3 4740 s.op->newline(-1) << "} else {";
e4cb375f 4741 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
4742 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4743 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
4744 s.op->newline() << "#ifdef __ia64__";
4745 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
4746 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4747 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4748 s.op->newline() << "if (rc == 0) {";
4749 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
4750 s.op->newline() << "if (rc != 0)";
4751 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4752 s.op->newline(-2) << "}";
4753 s.op->newline() << "#else";
606fd9c8 4754 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 4755 s.op->newline() << "#endif";
b20febf3 4756 s.op->newline(-1) << "}";
9063462a
FCE
4757 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
4758 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 4759 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 4760 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 4761 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
4762 // XXX: shall we increment numskipped?
4763 s.op->newline(-1) << "}";
4764
4765#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 4766 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 4767 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
4768 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
4769 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
4770 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
4771 s.op->newline() << "#ifdef __ia64__";
4772 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
4773 s.op->newline() << "#endif";
c48cb0cc
FCE
4774 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
4775 // not run for this early-abort case.
4776 s.op->newline(-1) << "}";
4777 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 4778 s.op->newline(-1) << "}";
9063462a
FCE
4779#endif
4780
b20febf3
FCE
4781 s.op->newline() << "else sdp->registered_p = 1;";
4782 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
4783}
4784
4785
b4be7cbc
FCE
4786void
4787dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
4788{
4789 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4790 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4791 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4792 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
4793 s.op->newline() << "int rc;";
4794
4795 // new module arrived?
4796 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
4797 s.op->newline(1) << "if (sdp->return_p) {";
4798 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
4799 s.op->newline() << "if (sdp->maxactive_p) {";
4800 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
4801 s.op->newline(-1) << "} else {";
4802 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
4803 s.op->newline(-1) << "}";
4804 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
4805 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
4806 s.op->newline() << "if (sdp->entry_probe) {";
4807 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4808 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4809 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4810 s.op->newline(-1) << "}";
4811 s.op->newline() << "#endif";
4812 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4813 s.op->newline() << "#ifdef __ia64__";
4814 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4815 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4816 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4817 s.op->newline() << "if (rc == 0) {";
4818 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4819 s.op->newline() << "if (rc != 0)";
4820 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4821 s.op->newline(-2) << "}";
4822 s.op->newline() << "#else";
4823 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
4824 s.op->newline() << "#endif";
4825 s.op->newline(-1) << "} else {";
4826 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4827 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4828 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
4829 s.op->newline() << "#ifdef __ia64__";
4830 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
4831 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4832 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4833 s.op->newline() << "if (rc == 0) {";
4834 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
4835 s.op->newline() << "if (rc != 0)";
4836 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4837 s.op->newline(-2) << "}";
4838 s.op->newline() << "#else";
4839 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
4840 s.op->newline() << "#endif";
4841 s.op->newline(-1) << "}";
4842 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
4843
4844 // old module disappeared?
4845 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
4846 s.op->newline(1) << "if (sdp->return_p) {";
4847 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
4848 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
4849 s.op->newline() << "#ifdef STP_TIMING";
4850 s.op->newline() << "if (kp->u.krp.nmissed)";
4851 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
4852 s.op->newline(-1) << "#endif";
4853 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
4854 s.op->newline() << "#ifdef STP_TIMING";
4855 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
4856 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
4857 s.op->newline(-1) << "#endif";
4858 s.op->newline(-1) << "} else {";
4859 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
4860 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
4861 s.op->newline() << "#ifdef STP_TIMING";
4862 s.op->newline() << "if (kp->u.kp.nmissed)";
4863 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
4864 s.op->newline(-1) << "#endif";
4865 s.op->newline(-1) << "}";
4866 s.op->newline() << "#if defined(__ia64__)";
4867 s.op->newline() << "unregister_kprobe (&kp->dummy);";
4868 s.op->newline() << "#endif";
4869 s.op->newline() << "sdp->registered_p = 0;";
4870 s.op->newline(-1) << "}";
4871
4872 s.op->newline(-1) << "}"; // for loop
4873}
4874
4875
4876
4877
46b84a80 4878void
b20febf3 4879dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 4880{
62f52bb0
JS
4881 if (has_semaphores)
4882 {
4883 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4884 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4885 s.op->newline() << "unsigned short sdt_semaphore = 0;"; // NB: fixed size
4886 s.op->newline() << "if (sdp->sdt_sem_address && __access_process_vm_noflush (sdp->tsk, sdp->sdt_sem_address, &sdt_semaphore, sizeof (sdt_semaphore), 0)) {";
4887 s.op->newline(1) << "sdt_semaphore --;";
4888 s.op->newline() << "__access_process_vm_noflush (sdp->tsk, sdp->sdt_sem_address, &sdt_semaphore, sizeof (sdt_semaphore), 1);";
4889 s.op->newline(-1) << "}";
4890 s.op->newline(-1) << "}";
4891 }
b642c901 4892
42cb22bd
MH
4893 //Unregister kprobes by batch interfaces.
4894 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4895 s.op->newline() << "j = 0;";
4896 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4897 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4898 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4899 s.op->newline() << "if (! sdp->registered_p) continue;";
4900 s.op->newline() << "if (!sdp->return_p)";
4901 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
4902 s.op->newline(-2) << "}";
4903 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
4904 s.op->newline() << "j = 0;";
4905 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4906 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4907 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4908 s.op->newline() << "if (! sdp->registered_p) continue;";
4909 s.op->newline() << "if (sdp->return_p)";
4910 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
4911 s.op->newline(-2) << "}";
4912 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
4913 s.op->newline() << "#ifdef __ia64__";
4914 s.op->newline() << "j = 0;";
4915 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4916 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4917 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4918 s.op->newline() << "if (! sdp->registered_p) continue;";
4919 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
4920 s.op->newline(-1) << "}";
4921 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
4922 s.op->newline() << "#endif";
42cb22bd
MH
4923 s.op->newline() << "#endif";
4924
b20febf3
FCE
4925 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4926 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4927 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
4928 s.op->newline() << "if (! sdp->registered_p) continue;";
4929 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 4930 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 4931 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 4932 s.op->newline() << "#endif";
606fd9c8 4933 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
73209876
FCE
4934 s.op->newline() << "#ifdef STP_TIMING";
4935 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 4936 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 4937 s.op->newline(-1) << "#endif";
606fd9c8 4938 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
73209876
FCE
4939 s.op->newline() << "#ifdef STP_TIMING";
4940 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 4941 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
73209876 4942 s.op->newline(-1) << "#endif";
557fb7a8 4943 s.op->newline(-1) << "} else {";
42cb22bd 4944 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 4945 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 4946 s.op->newline() << "#endif";
606fd9c8 4947 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
73209876
FCE
4948 s.op->newline() << "#ifdef STP_TIMING";
4949 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 4950 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 4951 s.op->newline(-1) << "#endif";
b20febf3 4952 s.op->newline(-1) << "}";
e4cb375f
MH
4953 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
4954 s.op->newline() << "unregister_kprobe (&kp->dummy);";
4955 s.op->newline() << "#endif";
b20febf3
FCE
4956 s.op->newline() << "sdp->registered_p = 0;";
4957 s.op->newline(-1) << "}";
46b84a80
DS
4958}
4959
8aabf152
FCE
4960
4961struct sdt_kprobe_var_expanding_visitor: public var_expanding_visitor
4962{
4963 sdt_kprobe_var_expanding_visitor(const string & process_name,
4964 const string & provider_name,
4965 const string & probe_name,
4966 const string & arg_string,
4967 int arg_count):
4968 process_name (process_name), provider_name (provider_name), probe_name (probe_name),
4969 arg_count (arg_count)
4970 {
4971 tokenize(arg_string, arg_tokens, " ");
822a6a3d 4972 assert(arg_count <= 10);
8aabf152
FCE
4973 }
4974 const string & process_name;
4975 const string & provider_name;
4976 const string & probe_name;
4977 int arg_count;
4978 vector<string> arg_tokens;
4979
4980 void visit_target_symbol (target_symbol* e);
40a0c64e 4981 void visit_cast_op (cast_op* e);
8aabf152
FCE
4982};
4983
4984
aff5d390 4985struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 4986{
ae1418f0 4987 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
4988 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
4989 int elf_machine,
4990 const string & process_name,
a794dbeb 4991 const string & provider_name,
aff5d390 4992 const string & probe_name,
71e5e13d 4993 stap_sdt_probe_type probe_type,
aff5d390 4994 const string & arg_string,
8aabf152 4995 int ac):
332ba7e7 4996 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
4997 provider_name (provider_name), probe_name (probe_name),
4998 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 4999 {
f83336a5
FCE
5000 /* Register name mapping table depends on the elf machine of this particular
5001 probe target process/file, not upon the host. So we can't just
5002 #ifdef _i686_ etc. */
ae1418f0
FCE
5003
5004#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5005 if (elf_machine == EM_X86_64) {
46a94997
SC
5006 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5007 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5008 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5009 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5010 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5011 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5012 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5013 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5014 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5015 DRI ("%sil", 4, QI);
5016 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5017 DRI ("%dil", 5, QI);
5018 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5019 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5020 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5021 DRI ("%r8b", 8, QI);
5022 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5023 DRI ("%r9b", 9, QI);
5024 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5025 DRI ("%r10b", 10, QI);
5026 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5027 DRI ("%r11b", 11, QI);
5028 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5029 DRI ("%r12b", 12, QI);
5030 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5031 DRI ("%r13b", 13, QI);
5032 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5033 DRI ("%r14b", 14, QI);
5034 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5035 DRI ("%r15b", 15, QI);
f83336a5 5036 } else if (elf_machine == EM_386) {
46a94997
SC
5037 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5038 DRI ("%ah", 0, QIh);
5039 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5040 DRI ("%ch", 1, QIh);
5041 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5042 DRI ("%dh", 2, QIh);
5043 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5044 DRI ("%bh", 3, QIh);
5045 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5046 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5047 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5048 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5049 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5050 DRI ("%r0", 0, DI);
5051 DRI ("%r1", 1, DI);
5052 DRI ("%r2", 2, DI);
5053 DRI ("%r3", 3, DI);
5054 DRI ("%r4", 4, DI);
5055 DRI ("%r5", 5, DI);
5056 DRI ("%r6", 6, DI);
5057 DRI ("%r7", 7, DI);
5058 DRI ("%r8", 8, DI);
5059 DRI ("%r9", 9, DI);
5060 DRI ("%r10", 10, DI);
5061 DRI ("%r11", 11, DI);
5062 DRI ("%r12", 12, DI);
5063 DRI ("%r13", 13, DI);
5064 DRI ("%r14", 14, DI);
5065 DRI ("%r15", 15, DI);
5066 DRI ("%r16", 16, DI);
5067 DRI ("%r17", 17, DI);
5068 DRI ("%r18", 18, DI);
5069 DRI ("%r19", 19, DI);
5070 DRI ("%r20", 20, DI);
5071 DRI ("%r21", 21, DI);
5072 DRI ("%r22", 22, DI);
5073 DRI ("%r23", 23, DI);
5074 DRI ("%r24", 24, DI);
5075 DRI ("%r25", 25, DI);
5076 DRI ("%r26", 26, DI);
5077 DRI ("%r27", 27, DI);
5078 DRI ("%r28", 28, DI);
5079 DRI ("%r29", 29, DI);
5080 DRI ("%r30", 30, DI);
5081 DRI ("%r31", 31, DI);
8aabf152 5082 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5083 DRI ("0", 0, DI);
5084 DRI ("1", 1, DI);
5085 DRI ("2", 2, DI);
5086 DRI ("3", 3, DI);
5087 DRI ("4", 4, DI);
5088 DRI ("5", 5, DI);
5089 DRI ("6", 6, DI);
5090 DRI ("7", 7, DI);
5091 DRI ("8", 8, DI);
5092 DRI ("9", 9, DI);
5093 DRI ("10", 10, DI);
5094 DRI ("11", 11, DI);
5095 DRI ("12", 12, DI);
5096 DRI ("13", 13, DI);
5097 DRI ("14", 14, DI);
5098 DRI ("15", 15, DI);
5099 DRI ("16", 16, DI);
5100 DRI ("17", 17, DI);
5101 DRI ("18", 18, DI);
5102 DRI ("19", 19, DI);
5103 DRI ("20", 20, DI);
5104 DRI ("21", 21, DI);
5105 DRI ("22", 22, DI);
5106 DRI ("23", 23, DI);
5107 DRI ("24", 24, DI);
5108 DRI ("25", 25, DI);
5109 DRI ("26", 26, DI);
5110 DRI ("27", 27, DI);
5111 DRI ("28", 28, DI);
5112 DRI ("29", 29, DI);
5113 DRI ("30", 30, DI);
5114 DRI ("31", 31, DI);
14900130 5115 } else if (elf_machine == EM_S390) {
46a94997
SC
5116 DRI ("%r0", 0, DI);
5117 DRI ("%r1", 1, DI);
5118 DRI ("%r2", 2, DI);
5119 DRI ("%r3", 3, DI);
5120 DRI ("%r4", 4, DI);
5121 DRI ("%r5", 5, DI);
5122 DRI ("%r6", 6, DI);
5123 DRI ("%r7", 7, DI);
5124 DRI ("%r8", 8, DI);
5125 DRI ("%r9", 9, DI);
5126 DRI ("%r10", 10, DI);
5127 DRI ("%r11", 11, DI);
5128 DRI ("%r12", 12, DI);
5129 DRI ("%r13", 13, DI);
5130 DRI ("%r14", 14, DI);
5131 DRI ("%r15", 15, DI);
14900130 5132 } else if (arg_count) {
8aabf152 5133 /* permit this case; just fall back to dwarf */
f83336a5 5134 }
ae1418f0 5135#undef DRI
f83336a5 5136
ebbd2b45 5137 need_debug_info = false;
aff5d390 5138 tokenize(arg_string, arg_tokens, " ");
822a6a3d 5139 assert(arg_count <= 10);
a8ec7719 5140 }
8aabf152 5141
f83336a5 5142 systemtap_session& session;
332ba7e7 5143 int elf_machine;
aff5d390 5144 const string & process_name;
a794dbeb 5145 const string & provider_name;
aff5d390 5146 const string & probe_name;
71e5e13d 5147 stap_sdt_probe_type probe_type;
8aabf152 5148 unsigned arg_count;
aff5d390 5149 vector<string> arg_tokens;
46a94997 5150 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5151 bool need_debug_info;
aff5d390
SC
5152
5153 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5154 void visit_target_symbol_arg (target_symbol* e);
5155 void visit_target_symbol_context (target_symbol* e);
40a0c64e 5156 void visit_cast_op (cast_op* e);
aff5d390
SC
5157};
5158
7a05f484
SC
5159
5160void
6ef331c8 5161sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5162{
6ef331c8 5163 if (e->addressof)
b530b5b3 5164 throw semantic_error(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5165
5166 if (e->name == "$$name")
7a05f484 5167 {
6ef331c8
SC
5168 literal_string *myname = new literal_string (probe_name);
5169 myname->tok = e->tok;
5170 provide(myname);
5171 return;
5172 }
7a05f484 5173
6ef331c8
SC
5174 else if (e->name == "$$provider")
5175 {
5176 literal_string *myname = new literal_string (provider_name);
5177 myname->tok = e->tok;
5178 provide(myname);
5179 return;
5180 }
a794dbeb 5181
6ef331c8
SC
5182 else if (e->name == "$$vars" || e->name == "$$parms")
5183 {
5184 e->assert_no_components("sdt", true);
822a6a3d 5185 assert(arg_count <= 10);
6ef331c8
SC
5186
5187 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
5188 // NB: we synthesize a new token here rather than reusing
5189 // e->tok, because print_format::print likes to use
5190 // its tok->content.
5191 token* pf_tok = new token(*e->tok);
5192 pf_tok->content = "sprintf";
63ea4244 5193
6ef331c8
SC
5194 print_format* pf = print_format::create(pf_tok);
5195
5196 for (unsigned i = 1; i <= arg_count; ++i)
5197 {
5198 if (i > 1)
5199 pf->raw_components += " ";
5200 target_symbol *tsym = new target_symbol;
5201 tsym->tok = e->tok;
5202 tsym->name = "$arg" + lex_cast(i);
5203 pf->raw_components += tsym->name;
5204 tsym->components = e->components;
5205
5206 expression *texp = require (tsym);
5207 if (!e->components.empty() &&
5208 e->components[0].type == target_symbol::comp_pretty_print)
5209 pf->raw_components += "=%s";
5210 else
5211 pf->raw_components += "=%#x";
5212 pf->args.push_back(texp);
5213 }
5214
5215 pf->components = print_format::string_to_components(pf->raw_components);
5216 provide (pf);
5217 }
5218 else
5219 assert(0); // shouldn't get here
5220}
5221
5222
5223void
5224sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5225{
5226 try
5227 {
8aabf152 5228 unsigned argno = 0; // the N in $argN
c69a87e0 5229 try
aff5d390 5230 {
5ecaa5a7 5231 if (startswith(e->name, "$arg"))
8aabf152 5232 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5233 }
c69a87e0 5234 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5235 {
8aabf152 5236 argno = 0;
aff5d390 5237 }
5ecaa5a7 5238
8aabf152
FCE
5239 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5240 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5241 {
8aabf152
FCE
5242 // NB: Either
5243 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5244 // 2) uprobe2_type $FOO (no probe args)
5245 // both of which get resolved later.
5246 need_debug_info = true;
5247 provide(e);
5248 return;
aff5d390 5249 }
277c21bc 5250
8aabf152
FCE
5251 assert (arg_tokens.size() >= argno);
5252 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5253
8aabf152
FCE
5254 // Now we try to parse this thing, which is an assembler operand
5255 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5256 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5257 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
b874bd52
SC
5258 // literal reg reg reg +
5259 // indirect offset
5260 // x86 $N %rR (%rR) N(%rR)
5261 // power iN R (R) N(R)
5262 // ia64 N rR [r16]
5263 // s390 N %rR 0(rR) N(r15)
5264 // arm #N rR [rR] [rR, #N]
5265
8aabf152
FCE
5266 expression* argexpr = 0; // filled in in case of successful parse
5267
5268 string percent_regnames;
5269 string regnames;
5270 vector<string> matches;
71e5e13d 5271 long precision;
8aabf152
FCE
5272 int rc;
5273
40fe32e0
SC
5274 // Parse the leading length
5275
5276 if (asmarg.find('@') != string::npos)
5277 {
5278 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5279 asmarg = asmarg.substr(asmarg.find('@')+1);
5280 }
71e5e13d
SC
5281 else
5282 {
5283 // V1/V2 do not have precision field so default to signed long
5284 // V3 asm does not have precision field so default to unsigned long
5285 if (probe_type == uprobe3_type)
5286 precision = sizeof(long); // this is an asm probe
5287 else
5288 precision = -sizeof(long);
5289 }
40fe32e0 5290
8aabf152
FCE
5291 // test for a numeric literal.
5292 // Only accept (signed) decimals throughout. XXX
5293
5294 // PR11821. NB: on powerpc, literals are not prefixed with $,
5295 // so this regex does not match. But that's OK, since without
5296 // -mregnames, we can't tell them apart from register numbers
5297 // anyway. With -mregnames, we could, if gcc somehow
5298 // communicated to us the presence of that option, but alas it
5299 // doesn't. http://gcc.gnu.org/PR44995.
9109f487 5300 rc = regexp_match (asmarg, "^[i\\$][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5301 if (! rc)
5302 {
75a371ce
JS
5303 string sn = matches[0].substr(1);
5304 int64_t n;
5305 try
5306 {
5307 // We have to pay attention to the size & sign, as gcc sometimes
5308 // propagates constants that don't quite match, like a negative
5309 // value to fill an unsigned type.
5310 switch (precision)
5311 {
5312 case -1: n = lex_cast< int8_t>(sn); break;
5313 case 1: n = lex_cast< uint8_t>(sn); break;
5314 case -2: n = lex_cast< int16_t>(sn); break;
5315 case 2: n = lex_cast<uint16_t>(sn); break;
5316 case -4: n = lex_cast< int32_t>(sn); break;
5317 case 4: n = lex_cast<uint32_t>(sn); break;
5318 default:
5319 case -8: n = lex_cast< int64_t>(sn); break;
5320 case 8: n = lex_cast<uint64_t>(sn); break;
5321 }
5322 }
5323 catch (std::runtime_error&)
5324 {
5325 goto not_matched;
5326 }
5327 literal_number* ln = new literal_number(n);
8aabf152
FCE
5328 ln->tok = e->tok;
5329 argexpr = ln;
5330 goto matched;
5331 }
5332
14900130
SC
5333 if (dwarf_regs.empty())
5334 goto not_matched;
d5b83cee 5335
8aabf152
FCE
5336 // Build regex pieces out of the known dwarf_regs. We keep two separate
5337 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5338 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5339 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5340 {
5341 string regname = ri->first;
5342 assert (regname != "");
5343 regnames += string("|")+regname;
5344 if (regname[0]=='%')
5345 percent_regnames += string("|")+regname;
5346 }
5347 // clip off leading |
5348 regnames = regnames.substr(1);
5349 percent_regnames = percent_regnames.substr(1);
5350
5351 // test for REGISTER
5352 // NB: Because PR11821, we must use percent_regnames here.
332ba7e7 5353 if (elf_machine == EM_PPC || elf_machine == EM_PPC64)
9109f487
SC
5354 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5355 else
332ba7e7 5356 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5357 if (! rc)
5358 {
5359 string regname = matches[1];
46a94997
SC
5360 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5361 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5362 {
5363 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5364 string width_adjust;
46a94997 5365 switch (ri->second.second)
19c22e1f 5366 {
892ec39a
SC
5367 case QI: width_adjust = ") & 0xff)"; break;
5368 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5369 case HI:
71e5e13d 5370 // preserve 16 bit register signness
892ec39a
SC
5371 width_adjust = ") & 0xffff)";
5372 if (precision < 0)
55b377f4 5373 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5374 break;
5375 case SI:
5376 // preserve 32 bit register signness
892ec39a
SC
5377 width_adjust = ") & 0xffffffff)";
5378 if (precision < 0)
55b377f4 5379 width_adjust += " << 32 >> 32";
19c22e1f 5380 break;
892ec39a 5381 default: width_adjust = "))";
19c22e1f 5382 }
55b377f4
SC
5383 string type = "";
5384 if (probe_type == uprobe3_type)
5385 type = (precision < 0
5386 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5387 type = type + "((";
8aabf152
FCE
5388 get_arg1->tok = e->tok;
5389 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5390 + string(" ((int64_t)") + type
8aabf152
FCE
5391 + (is_user_module (process_name)
5392 ? string("u_fetch_register(")
5393 : string("k_fetch_register("))
46a94997 5394 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5395 + width_adjust;
8aabf152
FCE
5396 argexpr = get_arg1;
5397 goto matched;
5398 }
5399 // invalid register name, fall through
5400 }
40fe32e0 5401
e5b7b83f 5402 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5403 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f
SC
5404 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
5405 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-]?[0-9]*)([+-]?[0-9]*)[(](")+regnames+string(")[)]$"), matches);
8aabf152
FCE
5406 if (! rc)
5407 {
e5b7b83f 5408 string regname;
8aabf152 5409 int64_t disp = 0;
e5b7b83f
SC
5410
5411 int idx;
5412 for (idx = matches.size() - 1; idx > 0; idx--)
5413 if (matches[idx].length())
5414 {
5415 regname = matches[idx];
5416 break;
5417 }
5418
5419 for (int i=1; i < idx; i++)
5420 if (matches[i].length())
5421 try
5422 {
5423 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5424 }
8aabf152
FCE
5425 catch (const runtime_error& f) // unparseable offset
5426 {
5427 goto not_matched; // can't just 'break' out of
5428 // this case or use a sentinel
5429 // value, unfortunately
5430 }
5431
8aabf152
FCE
5432 if (dwarf_regs.find (regname) != dwarf_regs.end()) // known register
5433 {
5434 // synthesize user_long(%{fetch_register(R)%} + D)
40fe32e0 5435
8aabf152
FCE
5436 embedded_expr *get_arg1 = new embedded_expr;
5437 get_arg1->tok = e->tok;
5438 get_arg1->code = string("/* unprivileged */ /* pure */")
5439 + (is_user_module (process_name)
5440 ? string("u_fetch_register(")
5441 : string("k_fetch_register("))
46a94997 5442 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5443 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5444
8aabf152
FCE
5445 literal_number* inc = new literal_number(disp);
5446 inc->tok = e->tok;
40fe32e0 5447
8aabf152
FCE
5448 binary_expression *be = new binary_expression;
5449 be->tok = e->tok;
5450 be->left = get_arg1;
5451 be->op = "+";
5452 be->right = inc;
40fe32e0 5453
8aabf152 5454 functioncall *fc = new functioncall;
40fe32e0
SC
5455 switch (precision)
5456 {
7f6ce9ab
SC
5457 case 1: case -1:
5458 fc->function = "user_int8"; break;
5459 case 2:
5460 fc->function = "user_uint16"; break;
5461 case -2:
5462 fc->function = "user_int16"; break;
5463 case 4:
5464 fc->function = "user_uint32"; break;
5465 case -4:
5466 fc->function = "user_int32"; break;
5467 case 8: case -8:
5468 fc->function = "user_int64"; break;
40fe32e0
SC
5469 default: fc->function = "user_long";
5470 }
8aabf152
FCE
5471 fc->tok = e->tok;
5472 fc->args.push_back(be);
366af4e7 5473
8aabf152
FCE
5474 argexpr = fc;
5475 goto matched;
5476 }
5477 // invalid register name, fall through
5478 }
5479
5480 not_matched:
5481 // The asmarg operand was not recognized. Back down to dwarf.
5482 if (! session.suppress_warnings)
84fef8ee
FCE
5483 {
5484 if (probe_type == UPROBE3_TYPE)
5485 session.print_warning (_F("Can't parse SDT_V3 operand '%s'", asmarg.c_str()), e->tok);
5486 else // must be *PROBE2; others don't get asm operands
5487 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s'",
5488 asmarg.c_str()), e->tok);
5489 }
8aabf152
FCE
5490 assert (argexpr == 0);
5491 need_debug_info = true;
5492 provide (e);
5493 return;
366af4e7 5494
8aabf152
FCE
5495 matched:
5496 assert (argexpr != 0);
366af4e7
RM
5497
5498 if (session.verbose > 2)
1e41115c 5499 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 5500 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 5501
aff5d390 5502 if (e->components.empty()) // We have a scalar
8aabf152
FCE
5503 {
5504 if (e->addressof)
b530b5b3 5505 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
5506 provide (argexpr);
5507 return;
5508 }
5509 else // $var->foo
5510 {
5511 cast_op *cast = new cast_op;
5512 cast->name = "@cast";
5513 cast->tok = e->tok;
5514 cast->operand = argexpr;
5515 cast->components = e->components;
5516 cast->type_name = probe_name + "_arg" + lex_cast(argno);
5517 cast->module = process_name;
5518 cast->visit(this);
5519 return;
5520 }
366af4e7 5521
8aabf152 5522 /* NOTREACHED */
aff5d390
SC
5523 }
5524 catch (const semantic_error &er)
5525 {
5526 e->chain (er);
5527 provide (e);
5528 }
5529}
5530
5531
6ef331c8
SC
5532void
5533sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
5534{
5535 try
5536 {
5537 assert(e->name.size() > 0 && e->name[0] == '$');
5538
5539 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
5540 visit_target_symbol_context (e);
5541 else
5542 visit_target_symbol_arg (e);
5543 }
5544 catch (const semantic_error &er)
5545 {
5546 e->chain (er);
5547 provide (e);
5548 }
5549}
5550
5551
40a0c64e
JS
5552void
5553sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
5554{
5555 // Fill in our current module context if needed
5556 if (e->module.empty())
5557 e->module = process_name;
5558
5559 var_expanding_visitor::visit_cast_op(e);
5560}
5561
5562
aff5d390
SC
5563void
5564sdt_kprobe_var_expanding_visitor::visit_target_symbol (target_symbol *e)
5565{
5566 try
5567 {
277c21bc 5568 if (e->name == "$$name")
aff5d390
SC
5569 {
5570 if (e->addressof)
b530b5b3 5571 throw semantic_error(_("cannot take address of sdt context variable"), e->tok);
aff5d390
SC
5572
5573 literal_string *myname = new literal_string (probe_name);
5574 myname->tok = e->tok;
5575 provide(myname);
5576 return;
5577 }
277c21bc 5578 if (e->name == "$$provider")
a794dbeb
FCE
5579 {
5580 if (e->addressof)
b530b5b3 5581 throw semantic_error(_("cannot take address of sdt context variable"), e->tok);
a794dbeb
FCE
5582
5583 literal_string *myname = new literal_string (provider_name);
5584 myname->tok = e->tok;
5585 provide(myname);
5586 return;
5587 }
aff5d390 5588
5ecaa5a7 5589 int argno = -1;
aff5d390
SC
5590 try
5591 {
5ecaa5a7
JS
5592 if (startswith(e->name, "$arg"))
5593 argno = lex_cast<int>(e->name.substr(4));
aff5d390
SC
5594 }
5595 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
5596 {
aff5d390 5597 }
5ecaa5a7 5598 if (argno < 0)
b530b5b3 5599 throw semantic_error(_("invalid variable, must be of the form $argN"), e->tok);
aff5d390 5600 if (argno < 1 || argno > arg_count)
b530b5b3 5601 throw semantic_error(_("invalid argument number"), e->tok);
5ecaa5a7 5602
c69a87e0
FCE
5603 bool lvalue = is_active_lvalue(e);
5604 functioncall *fc = new functioncall;
63ea4244 5605
c69a87e0
FCE
5606 // First two args are hidden: 1. pointer to probe name 2. task id
5607 if (arg_count < 2)
aff5d390 5608 {
71e5e13d 5609 fc->function = "long_arg";
aff5d390
SC
5610 fc->type = pe_long;
5611 fc->tok = e->tok;
5612 // skip the hidden args
5613 literal_number* num = new literal_number(argno + 2);
5614 num->tok = e->tok;
5615 fc->args.push_back(num);
5616 }
5617 else
5618 {
5619 // args are passed in arg3 as members of a struct
5620 fc->function = "user_long";
5621 fc->tok = e->tok;
5622 binary_expression *be = new binary_expression;
5623 be->tok = e->tok;
5624 functioncall *get_arg1 = new functioncall;
5625 get_arg1->function = "pointer_arg";
5626 get_arg1->tok = e->tok;
5627 // arg3 is the pointer to a struct of arguments
c57ea854 5628 literal_number* num = new literal_number(3);
aff5d390
SC
5629 num->tok = e->tok;
5630 get_arg1->args.push_back(num);
5631
5632 be->left = get_arg1;
5633 be->op = "+";
5634 // offset in struct to the desired arg
5635 literal_number* inc = new literal_number((argno - 1) * 8);
5636 inc->tok = e->tok;
5637 be->right = inc;
5638 fc->args.push_back(be);
5639 }
c69a87e0 5640 if (lvalue)
aff5d390 5641 *(target_symbol_setter_functioncalls.top()) = fc;
63ea4244 5642
aff5d390
SC
5643 if (e->components.empty()) // We have a scalar
5644 {
5645 if (e->addressof)
b530b5b3 5646 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
63ea4244 5647
aff5d390
SC
5648 provide(fc);
5649 return;
5650 }
c69a87e0 5651 cast_op *cast = new cast_op;
277c21bc 5652 cast->name = "@cast";
c69a87e0
FCE
5653 cast->tok = e->tok;
5654 cast->operand = fc;
5655 cast->components = e->components;
7f6b80bd 5656 cast->type_name = probe_name + "_arg" + lex_cast(argno);
c69a87e0 5657 cast->module = process_name;
63ea4244 5658
c69a87e0 5659 cast->visit(this);
7a05f484 5660 }
c69a87e0 5661 catch (const semantic_error &er)
ad002306 5662 {
1af1e62d 5663 e->chain (er);
c69a87e0 5664 provide (e);
ad002306 5665 }
7a05f484 5666}
46b84a80 5667
277c21bc 5668
40a0c64e
JS
5669void
5670sdt_kprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
5671{
5672 // Fill in our current module context if needed
5673 if (e->module.empty())
5674 e->module = process_name;
5675
5676 var_expanding_visitor::visit_cast_op(e);
5677}
5678
5679
576eaefe
SC
5680void
5681plt_expanding_visitor::visit_target_symbol (target_symbol *e)
5682{
5683 try
5684 {
5685 if (e->name == "$$name")
5686 {
5687 literal_string *myname = new literal_string (entry);
5688 myname->tok = e->tok;
5689 provide(myname);
5690 return;
5691 }
5692 }
5693 catch (const semantic_error &er)
5694 {
5695 e->chain (er);
5696 provide (e);
5697 }
5698}
5699
5700
edce5b67
JS
5701struct sdt_query : public base_query
5702{
5703 sdt_query(probe * base_probe, probe_point * base_loc,
5704 dwflpp & dw, literal_map_t const & params,
51d6bda3 5705 vector<derived_probe *> & results, const string user_lib);
edce5b67 5706
51d6bda3 5707 void query_library (const char *data);
576eaefe 5708 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
5709 void handle_query_module();
5710
5711private:
15284963 5712 stap_sdt_probe_type probe_type;
9109f487 5713 enum {probe_section=0, note_section=1} probe_loc;
edce5b67
JS
5714 probe * base_probe;
5715 probe_point * base_loc;
6846cfc8 5716 literal_map_t const & params;
edce5b67 5717 vector<derived_probe *> & results;
a794dbeb
FCE
5718 string pp_mark;
5719 string pp_provider;
51d6bda3 5720 string user_lib;
edce5b67
JS
5721
5722 set<string> probes_handled;
5723
5724 Elf_Data *pdata;
5725 size_t probe_scn_offset;
5726 size_t probe_scn_addr;
aff5d390 5727 uint64_t arg_count;
40fe32e0 5728 GElf_Addr base;
c57ea854 5729 GElf_Addr pc;
aff5d390 5730 string arg_string;
edce5b67 5731 string probe_name;
a794dbeb 5732 string provider_name;
79a0ca08 5733 Dwarf_Addr semaphore;
edce5b67
JS
5734
5735 bool init_probe_scn();
6b51ee12 5736 bool get_next_probe();
c57ea854
SC
5737 void iterate_over_probe_entries();
5738 void handle_probe_entry();
edce5b67 5739
40fe32e0
SC
5740 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
5741 void setup_note_probe_entry (int type, const char *data, size_t len);
5742
edce5b67 5743 void convert_probe(probe *base);
4ddb6dd0 5744 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 5745 probe* convert_location();
40fe32e0 5746 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
aff5d390 5747 bool have_kprobe() {return probe_type == kprobe1_type || probe_type == kprobe2_type;}
c57ea854
SC
5748 bool have_debuginfo_uprobe(bool need_debug_info)
5749 {return probe_type == uprobe1_type
40fe32e0 5750 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 5751 && need_debug_info);}
40fe32e0 5752 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
5753};
5754
5755
5756sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
5757 dwflpp & dw, literal_map_t const & params,
51d6bda3 5758 vector<derived_probe *> & results, const string user_lib):
74fe61bc
LB
5759 base_query(dw, params), probe_type(probe_type), probe_loc(probe_loc), base_probe(base_probe),
5760 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
5761 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
5762 semaphore(0)
edce5b67 5763{
a794dbeb
FCE
5764 assert(get_string_param(params, TOK_MARK, pp_mark));
5765 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
5766
ef428667
FCE
5767 // PR10245: permit usage of dtrace-y "-" separator in marker name;
5768 // map it to double-underscores.
5769 size_t pos = 0;
5770 while (1) // there may be more than one
5771 {
a794dbeb 5772 size_t i = pp_mark.find("-", pos);
ef428667 5773 if (i == string::npos) break;
a794dbeb 5774 pp_mark.replace (i, 1, "__");
ef428667
FCE
5775 pos = i+1; // resume searching after the inserted __
5776 }
a794dbeb
FCE
5777
5778 // XXX: same for pp_provider?
edce5b67
JS
5779}
5780
5781
5782void
c57ea854 5783sdt_query::handle_probe_entry()
edce5b67 5784{
c57ea854
SC
5785 if (! have_uprobe()
5786 && !probes_handled.insert(probe_name).second)
edce5b67
JS
5787 return;
5788
5789 if (sess.verbose > 3)
c57ea854 5790 {
b530b5b3
LB
5791 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
5792 //TRANSLATORS: is matched to.
5793 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
5794 switch (probe_type)
5795 {
5796 case uprobe1_type:
5797 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
5798 break;
5799 case uprobe2_type:
5800 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
5801 break;
40fe32e0
SC
5802 case uprobe3_type:
5803 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
5804 break;
c57ea854
SC
5805 case kprobe1_type:
5806 clog << "kprobe1" << endl;
5807 break;
5808 case kprobe2_type:
5809 clog << "kprobe2" << endl;
5810 break;
5811 }
5812 }
edce5b67 5813
c57ea854
SC
5814 // Extend the derivation chain
5815 probe *new_base = convert_location();
5816 probe_point *new_location = new_base->locations[0];
5817
c57ea854
SC
5818 bool need_debug_info = false;
5819
7d395255
JS
5820 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
5821 // or dwfl_module_getelf(...). We only need it for the machine type, which
5822 // should be the same. The bias is used for relocating debuginfoless probes,
5823 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 5824 Dwarf_Addr bias;
7d395255 5825 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854
SC
5826
5827 if (have_kprobe())
edce5b67 5828 {
c57ea854 5829 convert_probe(new_base);
c57ea854
SC
5830 // Expand the local variables in the probe body
5831 sdt_kprobe_var_expanding_visitor svv (module_val,
5832 provider_name,
5833 probe_name,
5834 arg_string,
5835 arg_count);
5836 svv.replace (new_base->body);
5837 }
5838 else
5839 {
5840 /* Figure out the architecture of this particular ELF file.
5841 The dwarfless register-name mappings depend on it. */
5842 GElf_Ehdr ehdr_mem;
5843 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
5844 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
5845 int elf_machine = em->e_machine;
5846 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine,
5847 module_val,
5848 provider_name,
5849 probe_name,
71e5e13d 5850 probe_type,
c57ea854
SC
5851 arg_string,
5852 arg_count);
5853 svv.replace (new_base->body);
5854 need_debug_info = svv.need_debug_info;
5855 }
5856
5857 unsigned i = results.size();
edce5b67 5858
c57ea854
SC
5859 if (have_kprobe())
5860 derive_probes(sess, new_base, results);
5861
5862 else
5863 {
5864 // XXX: why not derive_probes() in the uprobes case too?
5865 literal_map_t params;
5866 for (unsigned i = 0; i < new_location->components.size(); ++i)
39a3e397 5867 {
c57ea854
SC
5868 probe_point::component *c = new_location->components[i];
5869 params[c->functor] = c->arg;
39a3e397 5870 }
30263a73 5871
c57ea854
SC
5872 dwarf_query q(new_base, new_location, dw, params, results, "", "");
5873 q.has_mark = true; // enables mid-statement probing
edce5b67 5874
c57ea854
SC
5875 // V2 probes need dwarf info in case of a variable reference
5876 if (have_debuginfo_uprobe(need_debug_info))
5877 dw.iterate_over_modules(&query_module, &q);
5878 else if (have_debuginfoless_uprobe())
aff5d390 5879 {
c57ea854
SC
5880 string section;
5881 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
5882 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
5883 {
5884 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
5885 section = ".dynamic";
5886 }
5887 else
5888 section = ".absolute";
5889
5890 uprobe_derived_probe* p =
5891 new uprobe_derived_probe ("", "", 0, q.module_val, section,
5892 q.statement_num_val, reloc_addr, q, 0);
5893 p->saveargs (arg_count);
5894 results.push_back (p);
aff5d390 5895 }
c57ea854 5896 }
487bf4e2 5897 sess.unwindsym_modules.insert (dw.module_name);
c57ea854
SC
5898 record_semaphore(results, i);
5899}
edce5b67 5900
4ddb6dd0 5901
c57ea854
SC
5902void
5903sdt_query::handle_query_module()
5904{
5905 if (!init_probe_scn())
5906 return;
edce5b67 5907
c57ea854
SC
5908 if (sess.verbose > 3)
5909 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 5910
40fe32e0
SC
5911 if (probe_loc == note_section)
5912 {
5913 GElf_Shdr shdr_mem;
5914 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
5915
5916 if (shdr)
5917 base = shdr->sh_addr;
5918 else
5919 base = 0;
5920 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
5921 }
5922 else
5923 iterate_over_probe_entries ();
edce5b67
JS
5924}
5925
5926
5927bool
5928sdt_query::init_probe_scn()
5929{
448a86b7 5930 Elf* elf;
edce5b67 5931 GElf_Shdr shdr_mem;
40fe32e0
SC
5932
5933 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
5934 if (shdr)
5935 {
5936 probe_loc = note_section;
5937 return true;
5938 }
edce5b67 5939
448a86b7 5940 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 5941 if (shdr)
edce5b67 5942 {
fea74777
SC
5943 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
5944 probe_scn_offset = 0;
5945 probe_scn_addr = shdr->sh_addr;
5946 assert (pdata != NULL);
5947 if (sess.verbose > 4)
ce0f6648
LB
5948 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
5949 << pdata->d_size << endl;
40fe32e0 5950 probe_loc = probe_section;
fea74777 5951 return true;
edce5b67 5952 }
fea74777 5953 else
edce5b67 5954 return false;
edce5b67
JS
5955}
5956
40fe32e0
SC
5957void
5958sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
5959{
5960 sdt_query *me = (sdt_query*)object;
5961 me->setup_note_probe_entry (type, data, len);
5962}
5963
5964
5965void
5966sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
5967{
5968 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
5969 // && !memcmp (data->d_buf + name_off,
5970 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
5971
5972 // probes are in the .note.stapsdt section
5973#define _SDT_NOTE_TYPE 3
5974 if (type != _SDT_NOTE_TYPE)
5975 return;
5976
5977 union
5978 {
5979 Elf64_Addr a64[3];
5980 Elf32_Addr a32[3];
5981 } buf;
5982 Dwarf_Addr bias;
5983 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
5984 Elf_Data dst =
5985 {
5986 &buf, ELF_T_ADDR, EV_CURRENT,
5987 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
5988 };
5989 assert (dst.d_size <= sizeof buf);
5990
5991 if (len < dst.d_size + 3)
5992 return;
5993
5994 Elf_Data src =
5995 {
5996 (void *) data, ELF_T_ADDR, EV_CURRENT,
5997 dst.d_size, 0, 0
5998 };
5999
6000 if (gelf_xlatetom (elf, &dst, &src,
6001 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6002 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6003
6004 probe_type = uprobe3_type;
6005 const char * provider = data + dst.d_size;
6006 provider_name = provider;
6007 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
6008 probe_name = ++name;
6009
6010 // Did we find a matching probe?
6011 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6012 && ((pp_provider == "")
6013 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6014 return;
6015
6016 const char *args = (const char*)memchr (name, '\0', data + len - name);
6017 if (args++ == NULL ||
6018 memchr (args, '\0', data + len - name) != data + len - 1)
6019 if (name == NULL)
6020 return;
6021 arg_string = args;
6022
6023 arg_count = 0;
6024 for (unsigned i = 0; i < arg_string.length(); i++)
6025 if (arg_string[i] == ' ')
6026 arg_count += 1;
6027 if (arg_string.length() != 0)
6028 arg_count += 1;
6029
6030 GElf_Addr base_ref;
6031 if (gelf_getclass (elf) == ELFCLASS32)
6032 {
6033 pc = buf.a32[0];
6034 base_ref = buf.a32[1];
6035 semaphore = buf.a32[2];
6036 }
6037 else
6038 {
6039 pc = buf.a64[0];
6040 base_ref = buf.a64[1];
6041 semaphore = buf.a64[2];
6042 }
6043
6044 semaphore += base - base_ref;
6045 pc += base - base_ref;
6046
7d395255
JS
6047 // The semaphore also needs the ELF bias added now, so
6048 // record_semaphore can properly relocate it later.
6049 semaphore += bias;
6050
40fe32e0 6051 if (sess.verbose > 4)
b530b5b3 6052 clog << _F(" saw .note.stapsdt %s%s ", probe_name.c_str(), (provider_name != "" ? _(" (provider ")+provider_name+") " : "").c_str()) << "@0x" << hex << pc << dec << endl;
40fe32e0
SC
6053
6054 handle_probe_entry();
6055}
6056
6057
c57ea854
SC
6058void
6059sdt_query::iterate_over_probe_entries()
edce5b67 6060{
c57ea854 6061 // probes are in the .probe section
edce5b67
JS
6062 while (probe_scn_offset < pdata->d_size)
6063 {
aff5d390
SC
6064 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6065 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6066 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
aff5d390 6067 if (! have_uprobe() && ! have_kprobe())
edce5b67
JS
6068 {
6069 // Unless this is a mangled .probes section, this happens
6070 // because the name of the probe comes first, followed by
6071 // the sentinel.
6072 if (sess.verbose > 5)
b530b5b3 6073 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6074 probe_scn_offset += sizeof(__uint32_t);
6075 continue;
6076 }
aff5d390
SC
6077 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6078 {
6079 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
6080 if (pbe_v1->type_b != uprobe1_type && pbe_v1->type_b != kprobe1_type)
6081 continue;
6082 }
6083
6084 if (probe_type == uprobe1_type || probe_type == kprobe1_type)
6085 {
79a0ca08 6086 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6087 return;
79a0ca08 6088 semaphore = 0;
aff5d390 6089 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6090 provider_name = ""; // unknown
aff5d390
SC
6091 if (probe_type == uprobe1_type)
6092 {
6093 pc = pbe_v1->arg;
6094 arg_count = 0;
6095 }
6096 else if (probe_type == kprobe1_type)
6097 arg_count = pbe_v1->arg;
6098 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6099 }
6100 else if (probe_type == uprobe2_type || probe_type == kprobe2_type)
6101 {
79a0ca08 6102 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6103 return;
79a0ca08 6104 semaphore = pbe_v2->semaphore;
aff5d390 6105 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6106 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6107 arg_count = pbe_v2->arg_count;
6108 pc = pbe_v2->pc;
6109 if (pbe_v2->arg_string)
6110 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6111 // skip over pbe_v2, probe_name text and provider text
6112 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6113 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6114 }
edce5b67 6115 if (sess.verbose > 4)
b530b5b3 6116 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6117 << "@0x" << hex << pc << dec << endl;
edce5b67 6118
a794dbeb
FCE
6119 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6120 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6121 handle_probe_entry ();
edce5b67 6122 }
edce5b67
JS
6123}
6124
6125
6846cfc8 6126void
4ddb6dd0 6127sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6128{
a794dbeb
FCE
6129 for (unsigned i=0; i<2; i++) {
6130 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6131 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6132 // XXX: multiple addresses?
6133 if (sess.verbose > 2)
b530b5b3 6134 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6135
79a0ca08
SC
6136 Dwarf_Addr addr;
6137 if (this->semaphore)
6138 addr = this->semaphore;
6139 else
6140 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6141 if (addr)
6142 {
7d395255 6143 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6144 dwfl_module_relocate_address (dw.module, &addr);
6145 // XXX: relocation basis?
6146 for (unsigned i = start; i < results.size(); ++i)
6147 results[i]->sdt_semaphore_addr = addr;
6148 if (sess.verbose > 2)
b530b5b3 6149 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6150 return;
6151 }
6152 else
6153 if (sess.verbose > 2)
b530b5b3 6154 clog << _(", not found") << endl;
a794dbeb 6155 }
6846cfc8
SC
6156}
6157
6158
edce5b67
JS
6159void
6160sdt_query::convert_probe (probe *base)
6161{
6162 block *b = new block;
6163 b->tok = base->body->tok;
6164
6165 // XXX: Does this also need to happen for i386 under x86_64 stap?
ebbd2b45 6166 if (sess.architecture == "i386" && have_kprobe())
edce5b67
JS
6167 {
6168 functioncall *rp = new functioncall;
edce5b67
JS
6169 rp->function = "regparm";
6170 rp->tok = b->tok;
6171 literal_number* littid = new literal_number(0);
6172 littid->tok = b->tok;
6173 rp->args.push_back(littid);
6174 expr_statement* es = new expr_statement;
6175 es->tok = b->tok;
6176 es->value = rp;
6177 b->statements.push_back(es);
6178 }
edce5b67 6179
aff5d390 6180 if (have_kprobe())
edce5b67 6181 {
aff5d390 6182 // Generate: if (arg2 != kprobe2_type) next;
edce5b67
JS
6183 if_statement *istid = new if_statement;
6184 istid->thenblock = new next_statement;
6185 istid->elseblock = NULL;
6186 istid->tok = b->tok;
63ea4244 6187 istid->thenblock->tok = b->tok;
edce5b67
JS
6188 comparison *betid = new comparison;
6189 betid->op = "!=";
6190 betid->tok = b->tok;
6191
6192 functioncall *arg2 = new functioncall;
6193 arg2->function = "ulong_arg";
6194 arg2->tok = b->tok;
6195 literal_number* num = new literal_number(2);
6196 num->tok = b->tok;
6197 arg2->args.push_back(num);
6198
6199 betid->left = arg2;
aff5d390 6200 literal_number* littid = new literal_number(probe_type);
edce5b67
JS
6201 littid->tok = b->tok;
6202 betid->right = littid;
6203 istid->condition = betid;
6204 b->statements.push_back(istid);
6205 }
6206
6207 // Generate: if (arg1 != mark("label")) next;
6208 functioncall *fc = new functioncall;
bbafcb1e 6209 fc->function = "ulong_arg";
edce5b67 6210 fc->tok = b->tok;
bbafcb1e 6211 literal_number* num = new literal_number(1);
edce5b67
JS
6212 num->tok = b->tok;
6213 fc->args.push_back(num);
6214
6215 functioncall *fcus = new functioncall;
6216 fcus->function = "user_string";
6217 fcus->type = pe_string;
6218 fcus->tok = b->tok;
6219 fcus->args.push_back(fc);
6220
6221 if_statement *is = new if_statement;
6222 is->thenblock = new next_statement;
6223 is->elseblock = NULL;
6224 is->tok = b->tok;
63ea4244 6225 is->thenblock->tok = b->tok;
edce5b67
JS
6226 comparison *be = new comparison;
6227 be->op = "!=";
6228 be->tok = b->tok;
6229 be->left = fcus;
6230 be->right = new literal_string(probe_name);
63ea4244 6231 be->right->tok = b->tok;
edce5b67
JS
6232 is->condition = be;
6233 b->statements.push_back(is);
6234
6235 // Now replace the body
6236 b->statements.push_back(base->body);
6237 base->body = b;
6238}
6239
6240
c72aa911
JS
6241probe*
6242sdt_query::convert_location ()
edce5b67 6243{
c72aa911 6244 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6245 vector<probe_point::component*> derived_comps;
edce5b67 6246
662539d9
JS
6247 vector<probe_point::component*>::iterator it;
6248 for (it = specific_loc->components.begin();
6249 it != specific_loc->components.end(); ++it)
6250 if ((*it)->functor == TOK_PROCESS)
6251 {
6252 if (have_kprobe())
6253 // start the kernel probe_point
6254 derived_comps.push_back(new probe_point::component(TOK_KERNEL));
6255 else
6256 // copy the process name
6257 derived_comps.push_back(*it);
6258 }
6259 else if ((*it)->functor == TOK_LIBRARY)
6260 {
6261 if (!have_kprobe())
6262 // copy the library name for process probes
6263 derived_comps.push_back(*it);
6264 }
6265 else if ((*it)->functor == TOK_PROVIDER)
6266 {
6267 // replace the possibly wildcarded arg with the specific provider name
6268 *it = new probe_point::component(TOK_PROVIDER,
6269 new literal_string(provider_name));
6270 }
6271 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6272 {
6273 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6274 *it = new probe_point::component(TOK_MARK,
6275 new literal_string(probe_name));
a794dbeb 6276
aff5d390
SC
6277 if (sess.verbose > 3)
6278 switch (probe_type)
6279 {
6280 case uprobe1_type:
b530b5b3 6281 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6282 << hex << pc << dec << endl;
6283 break;
6284 case uprobe2_type:
b530b5b3 6285 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6286 << hex << pc << dec << endl;
6287 break;
40fe32e0 6288 case uprobe3_type:
b530b5b3 6289 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6290 << hex << pc << dec << endl;
6291 break;
6292 case kprobe1_type:
6293 clog << "probe_type == kprobe1" << endl;
6294 break;
6295 case kprobe2_type:
6296 clog << "probe_type == kprobe2" << endl;
6297 break;
aff5d390 6298 default:
b530b5b3
LB
6299 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6300 pp_mark.c_str()) << endl;
aff5d390
SC
6301 }
6302
c72aa911
JS
6303 switch (probe_type)
6304 {
aff5d390
SC
6305 case uprobe1_type:
6306 case uprobe2_type:
40fe32e0 6307 case uprobe3_type:
c72aa911 6308 // process("executable").statement(probe_arg)
662539d9
JS
6309 derived_comps.push_back
6310 (new probe_point::component(TOK_STATEMENT,
6311 new literal_number(pc, true)));
c72aa911
JS
6312 break;
6313
aff5d390
SC
6314 case kprobe1_type:
6315 case kprobe2_type:
b642c901 6316 // kernel.function("*getegid*")
662539d9
JS
6317 derived_comps.push_back
6318 (new probe_point::component(TOK_FUNCTION,
6319 new literal_string("*getegid*")));
b642c901 6320 break;
c72aa911 6321
a794dbeb 6322 default: // deprecated
c72aa911 6323 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6324 derived_comps.push_back
6325 (new probe_point::component(TOK_FUNCTION,
6326 new literal_string("*")));
6327 derived_comps.push_back
c72aa911 6328 (new probe_point::component(TOK_LABEL,
a794dbeb 6329 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6330 break;
6331 }
6332 }
edce5b67 6333
662539d9
JS
6334 probe_point* derived_loc = new probe_point(*specific_loc);
6335 derived_loc->components = derived_comps;
c72aa911 6336 return base_probe->create_alias(derived_loc, specific_loc);
edce5b67
JS
6337}
6338
6339
51d6bda3
SC
6340void
6341sdt_query::query_library (const char *library)
6342{
6343 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6344}
6345
6346
20c6c071 6347void
5227f1ea 6348dwarf_builder::build(systemtap_session & sess,
7a053d3b 6349 probe * base,
20c6c071 6350 probe_point * location,
86bf665e 6351 literal_map_t const & parameters,
20c6c071
GH
6352 vector<derived_probe *> & finished_results)
6353{
b20febf3
FCE
6354 // NB: the kernel/user dwlfpp objects are long-lived.
6355 // XXX: but they should be per-session, as this builder object
6356 // may be reused if we try to cross-instrument multiple targets.
84048984 6357
7a24d422 6358 dwflpp* dw = 0;
6d5d594e 6359 literal_map_t filled_parameters = parameters;
7a24d422 6360
7a24d422 6361 string module_name;
ae2552da
FCE
6362 if (has_null_param (parameters, TOK_KERNEL))
6363 {
6364 dw = get_kern_dw(sess, "kernel");
6365 }
6366 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6367 {
c523a015
LB
6368 size_t dash_pos = 0;
6369 while((dash_pos=module_name.find('-'))!=string::npos)
6370 module_name.replace(int(dash_pos),1,"_");
6371 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6372 // NB: glob patterns get expanded later, during the offline
6373 // elfutils module listing.
ae2552da 6374 dw = get_kern_dw(sess, module_name);
b8da0ad1 6375 }
6d5d594e 6376 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6377 {
6d5d594e
LB
6378 if(has_null_param(filled_parameters, TOK_PROCESS))
6379 {
6380 wordexp_t words;
6381 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6382 if(rc || words.we_wordc <= 0)
6383 throw semantic_error(_("unspecified process probe is invalid without a -c COMMAND"));
6384 module_name = words.we_wordv[0];
6385 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6386 // in the case of TOK_MARK we need to modify locations as well
6387 if(location->components[0]->functor==TOK_PROCESS &&
6388 location->components[0]->arg == 0)
6389 location->components[0]->arg = new literal_string(module_name);
6390 wordfree (& words);
6391 }
37001baa
FCE
6392 // PR6456 process("/bin/*") glob handling
6393 if (contains_glob_chars (module_name))
6394 {
6395 // Expand glob via rewriting the probe-point process("....")
6396 // parameter, asserted to be the first one.
6397
6398 assert (location->components.size() > 0);
6399 assert (location->components[0]->functor == TOK_PROCESS);
6400 assert (location->components[0]->arg);
6401 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6402 assert (lit);
6403
6404 // Evaluate glob here, and call derive_probes recursively with each match.
6405 glob_t the_blob;
6406 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3
LB
6407 if (rc)
6408 throw semantic_error (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
37001baa
FCE
6409 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6410 {
6411 if (pending_interrupts) return;
6412
6413 const char* globbed = the_blob.gl_pathv[i];
6414 struct stat st;
6415
6416 if (access (globbed, X_OK) == 0
6417 && stat (globbed, &st) == 0
6418 && S_ISREG (st.st_mode)) // see find_executable()
6419 {
7977a734
FCE
6420 // Need to call canonicalize here, in order to path-expand
6421 // patterns like process("stap*"). Otherwise it may go through
6422 // to the next round of expansion as ("stap"), leading to a $PATH
6423 // search that's not consistent with the glob search already done.
6424
6425 char *cf = canonicalize_file_name (globbed);
6426 if (cf) globbed = cf;
6427
37001baa 6428 if (sess.verbose > 1)
ce0f6648 6429 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
b530b5b3 6430 module_name.c_str(), globbed) << endl;
37001baa
FCE
6431 // synthesize a new probe_point, with the glob-expanded string
6432 probe_point *pp = new probe_point (*location);
6433 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
6434 new literal_string (globbed));
6435 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6436 pp->components[0] = ppc;
6437
7977a734
FCE
6438 probe* new_probe = new probe (*base, pp);
6439
6440 // We override "optional = true" here, as if the
6441 // wildcarded probe point was given a "?" suffix.
6442
6443 // This is because wildcard probes will be expected
6444 // by users to apply only to some subset of the
6445 // matching binaries, in the sense of "any", rather
6446 // than "all", sort of similarly how
6447 // module("*").function("...") patterns work.
6448
6449 derive_probes (sess, new_probe, finished_results,
6450 true /* NB: not location->optional */ );
37001baa
FCE
6451 }
6452 }
6453
6454 globfree (& the_blob);
6455 return; // avoid falling through
6456 }
6457
b642c901 6458 user_path = find_executable (module_name); // canonicalize it
d1bcbe71
RH
6459
6460 // if the executable starts with "#!", we look for the interpreter of the script
6461 {
6462 ifstream script_file (user_path.c_str () );
6463
6464 if (script_file.good ())
6465 {
6466 string line;
6467
6468 getline (script_file, line);
6469
6470 if (line.compare (0, 2, "#!") == 0)
6471 {
6472 string path_head = line.substr(2);
6473
6474 // remove white spaces at the beginning of the string
6475 size_t p2 = path_head.find_first_not_of(" \t");
6476
6477 if (p2 != string::npos)
6478 {
6479 string path = path_head.substr(p2);
6480
6481 // remove white spaces at the end of the string
6482 p2 = path.find_last_not_of(" \t\n");
6483 if (string::npos != p2)
6484 path.erase(p2+1);
6485
8e13c1a1
RH
6486 // handle "#!/usr/bin/env" redirect
6487 size_t offset = 0;
6488 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
6489 {
6490 offset = sizeof("/bin/env")-1;
6491 }
6492 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
6493 {
6494 offset = sizeof("/usr/bin/env")-1;
6495 }
6496
6497 if (offset != 0)
6498 {
6499 size_t p3 = path.find_first_not_of(" \t", offset);
6500
6501 if (p3 != string::npos)
6502 {
6503 string env_path = path.substr(p3);
6504 user_path = find_executable (env_path);
6505 }
6506 }
6507 else
6508 {
6509 user_path = find_executable (path);
6510 }
d1bcbe71
RH
6511
6512 struct stat st;
6513
6514 if (access (user_path.c_str(), X_OK) == 0
6515 && stat (user_path.c_str(), &st) == 0
6516 && S_ISREG (st.st_mode)) // see find_executable()
6517 {
6518 if (sess.verbose > 1)
b530b5b3
LB
6519 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6520 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
6521
6522 assert (location->components.size() > 0);
6523 assert (location->components[0]->functor == TOK_PROCESS);
6524 assert (location->components[0]->arg);
6525 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6526 assert (lit);
6527
6528 // synthesize a new probe_point, with the expanded string
6529 probe_point *pp = new probe_point (*location);
6530 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
6531 new literal_string (user_path.c_str()));
6532 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6533 pp->components[0] = ppc;
6534
6535 probe* new_probe = new probe (*base, pp);
6536
6537 derive_probes (sess, new_probe, finished_results);
6538
6539 script_file.close();
6540 return;
6541 }
6542 }
6543 }
6544 }
6545 script_file.close();
6546 }
6547
378d78b5
LB
6548 if(get_param (parameters, TOK_LIBRARY, user_lib)
6549 && user_lib.length() && ! contains_glob_chars (user_lib))
6550 module_name = find_executable (user_lib, "LD_LIBRARY_PATH");
63b4fd14 6551 else
b642c901 6552 module_name = user_path; // canonicalize it
d0a7f5a9 6553
f4000852
MW
6554 // There is a similar check in pass 4 (buildrun), but it is
6555 // needed here too to make sure alternatives for optional
6556 // (? or !) process probes are disposed and/or alternatives
6557 // are selected.
6558 if (sess.kernel_config["CONFIG_UTRACE"] != string("y"))
6559 throw semantic_error (_("process probes not available without kernel CONFIG_UTRACE"));
6560
7a24d422
FCE
6561 // user-space target; we use one dwflpp instance per module name
6562 // (= program or shared library)
707bf35e 6563 dw = get_user_dw(sess, module_name);
c8959a29 6564 }
20c6c071 6565
5896cd05 6566 if (sess.verbose > 3)
b530b5b3 6567 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 6568
a794dbeb
FCE
6569 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
6570 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 6571 {
51d6bda3 6572 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
6573 dw->iterate_over_modules(&query_module, &sdtq);
6574 return;
7a05f484 6575 }
20c6c071 6576
8f14e444 6577 unsigned results_pre = finished_results.size();
6d5d594e 6578 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
6579
6580 // XXX: kernel.statement.absolute is a special case that requires no
6581 // dwfl processing. This code should be in a separate builder.
7a24d422 6582 if (q.has_kernel && q.has_absolute)
37ebca01 6583 {
4baf0e53 6584 // assert guru mode for absolute probes
37ebca01
FCE
6585 if (! q.base_probe->privileged)
6586 {
b530b5b3 6587 throw semantic_error (_("absolute statement probe in unprivileged script"),
edce5b67 6588 q.base_probe->tok);
37ebca01
FCE
6589 }
6590
6591 // For kernel.statement(NUM).absolute probe points, we bypass
6592 // all the debuginfo stuff: We just wire up a
6593 // dwarf_derived_probe right here and now.
4baf0e53 6594 dwarf_derived_probe* p =
b8da0ad1
FCE
6595 new dwarf_derived_probe ("", "", 0, "kernel", "",
6596 q.statement_num_val, q.statement_num_val,
6597 q, 0);
37ebca01 6598 finished_results.push_back (p);
1a0dbc5a 6599 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
6600 return;
6601 }
6602
51178501 6603 dw->iterate_over_modules(&query_module, &q);
8f14e444
FCE
6604
6605
6606 // PR11553 special processing: .return probes requested, but
6607 // some inlined function instances matched.
6608 unsigned i_n_r = q.inlined_non_returnable.size();
6609 unsigned results_post = finished_results.size();
6610 if (i_n_r > 0)
6611 {
6612 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
6613 {
6614 string quicklist;
6615 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6616 it != q.inlined_non_returnable.end();
6617 it++)
6618 {
6619 quicklist += " " + (*it);
6620 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
6621 {
6622 quicklist += " ...";
6623 break;
6624 }
6625 }
c57ea854 6626
b530b5b3
LB
6627 sess.print_warning (_F(ngettext("cannot probe .return of %u inlined function %s",
6628 "cannot probe .return of %u inlined functions %s",
6629 quicklist.size()), i_n_r, quicklist.c_str()));
8f14e444
FCE
6630 // There will be also a "no matches" semantic error generated.
6631 }
6632 if (sess.verbose > 1)
b530b5b3
LB
6633 clog << _F(ngettext("skipped .return probe of %u inlined function",
6634 "skipped .return probe of %u inlined functions", i_n_r), i_n_r) << endl;
8f14e444
FCE
6635 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
6636 {
6637 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6638 it != q.inlined_non_returnable.end();
6639 it++)
6640 clog << (*it) << " ";
6641 clog << endl;
6642 }
6643 } // i_n_r > 0
5f0a03a6
JK
6644}
6645
6646symbol_table::~symbol_table()
6647{
c9efa5c9 6648 delete_map(map_by_addr);
5f0a03a6
JK
6649}
6650
6651void
2867a2a1 6652symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
822a6a3d 6653 Dwarf_Addr addr, Dwarf_Addr */*high_addr*/)
5f0a03a6 6654{
ab91b232
JK
6655#ifdef __powerpc__
6656 // Map ".sys_foo" to "sys_foo".
6657 if (name[0] == '.')
6658 name++;
6659#endif
5f0a03a6
JK
6660 func_info *fi = new func_info();
6661 fi->addr = addr;
6662 fi->name = name;
ab91b232 6663 fi->weak = weak;
2867a2a1 6664 fi->descriptor = descriptor;
5f0a03a6
JK
6665 map_by_name[fi->name] = fi;
6666 // TODO: Use a multimap in case there are multiple static
6667 // functions with the same name?
1c6b77e5 6668 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
6669}
6670
6671enum info_status
6672symbol_table::read_symbols(FILE *f, const string& path)
6673{
6674 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
6675 int ret;
2e67a43b
TM
6676 char *name = 0;
6677 char *mod = 0;
5f0a03a6
JK
6678 char type;
6679 unsigned long long addr;
6680 Dwarf_Addr high_addr = 0;
6681 int line = 0;
6682
6683 // %as (non-POSIX) mallocs space for the string and stores its address.
6684 while ((ret = fscanf(f, "%llx %c %as [%as", &addr, &type, &name, &mod)) > 0)
6685 {
2e67a43b
TM
6686 auto_free free_name(name);
6687 auto_free free_mod(mod);
5f0a03a6
JK
6688 line++;
6689 if (ret < 3)
6690 {
3d372d6b 6691 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 6692 line, path.c_str());
5f0a03a6
JK
6693 // Caller should delete symbol_table object.
6694 return info_absent;
6695 }
2e67a43b 6696 else if (ret > 3)
5f0a03a6
JK
6697 {
6698 // Modules are loaded above the kernel, so if we're getting
6699 // modules, we're done.
2e67a43b 6700 break;
5f0a03a6 6701 }
ab91b232 6702 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 6703 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
6704 }
6705
1c6b77e5 6706 if (map_by_addr.size() < 1)
5f0a03a6 6707 {
3d372d6b 6708 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 6709 path.c_str()) << endl;
5f0a03a6
JK
6710 return info_absent;
6711 }
6712 return info_present;
6713}
6714
6715// NB: This currently unused. We use get_from_elf() instead because
6716// that gives us raw addresses -- which we need for modules -- whereas
6717// nm provides the address relative to the beginning of the section.
6718enum info_status
83ca3872
MW
6719symbol_table::read_from_elf_file(const string &path,
6720 const systemtap_session &sess)
5f0a03a6 6721{
58502ae4
JS
6722 vector<string> cmd;
6723 cmd.push_back("/usr/bin/nm");
6724 cmd.push_back("-n");
6725 cmd.push_back("--defined-only");
6726 cmd.push_back("path");
6727
5f0a03a6 6728 FILE *f;
58502ae4
JS
6729 int child_fd;
6730 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
6731 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 6732 {
58502ae4 6733 // nm failures are detected by stap_waitpid
3d372d6b 6734 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 6735 path.c_str(), strerror(errno));
5f0a03a6
JK
6736 return info_absent;
6737 }
6738 enum info_status status = read_symbols(f, path);
58502ae4 6739 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 6740 {
83ca3872 6741 if (status == info_present && ! sess.suppress_warnings)
3d372d6b 6742 cerr << _F("Warning: nm cannot read symbol table from %s\n", path.c_str());
5f0a03a6
JK
6743 return info_absent;
6744 }
6745 return status;
6746}
6747
6748enum info_status
83ca3872
MW
6749symbol_table::read_from_text_file(const string& path,
6750 const systemtap_session &sess)
5f0a03a6
JK
6751{
6752 FILE *f = fopen(path.c_str(), "r");
6753 if (!f)
6754 {
83ca3872 6755 if (! sess.suppress_warnings)
3d372d6b 6756 cerr << _F("Warning: cannot read symbol table from %s -- %s\n",
b530b5b3 6757 path.c_str(), strerror(errno));
5f0a03a6
JK
6758 return info_absent;
6759 }
6760 enum info_status status = read_symbols(f, path);
6761 (void) fclose(f);
6762 return status;
6763}
6764
46f7b6be 6765void
f98c6346 6766symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
6767{
6768#ifdef __powerpc__
6769 /*
6770 * The .opd section contains function descriptors that can look
6771 * just like function entry points. For example, there's a function
6772 * descriptor called "do_exit" that links to the entry point ".do_exit".
6773 * Reject all symbols in .opd.
6774 */
6775 opd_section = SHN_UNDEF;
6776 Dwarf_Addr bias;
6777 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
6778 ?: dwfl_module_getelf (mod, &bias));
6779 Elf_Scn* scn = 0;
6780 size_t shstrndx;
6781
6782 if (!elf)
6783 return;
fcc30d6d 6784 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
6785 return;
6786 while ((scn = elf_nextscn(elf, scn)) != NULL)
6787 {
6788 GElf_Shdr shdr_mem;
6789 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
6790 if (!shdr)
6791 continue;
6792 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
6793 if (!strcmp(name, ".opd"))
6794 {
6795 opd_section = elf_ndxscn(scn);
6796 return;
6797 }
6798 }
6799#endif
6800}
6801
6802bool
6803symbol_table::reject_section(GElf_Word section)
6804{
6805 if (section == SHN_UNDEF)
6806 return true;
6807#ifdef __powerpc__
6808 if (section == opd_section)
6809 return true;
6810#endif
6811 return false;
6812}
6813
5f0a03a6
JK
6814enum info_status
6815symbol_table::get_from_elf()
6816{
6817 Dwarf_Addr high_addr = 0;
6818 Dwfl_Module *mod = mod_info->mod;
6819 int syments = dwfl_module_getsymtab(mod);
6820 assert(syments);
46f7b6be 6821 prepare_section_rejection(mod);
5f0a03a6
JK
6822 for (int i = 1; i < syments; ++i)
6823 {
6824 GElf_Sym sym;
ab91b232
JK
6825 GElf_Word section;
6826 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 6827 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 6828 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 6829 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
6830 }
6831 return info_present;
6832}
6833
5f0a03a6
JK
6834func_info *
6835symbol_table::get_func_containing_address(Dwarf_Addr addr)
6836{
1c6b77e5
JS
6837 iterator_t iter = map_by_addr.upper_bound(addr);
6838 if (iter == map_by_addr.begin())
5f0a03a6 6839 return NULL;
2e67a43b 6840 else
1c6b77e5 6841 return (--iter)->second;
5f0a03a6
JK
6842}
6843
3d372d6b
SC
6844func_info *
6845symbol_table::get_first_func()
6846{
6847 iterator_t iter = map_by_addr.begin();
6848 return (iter)->second;
6849}
6850
5f0a03a6
JK
6851func_info *
6852symbol_table::lookup_symbol(const string& name)
6853{
6854 map<string, func_info*>::iterator i = map_by_name.find(name);
6855 if (i == map_by_name.end())
6856 return NULL;
6857 return i->second;
6858}
6859
6860Dwarf_Addr
6861symbol_table::lookup_symbol_address(const string& name)
6862{
6863 func_info *fi = lookup_symbol(name);
6864 if (fi)
6865 return fi->addr;
6866 return 0;
6867}
6868
ab91b232
JK
6869// This is the kernel symbol table. The kernel macro cond_syscall creates
6870// a weak symbol for each system call and maps it to sys_ni_syscall.
6871// For system calls not implemented elsewhere, this weak symbol shows up
6872// in the kernel symbol table. Following the precedent of dwarfful stap,
6873// we refuse to consider such symbols. Here we delete them from our
6874// symbol table.
6875// TODO: Consider generalizing this and/or making it part of blacklist
6876// processing.
6877void
6878symbol_table::purge_syscall_stubs()
6879{
6880 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
6881 if (stub_addr == 0)
6882 return;
1c6b77e5 6883 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
6884 for (iterator_t iter = purge_range.first;
6885 iter != purge_range.second;
1c6b77e5 6886 )
ab91b232 6887 {
1c6b77e5 6888 func_info *fi = iter->second;
2e67a43b 6889 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 6890 {
2e67a43b 6891 map_by_name.erase(fi->name);
1c6b77e5 6892 map_by_addr.erase(iter++);
2e67a43b 6893 delete fi;
2e67a43b 6894 }
1c6b77e5
JS
6895 else
6896 iter++;
ab91b232
JK
6897 }
6898}
6899
5f0a03a6
JK
6900void
6901module_info::get_symtab(dwarf_query *q)
6902{
6903 systemtap_session &sess = q->sess;
6904
1c6b77e5
JS
6905 if (symtab_status != info_unknown)
6906 return;
6907
5f0a03a6
JK
6908 sym_table = new symbol_table(this);
6909 if (!elf_path.empty())
6910 {
83ca3872
MW
6911 if (name == TOK_KERNEL && !sess.kernel_symtab_path.empty()
6912 && ! sess.suppress_warnings)
3d372d6b 6913 cerr << _F("Warning: reading symbol table from %s -- ignoring %s\n",
b530b5b3 6914 elf_path.c_str(), sess.kernel_symtab_path.c_str()) << endl;
5f0a03a6
JK
6915 symtab_status = sym_table->get_from_elf();
6916 }
6917 else
6918 {
6919 assert(name == TOK_KERNEL);
6920 if (sess.kernel_symtab_path.empty())
6921 {
6922 symtab_status = info_absent;
3d372d6b 6923 cerr << _("Error: Cannot find vmlinux.\n"
b530b5b3 6924 " Consider using --kmap instead of --kelf.")
5f0a03a6
JK
6925 << endl;;
6926 }
6927 else
6928 {
6929 symtab_status =
83ca3872 6930 sym_table->read_from_text_file(sess.kernel_symtab_path, sess);
5f0a03a6
JK
6931 if (symtab_status == info_present)
6932 {
6933 sess.sym_kprobes_text_start =
6934 sym_table->lookup_symbol_address("__kprobes_text_start");
6935 sess.sym_kprobes_text_end =
6936 sym_table->lookup_symbol_address("__kprobes_text_end");
6937 sess.sym_stext = sym_table->lookup_symbol_address("_stext");
5f0a03a6
JK
6938 }
6939 }
6940 }
6941 if (symtab_status == info_absent)
6942 {
6943 delete sym_table;
6944 sym_table = NULL;
6945 return;
6946 }
6947
ab91b232
JK
6948 if (name == TOK_KERNEL)
6949 sym_table->purge_syscall_stubs();
5f0a03a6
JK
6950}
6951
1c6b77e5
JS
6952// update_symtab reconciles data between the elf symbol table and the dwarf
6953// function enumeration. It updates the symbol table entries with the dwarf
6954// die that describes the function, which also signals to query_module_symtab
6955// that a statement probe isn't needed. In return, it also adds aliases to the
6956// function table for names that share the same addr/die.
6957void
6958module_info::update_symtab(cu_function_cache_t *funcs)
6959{
6960 if (!sym_table)
6961 return;
6962
6963 cu_function_cache_t new_funcs;
6964
6965 for (cu_function_cache_t::iterator func = funcs->begin();
6966 func != funcs->end(); func++)
6967 {
6968 // optimization: inlines will never be in the symbol table
6969 if (dwarf_func_inline(&func->second) != 0)
6970 continue;
6971
1ffb8bd1
JS
6972 // XXX We may want to make additional efforts to match mangled elf names
6973 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
6974 // missing, so we may also need to try matching by address. See also the
6975 // notes about _Z in dwflpp::iterate_over_functions().
6976
1c6b77e5
JS
6977 func_info *fi = sym_table->lookup_symbol(func->first);
6978 if (!fi)
6979 continue;
6980
6981 // iterate over all functions at the same address
6982 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
6983 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
6984 {
6985 // update this function with the dwarf die
6986 it->second->die = func->second;
6987
6988 // if this function is a new alias, then
6989 // save it to merge into the function cache
6990 if (it->second != fi)
b7478964 6991 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
6992 }
6993 }
6994
6995 // add all discovered aliases back into the function cache
6996 // NB: this won't replace any names that dwarf may have already found
6997 funcs->insert(new_funcs.begin(), new_funcs.end());
6998}
6999
5f0a03a6
JK
7000module_info::~module_info()
7001{
7002 if (sym_table)
7003 delete sym_table;
b55bc428
FCE
7004}
7005
935447c8 7006// ------------------------------------------------------------------------
888af770 7007// user-space probes
935447c8
DS
7008// ------------------------------------------------------------------------
7009
935447c8 7010
888af770 7011struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7012{
89ba3085
FCE
7013private:
7014 string make_pbm_key (uprobe_derived_probe* p) {
7015 return p->module + "|" + p->section + "|" + lex_cast(p->pid);
7016 }
7017
935447c8 7018public:
888af770 7019 void emit_module_decls (systemtap_session& s);
935447c8
DS
7020 void emit_module_init (systemtap_session& s);
7021 void emit_module_exit (systemtap_session& s);
7022};
7023
7024
888af770
FCE
7025void
7026uprobe_derived_probe::join_group (systemtap_session& s)
7027{
7028 if (! s.uprobe_derived_probes)
7029 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7030 s.uprobe_derived_probes->enroll (this);
93646f4d 7031 enable_task_finder(s);
a96d1db0 7032
8a03658e
JS
7033 // Ask buildrun.cxx to build extra module if needed, and
7034 // signal staprun to load that module
7035 s.need_uprobes = true;
a96d1db0
DN
7036}
7037
888af770 7038
c0f84e7b
SC
7039void
7040uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7041{
7042 dwarf_derived_probe::getargs(arg_set);
7043 arg_set.insert(arg_set.end(), args.begin(), args.end());
7044}
7045
7046
7047void
7048uprobe_derived_probe::saveargs(int nargs)
7049{
7050 for (int i = 1; i <= nargs; i++)
7051 args.push_back("$arg" + lex_cast (i) + ":long");
7052}
7053
7054
2865d17a
DB
7055void
7056uprobe_derived_probe::emit_unprivileged_assertion (translator_output* o)
7057{
7058 // These probes are allowed for unprivileged users, but only in the
7059 // context of processes which they own.
7060 emit_process_owner_assertion (o);
7061}
7062
7063
888af770 7064struct uprobe_builder: public derived_probe_builder
a96d1db0 7065{
888af770 7066 uprobe_builder() {}
822a6a3d 7067 virtual void build(systemtap_session &,
a96d1db0
DN
7068 probe * base,
7069 probe_point * location,
86bf665e 7070 literal_map_t const & parameters,
a96d1db0
DN
7071 vector<derived_probe *> & finished_results)
7072 {
888af770 7073 int64_t process, address;
a96d1db0 7074
888af770 7075 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7076 (void) b1;
888af770 7077 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7078 (void) b2;
888af770
FCE
7079 bool rr = has_null_param (parameters, TOK_RETURN);
7080 assert (b1 && b2); // by pattern_root construction
a96d1db0 7081
0973d815 7082 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7083 }
7084};
7085
7086
7087void
775d51e5 7088uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
a96d1db0 7089{
888af770 7090 if (probes.empty()) return;
775d51e5 7091 s.op->newline() << "/* ---- user probes ---- */";
471fca5e
TM
7092 // If uprobes isn't in the kernel, pull it in from the runtime.
7093
7094 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7095 s.op->newline() << "#include <linux/uprobes.h>";
7096 s.op->newline() << "#else";
7097 s.op->newline() << "#include \"uprobes/uprobes.h\"";
7098 s.op->newline() << "#endif";
7099 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7100 s.op->newline() << "#define UPROBES_API_VERSION 1";
7101 s.op->newline() << "#endif";
a96d1db0 7102
43241c44
FCE
7103 // We'll probably need at least this many:
7104 unsigned minuprobes = probes.size();
7105 // .. but we don't want so many that .bss is inflated (PR10507):
7106 unsigned uprobesize = 64;
7107 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7108 unsigned maxuprobes = maxuprobesmem / uprobesize;
7109
aaf7ffe8
FCE
7110 // Let's choose a value on the geometric middle. This should end up
7111 // between minuprobes and maxuprobes. It's OK if this number turns
7112 // out to be < minuprobes or > maxuprobes. At worst, we get a
7113 // run-time error of one kind (too few: missed uprobe registrations)
7114 // or another (too many: vmalloc errors at module load time).
7115 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7116
6d0f3f0c 7117 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7118 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7119 s.op->newline() << "#endif";
a96d1db0 7120
cc52276b
WC
7121 // Forward decls
7122 s.op->newline() << "#include \"uprobes-common.h\"";
7123
5e112f92
FCE
7124 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7125 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7126 // XXX: consider a slab cache or somesuch for stap_uprobes
7127 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
5e112f92 7128 s.op->newline() << "DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7129
89ba3085
FCE
7130 s.op->assert_0_indent();
7131
89ba3085
FCE
7132 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7133 // This means we process probes[] in two passes.
7134 map <string,unsigned> module_index;
7135 unsigned module_index_ctr = 0;
7136
cc52276b
WC
7137 // not const since embedded task_finder_target struct changes
7138 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7139 s.op->indent(1);
7140 for (unsigned i=0; i<probes.size(); i++)
7141 {
7142 uprobe_derived_probe *p = probes[i];
7143 string pbmkey = make_pbm_key (p);
7144 if (module_index.find (pbmkey) == module_index.end())
7145 {
7146 module_index[pbmkey] = module_index_ctr++;
7147
7148 s.op->newline() << "{";
7149 // NB: it's essential that make_pbm_key() use all of and
7150 // only the same fields as we're about to emit.
7151 s.op->line() << " .finder={";
7152 if (p->pid != 0)
68910c97
JK
7153 s.op->line() << " .pid=" << p->pid << ",";
7154
7155 if (p->section == "") // .statement(addr).absolute
7156 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7157 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7158 {
7159 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7160 s.op->line() << " .callback=&stap_uprobe_process_found,";
7161 }
68910c97 7162 else if (p->section != ".absolute") // ET_DYN
89ba3085 7163 {
4ad95bbc
SC
7164 if (p->has_library)
7165 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7166 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7167 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7168 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7169 }
89ba3085 7170 s.op->line() << " },";
68910c97
JK
7171 if (p->module != "")
7172 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7173 s.op->line() << " },";
7174 }
c57ea854 7175 else
822a6a3d 7176 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7177 }
7178 s.op->newline(-1) << "};";
7179
7180 s.op->assert_0_indent();
7181
cc52276b
WC
7182 // NB: read-only structure
7183 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7184 s.op->indent(1);
888af770
FCE
7185 for (unsigned i =0; i<probes.size(); i++)
7186 {
7187 uprobe_derived_probe* p = probes[i];
7188 s.op->newline() << "{";
89ba3085
FCE
7189 string key = make_pbm_key (p);
7190 unsigned value = module_index[key];
759e1d76
FCE
7191 if (value != 0)
7192 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7193 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7194 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7195
038c38c6 7196 if (p->sdt_semaphore_addr != 0)
63b4fd14 7197 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7198 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0
JS
7199
7200 if (p->has_return)
7201 s.op->line() << " .return_p=1,";
888af770
FCE
7202 s.op->line() << " },";
7203 }
7204 s.op->newline(-1) << "};";
a96d1db0 7205
89ba3085
FCE
7206 s.op->assert_0_indent();
7207
48e685da 7208 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7209 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7210 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
7211 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
7212 "_STP_PROBE_HANDLER_UPROBE");
0e090c74 7213 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7214 << "sup->spec_index >= " << probes.size() << ") {";
7215 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7216 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7217 s.op->newline() << "atomic_dec (&c->busy);";
7218 s.op->newline() << "goto probe_epilogue;";
7219 s.op->newline(-1) << "}";
d9aed31e 7220 s.op->newline() << "c->uregs = regs;";
92c25572 7221 s.op->newline() << "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
6415ddde
MW
7222
7223 // Make it look like the IP is set as it would in the actual user
7224 // task when calling real probe handler. Reset IP regs on return, so
7225 // we don't confuse uprobes. PR10458
7226 s.op->newline() << "{";
7227 s.op->indent(1);
d9aed31e 7228 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7229 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7230 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7231 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7232 s.op->newline(-1) << "}";
7233
a96d1db0 7234 common_probe_entryfn_epilogue (s.op);
888af770 7235 s.op->newline(-1) << "}";
a96d1db0 7236
48e685da 7237 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7238 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7239 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
7240 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
7241 "_STP_PROBE_HANDLER_URETPROBE");
6dceb5c9 7242 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7243 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7244 << "sup->spec_index >= " << probes.size() << ") {";
7245 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7246 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7247 s.op->newline() << "atomic_dec (&c->busy);";
7248 s.op->newline() << "goto probe_epilogue;";
7249 s.op->newline(-1) << "}";
7250
d9aed31e 7251 s.op->newline() << "c->uregs = regs;";
92c25572 7252 s.op->newline() << "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
6415ddde
MW
7253
7254 // Make it look like the IP is set as it would in the actual user
7255 // task when calling real probe handler. Reset IP regs on return, so
7256 // we don't confuse uprobes. PR10458
7257 s.op->newline() << "{";
7258 s.op->indent(1);
d9aed31e 7259 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7260 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7261 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7262 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7263 s.op->newline(-1) << "}";
7264
888af770 7265 common_probe_entryfn_epilogue (s.op);
a96d1db0
DN
7266 s.op->newline(-1) << "}";
7267
89ba3085 7268 s.op->newline();
cc52276b 7269 s.op->newline() << "#include \"uprobes-common.c\"";
6d0f3f0c 7270 s.op->newline();
888af770 7271}
935447c8
DS
7272
7273
888af770
FCE
7274void
7275uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
935447c8 7276{
888af770 7277 if (probes.empty()) return;
935447c8 7278
5e112f92 7279 s.op->newline() << "/* ---- user probes ---- */";
935447c8 7280
01b05e2e 7281 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
7282 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
7283 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
7284 // NB: we assume the rest of the struct (specificaly, sup->up) is
7285 // initialized to zero. This is so that we can use
7286 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
7287 s.op->newline(-1) << "}";
7288 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 7289
89ba3085
FCE
7290 // Set up the task_finders
7291 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
7292 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 7293 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 7294 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 7295
5e112f92
FCE
7296 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
7297 // finders already registered, since mere registration does not
7298 // cause any utrace or memory allocation actions. That happens only
7299 // later, once the task finder engine starts running. So, for a
7300 // partial initialization requiring unwind, we need do nothing.
7301 s.op->newline() << "if (rc) break;";
a7a68293 7302
888af770
FCE
7303 s.op->newline(-1) << "}";
7304}
d0ea46ce 7305
d0a7f5a9 7306
888af770
FCE
7307void
7308uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
7309{
7310 if (probes.empty()) return;
7311 s.op->newline() << "/* ---- user probes ---- */";
e56e51c9 7312
6d0f3f0c
FCE
7313 // NB: there is no stap_unregister_task_finder_target call;
7314 // important stuff like utrace cleanups are done by
d41d451c
FCE
7315 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7316 //
7317 // This function blocks until all callbacks are completed, so there
7318 // is supposed to be no possibility of any registration-related code starting
7319 // to run in parallel with our shutdown here. So we don't need to protect the
7320 // stap_uprobes[] array with the mutex.
d0a7f5a9 7321
01b05e2e 7322 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7323 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7324 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7325 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7326
8faa1fc5 7327 // PR10655: decrement that ENABLED semaphore
c116c31b 7328 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7329 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7330 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7331 s.op->newline() << "struct task_struct *tsk;";
7332 s.op->newline() << "rcu_read_lock();";
6846cfc8 7333
86229a55
DS
7334 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7335 // that the pid is always in the global namespace, not in any
7336 // private namespace.
8faa1fc5 7337 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7338 // We'd like to call find_task_by_pid_ns() here, but it isn't
7339 // exported. So, we call what it calls...
7340 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7341 s.op->newline() << "#else";
7342 s.op->newline() << " tsk = find_task_by_pid (pid);";
7343 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7344
7345 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7346 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7347 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7348 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7349 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7350 s.op->newline() << "#endif";
3c5b8e2b 7351 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7352 s.op->newline(-1) << "}";
8faa1fc5
FCE
7353 // XXX: need to analyze possibility of race condition
7354 s.op->newline(-1) << "}";
7355 s.op->newline() << "rcu_read_unlock();";
7356 s.op->newline(-1) << "}";
6846cfc8 7357
3568f1dd
FCE
7358 s.op->newline() << "if (sups->return_p) {";
7359 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7360 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-uretprobe spec %d index %d pid %d addr %p\\n\", sup->spec_index, j, sup->up.pid, (void*) sup->up.vaddr);";
3568f1dd 7361 s.op->newline() << "#endif";
80b4ad8b
FCE
7362 // NB: PR6829 does not change that we still need to unregister at
7363 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7364 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7365 s.op->newline(-1) << "} else {";
7366 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7367 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-uprobe spec %d index %d pid %d addr %p\\n\", sup->spec_index, j, sup->up.pid, (void*) sup->up.vaddr);";
3568f1dd
FCE
7368 s.op->newline() << "#endif";
7369 s.op->newline() << "unregister_uprobe (& sup->up);";
7370 s.op->newline(-1) << "}";
935447c8 7371
6d0f3f0c 7372 s.op->newline() << "sup->spec_index = -1;";
935447c8 7373
3568f1dd
FCE
7374 // XXX: uprobe missed counts?
7375
6d0f3f0c 7376 s.op->newline(-1) << "}";
935447c8 7377
5e112f92 7378 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
7379}
7380
e6fe60e7
AM
7381// ------------------------------------------------------------------------
7382// Kprobe derived probes
7383// ------------------------------------------------------------------------
7384
4627ed58 7385static const string TOK_KPROBE("kprobe");
935447c8 7386
bae55db9 7387struct kprobe_derived_probe: public derived_probe
d0ea46ce 7388{
bae55db9
JS
7389 kprobe_derived_probe (probe *base,
7390 probe_point *location,
7391 const string& name,
7392 int64_t stmt_addr,
7393 bool has_return,
7394 bool has_statement,
7395 bool has_maxactive,
b642c901
SC
7396 bool has_path,
7397 bool has_library,
7398 long maxactive_val,
7399 const string& path,
7400 const string& library
bae55db9
JS
7401 );
7402 string symbol_name;
7403 Dwarf_Addr addr;
7404 bool has_return;
7405 bool has_statement;
7406 bool has_maxactive;
b642c901
SC
7407 bool has_path;
7408 bool has_library;
bae55db9 7409 long maxactive_val;
b642c901
SC
7410 string path;
7411 string library;
bae55db9
JS
7412 bool access_var;
7413 void printsig (std::ostream &o) const;
7414 void join_group (systemtap_session& s);
7415};
d0ea46ce 7416
bae55db9
JS
7417struct kprobe_derived_probe_group: public derived_probe_group
7418{
7419private:
7420 multimap<string,kprobe_derived_probe*> probes_by_module;
7421 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 7422
bae55db9
JS
7423public:
7424 void enroll (kprobe_derived_probe* probe);
7425 void emit_module_decls (systemtap_session& s);
7426 void emit_module_init (systemtap_session& s);
7427 void emit_module_exit (systemtap_session& s);
7428};
d0ea46ce 7429
e6fe60e7
AM
7430kprobe_derived_probe::kprobe_derived_probe (probe *base,
7431 probe_point *location,
b6371390 7432 const string& name,
e6fe60e7 7433 int64_t stmt_addr,
b6371390
JS
7434 bool has_return,
7435 bool has_statement,
7436 bool has_maxactive,
b642c901
SC
7437 bool has_path,
7438 bool has_library,
7439 long maxactive_val,
7440 const string& path,
7441 const string& library
b6371390 7442 ):
4c5d1300 7443 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 7444 symbol_name (name), addr (stmt_addr),
b6371390 7445 has_return (has_return), has_statement (has_statement),
b642c901
SC
7446 has_maxactive (has_maxactive), has_path (has_path),
7447 has_library (has_library),
7448 maxactive_val (maxactive_val),
7449 path (path), library (library)
e6fe60e7
AM
7450{
7451 this->tok = base->tok;
7452 this->access_var = false;
d0ea46ce 7453
e6fe60e7
AM
7454#ifndef USHRT_MAX
7455#define USHRT_MAX 32767
7456#endif
d0ea46ce 7457
46856d8d
JS
7458 // Expansion of $target variables in the probe body produces an error during
7459 // translate phase, since we're not using debuginfo
d0ea46ce 7460
e6fe60e7 7461 vector<probe_point::component*> comps;
46856d8d 7462 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 7463
46856d8d
JS
7464 if (has_statement)
7465 {
9ea68eb9
JS
7466 comps.push_back (new probe_point::component(TOK_STATEMENT,
7467 new literal_number(addr, true)));
46856d8d
JS
7468 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
7469 }
7470 else
7471 {
7472 size_t pos = name.find(':');
7473 if (pos != string::npos)
d0ea46ce 7474 {
46856d8d
JS
7475 string module = name.substr(0, pos);
7476 string function = name.substr(pos + 1);
7477 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
7478 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
7479 }
7480 else
7481 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 7482 }
d0ea46ce 7483
b6371390
JS
7484 if (has_return)
7485 comps.push_back (new probe_point::component(TOK_RETURN));
7486 if (has_maxactive)
7487 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 7488
e6fe60e7
AM
7489 this->sole_location()->components = comps;
7490}
d0ea46ce 7491
e6fe60e7
AM
7492void kprobe_derived_probe::printsig (ostream& o) const
7493{
7494 sole_location()->print (o);
7495 o << " /* " << " name = " << symbol_name << "*/";
7496 printsig_nested (o);
7497}
d0ea46ce 7498
e6fe60e7
AM
7499void kprobe_derived_probe::join_group (systemtap_session& s)
7500{
d0ea46ce 7501
e6fe60e7
AM
7502 if (! s.kprobe_derived_probes)
7503 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
7504 s.kprobe_derived_probes->enroll (this);
d0ea46ce 7505
e6fe60e7 7506}
d0ea46ce 7507
e6fe60e7
AM
7508void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
7509{
7510 probes_by_module.insert (make_pair (p->symbol_name, p));
7511 // probes of same symbol should share single kprobe/kretprobe
7512}
d0ea46ce 7513
e6fe60e7
AM
7514void
7515kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
7516{
7517 if (probes_by_module.empty()) return;
d0ea46ce 7518
e6fe60e7 7519 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 7520
e6fe60e7
AM
7521 // Warn of misconfigured kernels
7522 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
7523 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
7524 s.op->newline() << "#endif";
7525 s.op->newline();
d0ea46ce 7526
f07c3b68 7527 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 7528 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
7529 s.op->newline() << "#endif";
7530
e6fe60e7 7531 // Forward declare the master entry functions
88747011 7532 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 7533 s.op->line() << " struct pt_regs *regs);";
88747011 7534 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 7535 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 7536
e6fe60e7
AM
7537 // Emit an array of kprobe/kretprobe pointers
7538 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 7539 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 7540 s.op->newline() << "#endif";
d0ea46ce 7541
e6fe60e7 7542 // Emit the actual probe list.
d0ea46ce 7543
e6fe60e7
AM
7544 s.op->newline() << "static struct stap_dwarfless_kprobe {";
7545 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
7546 s.op->newline() << "#ifdef __ia64__";
7547 s.op->newline() << "struct kprobe dummy;";
7548 s.op->newline() << "#endif";
7549 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
7550 // NB: bss!
d0ea46ce 7551
e6fe60e7
AM
7552 s.op->newline() << "static struct stap_dwarfless_probe {";
7553 s.op->newline(1) << "const unsigned return_p:1;";
7554 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 7555 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
7556 s.op->newline() << "unsigned registered_p:1;";
7557 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 7558
e6fe60e7
AM
7559 // Function Names are mostly small and uniform enough to justify putting
7560 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 7561
faea5e16
JS
7562 size_t symbol_string_name_max = 0;
7563 size_t symbol_string_name_tot = 0;
e6fe60e7 7564 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 7565 {
e6fe60e7
AM
7566 kprobe_derived_probe* p = it->second;
7567#define DOIT(var,expr) do { \
7568 size_t var##_size = (expr) + 1; \
7569 var##_max = max (var##_max, var##_size); \
7570 var##_tot += var##_size; } while (0)
e6fe60e7
AM
7571 DOIT(symbol_string_name, p->symbol_name.size());
7572#undef DOIT
6270adc1
MH
7573 }
7574
e6fe60e7
AM
7575#define CALCIT(var) \
7576 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 7577
e6fe60e7
AM
7578 CALCIT(symbol_string);
7579#undef CALCIT
6270adc1 7580
bd659351 7581 s.op->newline() << "unsigned long address;";
26e63673 7582 s.op->newline() << "struct stap_probe * const probe;";
e6fe60e7
AM
7583 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
7584 s.op->indent(1);
6270adc1 7585
e6fe60e7
AM
7586 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
7587 {
7588 kprobe_derived_probe* p = it->second;
7589 s.op->newline() << "{";
7590 if (p->has_return)
7591 s.op->line() << " .return_p=1,";
6270adc1 7592
e6fe60e7
AM
7593 if (p->has_maxactive)
7594 {
7595 s.op->line() << " .maxactive_p=1,";
7596 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
7597 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
7598 }
6270adc1 7599
b350f56b
JS
7600 if (p->locations[0]->optional)
7601 s.op->line() << " .optional_p=1,";
7602
e6fe60e7 7603 if (p->has_statement)
c8d9d15e 7604 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 7605 else
c8d9d15e 7606 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 7607
faea5e16 7608 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 7609 s.op->line() << " },";
935447c8
DS
7610 }
7611
e6fe60e7 7612 s.op->newline(-1) << "};";
5d67b47c 7613
e6fe60e7
AM
7614 // Emit the kprobes callback function
7615 s.op->newline();
88747011 7616 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
7617 s.op->line() << " struct pt_regs *regs) {";
7618 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7619 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7620 // Check that the index is plausible
7621 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7622 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7623 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7624 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7625 s.op->line() << "];";
6eefe942
MW
7626 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7627 "_STP_PROBE_HANDLER_KPROBE");
d9aed31e 7628 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
7629
7630 // Make it look like the IP is set as it wouldn't have been replaced
7631 // by a breakpoint instruction when calling real probe handler. Reset
7632 // IP regs on return, so we don't confuse kprobes. PR10458
7633 s.op->newline() << "{";
7634 s.op->indent(1);
d9aed31e 7635 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 7636 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 7637 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7638 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7639 s.op->newline(-1) << "}";
7640
e6fe60e7
AM
7641 common_probe_entryfn_epilogue (s.op);
7642 s.op->newline() << "return 0;";
7643 s.op->newline(-1) << "}";
935447c8 7644
e6fe60e7
AM
7645 // Same for kretprobes
7646 s.op->newline();
88747011 7647 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
7648 s.op->line() << " struct pt_regs *regs) {";
7649 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 7650
e6fe60e7
AM
7651 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7652 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7653 // Check that the index is plausible
7654 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7655 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7656 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7657 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7658 s.op->line() << "];";
935447c8 7659
6eefe942
MW
7660 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7661 "_STP_PROBE_HANDLER_KRETPROBE");
d9aed31e 7662 s.op->newline() << "c->kregs = regs;";
6dceb5c9 7663 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
7664
7665 // Make it look like the IP is set as it wouldn't have been replaced
7666 // by a breakpoint instruction when calling real probe handler. Reset
7667 // IP regs on return, so we don't confuse kprobes. PR10458
7668 s.op->newline() << "{";
7669 s.op->indent(1);
d9aed31e 7670 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 7671 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 7672 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7673 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7674 s.op->newline(-1) << "}";
7675
e6fe60e7
AM
7676 common_probe_entryfn_epilogue (s.op);
7677 s.op->newline() << "return 0;";
7678 s.op->newline(-1) << "}";
bd659351 7679
03a4ec63 7680 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7681 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
7682 s.op->newline() << " struct module *owner,";
7683 s.op->newline() << " unsigned long val) {";
7684 s.op->newline(1) << "int i;";
fc1d2aa2
MW
7685 s.op->newline() << "int *p = (int *) data;";
7686 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
7687 << " && *p > 0; i++) {";
bd659351
MW
7688 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7689 s.op->newline() << "if (! sdp->address)";
fc1d2aa2 7690 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 7691 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
7692 s.op->newline() << "(*p)--;";
7693 s.op->newline(-1) << "}";
7694 s.op->newline(-2) << "}";
7695 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 7696 s.op->newline(-1) << "}";
03a4ec63 7697 s.op->newline() << "#endif";
935447c8
DS
7698}
7699
e6fe60e7 7700
6270adc1 7701void
e6fe60e7 7702kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 7703{
03a4ec63 7704 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
7705 s.op->newline() << "{";
7706 s.op->newline(1) << "int p = 0;";
7707 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
7708 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7709 s.op->newline() << "if (! sdp->address)";
7710 s.op->newline(1) << "p++;";
7711 s.op->newline(-2) << "}";
7712 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
7713 s.op->newline(-1) << "}";
03a4ec63 7714 s.op->newline() << "#endif";
bd659351 7715
e6fe60e7 7716 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 7717 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 7718 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 7719 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
7720 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
7721
7722 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7723 s.op->newline() << "if (! addr) {";
7724 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
7725 s.op->newline() << "if (!sdp->optional_p)";
7726 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
7727 s.op->newline(-1) << "continue;";
bd659351 7728 s.op->newline(-1) << "}";
03a4ec63
MW
7729 s.op->newline() << "#endif";
7730
26e63673 7731 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 7732 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 7733 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 7734 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 7735 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 7736 s.op->newline() << "#endif";
e6fe60e7
AM
7737 s.op->newline() << "if (sdp->maxactive_p) {";
7738 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
7739 s.op->newline(-1) << "} else {";
f07c3b68 7740 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 7741 s.op->newline(-1) << "}";
88747011 7742 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
7743 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
7744 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 7745 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 7746 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 7747 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 7748 s.op->newline() << "#endif";
c8d9d15e 7749 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
7750 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
7751 s.op->newline() << "if (rc == 0) {";
7752 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
7753 s.op->newline() << "if (rc != 0)";
7754 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
7755 s.op->newline(-2) << "}";
7756 s.op->newline() << "#else";
7757 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
7758 s.op->newline() << "#endif";
7759 s.op->newline(-1) << "} else {";
7760 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 7761 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 7762 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 7763 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 7764 s.op->newline() << "#endif";
88747011 7765 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 7766 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 7767 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 7768 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 7769 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 7770 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 7771 s.op->newline() << "#endif";
e6fe60e7
AM
7772 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
7773 s.op->newline() << "if (rc == 0) {";
7774 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
7775 s.op->newline() << "if (rc != 0)";
7776 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
7777 s.op->newline(-2) << "}";
7778 s.op->newline() << "#else";
7779 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
7780 s.op->newline() << "#endif";
7781 s.op->newline(-1) << "}";
7782 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
7783 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 7784 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 7785 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 7786 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
7787 // XXX: shall we increment numskipped?
7788 s.op->newline(-1) << "}";
6270adc1 7789
e6fe60e7
AM
7790 s.op->newline() << "else sdp->registered_p = 1;";
7791 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
7792}
7793
b4be7cbc 7794
e6fe60e7
AM
7795void
7796kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 7797{
e6fe60e7
AM
7798 //Unregister kprobes by batch interfaces.
7799 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
7800 s.op->newline() << "j = 0;";
7801 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7802 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7803 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7804 s.op->newline() << "if (! sdp->registered_p) continue;";
7805 s.op->newline() << "if (!sdp->return_p)";
c9116e99 7806 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 7807 s.op->newline(-2) << "}";
c9116e99 7808 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7809 s.op->newline() << "j = 0;";
7810 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7811 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7812 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7813 s.op->newline() << "if (! sdp->registered_p) continue;";
7814 s.op->newline() << "if (sdp->return_p)";
c9116e99 7815 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 7816 s.op->newline(-2) << "}";
c9116e99 7817 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7818 s.op->newline() << "#ifdef __ia64__";
7819 s.op->newline() << "j = 0;";
7820 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7821 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7822 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7823 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 7824 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 7825 s.op->newline(-1) << "}";
c9116e99 7826 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7827 s.op->newline() << "#endif";
7828 s.op->newline() << "#endif";
3e3bd7b6 7829
e6fe60e7
AM
7830 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7831 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7832 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7833 s.op->newline() << "if (! sdp->registered_p) continue;";
7834 s.op->newline() << "if (sdp->return_p) {";
7835 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
7836 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
7837 s.op->newline() << "#endif";
7838 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
7839 s.op->newline() << "#ifdef STP_TIMING";
7840 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 7841 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7
AM
7842 s.op->newline(-1) << "#endif";
7843 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
7844 s.op->newline() << "#ifdef STP_TIMING";
7845 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 7846 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
e6fe60e7
AM
7847 s.op->newline(-1) << "#endif";
7848 s.op->newline(-1) << "} else {";
7849 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
7850 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
7851 s.op->newline() << "#endif";
7852 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
7853 s.op->newline() << "#ifdef STP_TIMING";
7854 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 7855 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
7856 s.op->newline(-1) << "#endif";
7857 s.op->newline(-1) << "}";
7858 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
7859 s.op->newline() << "unregister_kprobe (&kp->dummy);";
7860 s.op->newline() << "#endif";
7861 s.op->newline() << "sdp->registered_p = 0;";
7862 s.op->newline(-1) << "}";
f8a968bc
JS
7863}
7864
e6fe60e7 7865struct kprobe_builder: public derived_probe_builder
3c1b3d06 7866{
e6fe60e7
AM
7867 kprobe_builder() {}
7868 virtual void build(systemtap_session & sess,
7869 probe * base,
7870 probe_point * location,
7871 literal_map_t const & parameters,
7872 vector<derived_probe *> & finished_results);
7873};
3c1b3d06
FCE
7874
7875
79189b84 7876void
822a6a3d 7877kprobe_builder::build(systemtap_session &,
e6fe60e7
AM
7878 probe * base,
7879 probe_point * location,
7880 literal_map_t const & parameters,
7881 vector<derived_probe *> & finished_results)
79189b84 7882{
e6fe60e7 7883 string function_string_val, module_string_val;
b642c901 7884 string path, library;
b6371390
JS
7885 int64_t statement_num_val = 0, maxactive_val = 0;
7886 bool has_function_str, has_module_str, has_statement_num;
7887 bool has_absolute, has_return, has_maxactive;
b642c901 7888 bool has_path, has_library;
79189b84 7889
b6371390
JS
7890 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
7891 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
7892 has_return = has_null_param (parameters, TOK_RETURN);
7893 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
7894 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
7895 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
7896 has_path = get_param (parameters, TOK_PROCESS, path);
7897 has_library = get_param (parameters, TOK_LIBRARY, library);
7898
7899 if (has_path)
7900 path = find_executable (path);
7901 if (has_library)
7902 library = find_executable (library, "LD_LIBRARY_PATH");
c57ea854 7903
b6371390 7904 if (has_function_str)
6fb70fb7 7905 {
b6371390
JS
7906 if (has_module_str)
7907 function_string_val = module_string_val + ":" + function_string_val;
86758d5f 7908
b6371390
JS
7909 finished_results.push_back (new kprobe_derived_probe (base,
7910 location, function_string_val,
7911 0, has_return,
7912 has_statement_num,
7913 has_maxactive,
b642c901
SC
7914 has_path,
7915 has_library,
7916 maxactive_val,
7917 path,
7918 library));
6fb70fb7 7919 }
e6fe60e7 7920 else
b6371390
JS
7921 {
7922 // assert guru mode for absolute probes
7923 if ( has_statement_num && has_absolute && !base->privileged )
b530b5b3 7924 throw semantic_error (_("absolute statement probe in unprivileged script"), base->tok);
b6371390
JS
7925
7926 finished_results.push_back (new kprobe_derived_probe (base,
7927 location, "",
7928 statement_num_val,
7929 has_return,
7930 has_statement_num,
7931 has_maxactive,
b642c901
SC
7932 has_path,
7933 has_library,
7934 maxactive_val,
7935 path,
7936 library));
96b030fe 7937 }
79189b84
JS
7938}
7939
dd225250
PS
7940// ------------------------------------------------------------------------
7941// Hardware breakpoint based probes.
7942// ------------------------------------------------------------------------
7943
7944static const string TOK_HWBKPT("data");
7945static const string TOK_HWBKPT_WRITE("write");
7946static const string TOK_HWBKPT_RW("rw");
7947static const string TOK_LENGTH("length");
7948
7949#define HWBKPT_READ 0
7950#define HWBKPT_WRITE 1
7951#define HWBKPT_RW 2
7952struct hwbkpt_derived_probe: public derived_probe
7953{
7954 hwbkpt_derived_probe (probe *base,
7955 probe_point *location,
7956 uint64_t addr,
7957 string symname,
7958 unsigned int len,
7959 bool has_only_read_access,
7960 bool has_only_write_access,
7961 bool has_rw_access
7962 );
7963 Dwarf_Addr hwbkpt_addr;
7964 string symbol_name;
7965 unsigned int hwbkpt_access,hwbkpt_len;
7966
7967 void printsig (std::ostream &o) const;
7968 void join_group (systemtap_session& s);
7969};
7970
7971struct hwbkpt_derived_probe_group: public derived_probe_group
7972{
dd225250 7973private:
dac77b80 7974 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
7975
7976public:
7977 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
7978 void emit_module_decls (systemtap_session& s);
7979 void emit_module_init (systemtap_session& s);
7980 void emit_module_exit (systemtap_session& s);
7981};
7982
7983hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
7984 probe_point *location,
7985 uint64_t addr,
7986 string symname,
7987 unsigned int len,
7988 bool has_only_read_access,
7989 bool has_only_write_access,
822a6a3d 7990 bool):
4c5d1300 7991 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
7992 hwbkpt_addr (addr),
7993 symbol_name (symname),
7994 hwbkpt_len (len)
7995{
7996 this->tok = base->tok;
7997
7998 vector<probe_point::component*> comps;
7999 comps.push_back (new probe_point::component(TOK_KERNEL));
8000
8001 if (hwbkpt_addr)
9ea68eb9
JS
8002 comps.push_back (new probe_point::component (TOK_HWBKPT,
8003 new literal_number(hwbkpt_addr, true)));
8004 else if (symbol_name.size())
8005 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
8006
8007 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
8008
8009 if (has_only_read_access)
9ea68eb9 8010 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
8011//TODO add code for comps.push_back for read, since this flag is not for x86
8012
8013 else
9ea68eb9
JS
8014 {
8015 if (has_only_write_access)
8016 {
8017 this->hwbkpt_access = HWBKPT_WRITE ;
8018 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
8019 }
8020 else
8021 {
8022 this->hwbkpt_access = HWBKPT_RW ;
8023 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
8024 }
8025 }
dd225250
PS
8026
8027 this->sole_location()->components = comps;
8028}
8029
8030void hwbkpt_derived_probe::printsig (ostream& o) const
8031{
8032 sole_location()->print (o);
8033 printsig_nested (o);
8034}
8035
8036void hwbkpt_derived_probe::join_group (systemtap_session& s)
8037{
dac77b80
FCE
8038 if (! s.hwbkpt_derived_probes)
8039 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
8040 s.hwbkpt_derived_probes->enroll (this, s);
8041}
8042
8043void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
8044{
dac77b80
FCE
8045 hwbkpt_probes.push_back (p);
8046
8047 unsigned max_hwbkpt_probes_by_arch = 0;
8048 if (s.architecture == "i386" || s.architecture == "x86_64")
8049 max_hwbkpt_probes_by_arch = 4;
8050 else if (s.architecture == "s390")
8051 max_hwbkpt_probes_by_arch = 1;
8052
c57ea854 8053 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
dac77b80 8054 if (! s.suppress_warnings)
b530b5b3
LB
8055 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
8056 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
8057}
8058
8059void
8060hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
8061{
dac77b80 8062 if (hwbkpt_probes.empty()) return;
dd225250
PS
8063
8064 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
8065
8066 s.op->newline() << "#include <linux/perf_event.h>";
8067 s.op->newline() << "#include <linux/hw_breakpoint.h>";
8068 s.op->newline();
8069
8070 // Forward declare the master entry functions
8071 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8072 s.op->line() << " int nmi,";
8073 s.op->line() << " struct perf_sample_data *data,";
8074 s.op->line() << " struct pt_regs *regs);";
79189b84 8075
dd225250
PS
8076 // Emit the actual probe list.
8077
8078 s.op->newline() << "static struct perf_event_attr ";
dac77b80 8079 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8080
8081 s.op->newline() << "static struct perf_event **";
dac77b80 8082 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8083 s.op->newline() << "static struct stap_hwbkpt_probe {";
8084 s.op->newline() << "int registered_p:1;";
43650b10 8085// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
8086// registered_p = 1 signifies a probe that got registered successfully
8087
faea5e16 8088 // Symbol Names are mostly small and uniform enough
dd225250 8089 // to justify putting const char*.
dac77b80 8090 s.op->newline() << "const char * const symbol;";
dd225250
PS
8091
8092 s.op->newline() << "const unsigned long address;";
8093 s.op->newline() << "uint8_t atype;";
bb0a4e12 8094 s.op->newline() << "unsigned int len;";
26e63673 8095 s.op->newline() << "struct stap_probe * const probe;";
dd225250
PS
8096 s.op->newline() << "} stap_hwbkpt_probes[] = {";
8097 s.op->indent(1);
8098
dac77b80 8099 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 8100 {
dac77b80 8101 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 8102 s.op->newline() << "{";
dd225250
PS
8103 if (p->symbol_name.size())
8104 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
8105 else
8106 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
8107 switch(p->hwbkpt_access){
8108 case HWBKPT_READ:
8109 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 8110 break;
dd225250
PS
8111 case HWBKPT_WRITE:
8112 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 8113 break;
dd225250
PS
8114 case HWBKPT_RW:
8115 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 8116 break;
dd225250
PS
8117 };
8118 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 8119 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 8120 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
8121 s.op->line() << " },";
8122 }
dac77b80 8123 s.op->newline(-1) << "};";
dd225250
PS
8124
8125 // Emit the hwbkpt callback function
8126 s.op->newline() ;
8127 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8128 s.op->line() << " int nmi,";
8129 s.op->line() << " struct perf_sample_data *data,";
8130 s.op->line() << " struct pt_regs *regs) {";
dac77b80
FCE
8131 s.op->newline(1) << "unsigned int i;";
8132 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
8133 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
8134 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8135 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
8136 s.op->newline() << "if (bp->attr.bp_addr==hp->bp_addr && bp->attr.bp_type==hp->bp_type && bp->attr.bp_len==hp->bp_len) {";
8137 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
6eefe942
MW
8138 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
8139 "_STP_PROBE_HANDLER_HWBKPT");
d9aed31e
MW
8140 s.op->newline() << "if (user_mode(regs)) {";
8141 s.op->newline(1)<< "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
8142 s.op->newline() << "c->uregs = regs;";
8143 s.op->newline(-1) << "} else {";
8144 s.op->newline(1) << "c->kregs = regs;";
8145 s.op->newline(-1) << "}";
26e63673 8146 s.op->newline() << "(*sdp->probe->ph) (c);";
dd225250 8147 common_probe_entryfn_epilogue (s.op);
dac77b80 8148 s.op->newline(-1) << "}";
dd225250
PS
8149 s.op->newline(-1) << "}";
8150 s.op->newline() << "return 0;";
dac77b80 8151 s.op->newline(-1) << "}";
dd225250
PS
8152}
8153
8154void
8155hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
8156{
dac77b80 8157 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
8158 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
8159 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8160 s.op->newline() << "void *addr = (void *) sdp->address;";
8161 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
8162 s.op->newline() << "hw_breakpoint_init(hp);";
8163 s.op->newline() << "if (addr)";
8164 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
8165 s.op->newline(-1) << "else { ";
8166 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
8167 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 8168 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
8169 s.op->newline() << "continue;";
8170 s.op->newline(-1) << "}";
8171 s.op->newline(-1) << "}";
8172 s.op->newline() << "hp->bp_type = sdp->atype;";
8173
8174 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 8175 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
8176 {
8177 s.op->newline() << "switch(sdp->len) {";
8178 s.op->newline() << "case 1:";
8179 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
8180 s.op->newline() << "break;";
8181 s.op->newline(-1) << "case 2:";
8182 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
8183 s.op->newline() << "break;";
8184 s.op->newline(-1) << "case 3:";
8185 s.op->newline() << "case 4:";
8186 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
8187 s.op->newline() << "break;";
8188 s.op->newline(-1) << "case 5:";
8189 s.op->newline() << "case 6:";
8190 s.op->newline() << "case 7:";
8191 s.op->newline() << "case 8:";
8192 s.op->newline() << "default:"; // XXX: could instead reject
8193 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
8194 s.op->newline() << "break;";
8195 s.op->newline(-1) << "}";
8196 }
8197 else // other architectures presumed straightforward
8198 s.op->newline() << "hp->bp_len = sdp->len;";
8199
26e63673 8200 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
8201 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
8202 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
8203 s.op->newline() << "#else";
dac77b80 8204 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 8205 s.op->newline() << "#endif";
43650b10
WC
8206 s.op->newline() << "rc = 0;";
8207 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
8208 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
8209 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
8210 s.op->newline(-1) << "}";
217ef1f4
WC
8211 s.op->newline() << "if (rc) {";
8212 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 8213 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 8214 s.op->newline(-1) << "}";
dd225250 8215 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
8216 s.op->newline(-1) << "}"; // for loop
8217}
8218
8219void
8220hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
8221{
8222 //Unregister hwbkpt probes.
dac77b80 8223 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 8224 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
8225 s.op->newline() << "if (sdp->registered_p == 0) continue;";
8226 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
8227 s.op->newline() << "sdp->registered_p = 0;";
8228 s.op->newline(-1) << "}";
8229}
8230
8231struct hwbkpt_builder: public derived_probe_builder
8232{
8233 hwbkpt_builder() {}
8234 virtual void build(systemtap_session & sess,
8235 probe * base,
8236 probe_point * location,
8237 literal_map_t const & parameters,
8238 vector<derived_probe *> & finished_results);
8239};
8240
8241void
8242hwbkpt_builder::build(systemtap_session & sess,
8243 probe * base,
8244 probe_point * location,
8245 literal_map_t const & parameters,
8246 vector<derived_probe *> & finished_results)
8247{
8248 string symbol_str_val;
8249 int64_t hwbkpt_address, len;
8250 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
8251
b47f3a55 8252 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
b530b5b3 8253 throw semantic_error (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
8254 location->components[0]->tok);
8255 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
b530b5b3 8256 throw semantic_error (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
8257 location->components[0]->tok);
8258
dd225250
PS
8259 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
8260 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
8261 has_len = get_param (parameters, TOK_LENGTH, len);
8262 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
8263 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
8264
8265 if (!has_len)
8266 len = 1;
8267
8268 if (has_addr)
8269 finished_results.push_back (new hwbkpt_derived_probe (base,
8270 location,
8271 hwbkpt_address,
8272 "",len,0,
8273 has_write,
8274 has_rw));
5d8a0aea 8275 else if (has_symbol_str)
dd225250
PS
8276 finished_results.push_back (new hwbkpt_derived_probe (base,
8277 location,
8278 0,
8279 symbol_str_val,len,0,
8280 has_write,
8281 has_rw));
5d8a0aea
FCE
8282 else
8283 assert (0);
dd225250 8284}
342d3f96 8285
0a6f5a3f
JS
8286// ------------------------------------------------------------------------
8287// statically inserted kernel-tracepoint derived probes
8288// ------------------------------------------------------------------------
8289
6fb70fb7 8290struct tracepoint_arg
79189b84 8291{
ad370dcc 8292 string name, c_type, typecast;
dcaa1a65 8293 bool usable, used, isptr;
f8a968bc 8294 Dwarf_Die type_die;
dcaa1a65 8295 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 8296};
79189b84 8297
0a6f5a3f
JS
8298struct tracepoint_derived_probe: public derived_probe
8299{
79189b84
JS
8300 tracepoint_derived_probe (systemtap_session& s,
8301 dwflpp& dw, Dwarf_Die& func_die,
8302 const string& tracepoint_name,
8303 probe* base_probe, probe_point* location);
bc9a523d 8304
79189b84 8305 systemtap_session& sess;
6fb70fb7
JS
8306 string tracepoint_name, header;
8307 vector <struct tracepoint_arg> args;
bc9a523d 8308
6fb70fb7 8309 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 8310 void getargs (std::list<std::string> &arg_set) const;
79189b84 8311 void join_group (systemtap_session& s);
3e3bd7b6 8312 void print_dupe_stamp(ostream& o);
0a6f5a3f 8313};
79189b84
JS
8314
8315
0a6f5a3f 8316struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 8317{
79189b84
JS
8318 void emit_module_decls (systemtap_session& s);
8319 void emit_module_init (systemtap_session& s);
8320 void emit_module_exit (systemtap_session& s);
0a6f5a3f 8321};
79189b84 8322
bc9a523d 8323
f8a968bc
JS
8324struct tracepoint_var_expanding_visitor: public var_expanding_visitor
8325{
8326 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
8327 vector <struct tracepoint_arg>& args):
8328 dw (dw), probe_name (probe_name), args (args) {}
8329 dwflpp& dw;
8330 const string& probe_name;
8331 vector <struct tracepoint_arg>& args;
bc9a523d 8332
f8a968bc
JS
8333 void visit_target_symbol (target_symbol* e);
8334 void visit_target_symbol_arg (target_symbol* e);
8335 void visit_target_symbol_context (target_symbol* e);
8336};
79189b84
JS
8337
8338
f8a968bc
JS
8339void
8340tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 8341{
277c21bc 8342 string argname = e->name.substr(1);
75ead1f7 8343
f8a968bc
JS
8344 // search for a tracepoint parameter matching this name
8345 tracepoint_arg *arg = NULL;
8346 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 8347 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
8348 {
8349 arg = &args[i];
8350 arg->used = true;
8351 break;
8352 }
75ead1f7 8353
f8a968bc
JS
8354 if (arg == NULL)
8355 {
8356 stringstream alternatives;
8357 for (unsigned i = 0; i < args.size(); ++i)
8358 alternatives << " $" << args[i].name;
046e7190 8359 alternatives << " $$name $$parms $$vars";
75ead1f7 8360
f8a968bc
JS
8361 // We hope that this value ends up not being referenced after all, so it
8362 // can be optimized out quietly.
b530b5b3
LB
8363 throw semantic_error(_F("unable to find tracepoint variable '%s' (alternatives: %s)",
8364 e->name.c_str(), alternatives.str().c_str()), e->tok);
f8a968bc
JS
8365 // NB: we can have multiple errors, since a target variable
8366 // may be expanded in several different contexts:
8367 // trace ("*") { $foo->bar }
f8a968bc 8368 }
75ead1f7 8369
f8a968bc 8370 // make sure we're not dereferencing base types
dc5a09fc 8371 if (!arg->isptr)
d19a9a82 8372 e->assert_no_components("tracepoint", true);
75ead1f7 8373
f8a968bc
JS
8374 // we can only write to dereferenced fields, and only if guru mode is on
8375 bool lvalue = is_active_lvalue(e);
8376 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
b530b5b3 8377 throw semantic_error(_F("write to tracepoint variable '%s' not permitted", e->name.c_str()), e->tok);
c69a87e0 8378
ad370dcc
JS
8379 // XXX: if a struct/union arg is passed by value, then writing to its fields
8380 // is also meaningless until you dereference past a pointer member. It's
8381 // harder to detect and prevent that though...
75ead1f7 8382
f8a968bc
JS
8383 if (e->components.empty())
8384 {
03c75a4a 8385 if (e->addressof)
b530b5b3 8386 throw semantic_error(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 8387
3e3bd7b6 8388 // Just grab the value from the probe locals
a45664f4
JS
8389 symbol* sym = new symbol;
8390 sym->tok = e->tok;
8391 sym->name = "__tracepoint_arg_" + arg->name;
8392 provide (sym);
f8a968bc
JS
8393 }
8394 else
8395 {
5f36109e
JS
8396 // make a copy of the original as a bare target symbol for the tracepoint
8397 // value, which will be passed into the dwarf dereferencing code
8398 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
8399 e2->components.clear();
8400
8401 if (e->components.back().type == target_symbol::comp_pretty_print)
8402 {
8403 if (lvalue)
b530b5b3 8404 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 8405
d19a9a82 8406 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
8407 dpp.expand()->visit (this);
8408 return;
8409 }
8410
f8a968bc
JS
8411 // Synthesize a function to dereference the dwarf fields,
8412 // with a pointer parameter that is the base tracepoint variable
8413 functiondecl *fdecl = new functiondecl;
59de45f1 8414 fdecl->synthetic = true;
f8a968bc
JS
8415 fdecl->tok = e->tok;
8416 embeddedcode *ec = new embeddedcode;
8417 ec->tok = e->tok;
75ead1f7 8418
f8a968bc 8419 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
277c21bc 8420 + "_" + e->name.substr(1)
aca66a36 8421 + "_" + lex_cast(tick++));
75ead1f7 8422
f8a968bc
JS
8423 fdecl->name = fname;
8424 fdecl->body = ec;
75ead1f7 8425
b5a0dd41
FCE
8426 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
8427 ec->code += "\n#define fetch_register k_fetch_register\n";
8428 ec->code += "#define store_register k_store_register\n";
c69a87e0
FCE
8429
8430 ec->code += dw.literal_stmt_for_pointer (&arg->type_die, e,
f8a968bc 8431 lvalue, fdecl->type);
75ead1f7 8432
f8a968bc
JS
8433 // Give the fdecl an argument for the raw tracepoint value
8434 vardecl *v1 = new vardecl;
8435 v1->type = pe_long;
8436 v1->name = "pointer";
8437 v1->tok = e->tok;
8438 fdecl->formal_args.push_back(v1);
75ead1f7 8439
6fda2dff
JS
8440 // Any non-literal indexes need to be passed in too.
8441 for (unsigned i = 0; i < e->components.size(); ++i)
8442 if (e->components[i].type == target_symbol::comp_expression_array_index)
8443 {
8444 vardecl *v = new vardecl;
8445 v->type = pe_long;
aca66a36 8446 v->name = "index" + lex_cast(i);
6fda2dff
JS
8447 v->tok = e->tok;
8448 fdecl->formal_args.push_back(v);
8449 }
8450
f8a968bc
JS
8451 if (lvalue)
8452 {
8453 // Modify the fdecl so it carries a pe_long formal
8454 // argument called "value".
75ead1f7 8455
f8a968bc
JS
8456 // FIXME: For the time being we only support setting target
8457 // variables which have base types; these are 'pe_long' in
8458 // stap's type vocabulary. Strings and pointers might be
8459 // reasonable, some day, but not today.
8460
8461 vardecl *v2 = new vardecl;
8462 v2->type = pe_long;
8463 v2->name = "value";
8464 v2->tok = e->tok;
8465 fdecl->formal_args.push_back(v2);
8466 }
8467 else
8468 ec->code += "/* pure */";
8469
64211010
DB
8470 ec->code += "/* unprivileged */";
8471
b5a0dd41
FCE
8472 // PR10601
8473 ec->code += "\n#undef fetch_register\n";
8474 ec->code += "\n#undef store_register\n";
aff5d390 8475
f8809d54 8476 fdecl->join (dw.sess);
75ead1f7 8477
f8a968bc
JS
8478 // Synthesize a functioncall.
8479 functioncall* n = new functioncall;
8480 n->tok = e->tok;
8481 n->function = fname;
6fda2dff
JS
8482 n->args.push_back(require(e2));
8483
8484 // Any non-literal indexes need to be passed in too.
8485 for (unsigned i = 0; i < e->components.size(); ++i)
8486 if (e->components[i].type == target_symbol::comp_expression_array_index)
8487 n->args.push_back(require(e->components[i].expr_index));
75ead1f7 8488
f8a968bc
JS
8489 if (lvalue)
8490 {
8491 // Provide the functioncall to our parent, so that it can be
8492 // used to substitute for the assignment node immediately above
8493 // us.
8494 assert(!target_symbol_setter_functioncalls.empty());
8495 *(target_symbol_setter_functioncalls.top()) = n;
8496 }
75ead1f7 8497
f8a968bc
JS
8498 provide (n);
8499 }
75ead1f7
JS
8500}
8501
8502
f8a968bc
JS
8503void
8504tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 8505{
03c75a4a 8506 if (e->addressof)
b530b5b3 8507 throw semantic_error(_("cannot take address of context variable"), e->tok);
03c75a4a 8508
f8a968bc 8509 if (is_active_lvalue (e))
b530b5b3 8510 throw semantic_error(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 8511
277c21bc 8512 if (e->name == "$$name")
f8a968bc 8513 {
5f36109e
JS
8514 e->assert_no_components("tracepoint");
8515
bfdaad1e
DS
8516 // Synthesize an embedded expression.
8517 embedded_expr *expr = new embedded_expr;
8518 expr->tok = e->tok;
8519 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 8520 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 8521 provide (expr);
f8a968bc 8522 }
277c21bc 8523 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 8524 {
5f36109e
JS
8525 e->assert_no_components("tracepoint", true);
8526
f8a968bc
JS
8527 token* pf_tok = new token(*e->tok);
8528 pf_tok->content = "sprintf";
0a6f5a3f 8529
d5e178c1 8530 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 8531
f8a968bc 8532 for (unsigned i = 0; i < args.size(); ++i)
b278033a 8533 {
dcaa1a65
JS
8534 if (!args[i].usable)
8535 continue;
f8a968bc
JS
8536 if (i > 0)
8537 pf->raw_components += " ";
8538 pf->raw_components += args[i].name;
3e3bd7b6 8539 target_symbol *tsym = new target_symbol;
f8a968bc 8540 tsym->tok = e->tok;
277c21bc 8541 tsym->name = "$" + args[i].name;
5f36109e 8542 tsym->components = e->components;
b278033a 8543
f8a968bc
JS
8544 // every variable should always be accessible!
8545 tsym->saved_conversion_error = 0;
8546 expression *texp = require (tsym); // NB: throws nothing ...
14a97852
JS
8547 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
8548 {
8549 if (dw.sess.verbose>2)
8550 for (semantic_error *c = tsym->saved_conversion_error;
8551 c != 0; c = c->chain)
b530b5b3 8552 clog << _("variable location problem: ") << c->what() << endl;
14a97852
JS
8553 pf->raw_components += "=?";
8554 continue;
8555 }
b278033a 8556
5f36109e
JS
8557 if (!e->components.empty() &&
8558 e->components[0].type == target_symbol::comp_pretty_print)
8559 pf->raw_components += "=%s";
8560 else
8561 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
8562 pf->args.push_back(texp);
8563 }
0a6f5a3f 8564
f8a968bc
JS
8565 pf->components = print_format::string_to_components(pf->raw_components);
8566 provide (pf);
b278033a 8567 }
f8a968bc
JS
8568 else
8569 assert(0); // shouldn't get here
0a6f5a3f
JS
8570}
8571
0a6f5a3f 8572void
f8a968bc 8573tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 8574{
aff5d390 8575 try
c69a87e0 8576 {
277c21bc 8577 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 8578
277c21bc 8579 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0
FCE
8580 visit_target_symbol_context (e);
8581 else
8582 visit_target_symbol_arg (e);
8583 }
8584 catch (const semantic_error &er)
8585 {
1af1e62d 8586 e->chain (er);
c69a87e0
FCE
8587 provide (e);
8588 }
0a6f5a3f
JS
8589}
8590
8591
8592
79189b84
JS
8593tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
8594 dwflpp& dw, Dwarf_Die& func_die,
8595 const string& tracepoint_name,
8596 probe* base, probe_point* loc):
4c5d1300 8597 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 8598 sess (s), tracepoint_name (tracepoint_name)
56894e91 8599{
79189b84
JS
8600 // create synthetic probe point name; preserve condition
8601 vector<probe_point::component*> comps;
8602 comps.push_back (new probe_point::component (TOK_KERNEL));
8603 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
8604 this->sole_location()->components = comps;
8605
6fb70fb7
JS
8606 // fill out the available arguments in this tracepoint
8607 build_args(dw, func_die);
56894e91 8608
6fb70fb7
JS
8609 // determine which header defined this tracepoint
8610 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
8611 header = decl_file;
8612
8613#if 0 /* This convention is not enforced. */
6fb70fb7
JS
8614 size_t header_pos = decl_file.rfind("trace/");
8615 if (header_pos == string::npos)
8616 throw semantic_error ("cannot parse header location for tracepoint '"
8617 + tracepoint_name + "' in '"
8618 + decl_file + "'");
8619 header = decl_file.substr(header_pos);
d4393459 8620#endif
56894e91 8621
6fb70fb7
JS
8622 // tracepoints from FOO_event_types.h should really be included from FOO.h
8623 // XXX can dwarf tell us the include hierarchy? it would be better to
8624 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 8625 // XXX: see also PR9993.
d4393459 8626 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
8627 if (header_pos != string::npos)
8628 header.erase(header_pos, 12);
56894e91 8629
f8a968bc
JS
8630 // Now expand the local variables in the probe body
8631 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 8632 v.replace (this->body);
a45664f4
JS
8633 for (unsigned i = 0; i < args.size(); i++)
8634 if (args[i].used)
8635 {
8636 vardecl* v = new vardecl;
8637 v->name = "__tracepoint_arg_" + args[i].name;
8638 v->tok = this->tok;
58701b78 8639 v->set_arity(0, this->tok);
a45664f4
JS
8640 v->type = pe_long;
8641 v->skip_init = true;
8642 this->locals.push_back (v);
8643 }
56894e91 8644
79189b84 8645 if (sess.verbose > 2)
ce0f6648 8646 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 8647}
dc38c0ae 8648
56894e91 8649
f8a968bc 8650static bool
dcaa1a65 8651resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 8652{
d19a9a82 8653 Dwarf_Die type;
dcaa1a65 8654 switch (dwarf_tag(&arg.type_die))
b20febf3 8655 {
f8a968bc
JS
8656 case DW_TAG_typedef:
8657 case DW_TAG_const_type:
8658 case DW_TAG_volatile_type:
8659 // iterate on the referent type
3d1ad340 8660 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 8661 && resolve_tracepoint_arg_type(arg));
f8a968bc
JS
8662 case DW_TAG_base_type:
8663 // base types will simply be treated as script longs
dcaa1a65 8664 arg.isptr = false;
f8a968bc
JS
8665 return true;
8666 case DW_TAG_pointer_type:
dcaa1a65
JS
8667 // pointers can be treated as script longs,
8668 // and if we know their type, they can also be dereferenced
d19a9a82
JS
8669 type = arg.type_die;
8670 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
8671 {
8672 // It still might be a non-type, e.g. const void,
8673 // so we need to strip away all qualifiers.
8674 int tag = dwarf_tag(&arg.type_die);
8675 if (tag != DW_TAG_typedef &&
8676 tag != DW_TAG_const_type &&
8677 tag != DW_TAG_volatile_type)
8678 {
8679 arg.isptr = true;
8680 break;
8681 }
8682 }
8683 if (!arg.isptr)
8684 arg.type_die = type;
ad370dcc
JS
8685 arg.typecast = "(intptr_t)";
8686 return true;
8687 case DW_TAG_structure_type:
8688 case DW_TAG_union_type:
8689 // for structs/unions which are passed by value, we turn it into
8690 // a pointer that can be dereferenced.
8691 arg.isptr = true;
8692 arg.typecast = "(intptr_t)&";
dcaa1a65 8693 return true;
f8a968bc
JS
8694 default:
8695 // should we consider other types too?
8696 return false;
b20febf3 8697 }
56894e91
JS
8698}
8699
8700
8701void
822a6a3d 8702tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 8703{
6fb70fb7
JS
8704 Dwarf_Die arg;
8705 if (dwarf_child(&func_die, &arg) == 0)
8706 do
8707 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
8708 {
8709 // build a tracepoint_arg for this parameter
8710 tracepoint_arg tparg;
23d106b9 8711 tparg.name = dwarf_diename(&arg);
56894e91 8712
6fb70fb7 8713 // read the type of this parameter
3d1ad340 8714 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 8715 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
ce0f6648
LB
8716 throw semantic_error (_F("cannot get type of parameter '%s' of tracepoint '%s'",
8717 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 8718
dcaa1a65 8719 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
8720 args.push_back(tparg);
8721 if (sess.verbose > 4)
b530b5b3
LB
8722 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s'",
8723 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str()) << endl;
6fb70fb7
JS
8724 }
8725 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
8726}
8727
dc38c0ae 8728void
d0bfd2ac 8729tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 8730{
dcaa1a65
JS
8731 for (unsigned i = 0; i < args.size(); ++i)
8732 if (args[i].usable)
d0bfd2ac 8733 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
8734}
8735
79189b84
JS
8736void
8737tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 8738{
79189b84
JS
8739 if (! s.tracepoint_derived_probes)
8740 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
8741 s.tracepoint_derived_probes->enroll (this);
8742}
e38d6504 8743
56894e91 8744
197a4d62 8745void
3e3bd7b6 8746tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 8747{
3e3bd7b6
JS
8748 for (unsigned i = 0; i < args.size(); i++)
8749 if (args[i].used)
8750 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 8751}
56894e91 8752
3e3bd7b6 8753
c9ccb642 8754static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 8755{
3c1b3d06
FCE
8756 vector<string> they_live;
8757 // PR 9993
8758 // XXX: may need this to be configurable
d4393459 8759 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
8760
8761 // PR11649: conditional extra header
8762 // for kvm tracepoints in 2.6.33ish
8763 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
8764 they_live.push_back ("#include <linux/kvm_host.h>");
8765 }
8766
50b72692 8767 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 8768 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
8769 if (s.kernel_source_tree != "")
8770 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
8771 they_live.push_back ("struct xfs_mount;");
8772 they_live.push_back ("struct xfs_inode;");
8773 they_live.push_back ("struct xfs_buf;");
8774 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 8775 they_live.push_back ("struct xfs_trans;");
9e0cd21a 8776 }
d4393459 8777
50b72692 8778 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
8779 they_live.push_back ("struct rpc_task;");
8780 }
8781
8782 they_live.push_back ("#include <asm/cputime.h>");
8783
c2cf1b87
FCE
8784 // linux 3.0
8785 they_live.push_back ("struct cpu_workqueue_struct;");
8786
50b72692 8787 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
8788 if (s.kernel_source_tree != "")
8789 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
8790
50b72692
HP
8791 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
8792 they_live.push_back ("struct ext3_reserve_window_node;");
8793
3c1b3d06
FCE
8794 return they_live;
8795}
47dd066d
WC
8796
8797
8798void
79189b84 8799tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 8800{
79189b84
JS
8801 if (probes.empty())
8802 return;
47dd066d 8803
96b030fe
JS
8804 s.op->newline() << "/* ---- tracepoint probes ---- */";
8805 s.op->newline();
79189b84 8806
3c1b3d06
FCE
8807 // PR9993: Add extra headers to work around undeclared types in individual
8808 // include/trace/foo.h files
c9ccb642 8809 const vector<string>& extra_decls = tracepoint_extra_decls (s, "XXXXXXX");
d4393459
FCE
8810 for (unsigned z=0; z<extra_decls.size(); z++)
8811 s.op->newline() << extra_decls[z] << "\n";
47dd066d 8812
6fb70fb7
JS
8813 for (unsigned i = 0; i < probes.size(); ++i)
8814 {
8815 tracepoint_derived_probe *p = probes[i];
47dd066d 8816
96b030fe
JS
8817 // emit a separate entry function for each probe, since tracepoints
8818 // don't provide any sort of context pointer.
392e08b7 8819 s.op->newline() << "#undef TRACE_INCLUDE_FILE";
d4393459 8820 s.op->newline() << "#undef TRACE_INCLUDE_PATH";
75ae2ec9
FCE
8821
8822 // strip include/ substring, the same way as done in get_tracequery_module()
8823 string header = p->header;
8824 size_t root_pos = header.rfind("include/");
8825 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
8826 s.op->newline() << "#include <" << header << ">";
5f73a260
JS
8827
8828 // Starting in 2.6.35, at the same time NOARGS was added, the callback
8829 // always has a void* as the first parameter. PR11599
8830 s.op->newline() << "#ifdef DECLARE_TRACE_NOARGS";
8831 s.op->newline() << "#define STAP_TP_DATA , NULL";
8832 s.op->newline() << "#define STAP_TP_PROTO void *cb_data"
8833 << " __attribute__ ((unused))";
8834 if (!p->args.empty())
8835 s.op->line() << ",";
8836 s.op->newline() << "#else";
8837 s.op->newline() << "#define STAP_TP_DATA";
8838 s.op->newline() << "#define STAP_TP_PROTO";
8839 if (p->args.empty())
8840 s.op->line() << " void";
8841 s.op->newline() << "#endif";
8842
6fb70fb7 8843 s.op->newline() << "static void enter_tracepoint_probe_" << i << "(";
5f73a260
JS
8844 s.op->newline(2) << "STAP_TP_PROTO";
8845
6fb70fb7
JS
8846 for (unsigned j = 0; j < p->args.size(); ++j)
8847 {
8848 if (j > 0)
5f73a260
JS
8849 s.op->line() << ",";
8850 s.op->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
6fb70fb7 8851 }
5f73a260
JS
8852 s.op->newline() << ")";
8853 s.op->newline(-2) << "{";
8854
26e63673 8855 s.op->newline(1) << "struct stap_probe * const probe = "
faea5e16 8856 << common_probe_init (p) << ";";
6eefe942
MW
8857 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "probe",
8858 "_STP_PROBE_HANDLER_TRACEPOINT");
6dceb5c9 8859 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
8860 << lex_cast_qstring (p->tracepoint_name)
8861 << ";";
f8a968bc
JS
8862 for (unsigned j = 0; j < p->args.size(); ++j)
8863 if (p->args[j].used)
8864 {
66671fd8 8865 s.op->newline() << "c->probe_locals." << p->name << ".__tracepoint_arg_"
f8a968bc 8866 << p->args[j].name << " = (int64_t)";
ad370dcc 8867 s.op->line() << p->args[j].typecast;
f8a968bc
JS
8868 s.op->line() << "__tracepoint_arg_" << p->args[j].name << ";";
8869 }
26e63673 8870 s.op->newline() << "(*probe->ph) (c);";
6fb70fb7
JS
8871 common_probe_entryfn_epilogue (s.op);
8872 s.op->newline(-1) << "}";
47dd066d 8873
96b030fe
JS
8874 // emit normalized registration functions
8875 s.op->newline() << "static int register_tracepoint_probe_" << i << "(void) {";
8876 s.op->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 8877 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
96b030fe 8878 s.op->newline(-1) << "}";
47dd066d 8879
86758d5f
JS
8880 // NB: we're not prepared to deal with unreg failures. However, failures
8881 // can only occur if the tracepoint doesn't exist (yet?), or if we
8882 // weren't even registered. The former should be OKed by the initial
8883 // registration call, and the latter is safe to ignore.
8884 s.op->newline() << "static void unregister_tracepoint_probe_" << i << "(void) {";
8885 s.op->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 8886 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
96b030fe 8887 s.op->newline(-1) << "}";
6fb70fb7 8888 s.op->newline();
5f73a260
JS
8889
8890 s.op->newline() << "#undef STAP_TP_DATA";
8891 s.op->newline() << "#undef STAP_TP_PROTO";
8892 s.op->newline();
af304783
DS
8893 }
8894
96b030fe
JS
8895 // emit an array of registration functions for easy init/shutdown
8896 s.op->newline() << "static struct stap_tracepoint_probe {";
8897 s.op->newline(1) << "int (*reg)(void);";
86758d5f 8898 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
8899 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
8900 s.op->indent(1);
8901 for (unsigned i = 0; i < probes.size(); ++i)
8902 {
8903 s.op->newline () << "{";
8904 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
8905 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
8906 s.op->line() << " },";
8907 }
8908 s.op->newline(-1) << "};";
8909 s.op->newline();
47dd066d
WC
8910}
8911
8912
79189b84
JS
8913void
8914tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 8915{
79189b84
JS
8916 if (probes.size () == 0)
8917 return;
47dd066d 8918
79189b84 8919 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
8920 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
8921 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
8922 s.op->newline() << "if (rc) {";
8923 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
8924 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
8925 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
8926 s.op->newline(-1) << "}";
8927 s.op->newline(-1) << "}";
47dd066d 8928
bc9a523d
FCE
8929 // This would be technically proper (on those autoconf-detectable
8930 // kernels that include this function in tracepoint.h), however we
8931 // already make several calls to synchronze_sched() during our
8932 // shutdown processes.
47dd066d 8933
bc9a523d
FCE
8934 // s.op->newline() << "if (rc)";
8935 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
8936 // s.op->indent(-1);
79189b84 8937}
47dd066d
WC
8938
8939
79189b84
JS
8940void
8941tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 8942{
79189b84
JS
8943 if (probes.empty())
8944 return;
47dd066d 8945
96b030fe
JS
8946 s.op->newline() << "/* deregister tracepoint probes */";
8947 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
8948 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
8949 s.op->indent(-1);
47dd066d 8950
bc9a523d 8951 // Not necessary: see above.
47dd066d 8952
bc9a523d 8953 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 8954}
b20febf3 8955
47dd066d 8956
75ead1f7 8957struct tracepoint_query : public base_query
47dd066d 8958{
75ead1f7
JS
8959 tracepoint_query(dwflpp & dw, const string & tracepoint,
8960 probe * base_probe, probe_point * base_loc,
8961 vector<derived_probe *> & results):
8962 base_query(dw, "*"), tracepoint(tracepoint),
8963 base_probe(base_probe), base_loc(base_loc),
8964 results(results) {}
47dd066d 8965
75ead1f7 8966 const string& tracepoint;
47dd066d 8967
75ead1f7
JS
8968 probe * base_probe;
8969 probe_point * base_loc;
8970 vector<derived_probe *> & results;
f982c59b 8971 set<string> probed_names;
47dd066d 8972
75ead1f7
JS
8973 void handle_query_module();
8974 int handle_query_cu(Dwarf_Die * cudie);
8975 int handle_query_func(Dwarf_Die * func);
822a6a3d 8976 void query_library (const char *) {}
576eaefe 8977 void query_plt (const char *entry, size_t addr) {}
b20febf3 8978
75ead1f7
JS
8979 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
8980 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
8981};
47dd066d
WC
8982
8983
8984void
75ead1f7 8985tracepoint_query::handle_query_module()
47dd066d 8986{
75ead1f7
JS
8987 // look for the tracepoints in each CU
8988 dw.iterate_over_cus(tracepoint_query_cu, this);
47dd066d
WC
8989}
8990
8991
75ead1f7
JS
8992int
8993tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 8994{
75ead1f7 8995 dw.focus_on_cu (cudie);
47dd066d 8996
75ead1f7
JS
8997 // look at each function to see if it's a tracepoint
8998 string function = "stapprobe_" + tracepoint;
8999 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
9000}
9001
9002
75ead1f7
JS
9003int
9004tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 9005{
75ead1f7 9006 dw.focus_on_function (func);
47dd066d 9007
60d98537 9008 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 9009 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
9010
9011 // check for duplicates -- sometimes tracepoint headers may be indirectly
9012 // included in more than one of our tracequery modules.
9013 if (!probed_names.insert(tracepoint_instance).second)
9014 return DWARF_CB_OK;
9015
79189b84
JS
9016 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
9017 tracepoint_instance,
9018 base_probe, base_loc);
9019 results.push_back (dp);
75ead1f7 9020 return DWARF_CB_OK;
47dd066d
WC
9021}
9022
9023
75ead1f7
JS
9024int
9025tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 9026{
75ead1f7 9027 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 9028 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9029 return q->handle_query_cu(cudie);
47dd066d
WC
9030}
9031
9032
75ead1f7
JS
9033int
9034tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 9035{
75ead1f7 9036 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 9037 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9038 return q->handle_query_func(func);
47dd066d
WC
9039}
9040
9041
0a6f5a3f 9042struct tracepoint_builder: public derived_probe_builder
47dd066d 9043{
0a6f5a3f
JS
9044private:
9045 dwflpp *dw;
9046 bool init_dw(systemtap_session& s);
c9ccb642
FCE
9047 void get_tracequery_modules(systemtap_session& s,
9048 const vector<string>& headers,
9049 vector<string>& modules);
47dd066d 9050
0a6f5a3f 9051public:
47dd066d 9052
0a6f5a3f
JS
9053 tracepoint_builder(): dw(0) {}
9054 ~tracepoint_builder() { delete dw; }
47dd066d 9055
0a6f5a3f
JS
9056 void build_no_more (systemtap_session& s)
9057 {
9058 if (dw && s.verbose > 3)
b530b5b3 9059 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
9060 delete dw;
9061 dw = NULL;
435f53a7
FCE
9062
9063 delete_session_module_cache (s);
0a6f5a3f 9064 }
47dd066d 9065
0a6f5a3f
JS
9066 void build(systemtap_session& s,
9067 probe *base, probe_point *location,
9068 literal_map_t const& parameters,
9069 vector<derived_probe*>& finished_results);
9070};
47dd066d 9071
47dd066d 9072
c9ccb642 9073
2a0e62a8 9074// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
9075// tracepoint-related header files given. Return the generated or cached
9076// modules[].
9077
9078void
9079tracepoint_builder::get_tracequery_modules(systemtap_session& s,
9080 const vector<string>& headers,
9081 vector<string>& modules)
0a6f5a3f 9082{
c95eddf7 9083 if (s.verbose > 2)
55e50c24 9084 {
ce0f6648 9085 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
9086 for (size_t i = 0; i < headers.size(); ++i)
9087 clog << " " << headers[i] << endl;
9088 }
c95eddf7 9089
2a0e62a8
JS
9090 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
9091 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
9092 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
9093 // so we prefer not to repeat this.
9094 vector<string> uncached_headers;
9095 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 9096 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
9097
9098 // They may be in the cache already.
9099 if (s.use_cache && !s.poison_cache)
9100 for (size_t i=0; i<headers.size(); i++)
9101 {
9102 // see if the cached module exists
2a0e62a8 9103 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
9104 if (!tracequery_path.empty() && file_exists(tracequery_path))
9105 {
9106 if (s.verbose > 2)
9107 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
c252fca2
JS
9108
9109 // an empty file is a cached failure
9110 if (get_file_size(tracequery_path) > 0)
9111 modules.push_back (tracequery_path);
c9ccb642
FCE
9112 }
9113 else
9114 uncached_headers.push_back(headers[i]);
9115 }
9116 else
9117 uncached_headers = headers;
47dd066d 9118
c9ccb642
FCE
9119 // If we have nothing left to search for, quit
9120 if (uncached_headers.empty()) return;
f982c59b 9121
c9ccb642 9122 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 9123
c9ccb642
FCE
9124 // We could query several subsets of headers[] to make this go
9125 // faster, but let's KISS and do one at a time.
9126 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 9127 {
c9ccb642
FCE
9128 const string& header = uncached_headers[i];
9129
9130 // create a tracequery source file
9131 ostringstream osrc;
9132
9133 // PR9993: Add extra headers to work around undeclared types in individual
9134 // include/trace/foo.h files
9135 vector<string> short_decls = tracepoint_extra_decls(s, header);
9136
9137 // add each requested tracepoint header
75ae2ec9 9138 size_t root_pos = header.rfind("include/");
d4393459 9139 short_decls.push_back(string("#include <") +
75ae2ec9 9140 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 9141 string(">"));
f982c59b 9142
c9ccb642
FCE
9143 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
9144 osrc << "#include <linux/tracepoint.h>" << endl;
9145
9146 // override DECLARE_TRACE to synthesize probe functions for us
9147 osrc << "#undef DECLARE_TRACE" << endl;
9148 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
9149 osrc << " void stapprobe_##name(proto) {}" << endl;
9150
9151 // 2.6.35 added the NOARGS variant, but it's the same for us
9152 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
9153 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
9154 osrc << " DECLARE_TRACE(name, void, )" << endl;
9155
9156 // older tracepoints used DEFINE_TRACE, so redirect that too
9157 osrc << "#undef DEFINE_TRACE" << endl;
9158 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
9159 osrc << " DECLARE_TRACE(name, TPPROTO(proto), TPARGS(args))" << endl;
9160
9161 // add the specified decls/#includes
9162 for (unsigned z=0; z<short_decls.size(); z++)
9163 osrc << "#undef TRACE_INCLUDE_FILE\n"
9164 << "#undef TRACE_INCLUDE_PATH\n"
9165 << short_decls[z] << "\n";
9166
9167 // finish up the module source
9168 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 9169
c9ccb642
FCE
9170 // save the source file away
9171 headers_tracequery_src[header] = osrc.str();
9172 }
9173
9174 // now build them all together
2a0e62a8 9175 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
e16dc041 9176
c9ccb642
FCE
9177 // now plop them into the cache
9178 if (s.use_cache)
9179 for (size_t i=0; i<uncached_headers.size(); i++)
9180 {
9181 const string& header = uncached_headers[i];
2a0e62a8
JS
9182 const string& tracequery_obj = tracequery_objs[header];
9183 const string& tracequery_path = headers_cache_obj[header];
9184 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 9185 {
2a0e62a8 9186 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
9187 modules.push_back (tracequery_path);
9188 }
c252fca2
JS
9189 else
9190 // cache an empty file for failures
9191 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 9192 }
f982c59b
JS
9193}
9194
9195
d4393459 9196
f982c59b
JS
9197bool
9198tracepoint_builder::init_dw(systemtap_session& s)
9199{
9200 if (dw != NULL)
9201 return true;
9202
9203 vector<string> tracequery_modules;
55e50c24 9204 vector<string> system_headers;
f982c59b
JS
9205
9206 glob_t trace_glob;
d4393459
FCE
9207
9208 // find kernel_source_tree
9209 if (s.kernel_source_tree == "")
f982c59b 9210 {
d4393459
FCE
9211 unsigned found;
9212 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
9213 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
9214 if (found)
9215 {
9216 Dwarf_Die *cudie = 0;
9217 Dwarf_Addr bias;
9218 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
9219 {
9220 if (pending_interrupts) break;
9221 Dwarf_Attribute attr;
9222 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
9223 if (name)
9224 {
61f1a63b 9225 if (s.verbose > 2)
b530b5b3 9226 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
61f1a63b 9227
d4393459
FCE
9228 s.kernel_source_tree = name;
9229 break; // skip others; modern Kbuild uses same comp_dir for them all
9230 }
9231 }
9232 }
9233 }
9234
9235 // prefixes
9236 vector<string> glob_prefixes;
9237 glob_prefixes.push_back (s.kernel_build_tree);
9238 if (s.kernel_source_tree != "")
9239 glob_prefixes.push_back (s.kernel_source_tree);
9240
9241 // suffixes
9242 vector<string> glob_suffixes;
9243 glob_suffixes.push_back("include/trace/events/*.h");
9244 glob_suffixes.push_back("include/trace/*.h");
9245 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
f89ff3e2 9246 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d4393459
FCE
9247
9248 // compute cartesian product
9249 vector<string> globs;
9250 for (unsigned i=0; i<glob_prefixes.size(); i++)
9251 for (unsigned j=0; j<glob_suffixes.size(); j++)
9252 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
9253
9254 for (unsigned z = 0; z < globs.size(); z++)
9255 {
9256 string glob_str = globs[z];
9257 if (s.verbose > 3)
b530b5b3 9258 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 9259
f982c59b
JS
9260 glob(glob_str.c_str(), 0, NULL, &trace_glob);
9261 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
9262 {
9263 string header(trace_glob.gl_pathv[i]);
9264
9265 // filter out a few known "internal-only" headers
60d98537
JS
9266 if (endswith(header, "/define_trace.h") ||
9267 endswith(header, "/ftrace.h") ||
9268 endswith(header, "/trace_events.h") ||
9269 endswith(header, "_event_types.h"))
f982c59b
JS
9270 continue;
9271
55e50c24 9272 system_headers.push_back(header);
f982c59b
JS
9273 }
9274 globfree(&trace_glob);
9275 }
9276
c9ccb642
FCE
9277 // Build tracequery modules
9278 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 9279
f982c59b
JS
9280 // TODO: consider other sources of tracepoint headers too, like from
9281 // a command-line parameter or some environment or .systemtaprc
47dd066d 9282
59c11f91 9283 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
9284 return true;
9285}
47dd066d 9286
0a6f5a3f
JS
9287void
9288tracepoint_builder::build(systemtap_session& s,
9289 probe *base, probe_point *location,
9290 literal_map_t const& parameters,
9291 vector<derived_probe*>& finished_results)
9292{
9293 if (!init_dw(s))
9294 return;
47dd066d 9295
75ead1f7
JS
9296 string tracepoint;
9297 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 9298
75ead1f7 9299 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 9300 dw->iterate_over_modules(&query_module, &q);
47dd066d 9301}
47dd066d 9302
e6fe60e7 9303
b55bc428 9304// ------------------------------------------------------------------------
bd2b1e68 9305// Standard tapset registry.
b55bc428
FCE
9306// ------------------------------------------------------------------------
9307
7a053d3b 9308void
f8220a7b 9309register_standard_tapsets(systemtap_session & s)
b55bc428 9310{
47e0478e 9311 register_tapset_been(s);
93646f4d 9312 register_tapset_itrace(s);
dd0e4fa7 9313 register_tapset_mark(s);
7a212aa8 9314 register_tapset_procfs(s);
912e8c59 9315 register_tapset_timers(s);
b84779a5 9316 register_tapset_utrace(s);
b98a8d73 9317
7a24d422 9318 // dwarf-based kprobe/uprobe parts
c4ce66a1 9319 dwarf_derived_probe::register_patterns(s);
30a279be 9320
888af770
FCE
9321 // XXX: user-space starter set
9322 s.pattern_root->bind_num(TOK_PROCESS)
9323 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
27dc09b1 9324 ->bind_unprivileged()
888af770
FCE
9325 ->bind(new uprobe_builder ());
9326 s.pattern_root->bind_num(TOK_PROCESS)
9327 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
27dc09b1 9328 ->bind_unprivileged()
888af770
FCE
9329 ->bind(new uprobe_builder ());
9330
0a6f5a3f
JS
9331 // kernel tracepoint probes
9332 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
9333 ->bind(new tracepoint_builder());
9334
e6fe60e7
AM
9335 // Kprobe based probe
9336 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
9337 ->bind(new kprobe_builder());
9338 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9339 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
9340 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9341 ->bind(new kprobe_builder());
b6371390
JS
9342 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9343 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
9344 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9345 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
9346 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9347 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9348 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
9349 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
9350 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
9351
9352 //Hwbkpt based probe
b47f3a55
FCE
9353 // NB: we formerly registered the probe point types only if the kernel configuration
9354 // allowed it. However, we get better error messages if we allow probes to resolve.
9355 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9356 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9357 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
9358 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9359 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9360 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9361 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
9362 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9363 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9364 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9365 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9366 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9367 // length supported with address only, not symbol names
83ea76b1
WC
9368
9369 //perf event based probe
4763f713 9370 register_tapset_perf(s);
b55bc428 9371}
dc38c0ae
DS
9372
9373
b20febf3
FCE
9374vector<derived_probe_group*>
9375all_session_groups(systemtap_session& s)
dc38c0ae 9376{
b20febf3 9377 vector<derived_probe_group*> g;
912e8c59
JS
9378
9379#define DOONE(x) \
9380 if (s. x##_derived_probes) \
9381 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
9382
9383 // Note that order *is* important here. We want to make sure we
9384 // register (actually run) begin probes before any other probe type
9385 // is run. Similarly, when unregistering probes, we want to
9386 // unregister (actually run) end probes after every other probe type
9387 // has be unregistered. To do the latter,
9388 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
9389 DOONE(be);
9390 DOONE(dwarf);
888af770 9391 DOONE(uprobe);
b20febf3
FCE
9392 DOONE(timer);
9393 DOONE(profile);
9394 DOONE(mark);
0a6f5a3f 9395 DOONE(tracepoint);
e6fe60e7 9396 DOONE(kprobe);
dd225250 9397 DOONE(hwbkpt);
83ea76b1 9398 DOONE(perf);
b20febf3 9399 DOONE(hrtimer);
ce82316f 9400 DOONE(procfs);
935447c8
DS
9401
9402 // Another "order is important" item. We want to make sure we
9403 // "register" the dummy task_finder probe group after all probe
9404 // groups that use the task_finder.
9405 DOONE(utrace);
a96d1db0 9406 DOONE(itrace);
935447c8 9407 DOONE(task_finder);
b20febf3
FCE
9408#undef DOONE
9409 return g;
46b84a80 9410}
73267b89
JS
9411
9412/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.388058 seconds and 5 git commands to generate.