]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
PR14929: add error::dwarf man page
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
1af100fc 2// Copyright (C) 2005-2013 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
71db462b
DS
82common_probe_entryfn_prologue (systemtap_session& s,
83 string statestr, string probe,
84 string probe_type, bool overload_processing)
b20febf3 85{
71db462b 86 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 87 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 88 s.op->newline() << "#else";
653e6a9a 89
71db462b
DS
90 s.op->newline() << "struct context* __restrict__ c;";
91 s.op->newline() << "#if !INTERRUPTIBLE";
92 s.op->newline() << "unsigned long flags;";
93 s.op->newline() << "#endif";
b20febf3 94
f887a8c9 95 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 96 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
97 s.op->newline() << "#endif";
98 if (overload_processing && !s.runtime_usermode_p())
71db462b 99 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 100 else
71db462b 101 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 102
f887a8c9
DS
103 if (! s.runtime_usermode_p())
104 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
105 else
106 {
107 s.op->newline() << "struct timespec timespec_atstart;";
108 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atstart);";
109 }
71db462b 110 s.op->newline() << "#endif";
994aac0e 111
71db462b
DS
112 s.op->newline() << "#if INTERRUPTIBLE";
113 s.op->newline() << "preempt_disable ();";
114 s.op->newline() << "#else";
115 s.op->newline() << "local_irq_save (flags);";
116 s.op->newline() << "#endif";
b20febf3 117
ac3af990 118 if (! s.runtime_usermode_p())
71db462b
DS
119 {
120 // Check for enough free enough stack space
121 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
122 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
123 // XXX: may need porting to platforms where task_struct is not
124 // at bottom of kernel stack NB: see also
125 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 126 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 127 s.op->newline() << "#ifdef STP_TIMING";
065d5567 128 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
129 s.op->newline() << "#endif";
130 s.op->newline() << "goto probe_epilogue;";
131 s.op->newline(-1) << "}";
132 }
c931ec8a 133
065d5567 134 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
135 s.op->newline(1) << "goto probe_epilogue;";
136 s.op->indent(-1);
9a604fac 137
1d0e697d
DS
138 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
139 if (s.runtime_usermode_p())
140 {
141 s.op->newline() << "if (!c) {";
142 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 143 s.op->newline() << "atomic_inc (skipped_count());";
1d0e697d
DS
144 s.op->newline() << "#endif";
145 s.op->newline() << "#ifdef STP_TIMING";
065d5567 146 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
1d0e697d
DS
147 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
148 s.op->newline() << "_stp_warn (\"Skipped %s\\n\", " << probe << "->pp);";
149 s.op->newline() << "#endif";
150 s.op->newline() << "#endif";
151 s.op->newline() << "goto probe_epilogue;";
152 s.op->newline(-1) << "}";
153 }
154
71db462b
DS
155 s.op->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
156 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 157 s.op->newline() << "atomic_inc (skipped_count());";
71db462b
DS
158 s.op->newline() << "#endif";
159 s.op->newline() << "#ifdef STP_TIMING";
065d5567 160 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
71db462b
DS
161 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
162 s.op->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 163 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
164 // NB: There is a conceivable race condition here with reading
165 // c->probe_point, knowing that this other probe is sort of running.
166 // However, in reality, it's interrupted. Plus even if it were able
167 // to somehow start again, and stop before we read c->probe_point,
168 // at least we have that ?: "?" bit in there to avoid a NULL deref.
71db462b
DS
169 s.op->newline() << "#endif";
170 s.op->newline() << "#endif";
171 s.op->newline() << "atomic_dec (& c->busy);";
172 s.op->newline() << "goto probe_epilogue;";
173 s.op->newline(-1) << "}";
174 s.op->newline();
175 s.op->newline() << "c->last_stmt = 0;";
176 s.op->newline() << "c->last_error = 0;";
177 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
178 s.op->newline() << "c->uregs = 0;";
179 s.op->newline() << "c->kregs = 0;";
180 s.op->newline() << "#if defined __ia64__";
181 s.op->newline() << "c->unwaddr = 0;";
182 s.op->newline() << "#endif";
183 s.op->newline() << "c->probe_point = " << probe << "->pp;";
184 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
185 s.op->newline() << "c->probe_name = " << probe << "->pn;";
186 s.op->newline() << "#endif";
187 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 188 // reset Individual Probe State union
71db462b 189 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 190 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
191 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
192 s.op->newline() << "c->regparm = 0;";
193 s.op->newline() << "#endif";
e0a17418 194
152fa051
LB
195 if(!s.suppress_time_limits){
196 s.op->newline() << "#if INTERRUPTIBLE";
197 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
198 s.op->newline() << "#else";
199 s.op->newline() << "c->actionremaining = MAXACTION;";
200 s.op->newline() << "#endif";
201 }
9915575b
FCE
202 // NB: The following would actually be incorrect.
203 // That's because cycles_sum/cycles_base values are supposed to survive
204 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
205 // cycles), the values will be reset.
206 /*
71db462b
DS
207 s.op->newline() << "#ifdef STP_OVERLOAD";
208 s.op->newline() << "c->cycles_sum = 0;";
209 s.op->newline() << "c->cycles_base = 0;";
210 s.op->newline() << "#endif";
9915575b 211 */
44cfbe25
SM
212
213 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
214 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
215 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
216 s.op->newline() << "#endif";
b20febf3 217}
9a604fac 218
a44a0785 219
b20febf3 220void
f887a8c9
DS
221common_probe_entryfn_epilogue (systemtap_session& s,
222 bool overload_processing)
b20febf3 223{
f887a8c9
DS
224 if (overload_processing && !s.runtime_usermode_p())
225 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 226 else
f887a8c9
DS
227 s.op->newline() << "#ifdef STP_TIMING";
228 s.op->newline() << "{";
229 s.op->indent(1);
230 if (! s.runtime_usermode_p())
231 {
232 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
233 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
234 // fewer, if the hardware counter rolls over really quickly. We
235 // handle 32-bit wraparound here.
236 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
237 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
238 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
239 s.op->indent(-1);
240 }
241 else
242 {
243 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
244 s.op->newline() << "long cycles_elapsed;";
245 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atend);";
246 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
247 // 'cycles_elapsed' is really elapsed nanoseconds
248 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
249 }
250
251 s.op->newline() << "#ifdef STP_TIMING";
252 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
253 s.op->newline() << "#endif";
254
255 if (overload_processing && !s.runtime_usermode_p())
256 {
257 s.op->newline() << "#ifdef STP_OVERLOAD";
258 s.op->newline() << "{";
a58d79d0
DS
259 // If the cycle count has wrapped (cycles_atend > cycles_base),
260 // let's go ahead and pretend the interval has been reached.
261 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
262 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
263 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
264 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
265 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
266
267 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
268 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
269 // has overloaded the system and we need to quit.
7baf48e9
FCE
270 // NB: this is not suppressible via --suppress-runtime-errors,
271 // because this is a system safety metric that we cannot trust
272 // unprivileged users to override.
f887a8c9
DS
273 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
274 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
275 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
276 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
277 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
278 s.op->newline(-1) << "}";
279
280 s.op->newline() << "c->cycles_base = cycles_atend;";
281 s.op->newline() << "c->cycles_sum = 0;";
282 s.op->newline(-1) << "}";
283 s.op->newline(-1) << "}";
284 s.op->newline() << "#endif";
a58d79d0 285 }
e57b735a 286
f887a8c9
DS
287 s.op->newline(-1) << "}";
288 s.op->newline() << "#endif";
e57b735a 289
f887a8c9
DS
290 s.op->newline() << "c->probe_point = 0;"; // vacated
291 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
292 s.op->newline() << "c->probe_name = 0;";
293 s.op->newline() << "#endif";
294 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
295
296
f887a8c9
DS
297 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
298 s.op->indent(1);
299 if (s.suppress_handler_errors) // PR 13306
7baf48e9 300 {
065d5567 301 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
302 }
303 else
304 {
f887a8c9
DS
305 s.op->newline() << "if (c->last_stmt != NULL)";
306 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
307 s.op->newline(-1) << "else";
308 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
309 s.op->indent(-1);
065d5567
JS
310 s.op->newline() << "atomic_inc (error_count());";
311 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
312 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
313 s.op->newline() << "_stp_exit ();";
314 s.op->newline(-1) << "}";
7baf48e9
FCE
315 }
316
f887a8c9 317 s.op->newline(-1) << "}";
7baf48e9
FCE
318
319
f887a8c9 320 s.op->newline() << "atomic_dec (&c->busy);";
e57b735a 321
f887a8c9
DS
322 s.op->newline(-1) << "probe_epilogue:"; // context is free
323 s.op->indent(1);
e57b735a 324
1d0e697d 325 s.op->newline() << "_stp_runtime_entryfn_put_context();";
f887a8c9 326 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
327 {
328 // Check for excessive skip counts.
065d5567
JS
329 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
330 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
331 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
332 s.op->newline(-1) << "}";
7baf48e9 333 }
e57b735a 334
f887a8c9
DS
335 s.op->newline() << "#if INTERRUPTIBLE";
336 s.op->newline() << "preempt_enable_no_resched ();";
337 s.op->newline() << "#else";
338 s.op->newline() << "local_irq_restore (flags);";
339 s.op->newline() << "#endif";
653e6a9a 340
f887a8c9 341 s.op->newline() << "#endif // STP_ALIBI";
440f755a 342}
e57b735a 343
e57b735a 344
440f755a 345// ------------------------------------------------------------------------
e57b735a 346
440f755a
JS
347// ------------------------------------------------------------------------
348// Dwarf derived probes. "We apologize for the inconvience."
349// ------------------------------------------------------------------------
e57b735a 350
4627ed58
JS
351static const string TOK_KERNEL("kernel");
352static const string TOK_MODULE("module");
353static const string TOK_FUNCTION("function");
354static const string TOK_INLINE("inline");
355static const string TOK_CALL("call");
4bda987e 356static const string TOK_EXPORTED("exported");
4627ed58
JS
357static const string TOK_RETURN("return");
358static const string TOK_MAXACTIVE("maxactive");
359static const string TOK_STATEMENT("statement");
360static const string TOK_ABSOLUTE("absolute");
361static const string TOK_PROCESS("process");
a794dbeb 362static const string TOK_PROVIDER("provider");
4627ed58
JS
363static const string TOK_MARK("mark");
364static const string TOK_TRACE("trace");
365static const string TOK_LABEL("label");
63b4fd14 366static const string TOK_LIBRARY("library");
576eaefe 367static const string TOK_PLT("plt");
e57b735a 368
1adf8ef1 369static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 370static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 371
440f755a
JS
372// Can we handle this query with just symbol-table info?
373enum dbinfo_reqt
374{
375 dbr_unknown,
376 dbr_none, // kernel.statement(NUM).absolute
377 dbr_need_symtab, // can get by with symbol table if there's no dwarf
378 dbr_need_dwarf
379};
e57b735a 380
20e4a32c 381
440f755a
JS
382struct base_query; // forward decls
383struct dwarf_query;
384struct dwflpp;
385struct symbol_table;
20e4a32c 386
a781f401 387
440f755a
JS
388struct
389symbol_table
390{
391 module_info *mod_info; // associated module
392 map<string, func_info*> map_by_name;
1c6b77e5
JS
393 multimap<Dwarf_Addr, func_info*> map_by_addr;
394 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
395 typedef pair<iterator_t, iterator_t> range_t;
396#ifdef __powerpc__
397 GElf_Word opd_section;
398#endif
2867a2a1
JS
399 void add_symbol(const char *name, bool weak, bool descriptor,
400 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 401 enum info_status read_symbols(FILE *f, const string& path);
83ca3872 402 enum info_status read_from_elf_file(const string& path,
2713ea24 403 systemtap_session &sess);
83ca3872 404 enum info_status read_from_text_file(const string& path,
2713ea24 405 systemtap_session &sess);
440f755a
JS
406 enum info_status get_from_elf();
407 void prepare_section_rejection(Dwfl_Module *mod);
408 bool reject_section(GElf_Word section);
440f755a
JS
409 void purge_syscall_stubs();
410 func_info *lookup_symbol(const string& name);
411 Dwarf_Addr lookup_symbol_address(const string& name);
412 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 413 func_info *get_first_func();
7a053d3b 414
440f755a
JS
415 symbol_table(module_info *mi) : mod_info(mi) {}
416 ~symbol_table();
417};
77de5e9e 418
440f755a
JS
419static bool null_die(Dwarf_Die *die)
420{
822a6a3d 421 static Dwarf_Die null;
440f755a
JS
422 return (!die || !memcmp(die, &null, sizeof(null)));
423}
c4ce66a1
JS
424
425
7a053d3b 426enum
bd2b1e68 427function_spec_type
7a053d3b 428 {
bd2b1e68
GH
429 function_alone,
430 function_and_file,
7a053d3b 431 function_file_and_line
bd2b1e68
GH
432 };
433
ec4373ff 434
bd2b1e68 435struct dwarf_builder;
f10534c6 436struct dwarf_var_expanding_visitor;
77de5e9e 437
2930abc7 438
b20febf3
FCE
439// XXX: This class is a candidate for subclassing to separate
440// the relocation vs non-relocation variants. Likewise for
441// kprobe vs kretprobe variants.
442
443struct dwarf_derived_probe: public derived_probe
b55bc428 444{
b20febf3
FCE
445 dwarf_derived_probe (const string& function,
446 const string& filename,
447 int line,
448 const string& module,
449 const string& section,
450 Dwarf_Addr dwfl_addr,
2930abc7 451 Dwarf_Addr addr,
b20febf3
FCE
452 dwarf_query & q,
453 Dwarf_Die* scope_die);
20e4a32c 454
b20febf3
FCE
455 string module;
456 string section;
457 Dwarf_Addr addr;
63b4fd14 458 string path;
27dc09b1 459 bool has_process;
2930abc7 460 bool has_return;
c9bad430 461 bool has_maxactive;
63b4fd14 462 bool has_library;
c9bad430 463 long maxactive_val;
4ad95bbc 464 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
465 string user_path;
466 string user_lib;
b95e2b79 467 bool access_vars;
2930abc7 468
af234c40
JS
469 unsigned saved_longs, saved_strings;
470 dwarf_derived_probe* entry_handler;
471
b8da0ad1 472 void printsig (std::ostream &o) const;
6b66b9f7 473 virtual void join_group (systemtap_session& s);
9020300d 474 void emit_probe_local_init(translator_output * o);
d0bfd2ac 475 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 476
42e38653 477 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
478 void print_dupe_stamp(ostream& o);
479
bd2b1e68 480 // Pattern registration helpers.
7a053d3b 481 static void register_statement_variants(match_node * root,
27dc09b1 482 dwarf_builder * dw,
42e38653 483 privilege_t privilege);
fd6602a0 484 static void register_function_variants(match_node * root,
27dc09b1 485 dwarf_builder * dw,
42e38653 486 privilege_t privilege);
440d9b00
DB
487 static void register_function_and_statement_variants(systemtap_session& s,
488 match_node * root,
27dc09b1 489 dwarf_builder * dw,
42e38653 490 privilege_t privilege);
b1615c74
JS
491 static void register_sdt_variants(systemtap_session& s,
492 match_node * root,
493 dwarf_builder * dw);
494 static void register_plt_variants(systemtap_session& s,
495 match_node * root,
496 dwarf_builder * dw);
c4ce66a1 497 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
498
499protected:
500 dwarf_derived_probe(probe *base,
501 probe_point *location,
502 Dwarf_Addr addr,
503 bool has_return):
74fe61bc
LB
504 derived_probe(base, location), addr(addr), has_process(0),
505 has_return(has_return), has_maxactive(0), has_library(0),
506 maxactive_val(0), access_vars(false), saved_longs(0),
507 saved_strings(0), entry_handler(0)
6b66b9f7
JS
508 {}
509
510private:
d0bfd2ac 511 list<string> args;
8c67c337 512 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
513};
514
dc38c0ae 515
6b66b9f7 516struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 517{
6d0f3f0c 518 int pid; // 0 => unrestricted
0973d815 519
6d0f3f0c
FCE
520 uprobe_derived_probe (const string& function,
521 const string& filename,
522 int line,
523 const string& module,
6d0f3f0c
FCE
524 const string& section,
525 Dwarf_Addr dwfl_addr,
526 Dwarf_Addr addr,
527 dwarf_query & q,
6b66b9f7
JS
528 Dwarf_Die* scope_die):
529 dwarf_derived_probe(function, filename, line, module, section,
530 dwfl_addr, addr, q, scope_die), pid(0)
531 {}
6d0f3f0c 532
0973d815
FCE
533 // alternate constructor for process(PID).statement(ADDR).absolute
534 uprobe_derived_probe (probe *base,
535 probe_point *location,
536 int pid,
537 Dwarf_Addr addr,
6b66b9f7
JS
538 bool has_return):
539 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
540 {}
9ace370f 541
6d0f3f0c 542 void join_group (systemtap_session& s);
2865d17a 543
42e38653 544 void emit_privilege_assertion (translator_output*);
8f6d8c2b 545 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
546 void getargs(std::list<std::string> &arg_set) const;
547 void saveargs(int nargs);
548private:
549 list<string> args;
6d0f3f0c
FCE
550};
551
dc38c0ae
DS
552struct dwarf_derived_probe_group: public derived_probe_group
553{
554private:
b20febf3
FCE
555 multimap<string,dwarf_derived_probe*> probes_by_module;
556 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
557
558public:
08b5a50c 559 dwarf_derived_probe_group() {}
b20febf3
FCE
560 void enroll (dwarf_derived_probe* probe);
561 void emit_module_decls (systemtap_session& s);
562 void emit_module_init (systemtap_session& s);
b4be7cbc 563 void emit_module_refresh (systemtap_session& s);
b20febf3 564 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
565};
566
567
20c6c071 568// Helper struct to thread through the dwfl callbacks.
2c384610 569struct base_query
20c6c071 570{
c4ce66a1
JS
571 base_query(dwflpp & dw, literal_map_t const & params);
572 base_query(dwflpp & dw, const string & module_val);
2c384610 573 virtual ~base_query() {}
bd2b1e68 574
5227f1ea 575 systemtap_session & sess;
2c384610 576 dwflpp & dw;
5227f1ea 577
bd2b1e68 578 // Parameter extractors.
86bf665e 579 static bool has_null_param(literal_map_t const & params,
888af770 580 string const & k);
86bf665e 581 static bool get_string_param(literal_map_t const & params,
bd2b1e68 582 string const & k, string & v);
86bf665e 583 static bool get_number_param(literal_map_t const & params,
bd2b1e68 584 string const & k, long & v);
86bf665e 585 static bool get_number_param(literal_map_t const & params,
c239d28c 586 string const & k, Dwarf_Addr & v);
f301a9ff 587 static void query_library_callback (void *object, const char *data);
576eaefe 588 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 589 virtual void query_library (const char *data) = 0;
576eaefe 590 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 591
b55bc428 592
2c384610
DS
593 // Extracted parameters.
594 bool has_kernel;
91af0778
FCE
595 bool has_module;
596 bool has_process;
63b4fd14 597 bool has_library;
576eaefe
SC
598 bool has_plt;
599 bool has_statement;
2c384610 600 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 601 string path; // executable path if module is a .so
576eaefe 602 string plt_val; // has_plt => plt wildcard
2c384610
DS
603
604 virtual void handle_query_module() = 0;
605};
606
607
c4ce66a1 608base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 609 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 610{
91af0778 611 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
612 if (has_kernel)
613 module_val = "kernel";
91af0778
FCE
614
615 has_module = get_string_param (params, TOK_MODULE, module_val);
616 if (has_module)
617 has_process = false;
4baf0e53 618 else
d0a7f5a9 619 {
63b4fd14 620 string library_name;
576eaefe 621 long statement_num_val;
d0a7f5a9 622 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 623 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
624 if ((has_plt = has_null_param (params, TOK_PLT)))
625 plt_val = "*";
626 else has_plt = get_string_param (params, TOK_PLT, plt_val);
18418d34
SC
627 if (has_plt)
628 sess.consult_symtab = true;
576eaefe
SC
629 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
630
84c84ac4 631 if (has_process)
05fb3e0c 632 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
633 if (has_library)
634 {
635 if (! contains_glob_chars (library_name))
636 {
05fb3e0c
WF
637 path = path_remove_sysroot(sess, module_val);
638 module_val = find_executable (library_name, sess.sysroot,
639 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
640 if (module_val.find('/') == string::npos)
641 {
642 // We didn't find library_name so use iterate_over_libraries
643 module_val = path;
644 path = library_name;
645 }
84c84ac4
SC
646 }
647 else
648 path = library_name;
649 }
d0a7f5a9 650 }
91af0778
FCE
651
652 assert (has_kernel || has_process || has_module);
2c384610
DS
653}
654
c4ce66a1 655base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
656 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
657 module_val(module_val)
c4ce66a1
JS
658{
659 // NB: This uses '/' to distinguish between kernel modules and userspace,
660 // which means that userspace modules won't get any PATH searching.
661 if (module_val.find('/') == string::npos)
662 {
663 has_kernel = (module_val == TOK_KERNEL);
664 has_module = !has_kernel;
665 has_process = false;
666 }
667 else
668 {
669 has_kernel = has_module = false;
670 has_process = true;
671 }
672}
673
2c384610 674bool
86bf665e 675base_query::has_null_param(literal_map_t const & params,
2c384610
DS
676 string const & k)
677{
888af770 678 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
679}
680
681
682bool
86bf665e 683base_query::get_string_param(literal_map_t const & params,
2c384610
DS
684 string const & k, string & v)
685{
686 return derived_probe_builder::get_param (params, k, v);
687}
688
689
690bool
86bf665e 691base_query::get_number_param(literal_map_t const & params,
2c384610
DS
692 string const & k, long & v)
693{
694 int64_t value;
695 bool present = derived_probe_builder::get_param (params, k, value);
696 v = (long) value;
697 return present;
698}
699
700
701bool
86bf665e 702base_query::get_number_param(literal_map_t const & params,
2c384610
DS
703 string const & k, Dwarf_Addr & v)
704{
705 int64_t value;
706 bool present = derived_probe_builder::get_param (params, k, value);
707 v = (Dwarf_Addr) value;
708 return present;
709}
710
2c384610
DS
711struct dwarf_query : public base_query
712{
e1278bd4 713 dwarf_query(probe * base_probe,
2c384610
DS
714 probe_point * base_loc,
715 dwflpp & dw,
86bf665e 716 literal_map_t const & params,
b642c901
SC
717 vector<derived_probe *> & results,
718 const string user_path,
719 const string user_lib);
2c384610 720
c4ce66a1 721 vector<derived_probe *> & results;
8f14e444 722 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
723 probe * base_probe;
724 probe_point * base_loc;
b642c901
SC
725 string user_path;
726 string user_lib;
c4ce66a1 727
2c384610 728 virtual void handle_query_module();
5f0a03a6
JK
729 void query_module_dwarf();
730 void query_module_symtab();
5d5bd369 731 void query_library (const char *data);
576eaefe 732 void query_plt (const char *entry, size_t addr);
2c384610 733
2930abc7
FCE
734 void add_probe_point(string const & funcname,
735 char const * filename,
736 int line,
737 Dwarf_Die *scope_die,
738 Dwarf_Addr addr);
36f9dd1d 739
857bdfd1
JS
740 // Track addresses we've already seen in a given module
741 set<Dwarf_Addr> alias_dupes;
742
7fdd3e2c
JS
743 // Track inlines we've already seen as well
744 // NB: this can't be compared just by entrypc, as inlines can overlap
745 set<inline_instance_info> inline_dupes;
746
2930abc7 747 // Extracted parameters.
7a053d3b 748 string function_val;
20c6c071
GH
749
750 bool has_function_str;
751 bool has_statement_str;
752 bool has_function_num;
753 bool has_statement_num;
7a053d3b
RM
754 string statement_str_val;
755 string function_str_val;
c239d28c
GH
756 Dwarf_Addr statement_num_val;
757 Dwarf_Addr function_num_val;
20c6c071 758
b8da0ad1 759 bool has_call;
4bda987e 760 bool has_exported;
b8da0ad1 761 bool has_inline;
20c6c071
GH
762 bool has_return;
763
c9bad430
DS
764 bool has_maxactive;
765 long maxactive_val;
766
20c6c071
GH
767 bool has_label;
768 string label_val;
769
770 bool has_relative;
771 long relative_val;
772
37ebca01
FCE
773 bool has_absolute;
774
467bea43
SC
775 bool has_mark;
776
5f0a03a6
JK
777 enum dbinfo_reqt dbinfo_reqt;
778 enum dbinfo_reqt assess_dbinfo_reqt();
779
7d6d0afc 780 void parse_function_spec(const string & spec);
20c6c071 781 function_spec_type spec_type;
7d6d0afc 782 vector<string> scopes;
20c6c071
GH
783 string function;
784 string file;
0c8b7d37 785 line_t line_type;
879eb9e9 786 int line[2];
5f0a03a6 787 bool query_done; // Found exact match
20c6c071 788
bd25380d 789 set<string> filtered_srcfiles;
7e1279ea
FCE
790
791 // Map official entrypc -> func_info object
86bf665e
TM
792 inline_instance_map_t filtered_inlines;
793 func_info_map_t filtered_functions;
7e1279ea
FCE
794 bool choose_next_line;
795 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
796
797 void query_module_functions ();
b55bc428
FCE
798};
799
98afd80e 800
435f53a7
FCE
801static void delete_session_module_cache (systemtap_session& s); // forward decl
802
803
98afd80e 804struct dwarf_builder: public derived_probe_builder
b55bc428 805{
665e1256 806 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 807 map <string,dwflpp*> user_dw;
b642c901
SC
808 string user_path;
809 string user_lib;
ae2552da 810 dwarf_builder() {}
aa30ccd3 811
ae2552da 812 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 813 {
ea14cf67
FCE
814 if (kern_dw[module] == 0)
815 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 816 return kern_dw[module];
707bf35e
JS
817 }
818
819 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
820 {
ea14cf67
FCE
821 if (user_dw[module] == 0)
822 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
823 return user_dw[module];
824 }
7a24d422
FCE
825
826 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 827 void dwarf_build_no_more (bool)
aa30ccd3 828 {
435f53a7
FCE
829 delete_map(kern_dw);
830 delete_map(user_dw);
7a24d422
FCE
831 }
832
833 void build_no_more (systemtap_session &s)
834 {
835 dwarf_build_no_more (s.verbose > 3);
435f53a7 836 delete_session_module_cache (s);
aa30ccd3
FCE
837 }
838
e38d6504
RM
839 ~dwarf_builder()
840 {
7a24d422 841 dwarf_build_no_more (false);
c8959a29 842 }
aa30ccd3 843
5227f1ea 844 virtual void build(systemtap_session & sess,
7a053d3b 845 probe * base,
20c6c071 846 probe_point * location,
86bf665e 847 literal_map_t const & parameters,
20c6c071 848 vector<derived_probe *> & finished_results);
b55bc428
FCE
849};
850
5111fc3e 851
e1278bd4 852dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
853 probe_point * base_loc,
854 dwflpp & dw,
86bf665e 855 literal_map_t const & params,
b642c901
SC
856 vector<derived_probe *> & results,
857 const string user_path,
858 const string user_lib)
c4ce66a1 859 : base_query(dw, params), results(results),
b642c901 860 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
861 user_path(user_path), user_lib(user_lib), has_relative(false),
862 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
863{
864 // Reduce the query to more reasonable semantic values (booleans,
865 // extracted strings, numbers, etc).
bd2b1e68
GH
866 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
867 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
868
869 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
870 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
871
0f336e95
SC
872 has_label = get_string_param(params, TOK_LABEL, label_val);
873
b8da0ad1 874 has_call = has_null_param(params, TOK_CALL);
4bda987e 875 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 876 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 877 has_return = has_null_param(params, TOK_RETURN);
c9bad430 878 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 879 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 880 has_mark = false;
37ebca01 881
bd2b1e68 882 if (has_function_str)
7d6d0afc 883 parse_function_spec(function_str_val);
bd2b1e68 884 else if (has_statement_str)
7d6d0afc 885 parse_function_spec(statement_str_val);
0daad364 886
5f0a03a6
JK
887 dbinfo_reqt = assess_dbinfo_reqt();
888 query_done = false;
0daad364
JS
889}
890
891
440f755a
JS
892func_info_map_t *
893get_filtered_functions(dwarf_query *q)
894{
895 return &q->filtered_functions;
896}
897
898
899inline_instance_map_t *
900get_filtered_inlines(dwarf_query *q)
901{
902 return &q->filtered_inlines;
903}
904
905
2c384610 906void
5f0a03a6 907dwarf_query::query_module_dwarf()
2c384610
DS
908{
909 if (has_function_num || has_statement_num)
910 {
911 // If we have module("foo").function(0xbeef) or
912 // module("foo").statement(0xbeef), the address is relative
913 // to the start of the module, so we seek the function
914 // number plus the module's bias.
6b517475
JS
915 Dwarf_Addr addr = has_function_num ?
916 function_num_val : statement_num_val;
08d1d520
MW
917
918 // These are raw addresses, we need to know what the elf_bias
919 // is to feed it to libdwfl based functions.
920 Dwarf_Addr elf_bias;
921 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
922 assert(elf);
923 addr += elf_bias;
6b517475 924 query_addr(addr, this);
2c384610
DS
925 }
926 else
927 {
928 // Otherwise if we have a function("foo") or statement("foo")
929 // specifier, we have to scan over all the CUs looking for
930 // the function(s) in question
931 assert(has_function_str || has_statement_str);
4df79aaf
JS
932
933 // For simple cases, no wildcard and no source:line, we can do a very
934 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
935 if (spec_type == function_alone &&
936 !dw.name_has_wildcard(function) &&
937 !startswith(function, "_Z"))
4df79aaf
JS
938 query_module_functions();
939 else
337b7c44 940 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
941 }
942}
943
5f0a03a6
JK
944static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
945 dwarf_query * q);
946
947void
948dwarf_query::query_module_symtab()
949{
950 // Get the symbol table if it's necessary, sufficient, and not already got.
951 if (dbinfo_reqt == dbr_need_dwarf)
952 return;
953
954 module_info *mi = dw.mod_info;
955 if (dbinfo_reqt == dbr_need_symtab)
956 {
957 if (mi->symtab_status == info_unknown)
958 mi->get_symtab(this);
959 if (mi->symtab_status == info_absent)
960 return;
961 }
962
963 func_info *fi = NULL;
964 symbol_table *sym_table = mi->sym_table;
965
966 if (has_function_str)
967 {
968 // Per dwarf_query::assess_dbinfo_reqt()...
969 assert(spec_type == function_alone);
970 if (dw.name_has_wildcard(function_str_val))
971 {
972 // Until we augment the blacklist sufficently...
973 if (function_str_val.find_first_not_of("*?") == string::npos)
974 {
975 // e.g., kernel.function("*")
b530b5b3
LB
976 cerr << _F("Error: Pattern '%s' matches every single "
977 "instruction address in the symbol table,\n"
978 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
979 return;
980 }
2e67a43b 981 symbol_table::iterator_t iter;
1c6b77e5
JS
982 for (iter = sym_table->map_by_addr.begin();
983 iter != sym_table->map_by_addr.end();
2e67a43b 984 ++iter)
5f0a03a6 985 {
1c6b77e5 986 fi = iter->second;
5f0a03a6
JK
987 if (!null_die(&fi->die))
988 continue; // already handled in query_module_dwarf()
989 if (dw.function_name_matches_pattern(fi->name, function_str_val))
990 query_func_info(fi->addr, *fi, this);
991 }
992 }
993 else
994 {
995 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 996 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
997 query_func_info(fi->addr, *fi, this);
998 }
999 }
1000 else
1001 {
1002 assert(has_function_num || has_statement_num);
1003 // Find the "function" in which the indicated address resides.
1004 Dwarf_Addr addr =
1005 (has_function_num ? function_num_val : statement_num_val);
576eaefe 1006 if (has_plt)
3d372d6b
SC
1007 {
1008 // Use the raw address from the .plt
1009 fi = sym_table->get_first_func();
1010 fi->addr = addr;
1011 }
1012 else
1013 fi = sym_table->get_func_containing_address(addr);
1014
5f0a03a6
JK
1015 if (!fi)
1016 {
2713ea24
CM
1017 sess.print_warning(_F("address %#" PRIx64 " out of range for module %s",
1018 addr, dw.module_name.c_str()));
1019 return;
5f0a03a6
JK
1020 }
1021 if (!null_die(&fi->die))
1022 {
1023 // addr looks like it's in the compilation unit containing
1024 // the indicated function, but query_module_dwarf() didn't
1025 // match addr to any compilation unit, so addr must be
1026 // above that cu's address range.
2713ea24
CM
1027 sess.print_warning(_F("address %#" PRIx64 " maps to no known compilation unit in module %s",
1028 addr, dw.module_name.c_str()));
5f0a03a6
JK
1029 return;
1030 }
1031 query_func_info(fi->addr, *fi, this);
1032 }
1033}
1034
1035void
1036dwarf_query::handle_query_module()
1037{
1c6b77e5
JS
1038 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
1039 dw.get_module_dwarf(false, report);
1040
1041 // prebuild the symbol table to resolve aliases
1042 dw.mod_info->get_symtab(this);
1043
857bdfd1
JS
1044 // reset the dupe-checking for each new module
1045 alias_dupes.clear();
7fdd3e2c 1046 inline_dupes.clear();
857bdfd1 1047
5f0a03a6
JK
1048 if (dw.mod_info->dwarf_status == info_present)
1049 query_module_dwarf();
1c6b77e5 1050
5f0a03a6
JK
1051 // Consult the symbol table if we haven't found all we're looking for.
1052 // asm functions can show up in the symbol table but not in dwarf.
1053 if (sess.consult_symtab && !query_done)
1054 query_module_symtab();
1055}
1056
2c384610 1057
7d6d0afc
JS
1058void
1059dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1060{
1d12a9b2
JS
1061 line_type = ABSOLUTE;
1062 line[0] = line[1] = 0;
1063
91699a70 1064 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1065
7d6d0afc 1066 // look for named scopes
91699a70
JS
1067 scope_pos = spec.rfind("::");
1068 if (scope_pos != string::npos)
bd2b1e68 1069 {
91699a70
JS
1070 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1071 scope_pos += 2;
bd2b1e68 1072 }
91699a70
JS
1073 else
1074 scope_pos = 0;
bd2b1e68 1075
7d6d0afc
JS
1076 // look for a source separator
1077 src_pos = spec.find('@', scope_pos);
1078 if (src_pos == string::npos)
bd2b1e68 1079 {
7d6d0afc
JS
1080 function = spec.substr(scope_pos);
1081 spec_type = function_alone;
bd2b1e68 1082 }
7d6d0afc 1083 else
879eb9e9 1084 {
7d6d0afc 1085 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1086
7d6d0afc
JS
1087 // look for a line-number separator
1088 line_pos = spec.find_first_of(":+", src_pos);
1089 if (line_pos == string::npos)
1090 {
1091 file = spec.substr(src_pos + 1);
1092 spec_type = function_and_file;
1093 }
1094 else
1095 {
1096 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1097
1098 // classify the line spec
1099 spec_type = function_file_and_line;
1100 if (spec[line_pos] == '+')
1101 line_type = RELATIVE;
1102 else if (spec[line_pos + 1] == '*' &&
1103 spec.length() == line_pos + 2)
1104 line_type = WILDCARD;
1105 else
1106 line_type = ABSOLUTE;
1107
1108 if (line_type != WILDCARD)
1109 try
1110 {
1111 // try to parse either N or N-M
1112 dash_pos = spec.find('-', line_pos + 1);
1113 if (dash_pos == string::npos)
1114 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1115 else
1116 {
1117 line_type = RANGE;
1118 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1119 dash_pos - line_pos - 1));
1120 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1121 }
1122 }
1123 catch (runtime_error & exn)
1124 {
1125 goto bad;
1126 }
1127 }
bd2b1e68
GH
1128 }
1129
7d6d0afc
JS
1130 if (function.empty() ||
1131 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1132 goto bad;
1133
7d6d0afc 1134 if (sess.verbose > 2)
bd2b1e68 1135 {
b530b5b3
LB
1136 //clog << "parsed '" << spec << "'";
1137 clog << _F("parse '%s'", spec.c_str());
41c262f3 1138
7d6d0afc
JS
1139 if (!scopes.empty())
1140 clog << ", scope '" << scopes[0] << "'";
1141 for (unsigned i = 1; i < scopes.size(); ++i)
1142 clog << "::'" << scopes[i] << "'";
41c262f3 1143
7d6d0afc
JS
1144 clog << ", func '" << function << "'";
1145
1146 if (spec_type != function_alone)
1147 clog << ", file '" << file << "'";
1148
1149 if (spec_type == function_file_and_line)
1150 {
1151 clog << ", line ";
1152 switch (line_type)
1153 {
1154 case ABSOLUTE:
1155 clog << line[0];
1156 break;
1157
1158 case RELATIVE:
1159 clog << "+" << line[0];
1160 break;
1161
1162 case RANGE:
1163 clog << line[0] << " - " << line[1];
1164 break;
1165
1166 case WILDCARD:
1167 clog << "*";
1168 break;
1169 }
1170 }
1171
1172 clog << endl;
bd2b1e68
GH
1173 }
1174
7d6d0afc
JS
1175 return;
1176
1177bad:
b530b5b3 1178 throw semantic_error(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1179 base_probe->tok);
bd2b1e68
GH
1180}
1181
05fb3e0c
WF
1182string path_remove_sysroot(const systemtap_session& sess, const string& path)
1183{
1184 size_t pos;
1185 string retval = path;
1186 if (!sess.sysroot.empty() &&
1187 (pos = retval.find(sess.sysroot)) != string::npos)
1188 retval.replace(pos, sess.sysroot.length(), "/");
1189 return retval;
1190}
bd2b1e68 1191
36f9dd1d 1192void
1ffb8bd1 1193dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1194 const char* filename,
36f9dd1d 1195 int line,
b20febf3 1196 Dwarf_Die* scope_die,
36f9dd1d
FCE
1197 Dwarf_Addr addr)
1198{
b20febf3 1199 string reloc_section; // base section for relocation purposes
27646582 1200 Dwarf_Addr reloc_addr; // relocated
b20febf3 1201 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1202 string funcname = dw_funcname;
36f9dd1d 1203
37ebca01
FCE
1204 assert (! has_absolute); // already handled in dwarf_builder::build()
1205
576eaefe
SC
1206 if (!has_plt)
1207 reloc_addr = dw.relocate_address(addr, reloc_section);
1208 else
1209 {
3d372d6b 1210 // Set the reloc_section but use the plt entry for reloc_addr
576eaefe
SC
1211 dw.relocate_address(addr, reloc_section);
1212 reloc_addr = addr;
1213 }
2930abc7 1214
1ffb8bd1 1215 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1216 const char* linkage_name;
1217 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1218 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1219 funcname = linkage_name;
1220
7f9f3386
FCE
1221 if (sess.verbose > 1)
1222 {
b530b5b3 1223 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1224 if (string(module) == TOK_KERNEL)
b530b5b3 1225 clog << _(" kernel");
91af0778 1226 else if (has_module)
b530b5b3 1227 clog << _(" module=") << module;
91af0778 1228 else if (has_process)
b530b5b3 1229 clog << _(" process=") << module;
b20febf3 1230 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1231 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1232 }
4baf0e53 1233
27646582 1234 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1235 addr, has_return);
b20febf3
FCE
1236 if (sess.verbose > 1)
1237 clog << endl;
7f9f3386 1238
84048984
FCE
1239 if (module == TOK_KERNEL)
1240 {
1241 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1242 reloc_addr = addr - sess.sym_stext;
37ebca01 1243 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1244 }
1245
b20febf3
FCE
1246 if (! bad)
1247 {
1a0dbc5a 1248 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1249
1250 if (has_process)
1251 {
05fb3e0c 1252 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1253 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1254 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1255 *this, scope_die));
1256 }
1257 else
1258 {
1259 assert (has_kernel || has_module);
1260 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1261 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1262 *this, scope_die));
1263 }
b20febf3 1264 }
2930abc7
FCE
1265}
1266
5f0a03a6
JK
1267enum dbinfo_reqt
1268dwarf_query::assess_dbinfo_reqt()
1269{
1270 if (has_absolute)
1271 {
1272 // kernel.statement(NUM).absolute
1273 return dbr_none;
1274 }
1275 if (has_inline)
1276 {
1277 // kernel.function("f").inline or module("m").function("f").inline
1278 return dbr_need_dwarf;
1279 }
1280 if (has_function_str && spec_type == function_alone)
1281 {
1282 // kernel.function("f") or module("m").function("f")
1283 return dbr_need_symtab;
1284 }
1285 if (has_statement_num)
1286 {
1287 // kernel.statement(NUM) or module("m").statement(NUM)
1288 // Technically, all we need is the module offset (or _stext, for
1289 // the kernel). But for that we need either the ELF file or (for
1290 // _stext) the symbol table. In either case, the symbol table
1291 // is available, and that allows us to map the NUM (address)
1292 // to a function, which is goodness.
1293 return dbr_need_symtab;
1294 }
1295 if (has_function_num)
1296 {
1297 // kernel.function(NUM) or module("m").function(NUM)
1298 // Need the symbol table so we can back up from NUM to the
1299 // start of the function.
1300 return dbr_need_symtab;
1301 }
1302 // Symbol table tells us nothing about source files or line numbers.
1303 return dbr_need_dwarf;
1304}
2930abc7
FCE
1305
1306
b8da0ad1
FCE
1307// The critical determining factor when interpreting a pattern
1308// string is, perhaps surprisingly: "presence of a lineno". The
1309// presence of a lineno changes the search strategy completely.
1310//
1311// Compare the two cases:
1312//
1313// 1. {statement,function}(foo@file.c:lineno)
1314// - find the files matching file.c
1315// - in each file, find the functions matching foo
1316// - query the file for line records matching lineno
1317// - iterate over the line records,
1318// - and iterate over the functions,
1319// - if(haspc(function.DIE, line.addr))
1320// - if looking for statements: probe(lineno.addr)
1321// - if looking for functions: probe(function.{entrypc,return,etc.})
1322//
1323// 2. {statement,function}(foo@file.c)
1324// - find the files matching file.c
1325// - in each file, find the functions matching foo
1326// - probe(function.{entrypc,return,etc.})
1327//
1328// Thus the first decision we make is based on the presence of a
1329// lineno, and we enter entirely different sets of callbacks
1330// depending on that decision.
1331//
1332// Note that the first case is a generalization fo the second, in that
1333// we could theoretically search through line records for matching
1334// file names (a "table scan" in rdbms lingo). Luckily, file names
1335// are already cached elsewhere, so we can do an "index scan" as an
1336// optimization.
7e1279ea 1337
bd2b1e68 1338static void
4cd232e4 1339query_statement (string const & func,
20e4a32c 1340 char const * file,
4cd232e4 1341 int line,
bcc12710 1342 Dwarf_Die *scope_die,
20e4a32c 1343 Dwarf_Addr stmt_addr,
4cd232e4 1344 dwarf_query * q)
bd2b1e68 1345{
39bcd429
FCE
1346 try
1347 {
cee35f73 1348 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1349 line, scope_die, stmt_addr);
39bcd429
FCE
1350 }
1351 catch (const semantic_error& e)
1352 {
1353 q->sess.print_error (e);
1354 }
bd2b1e68
GH
1355}
1356
6b517475
JS
1357static void
1358query_addr(Dwarf_Addr addr, dwarf_query *q)
1359{
1360 dwflpp &dw = q->dw;
1361
08d1d520
MW
1362 if (q->sess.verbose > 2)
1363 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1364
1365 // First pick which CU contains this address
1366 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1367 if (!cudie) // address could be wildly out of range
1368 return;
1369 dw.focus_on_cu(cudie);
1370
1371 // Now compensate for the dw bias
1372 addr -= dw.module_bias;
1373
1374 // Per PR5787, we look up the scope die even for
1375 // statement_num's, for blacklist sensitivity and $var
1376 // resolution purposes.
1377
1378 // Find the scopes containing this address
1379 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1380 if (scopes.empty())
1381 return;
1382
1383 // Look for the innermost containing function
1384 Dwarf_Die *fnscope = NULL;
1385 for (size_t i = 0; i < scopes.size(); ++i)
1386 {
1387 int tag = dwarf_tag(&scopes[i]);
1388 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1389 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1390 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1391 {
1392 fnscope = &scopes[i];
1393 break;
1394 }
1395 }
1396 if (!fnscope)
1397 return;
1398 dw.focus_on_function(fnscope);
1399
1400 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1401
1402 const char *file = dwarf_decl_file(fnscope);
1403 int line;
1404 dwarf_decl_line(fnscope, &line);
1405
1406 // Function probes should reset the addr to the function entry
1407 // and possibly perform prologue searching
1408 if (q->has_function_num)
1409 {
1410 dw.die_entrypc(fnscope, &addr);
1411 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1412 (q->sess.prologue_searching || q->has_process)) // PR 6871
1413 {
1414 func_info func;
1415 func.die = *fnscope;
1416 func.name = dw.function_name;
1417 func.decl_file = file;
1418 func.decl_line = line;
1419 func.entrypc = addr;
1420
1421 func_info_map_t funcs(1, func);
1422 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1423 if (q->has_return) // PR13200
1424 {
1425 if (q->sess.verbose > 2)
1426 clog << "ignoring prologue for .return probes" << endl;
1427 }
1428 else
1429 {
1430 if (funcs[0].prologue_end)
1431 addr = funcs[0].prologue_end;
1432 }
6b517475
JS
1433 }
1434 }
1435 else
1436 {
1437 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1438 if (address_line)
1439 {
1440 file = address_line.linesrc();
1441 line = address_line.lineno();
1442 }
1443
1444 // Verify that a raw address matches the beginning of a
1445 // statement. This is a somewhat lame check that the address
1446 // is at the start of an assembly instruction. Mark probes are in the
1447 // middle of a macro and thus not strictly at a statement beginning.
1448 // Guru mode may override this check.
1449 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1450 {
1451 stringstream msg;
2a97f50b 1452 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1453 addr);
6b517475 1454 if (address_line)
2a97f50b 1455 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1456 else
b530b5b3
LB
1457 msg << _F(" (no line info found for '%s', in module '%s')",
1458 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475
JS
1459 if (! q->sess.guru_mode)
1460 throw semantic_error(msg.str());
2713ea24 1461 else
6b517475
JS
1462 q->sess.print_warning(msg.str());
1463 }
1464 }
1465
1466 // Build a probe at this point
1467 query_statement(dw.function_name, file, line, scope, addr, q);
1468}
1469
8096dd7d
JS
1470static void
1471query_label (string const & func,
1472 char const * label,
1473 char const * file,
1474 int line,
1475 Dwarf_Die *scope_die,
1476 Dwarf_Addr stmt_addr,
1477 dwarf_query * q)
1478{
6b517475
JS
1479 assert (q->has_statement_str || q->has_function_str);
1480
8096dd7d
JS
1481 size_t i = q->results.size();
1482
1483 // weed out functions whose decl_file isn't one of
1484 // the source files that we actually care about
6b517475 1485 if (q->spec_type != function_alone &&
8096dd7d
JS
1486 q->filtered_srcfiles.count(file) == 0)
1487 return;
1488
1489 query_statement(func, file, line, scope_die, stmt_addr, q);
1490
c72aa911
JS
1491 // after the fact, insert the label back into the derivation chain
1492 probe_point::component* ppc =
1493 new probe_point::component(TOK_LABEL, new literal_string (label));
1494 for (; i < q->results.size(); ++i)
1495 {
1496 derived_probe* p = q->results[i];
1497 probe_point* pp = new probe_point(*p->locations[0]);
1498 pp->components.push_back (ppc);
1499 p->base = p->base->create_alias(p->locations[0], pp);
1500 }
8096dd7d
JS
1501}
1502
7e1279ea 1503static void
3e961ba6 1504query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1505 dwarf_query * q)
1506{
b6581717 1507 try
7e1279ea 1508 {
8f14e444
FCE
1509 assert (! q->has_return); // checked by caller already
1510 if (q->sess.verbose>2)
b530b5b3
LB
1511 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1512 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1513 query_statement (ii.name, ii.decl_file, ii.decl_line,
1514 &ii.die, ii.entrypc, q);
7e1279ea 1515 }
b6581717 1516 catch (semantic_error &e)
7e1279ea 1517 {
b6581717 1518 q->sess.print_error (e);
7e1279ea
FCE
1519 }
1520}
1521
1522static void
1523query_func_info (Dwarf_Addr entrypc,
bcc12710 1524 func_info & fi,
7e1279ea
FCE
1525 dwarf_query * q)
1526{
b6581717 1527 try
7e1279ea 1528 {
b6581717
GH
1529 if (q->has_return)
1530 {
1531 // NB. dwarf_derived_probe::emit_registrations will emit a
1532 // kretprobe based on the entrypc in this case.
464379bb
FCE
1533 if (fi.prologue_end != 0 && q->has_return) // PR13200
1534 {
1535 if (q->sess.verbose > 2)
1536 clog << "ignoring prologue for .return probes" << endl;
1537 }
20e4a32c 1538 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1539 &fi.die, entrypc, q);
1540 }
1541 else
1542 {
35dc8b04 1543 if (fi.prologue_end != 0)
44f75386 1544 {
44f75386
FCE
1545 query_statement (fi.name, fi.decl_file, fi.decl_line,
1546 &fi.die, fi.prologue_end, q);
1547 }
1548 else
1549 {
1550 query_statement (fi.name, fi.decl_file, fi.decl_line,
1551 &fi.die, entrypc, q);
1552 }
b6581717 1553 }
7e1279ea 1554 }
b6581717 1555 catch (semantic_error &e)
7e1279ea 1556 {
b6581717 1557 q->sess.print_error (e);
7e1279ea
FCE
1558 }
1559}
1560
1561
bd4b874d
SC
1562static void
1563query_srcfile_label (const dwarf_line_t& line, void * arg)
1564{
1565 dwarf_query * q = static_cast<dwarf_query *>(arg);
1566
1567 Dwarf_Addr addr = line.addr();
1568
1569 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1570 i != q->filtered_functions.end(); ++i)
1571 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1572 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1573 q, query_label);
1574
1575 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1576 i != q->filtered_inlines.end(); ++i)
1577 if (q->dw.die_has_pc (i->die, addr))
1578 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1579 q, query_label);
bd4b874d
SC
1580}
1581
7e1279ea 1582static void
86bf665e 1583query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1584{
1585 dwarf_query * q = static_cast<dwarf_query *>(arg);
1586
86bf665e 1587 Dwarf_Addr addr = line.addr();
4cd232e4 1588
86bf665e 1589 int lineno = line.lineno();
847bf07f 1590
86bf665e 1591 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1592 i != q->filtered_functions.end(); ++i)
1593 {
3e961ba6 1594 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1595 {
b0ee93c4 1596 if (q->sess.verbose>3)
b530b5b3 1597 clog << _("function DIE lands on srcfile\n");
4cd232e4 1598 if (q->has_statement_str)
f5958c8f
JS
1599 {
1600 Dwarf_Die scope;
1601 q->dw.inner_die_containing_pc(i->die, addr, scope);
1602 query_statement (i->name, i->decl_file,
1603 lineno, // NB: not q->line !
1604 &scope, addr, q);
1605 }
4cd232e4 1606 else
3e961ba6 1607 query_func_info (i->entrypc, *i, q);
7e1279ea 1608 }
20e4a32c
RM
1609 }
1610
86bf665e 1611 for (inline_instance_map_t::iterator i
897820ca
GH
1612 = q->filtered_inlines.begin();
1613 i != q->filtered_inlines.end(); ++i)
1614 {
3e961ba6 1615 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1616 {
b0ee93c4 1617 if (q->sess.verbose>3)
b530b5b3 1618 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1619 if (q->has_statement_str)
f5958c8f
JS
1620 {
1621 Dwarf_Die scope;
1622 q->dw.inner_die_containing_pc(i->die, addr, scope);
1623 query_statement (i->name, i->decl_file,
1624 q->line[0], &scope, addr, q);
1625 }
897820ca 1626 else
3e961ba6 1627 query_inline_instance_info (*i, q);
897820ca 1628 }
20e4a32c 1629 }
7e1279ea
FCE
1630}
1631
1632
7fdd3e2c
JS
1633bool
1634inline_instance_info::operator<(const inline_instance_info& other) const
1635{
1636 if (entrypc != other.entrypc)
1637 return entrypc < other.entrypc;
1638
1639 if (decl_line != other.decl_line)
1640 return decl_line < other.decl_line;
1641
1642 int cmp = name.compare(other.name);
1643 if (!cmp)
1644 cmp = strcmp(decl_file, other.decl_file);
1645 return cmp < 0;
1646}
1647
1648
4fa7b22b 1649static int
7e1279ea 1650query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1651{
1652 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475 1653 assert (q->has_statement_str || q->has_function_str);
4bda987e 1654 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1655
39bcd429 1656 try
7a053d3b 1657 {
b0ee93c4 1658 if (q->sess.verbose>2)
b530b5b3 1659 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1660
6b517475
JS
1661 Dwarf_Addr entrypc;
1662 if (q->dw.die_entrypc (die, &entrypc))
1663 {
1664 inline_instance_info inl;
1665 inl.die = *die;
1666 inl.name = q->dw.function_name;
1667 inl.entrypc = entrypc;
1668 q->dw.function_file (&inl.decl_file);
1669 q->dw.function_line (&inl.decl_line);
1670
1671 // make sure that this inline hasn't already
1672 // been matched from a different CU
1673 if (q->inline_dupes.insert(inl).second)
1674 q->filtered_inlines.push_back(inl);
1675 }
7e1279ea
FCE
1676 return DWARF_CB_OK;
1677 }
1678 catch (const semantic_error& e)
1679 {
1680 q->sess.print_error (e);
1681 return DWARF_CB_ABORT;
1682 }
1683}
bb788f9f 1684
7e1279ea 1685static int
2da9cedb 1686query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1687{
2da9cedb 1688 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1689 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1690
bd25380d
JS
1691 // weed out functions whose decl_file isn't one of
1692 // the source files that we actually care about
6b517475 1693 if (q->spec_type != function_alone &&
bd25380d 1694 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1695 return DWARF_CB_OK;
bd25380d 1696
7e1279ea
FCE
1697 try
1698 {
7e1279ea
FCE
1699 q->dw.focus_on_function (func);
1700
7d6d0afc
JS
1701 if (!q->dw.function_scope_matches(q->scopes))
1702 return DWARF_CB_OK;
1703
857bdfd1
JS
1704 // make sure that this function address hasn't
1705 // already been matched under an aliased name
1706 Dwarf_Addr addr;
1707 if (!q->dw.func_is_inline() &&
1708 dwarf_entrypc(func, &addr) == 0 &&
1709 !q->alias_dupes.insert(addr).second)
1710 return DWARF_CB_OK;
1711
4bda987e 1712 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1713 {
4bda987e 1714 if (q->sess.verbose>3)
b530b5b3 1715 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1716 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1717 }
8f14e444
FCE
1718 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1719 {
1720 q->inlined_non_returnable.insert (q->dw.function_name);
1721 }
396afcee 1722 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1723 {
4bda987e
SC
1724 if (q->has_exported && !q->dw.func_is_exported ())
1725 return DWARF_CB_OK;
6b517475 1726 if (q->sess.verbose>2)
b530b5b3 1727 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1728
1729 func_info func;
1730 q->dw.function_die (&func.die);
1731 func.name = q->dw.function_name;
1732 q->dw.function_file (&func.decl_file);
1733 q->dw.function_line (&func.decl_line);
1734
1735 Dwarf_Addr entrypc;
1736 if (q->dw.function_entrypc (&entrypc))
1737 {
1738 func.entrypc = entrypc;
1739 q->filtered_functions.push_back (func);
1740 }
1741 /* else this function is fully inlined, just ignore it */
7e1279ea 1742 }
39bcd429 1743 return DWARF_CB_OK;
bd2b1e68 1744 }
39bcd429 1745 catch (const semantic_error& e)
bd2b1e68 1746 {
39bcd429
FCE
1747 q->sess.print_error (e);
1748 return DWARF_CB_ABORT;
bd2b1e68 1749 }
bd2b1e68
GH
1750}
1751
1752static int
1753query_cu (Dwarf_Die * cudie, void * arg)
1754{
20c6c071 1755 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1756 assert (q->has_statement_str || q->has_function_str);
1757
85007c04 1758 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1759
39bcd429 1760 try
bd2b1e68 1761 {
7e1279ea 1762 q->dw.focus_on_cu (cudie);
b5d77020 1763
b0ee93c4 1764 if (false && q->sess.verbose>2)
b530b5b3
LB
1765 clog << _F("focused on CU '%s', in module '%s'\n",
1766 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1767
6b517475
JS
1768 q->filtered_srcfiles.clear();
1769 q->filtered_functions.clear();
1770 q->filtered_inlines.clear();
1771
1772 // In this path, we find "abstract functions", record
1773 // information about them, and then (depending on lineno
1774 // matching) possibly emit one or more of the function's
1775 // associated addresses. Unfortunately the control of this
1776 // cannot easily be turned inside out.
1777
1778 if (q->spec_type != function_alone)
39bcd429 1779 {
6b517475
JS
1780 // If we have a pattern string with a filename, we need
1781 // to elaborate the srcfile mask in question first.
1782 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1783
1784 // If we have a file pattern and *no* srcfile matches, there's
1785 // no need to look further into this CU, so skip.
1786 if (q->filtered_srcfiles.empty())
1787 return DWARF_CB_OK;
1788 }
e4c58386 1789
6b517475
JS
1790 // Pick up [entrypc, name, DIE] tuples for all the functions
1791 // matching the query, and fill in the prologue endings of them
1792 // all in a single pass.
5898b6e1 1793 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1794 if (rc != DWARF_CB_OK)
1795 q->query_done = true;
1796
1797 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1798 && !q->has_statement_str) // PR 2608
1799 if (! q->filtered_functions.empty())
1800 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1801 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1802 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1803
1804 if (q->spec_type == function_file_and_line)
1805 {
58b070fb 1806 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1807 if (q->has_function_str)
b530b5b3
LB
1808 q->sess.print_warning (_("For probing a particular line, use a "
1809 ".statement() probe, not .function()"),
af2e341f 1810 q->base_probe->tok);
58b070fb 1811
6b517475
JS
1812 // If we have a pattern string with target *line*, we
1813 // have to look at lines in all the matched srcfiles.
1814 void (* callback) (const dwarf_line_t&, void*) =
1815 q->has_label ? query_srcfile_label : query_srcfile_line;
1816 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1817 i != q->filtered_srcfiles.end(); ++i)
1818 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1819 q->line_type, callback, q->function, q);
1820 }
1821 else if (q->has_label)
1822 {
1823 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1824 i != q->filtered_functions.end(); ++i)
1825 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1826 q, query_label);
1827
1828 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1829 i != q->filtered_inlines.end(); ++i)
1830 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1831 q, query_label);
39bcd429 1832 }
6b517475
JS
1833 else
1834 {
1835 // Otherwise, simply probe all resolved functions.
1836 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1837 i != q->filtered_functions.end(); ++i)
1838 query_func_info (i->entrypc, *i, q);
1839
1840 // And all inline instances (if we're not excluding inlines with ".call")
1841 if (! q->has_call)
1842 for (inline_instance_map_t::iterator i
1843 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1844 query_inline_instance_info (*i, q);
1845 }
39bcd429 1846 return DWARF_CB_OK;
bd2b1e68 1847 }
39bcd429 1848 catch (const semantic_error& e)
bd2b1e68 1849 {
39bcd429
FCE
1850 q->sess.print_error (e);
1851 return DWARF_CB_ABORT;
bd2b1e68 1852 }
bd2b1e68
GH
1853}
1854
0ce64fb8 1855
4df79aaf
JS
1856void
1857dwarf_query::query_module_functions ()
1858{
1859 try
1860 {
1861 filtered_srcfiles.clear();
1862 filtered_functions.clear();
1863 filtered_inlines.clear();
1864
1865 // Collect all module functions so we know which CUs are interesting
1866 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1867 if (rc != DWARF_CB_OK)
1868 {
1869 query_done = true;
1870 return;
1871 }
1872
1873 set<void*> used_cus; // by cu->addr
1874 vector<Dwarf_Die> cus;
1875 Dwarf_Die cu_mem;
1876
1877 for (func_info_map_t::iterator i = filtered_functions.begin();
1878 i != filtered_functions.end(); ++i)
1879 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1880 used_cus.insert(cu_mem.addr).second)
1881 cus.push_back(cu_mem);
1882
1883 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1884 i != filtered_inlines.end(); ++i)
1885 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1886 used_cus.insert(cu_mem.addr).second)
1887 cus.push_back(cu_mem);
1888
1889 // Reset the dupes since we didn't actually collect them the first time
1890 alias_dupes.clear();
1891 inline_dupes.clear();
1892
1893 // Run the query again on the individual CUs
1894 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1895 query_cu(&*i, this);
1896 }
1897 catch (const semantic_error& e)
1898 {
1899 sess.print_error (e);
1900 }
1901}
1902
1903
5f0a03a6
JK
1904static void
1905validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1906{
1907 // Validate the machine code in this elf file against the
1908 // session machine. This is important, in case the wrong kind
1909 // of debuginfo is being automagically processed by elfutils.
1910 // While we can tell i686 apart from x86-64, unfortunately
1911 // we can't help confusing i586 vs i686 (both EM_386).
1912
1913 Dwarf_Addr bias;
1914 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1915 // because dwfl_module_getelf can force costly section relocations
1916 // we don't really need, while either will do for this purpose.
1917 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1918 ?: dwfl_module_getelf (mod, &bias));
1919
1920 GElf_Ehdr ehdr_mem;
1921 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1922 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 1923 assert(em);
5f0a03a6
JK
1924 int elf_machine = em->e_machine;
1925 const char* debug_filename = "";
1926 const char* main_filename = "";
1927 (void) dwfl_module_info (mod, NULL, NULL,
1928 NULL, NULL, NULL,
1929 & main_filename,
1930 & debug_filename);
1931 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1932
1933 string expect_machine; // to match sess.machine (i.e., kernel machine)
1934 string expect_machine2;
5f0a03a6 1935
d27e6fd5 1936 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1937 switch (elf_machine)
1938 {
756c9462
FCE
1939 // x86 and ppc are bi-architecture; a 64-bit kernel
1940 // can normally run either 32-bit or 64-bit *userspace*.
1941 case EM_386:
1942 expect_machine = "i?86";
1943 if (! q->has_process) break; // 32-bit kernel/module
1944 /* FALLSTHROUGH */
1945 case EM_X86_64:
1946 expect_machine2 = "x86_64";
1947 break;
1948 case EM_PPC:
756c9462 1949 case EM_PPC64:
5a1c472e 1950 expect_machine = "powerpc";
756c9462 1951 break;
3fe7d888 1952 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 1953 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 1954 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
1955 // XXX: fill in some more of these
1956 default: expect_machine = "?"; break;
1957 }
1958
1959 if (! debug_filename) debug_filename = main_filename;
1960 if (! debug_filename) debug_filename = name;
1961
756c9462
FCE
1962 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
1963 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
1964 {
1965 stringstream msg;
b530b5b3
LB
1966 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
1967 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
1968 sess_machine.c_str(), debug_filename);
5f0a03a6
JK
1969 throw semantic_error(msg.str ());
1970 }
1971
b57082de 1972 if (q->sess.verbose>1)
2a97f50b 1973 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
1974 " file %s ELF machine %s|%s (code %d)\n",
1975 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
1976 q->dw.module_bias, debug_filename, expect_machine.c_str(),
1977 expect_machine2.c_str(), elf_machine);
5f0a03a6 1978}
1d3a40b6 1979
91af0778
FCE
1980
1981
1982static Dwarf_Addr
1983lookup_symbol_address (Dwfl_Module *m, const char* wanted)
1984{
1985 int syments = dwfl_module_getsymtab(m);
1986 assert(syments);
1987 for (int i = 1; i < syments; ++i)
1988 {
1989 GElf_Sym sym;
1990 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
1991 if (name != NULL && strcmp(name, wanted) == 0)
1992 return sym.st_value;
1993 }
1994
1995 return 0;
1996}
1997
1998
1999
bd2b1e68 2000static int
b8da0ad1 2001query_module (Dwfl_Module *mod,
91af0778 2002 void **,
b8da0ad1 2003 const char *name,
6f4c1275 2004 Dwarf_Addr addr,
b8da0ad1 2005 void *arg)
bd2b1e68 2006{
91af0778 2007 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 2008
39bcd429 2009 try
e38d6504 2010 {
91af0778
FCE
2011 module_info* mi = q->sess.module_cache->cache[name];
2012 if (mi == 0)
2013 {
2014 mi = q->sess.module_cache->cache[name] = new module_info(name);
2015
6f4c1275
FCE
2016 mi->mod = mod;
2017 mi->addr = addr;
91af0778 2018
6f4c1275
FCE
2019 const char* debug_filename = "";
2020 const char* main_filename = "";
2021 (void) dwfl_module_info (mod, NULL, NULL,
2022 NULL, NULL, NULL,
2023 & main_filename,
2024 & debug_filename);
2025
ab3ed72d 2026 if (debug_filename || main_filename)
91af0778 2027 {
6f4c1275
FCE
2028 mi->elf_path = debug_filename ?: main_filename;
2029 }
2030 else if (name == TOK_KERNEL)
2031 {
2032 mi->dwarf_status = info_absent;
91af0778 2033 }
91af0778
FCE
2034 }
2035 // OK, enough of that module_info caching business.
2036
5f0a03a6 2037 q->dw.focus_on_module(mod, mi);
d9b516ca 2038
39bcd429
FCE
2039 // If we have enough information in the pattern to skip a module and
2040 // the module does not match that information, return early.
b8da0ad1 2041 if (!q->dw.module_name_matches(q->module_val))
85007c04 2042 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2043
2044 // Don't allow module("*kernel*") type expressions to match the
2045 // elfutils module "kernel", which we refer to in the probe
2046 // point syntax exclusively as "kernel.*".
2047 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2048 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2049
5f0a03a6
JK
2050 if (mod)
2051 validate_module_elf(mod, name, q);
2052 else
91af0778
FCE
2053 assert(q->has_kernel); // and no vmlinux to examine
2054
2055 if (q->sess.verbose>2)
b530b5b3 2056 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2057
2058
2059 // Collect a few kernel addresses. XXX: these belong better
2060 // to the sess.module_info["kernel"] struct.
2061 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2062 {
91af0778
FCE
2063 if (! q->sess.sym_kprobes_text_start)
2064 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2065 if (! q->sess.sym_kprobes_text_end)
2066 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2067 if (! q->sess.sym_stext)
2068 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2069 }
2070
47e226ed
SC
2071 // We either have a wildcard or an unresolved library
2072 if (q->has_library && (contains_glob_chars (q->path)
2073 || q->path.find('/') == string::npos))
84c84ac4
SC
2074 // handle .library(GLOB)
2075 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2076 // .plt is translated to .plt.statement(N). We only want to iterate for the
2077 // .plt case
2078 else if (q->has_plt && ! q->has_statement)
2079 q->dw.iterate_over_plt (q, &q->query_plt_callback);
84c84ac4
SC
2080 else
2081 // search the module for matches of the probe point.
2082 q->handle_query_module();
bb788f9f 2083
b8da0ad1 2084 // If we know that there will be no more matches, abort early.
85007c04 2085 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2086 return DWARF_CB_ABORT;
2087 else
2088 return DWARF_CB_OK;
7a053d3b 2089 }
39bcd429 2090 catch (const semantic_error& e)
bd2b1e68 2091 {
39bcd429
FCE
2092 q->sess.print_error (e);
2093 return DWARF_CB_ABORT;
bd2b1e68 2094 }
bd2b1e68
GH
2095}
2096
35d4ab18 2097
84c84ac4 2098void
5d5bd369 2099base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2100{
2101 base_query *me = (base_query*)q;
5d5bd369 2102 me->query_library (data);
84c84ac4
SC
2103}
2104
2105
2106void
51d6bda3
SC
2107query_one_library (const char *library, dwflpp & dw,
2108 const string user_lib, probe * base_probe, probe_point *base_loc,
2109 vector<derived_probe *> & results)
84c84ac4 2110{
47e226ed 2111 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2112 {
05fb3e0c
WF
2113 string library_path = find_executable (library, "", dw.sess.sysenv,
2114 "LD_LIBRARY_PATH");
84c84ac4
SC
2115 probe_point* specific_loc = new probe_point(*base_loc);
2116 specific_loc->optional = true;
2117 vector<probe_point::component*> derived_comps;
2118
2119 vector<probe_point::component*>::iterator it;
2120 for (it = specific_loc->components.begin();
2121 it != specific_loc->components.end(); ++it)
2122 if ((*it)->functor == TOK_LIBRARY)
2123 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2124 new literal_string(library_path)));
2125 else
2126 derived_comps.push_back(*it);
2127 probe_point* derived_loc = new probe_point(*specific_loc);
2128 derived_loc->components = derived_comps;
2129 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
51d6bda3
SC
2130 derive_probes(dw.sess, new_base, results);
2131 if (dw.sess.verbose > 2)
84c84ac4
SC
2132 clog << _("module=") << library_path;
2133 }
2134}
2135
2136
51d6bda3
SC
2137void
2138dwarf_query::query_library (const char *library)
2139{
2140 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2141}
2142
576eaefe
SC
2143struct plt_expanding_visitor: public var_expanding_visitor
2144{
2145 plt_expanding_visitor(const string & entry):
2146 entry (entry)
2147 {
2148 }
2149 const string & entry;
2150
2151 void visit_target_symbol (target_symbol* e);
2152};
2153
2154
2155void
2156base_query::query_plt_callback (void *q, const char *entry, size_t address)
2157{
2158 base_query *me = (base_query*)q;
2159 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2160 me->query_plt (entry, address);
2161}
2162
2163
2164void
2165query_one_plt (const char *entry, long addr, dwflpp & dw,
2166 probe * base_probe, probe_point *base_loc,
2167 vector<derived_probe *> & results)
2168{
2169 probe_point* specific_loc = new probe_point(*base_loc);
2170 specific_loc->optional = true;
2171 vector<probe_point::component*> derived_comps;
2172
2173 if (dw.sess.verbose > 2)
2174 clog << _F("plt entry=%s\n", entry);
2175
2176 // query_module_symtab requires .plt to recognize that it can set the probe at
2177 // a plt entry so we convert process.plt to process.plt.statement
2178 vector<probe_point::component*>::iterator it;
2179 for (it = specific_loc->components.begin();
2180 it != specific_loc->components.end(); ++it)
2181 if ((*it)->functor == TOK_PLT)
3d372d6b
SC
2182 {
2183 derived_comps.push_back(*it);
2184 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
2185 new literal_number(addr)));
2186 }
576eaefe
SC
2187 else
2188 derived_comps.push_back(*it);
2189 probe_point* derived_loc = new probe_point(*specific_loc);
2190 derived_loc->components = derived_comps;
2191 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
2192 string e = string(entry);
2193 plt_expanding_visitor pltv (e);
2194 pltv.replace (new_base->body);
2195 derive_probes(dw.sess, new_base, results);
2196}
2197
2198
2199void
2200dwarf_query::query_plt (const char *entry, size_t address)
2201{
2202 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2203}
51d6bda3 2204
435f53a7
FCE
2205// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2206// but the needed declaration for module_cache is not available there.
2207// Nor for that matter in session.cxx. Only in this CU is that field ever
2208// set (in query_module() above), so we clean it up here too.
2209static void
2210delete_session_module_cache (systemtap_session& s)
2211{
2212 if (s.module_cache) {
2213 if (s.verbose > 3)
b530b5b3 2214 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2215 delete s.module_cache;
2216 s.module_cache = 0;
2217 }
2218}
2219
2220
de688825 2221struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2222{
77de5e9e 2223 dwarf_query & q;
bcc12710 2224 Dwarf_Die *scope_die;
77de5e9e 2225 Dwarf_Addr addr;
8c819921 2226 block *add_block;
2260f4e3 2227 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2228 // NB: tids are not always collected in add_block & add_call_probe, because
2229 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2230 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2231 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2232 unsigned saved_longs, saved_strings; // data saved within kretprobes
2233 map<std::string, expression *> return_ts_map;
729455a7 2234 vector<Dwarf_Die> scopes;
b95e2b79 2235 bool visited;
77de5e9e 2236
de688825 2237 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2238 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2239 add_block_tid(false), add_call_probe_tid(false),
af234c40 2240 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2241 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2242 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2243 void visit_target_symbol_saved_return (target_symbol* e);
2244 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2245 void visit_target_symbol (target_symbol* e);
c24447be 2246 void visit_cast_op (cast_op* e);
8cc799a5 2247 void visit_entry_op (entry_op* e);
729455a7 2248private:
bfa7e523 2249 vector<Dwarf_Die>& getcuscope(target_symbol *e);
729455a7 2250 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2251};
2252
2253
de688825 2254unsigned var_expanding_visitor::tick = 0;
77de5e9e 2255
a50de939 2256
74fe61bc 2257var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2258{
2259 // FIXME: for the time being, by default we only support plain '$foo
2260 // = bar', not '+=' or any other op= variant. This is fixable, but a
2261 // bit ugly.
2262 //
2263 // If derived classes desire to add additional operator support, add
2264 // new operators to this list in the derived class constructor.
2265 valid_ops.insert ("=");
2266}
2267
2268
87214add
JS
2269bool
2270var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2271 expression*& lvalue, expression*& rvalue)
77de5e9e 2272{
e57b735a
GH
2273 // Our job would normally be to require() the left and right sides
2274 // into a new assignment. What we're doing is slightly trickier:
2275 // we're pushing a functioncall** onto a stack, and if our left
2276 // child sets the functioncall* for that value, we're going to
2277 // assume our left child was a target symbol -- transformed into a
2278 // set_target_foo(value) call, and it wants to take our right child
2279 // as the argument "value".
2280 //
2281 // This is why some people claim that languages with
2282 // constructor-decomposing case expressions have a leg up on
2283 // visitors.
2284
2285 functioncall *fcall = NULL;
d9b516ca 2286
a50de939 2287 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2288 const string* old_op = op;
2289 op = &eop;
a50de939 2290
e57b735a 2291 target_symbol_setter_functioncalls.push (&fcall);
87214add 2292 replace (lvalue);
e57b735a 2293 target_symbol_setter_functioncalls.pop ();
87214add
JS
2294 replace (rvalue);
2295
2296 op = old_op;
e57b735a
GH
2297
2298 if (fcall != NULL)
77de5e9e 2299 {
e57b735a
GH
2300 // Our left child is informing us that it was a target variable
2301 // and it has been replaced with a set_target_foo() function
2302 // call; we are going to provide that function call -- with the
2303 // right child spliced in as sole argument -- in place of
de688825 2304 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2305
87214add 2306 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2307 {
2308 // Build up a list of supported operators.
2309 string ops;
2310 std::set<string>::iterator i;
b530b5b3 2311 int valid_ops_size = 0;
a50de939 2312 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2313 {
a50de939 2314 ops += " " + *i + ",";
b530b5b3
LB
2315 valid_ops_size++;
2316 }
a50de939
DS
2317 ops.resize(ops.size() - 1); // chop off the last ','
2318
2319 // Throw the error.
1e41115c
LB
2320 throw semantic_error (_F(ngettext("Only the following assign operator is implemented on target variables: %s",
2321 "Only the following assign operators are implemented on target variables: %s",
b530b5b3
LB
2322 valid_ops_size), ops.c_str()), tok);
2323
a50de939 2324 }
e57b735a 2325
87214add
JS
2326 assert (lvalue == fcall);
2327 if (rvalue)
2328 fcall->args.push_back (rvalue);
4ed05b15 2329 provide (fcall);
87214add 2330 return true;
77de5e9e 2331 }
e57b735a 2332 else
87214add
JS
2333 return false;
2334}
2335
2336
2337void
2338var_expanding_visitor::visit_assignment (assignment* e)
2339{
2340 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2341 provide (e);
2342}
2343
2344
2345void
2346var_expanding_visitor::visit_pre_crement (pre_crement* e)
2347{
2348 expression *dummy = NULL;
2349 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2350 provide (e);
2351}
2352
2353
2354void
2355var_expanding_visitor::visit_post_crement (post_crement* e)
2356{
2357 expression *dummy = NULL;
2358 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2359 provide (e);
2360}
2361
2362
2363void
2364var_expanding_visitor::visit_delete_statement (delete_statement* s)
2365{
2366 string fakeop = "delete";
2367 expression *dummy = NULL;
2368 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2369 provide (s);
e57b735a 2370}
d9b516ca 2371
d7f3e0c5 2372
30263a73
FCE
2373void
2374var_expanding_visitor::visit_defined_op (defined_op* e)
2375{
2376 bool resolved = true;
2377
2378 defined_ops.push (e);
2379 try {
2380 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2381 // defined with a target_symbol* operand, a subsidiary call may attempt to
2382 // rewrite it to a general expression* instead, and require<> happily
2383 // casts to/from void*, causing possible memory corruption. We use
2384 // expression* here, being the general case of rewritten $variable.
2385 expression *foo1 = e->operand;
2386 foo1 = require (foo1);
2387
c69a87e0 2388 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2389 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2390 // erroneous resolutions. Some would signal a visit_target_symbol failure
2391 // with an exception, with a set flag within the target_symbol, or nothing
2392 // at all.
30263a73 2393 //
c69a87e0
FCE
2394 // Now, failures always have to be signalled with a
2395 // saved_conversion_error being chained to the target_symbol.
2396 // Successes have to result in an attempted rewrite of the
850bfddd 2397 // target_symbol (via provide()).
780f11ff 2398 //
c69a87e0
FCE
2399 // Edna Mode: "no capes". fche: "no exceptions".
2400
30263a73
FCE
2401 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2402 //
2403 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2404 //
2405 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2406 // dwarf probe to take care of it.
2407 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2408 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2409 //
30263a73
FCE
2410 // utrace: success: rewrites to function; failure: semantic_error
2411 //
850bfddd 2412 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2413
2414 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2415 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2416 resolved = false;
a45664f4 2417 else if (foo2) // unresolved but not marked failing
b7aedf26 2418 {
780f11ff
JS
2419 // There are some visitors that won't touch certain target_symbols,
2420 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2421 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2422 e->operand = foo2;
2423 provide (e);
2424 return;
2425 }
30263a73
FCE
2426 else // resolved, rewritten to some other expression type
2427 resolved = true;
780f11ff 2428 } catch (const semantic_error& e) {
c69a87e0 2429 assert (0); // should not happen
30263a73
FCE
2430 }
2431 defined_ops.pop ();
2432
2433 literal_number* ln = new literal_number (resolved ? 1 : 0);
2434 ln->tok = e->tok;
2435 provide (ln);
2436}
2437
2438
5f36109e
JS
2439struct dwarf_pretty_print
2440{
2441 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2442 const string& local, bool userspace_p,
2443 const target_symbol& e):
d19a9a82
JS
2444 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2445 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2446 {
2447 init_ts (e);
2448 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2449 }
2450
2451 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2452 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2453 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2454 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2455 {
2456 init_ts (e);
2457 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2458 }
2459
2460 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2461 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2462 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2463 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2464 {
2465 init_ts (e);
2466 dw.type_die_for_pointer (type_die, ts, &base_type);
2467 }
2468
2469 functioncall* expand ();
ce83ff57 2470 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2471
2472private:
2473 dwflpp& dw;
2474 target_symbol* ts;
7d11d8c9 2475 bool print_full;
5f36109e
JS
2476 Dwarf_Die base_type;
2477
2478 string local;
2479 vector<Dwarf_Die> scopes;
2480 Dwarf_Addr pc;
2481
2482 expression* pointer;
2483 Dwarf_Die pointer_type;
2484
d19a9a82 2485 const bool userspace_p, deref_p;
5f36109e
JS
2486
2487 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2488 print_format* pf, bool top=false);
600551ca
JS
2489 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2490 print_format* pf);
5f36109e 2491 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2492 print_format* pf);
5f36109e 2493 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2494 print_format* pf, bool top);
5f36109e 2495 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2496 print_format* pf, bool top);
5f36109e 2497 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2498 print_format* pf, bool top);
5f36109e 2499 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2500 print_format* pf, int& count);
bbee5bb8 2501 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2502
2503 void init_ts (const target_symbol& e);
2504 expression* deref (target_symbol* e);
c55ea10d 2505 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2506};
2507
2508
2509void
2510dwarf_pretty_print::init_ts (const target_symbol& e)
2511{
2512 // Work with a new target_symbol so we can modify arguments
2513 ts = new target_symbol (e);
2514
2515 if (ts->addressof)
b530b5b3 2516 throw semantic_error(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2517
2518 if (ts->components.empty() ||
2519 ts->components.back().type != target_symbol::comp_pretty_print)
b530b5b3 2520 throw semantic_error(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2521 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2522 ts->components.pop_back();
2523}
2524
2525
2526functioncall*
2527dwarf_pretty_print::expand ()
2528{
2529 static unsigned tick = 0;
2530
2531 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2532 // try {
2533 // return sprintf("{.foo=...}", (ts)->foo, ...)
2534 // } catch {
2535 // return "ERROR"
2536 // }
5f36109e
JS
2537 // }
2538
2539 // Create the function decl and call.
2540
2541 functiondecl *fdecl = new functiondecl;
2542 fdecl->tok = ts->tok;
2543 fdecl->synthetic = true;
2544 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2545 fdecl->type = pe_string;
2546
2547 functioncall* fcall = new functioncall;
2548 fcall->tok = ts->tok;
2549 fcall->function = fdecl->name;
140be17a 2550 fcall->type = pe_string;
5f36109e
JS
2551
2552 // If there's a <pointer>, replace it with a new var and make that
2553 // the first function argument.
2554 if (pointer)
2555 {
2556 vardecl *v = new vardecl;
2557 v->type = pe_long;
2558 v->name = "pointer";
2559 v->tok = ts->tok;
2560 fdecl->formal_args.push_back (v);
2561 fcall->args.push_back (pointer);
2562
2563 symbol* sym = new symbol;
2564 sym->tok = ts->tok;
2565 sym->name = v->name;
5f36109e
JS
2566 pointer = sym;
2567 }
2568
2569 // For each expression argument, replace it with a function argument.
2570 for (unsigned i = 0; i < ts->components.size(); ++i)
2571 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2572 {
2573 vardecl *v = new vardecl;
2574 v->type = pe_long;
2575 v->name = "index" + lex_cast(i);
2576 v->tok = ts->tok;
2577 fdecl->formal_args.push_back (v);
2578 fcall->args.push_back (ts->components[i].expr_index);
2579
2580 symbol* sym = new symbol;
2581 sym->tok = ts->tok;
2582 sym->name = v->name;
5f36109e
JS
2583 ts->components[i].expr_index = sym;
2584 }
2585
2586 // Create the return sprintf.
2587 token* pf_tok = new token(*ts->tok);
2588 pf_tok->content = "sprintf";
2589 print_format* pf = print_format::create(pf_tok);
2590 return_statement* rs = new return_statement;
2591 rs->tok = ts->tok;
2592 rs->value = pf;
5f36109e
JS
2593
2594 // Recurse into the actual values.
7d11d8c9 2595 recurse (&base_type, ts, pf, true);
5f36109e
JS
2596 pf->components = print_format::string_to_components(pf->raw_components);
2597
7d11d8c9
JS
2598 // Create the try-catch net
2599 try_block* tb = new try_block;
2600 tb->tok = ts->tok;
2601 tb->try_block = rs;
2602 tb->catch_error_var = 0;
2603 return_statement* rs2 = new return_statement;
2604 rs2->tok = ts->tok;
2605 rs2->value = new literal_string ("ERROR");
2606 rs2->value->tok = ts->tok;
2607 tb->catch_block = rs2;
2608 fdecl->body = tb;
2609
f8809d54 2610 fdecl->join (dw.sess);
5f36109e
JS
2611 return fcall;
2612}
2613
2614
2615void
2616dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2617 print_format* pf, bool top)
5f36109e
JS
2618{
2619 Dwarf_Die type;
2620 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2621
2622 switch (dwarf_tag(&type))
2623 {
2624 default:
2625 // XXX need a warning?
2626 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2627 // + ") for " + dwarf_type_name(&type), e->tok);
2628 pf->raw_components.append("?");
2629 break;
2630
2631 case DW_TAG_enumeration_type:
2632 case DW_TAG_base_type:
7d11d8c9 2633 recurse_base (&type, e, pf);
5f36109e
JS
2634 break;
2635
2636 case DW_TAG_array_type:
7d11d8c9 2637 recurse_array (&type, e, pf, top);
5f36109e
JS
2638 break;
2639
2640 case DW_TAG_pointer_type:
2641 case DW_TAG_reference_type:
2642 case DW_TAG_rvalue_reference_type:
7d11d8c9 2643 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2644 break;
2645
2646 case DW_TAG_subroutine_type:
c55ea10d 2647 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2648 break;
2649
2650 case DW_TAG_union_type:
5f36109e
JS
2651 case DW_TAG_structure_type:
2652 case DW_TAG_class_type:
7d11d8c9 2653 recurse_struct (&type, e, pf, top);
5f36109e
JS
2654 break;
2655 }
2656}
2657
2658
600551ca
JS
2659// Bit fields are handled as a special-case combination of recurse() and
2660// recurse_base(), only called from recurse_struct_members(). The main
2661// difference is that the value is always printed numerically, even if the
2662// underlying type is a char.
2663void
2664dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2665 print_format* pf)
2666{
2667 Dwarf_Die type;
2668 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2669
2670 int tag = dwarf_tag(&type);
2671 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2672 {
2673 // XXX need a warning?
2674 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2675 // + ") for " + dwarf_type_name(&type), e->tok);
2676 pf->raw_components.append("?");
2677 return;
2678 }
2679
2680 Dwarf_Attribute attr;
2681 Dwarf_Word encoding = (Dwarf_Word) -1;
2682 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2683 &encoding);
2684 switch (encoding)
2685 {
2686 case DW_ATE_float:
2687 case DW_ATE_complex_float:
2688 // XXX need a warning?
2689 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2690 // + ") for " + dwarf_type_name(&type), e->tok);
2691 pf->raw_components.append("?");
2692 break;
2693
2694 case DW_ATE_unsigned:
2695 case DW_ATE_unsigned_char:
2696 push_deref (pf, "%u", e);
2697 break;
2698
2699 case DW_ATE_signed:
2700 case DW_ATE_signed_char:
2701 default:
2702 push_deref (pf, "%i", e);
2703 break;
2704 }
2705}
2706
2707
5f36109e
JS
2708void
2709dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2710 print_format* pf)
5f36109e
JS
2711{
2712 Dwarf_Attribute attr;
2713 Dwarf_Word encoding = (Dwarf_Word) -1;
2714 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2715 &encoding);
5f36109e
JS
2716 switch (encoding)
2717 {
2718 case DW_ATE_float:
2719 case DW_ATE_complex_float:
2720 // XXX need a warning?
2721 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2722 // + ") for " + dwarf_type_name(type), e->tok);
2723 pf->raw_components.append("?");
5f36109e
JS
2724 break;
2725
6561d8d1 2726 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2727 case DW_ATE_signed_char:
2728 case DW_ATE_unsigned_char:
941101c1
JS
2729 // Use escapes to make sure that non-printable characters
2730 // don't interrupt our stream (especially '\0' values).
2731 push_deref (pf, "'%#c'", e);
5f36109e
JS
2732 break;
2733
2734 case DW_ATE_unsigned:
c55ea10d 2735 push_deref (pf, "%u", e);
5f36109e
JS
2736 break;
2737
600551ca 2738 case DW_ATE_signed:
5f36109e 2739 default:
c55ea10d 2740 push_deref (pf, "%i", e);
5f36109e
JS
2741 break;
2742 }
5f36109e
JS
2743}
2744
2745
2746void
2747dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2748 print_format* pf, bool top)
5f36109e 2749{
7d11d8c9
JS
2750 if (!top && !print_full)
2751 {
2752 pf->raw_components.append("[...]");
2753 return;
2754 }
2755
5f36109e
JS
2756 Dwarf_Die childtype;
2757 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2758
2759 if (print_chars (&childtype, e, pf))
2760 return;
2761
5f36109e
JS
2762 pf->raw_components.append("[");
2763
2764 // We print the array up to the first 5 elements.
2765 // XXX how can we determine the array size?
2766 // ... for now, just print the first element
64cddf39 2767 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2768 unsigned i, size = 1;
64cddf39 2769 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2770 {
2771 if (i > 0)
2772 pf->raw_components.append(", ");
2773 target_symbol* e2 = new target_symbol(*e);
2774 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2775 recurse (&childtype, e2, pf);
5f36109e
JS
2776 }
2777 if (i < size || 1/*XXX until real size is known */)
2778 pf->raw_components.append(", ...");
2779 pf->raw_components.append("]");
2780}
2781
2782
2783void
2784dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2785 print_format* pf, bool top)
5f36109e 2786{
7d11d8c9 2787 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2788 bool void_p = true;
7d11d8c9 2789 Dwarf_Die pointee;
bbee5bb8 2790 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2791 {
2792 try
2793 {
2794 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2795 void_p = false;
2796 }
2797 catch (const semantic_error&) {}
2798 }
2799
2800 if (!void_p)
5f36109e 2801 {
bbee5bb8
JS
2802 if (print_chars (&pointee, e, pf))
2803 return;
2804
2805 if (top)
2806 {
2807 recurse (&pointee, e, pf, top);
2808 return;
2809 }
5f36109e 2810 }
bbee5bb8 2811
c55ea10d 2812 push_deref (pf, "%p", e);
5f36109e
JS
2813}
2814
2815
2816void
2817dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2818 print_format* pf, bool top)
5f36109e 2819{
bdec0e18
JS
2820 if (dwarf_hasattr(type, DW_AT_declaration))
2821 {
a44a7cb5 2822 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2823 if (!resolved)
2824 {
2825 // could be an error, but for now just stub it
2826 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2827 pf->raw_components.append("{...}");
2828 return;
2829 }
2830 type = resolved;
2831 }
2832
5f36109e
JS
2833 int count = 0;
2834 pf->raw_components.append("{");
7d11d8c9
JS
2835 if (top || print_full)
2836 recurse_struct_members (type, e, pf, count);
2837 else
2838 pf->raw_components.append("...");
5f36109e
JS
2839 pf->raw_components.append("}");
2840}
2841
2842
2843void
2844dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2845 print_format* pf, int& count)
5f36109e 2846{
a80f28d8
JS
2847 /* With inheritance, a subclass may mask member names of parent classes, so
2848 * our search among the inheritance tree must be breadth-first rather than
2849 * depth-first (recursive). The type die is still our starting point. When
2850 * we encounter a masked name, just skip it. */
2851 set<string> dupes;
2852 deque<Dwarf_Die> inheritees(1, *type);
2853 for (; !inheritees.empty(); inheritees.pop_front())
2854 {
dee830d9 2855 Dwarf_Die child, childtype, import;
a80f28d8
JS
2856 if (dwarf_child (&inheritees.front(), &child) == 0)
2857 do
2858 {
2859 target_symbol* e2 = e;
5f36109e 2860
a80f28d8
JS
2861 // skip static members
2862 if (dwarf_hasattr(&child, DW_AT_declaration))
2863 continue;
5f36109e 2864
a80f28d8 2865 int tag = dwarf_tag (&child);
5f36109e 2866
dee830d9
MW
2867 /* Pretend imported units contain members by recursing into
2868 struct_member printing with the same count. */
2869 if (tag == DW_TAG_imported_unit
2870 && dwarf_attr_die (&child, DW_AT_import, &import))
2871 recurse_struct_members (&import, e2, pf, count);
2872
a80f28d8
JS
2873 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2874 continue;
5f36109e 2875
a80f28d8 2876 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2877
a80f28d8
JS
2878 if (tag == DW_TAG_inheritance)
2879 {
2880 inheritees.push_back(childtype);
2881 continue;
2882 }
5f36109e 2883
a80f28d8
JS
2884 int childtag = dwarf_tag (&childtype);
2885 const char *member = dwarf_diename (&child);
3a147004 2886
a80f28d8
JS
2887 // "_vptr.foo" members are C++ virtual function tables,
2888 // which (generally?) aren't interesting for users.
2889 if (member && startswith(member, "_vptr."))
2890 continue;
3a147004 2891
a80f28d8
JS
2892 // skip inheritance-masked duplicates
2893 if (member && !dupes.insert(member).second)
2894 continue;
64cddf39 2895
a80f28d8
JS
2896 if (++count > 1)
2897 pf->raw_components.append(", ");
64cddf39 2898
a80f28d8
JS
2899 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2900 if (pf->args.size() >= 32)
2901 {
2902 pf->raw_components.append("...");
2903 break;
2904 }
2905
2906 if (member)
2907 {
2908 pf->raw_components.append(".");
2909 pf->raw_components.append(member);
5f36109e 2910
a80f28d8
JS
2911 e2 = new target_symbol(*e);
2912 e2->components.push_back (target_symbol::component(e->tok, member));
2913 }
2914 else if (childtag == DW_TAG_union_type)
2915 pf->raw_components.append("<union>");
2916 else if (childtag == DW_TAG_structure_type)
2917 pf->raw_components.append("<class>");
2918 else if (childtag == DW_TAG_class_type)
2919 pf->raw_components.append("<struct>");
2920 pf->raw_components.append("=");
600551ca
JS
2921
2922 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
2923 recurse_bitfield (&childtype, e2, pf);
2924 else
2925 recurse (&childtype, e2, pf);
5f36109e 2926 }
a80f28d8
JS
2927 while (dwarf_siblingof (&child, &child) == 0);
2928 }
5f36109e
JS
2929}
2930
2931
bbee5bb8
JS
2932bool
2933dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2934 print_format* pf)
2935{
2936 Dwarf_Die type;
2937 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
2938
2939 Dwarf_Attribute attr;
2940 Dwarf_Word encoding = (Dwarf_Word) -1;
2941 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2942 &encoding);
2943 switch (encoding)
bbee5bb8 2944 {
6561d8d1
JS
2945 case DW_ATE_UTF:
2946 case DW_ATE_signed_char:
2947 case DW_ATE_unsigned_char:
2948 break;
2949 default:
2950 return false;
2951 }
2952
2953 string function = userspace_p ? "user_string2" : "kernel_string2";
2954 Dwarf_Word size = (Dwarf_Word) -1;
2955 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
2956 switch (size)
2957 {
2958 case 1:
2959 break;
2960 case 2:
2961 function += "_utf16";
2962 break;
2963 case 4:
2964 function += "_utf32";
2965 break;
2966 default:
2967 return false;
2968 }
2969
2970 if (push_deref (pf, "\"%s\"", e))
2971 {
2972 // steal the last arg for a string access
2973 assert (!pf->args.empty());
2974 functioncall* fcall = new functioncall;
2975 fcall->tok = e->tok;
2976 fcall->function = function;
2977 fcall->args.push_back (pf->args.back());
2978 expression *err_msg = new literal_string ("<unknown>");
2979 err_msg->tok = e->tok;
2980 fcall->args.push_back (err_msg);
2981 pf->args.back() = fcall;
bbee5bb8 2982 }
6561d8d1 2983 return true;
bbee5bb8
JS
2984}
2985
a5ce5211
MW
2986// PR10601: adapt to kernel-vs-userspace loc2c-runtime
2987static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
2988 + "#define fetch_register k_fetch_register\n"
2989 + "#define store_register k_store_register\n"
2990 + "#define deref kderef\n"
2991 + "#define store_deref store_kderef\n";
a5ce5211
MW
2992
2993static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
2994 + "#define fetch_register u_fetch_register\n"
2995 + "#define store_register u_store_register\n"
2996 + "#define deref uderef\n"
2997 + "#define store_deref store_uderef\n";
a5ce5211
MW
2998
2999#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3000 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3001
3002static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3003 + "#undef fetch_register\n"
3004 + "#undef store_register\n"
3005 + "#undef deref\n"
3006 + "#undef store_deref\n";
bbee5bb8 3007
5f36109e
JS
3008expression*
3009dwarf_pretty_print::deref (target_symbol* e)
3010{
3011 static unsigned tick = 0;
3012
d19a9a82
JS
3013 if (!deref_p)
3014 {
3015 assert (pointer && e->components.empty());
3016 return pointer;
3017 }
3018
5f36109e
JS
3019 // Synthesize a function to dereference the dwarf fields,
3020 // with a pointer parameter that is the base tracepoint variable
3021 functiondecl *fdecl = new functiondecl;
3022 fdecl->synthetic = true;
3023 fdecl->tok = e->tok;
3024 embeddedcode *ec = new embeddedcode;
3025 ec->tok = e->tok;
3026
3027 fdecl->name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3028 fdecl->body = ec;
3029
3030 // Synthesize a functioncall.
3031 functioncall* fcall = new functioncall;
3032 fcall->tok = e->tok;
3033 fcall->function = fdecl->name;
5f36109e 3034
a5ce5211 3035 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
5f36109e
JS
3036
3037 if (pointer)
3038 {
3039 ec->code += dw.literal_stmt_for_pointer (&pointer_type, e,
3040 false, fdecl->type);
3041
3042 vardecl *v = new vardecl;
3043 v->type = pe_long;
3044 v->name = "pointer";
3045 v->tok = e->tok;
3046 fdecl->formal_args.push_back(v);
3047 fcall->args.push_back(pointer);
3048 }
3049 else if (!local.empty())
3050 ec->code += dw.literal_stmt_for_local (scopes, pc, local, e,
3051 false, fdecl->type);
3052 else
3053 ec->code += dw.literal_stmt_for_return (&scopes[0], pc, e,
3054 false, fdecl->type);
3055
3056 // Any non-literal indexes need to be passed in too.
3057 for (unsigned i = 0; i < e->components.size(); ++i)
3058 if (e->components[i].type == target_symbol::comp_expression_array_index)
3059 {
3060 vardecl *v = new vardecl;
3061 v->type = pe_long;
3062 v->name = "index" + lex_cast(i);
3063 v->tok = e->tok;
3064 fdecl->formal_args.push_back(v);
3065 fcall->args.push_back(e->components[i].expr_index);
3066 }
3067
3068 ec->code += "/* pure */";
3069 ec->code += "/* unprivileged */";
3070
a5ce5211 3071 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e 3072
f8809d54 3073 fdecl->join (dw.sess);
5f36109e
JS
3074 return fcall;
3075}
3076
3077
c55ea10d
JS
3078bool
3079dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3080 target_symbol* e)
3081{
3082 expression* e2 = NULL;
3083 try
3084 {
3085 e2 = deref (e);
3086 }
3087 catch (const semantic_error&)
3088 {
3089 pf->raw_components.append ("?");
3090 return false;
3091 }
3092 pf->raw_components.append (fmt);
3093 pf->args.push_back (e2);
3094 return true;
3095}
3096
3097
e57b735a 3098void
a7999c82 3099dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3100{
a7999c82
JS
3101 // Get the full name of the target symbol.
3102 stringstream ts_name_stream;
3103 e->print(ts_name_stream);
3104 string ts_name = ts_name_stream.str();
3105
3106 // Check and make sure we haven't already seen this target
3107 // variable in this return probe. If we have, just return our
3108 // last replacement.
af234c40 3109 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3110 if (i != return_ts_map.end())
85ecf79a 3111 {
a7999c82
JS
3112 provide (i->second);
3113 return;
3114 }
85ecf79a 3115
70208613
JS
3116 // Attempt the expansion directly first, so if there's a problem with the
3117 // variable we won't have a bogus entry probe lying around. Like in
3118 // saveargs(), we pretend for a moment that we're not in a .return.
3119 bool saved_has_return = q.has_return;
3120 q.has_return = false;
3121 expression *repl = e;
3122 replace (repl);
3123 q.has_return = saved_has_return;
3124 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3125 if (n && n->saved_conversion_error)
3126 {
3127 provide (repl);
3128 return;
3129 }
3130
af234c40
JS
3131 expression *exp;
3132 if (!q.has_process &&
3133 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3134 exp = gen_kretprobe_saved_return(repl);
af234c40 3135 else
cc9001af 3136 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3137
3138 // Provide the variable to our parent so it can be used as a
3139 // substitute for the target symbol.
3140 provide (exp);
3141
3142 // Remember this replacement since we might be able to reuse
3143 // it later if the same return probe references this target
3144 // symbol again.
3145 return_ts_map[ts_name] = exp;
3146}
3147
4a2970a3 3148static expression*
23dc94f6
DS
3149gen_mapped_saved_return(systemtap_session &sess, expression* e,
3150 const string& name,
3151 block *& add_block, bool& add_block_tid,
3152 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3153{
23dc94f6
DS
3154 static unsigned tick = 0;
3155
a7999c82
JS
3156 // We've got to do several things here to handle target
3157 // variables in return probes.
85ecf79a 3158
a7999c82
JS
3159 // (1) Synthesize two global arrays. One is the cache of the
3160 // target variable and the other contains a thread specific
3161 // nesting level counter. The arrays will look like
3162 // this:
3163 //
23dc94f6
DS
3164 // _entry_tvar_{name}_{num}
3165 // _entry_tvar_{name}_{num}_ctr
a7999c82 3166
23dc94f6 3167 string aname = (string("_entry_tvar_")
cc9001af 3168 + name
aca66a36 3169 + "_" + lex_cast(tick++));
a7999c82
JS
3170 vardecl* vd = new vardecl;
3171 vd->name = aname;
3172 vd->tok = e->tok;
23dc94f6 3173 sess.globals.push_back (vd);
a7999c82
JS
3174
3175 string ctrname = aname + "_ctr";
3176 vd = new vardecl;
3177 vd->name = ctrname;
3178 vd->tok = e->tok;
23dc94f6 3179 sess.globals.push_back (vd);
a7999c82
JS
3180
3181 // (2) Create a new code block we're going to insert at the
3182 // beginning of this probe to get the cached value into a
3183 // temporary variable. We'll replace the target variable
3184 // reference with the temporary variable reference. The code
3185 // will look like this:
3186 //
23dc94f6
DS
3187 // _entry_tvar_tid = tid()
3188 // _entry_tvar_{name}_{num}_tmp
3189 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3190 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3191 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3192 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3193 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3194 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3195
3196 // (2a) Synthesize the tid temporary expression, which will look
3197 // like this:
3198 //
23dc94f6 3199 // _entry_tvar_tid = tid()
a7999c82 3200 symbol* tidsym = new symbol;
23dc94f6 3201 tidsym->name = string("_entry_tvar_tid");
a7999c82 3202 tidsym->tok = e->tok;
85ecf79a 3203
a7999c82
JS
3204 if (add_block == NULL)
3205 {
3206 add_block = new block;
3207 add_block->tok = e->tok;
8cc799a5 3208 }
8c819921 3209
8cc799a5
JS
3210 if (!add_block_tid)
3211 {
a7999c82
JS
3212 // Synthesize a functioncall to grab the thread id.
3213 functioncall* fc = new functioncall;
3214 fc->tok = e->tok;
3215 fc->function = string("tid");
8c819921 3216
23dc94f6 3217 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3218 assignment* a = new assignment;
3219 a->tok = e->tok;
3220 a->op = "=";
a7999c82
JS
3221 a->left = tidsym;
3222 a->right = fc;
8c819921
DS
3223
3224 expr_statement* es = new expr_statement;
3225 es->tok = e->tok;
3226 es->value = a;
8c819921 3227 add_block->statements.push_back (es);
8cc799a5 3228 add_block_tid = true;
a7999c82 3229 }
8c819921 3230
a7999c82
JS
3231 // (2b) Synthesize an array reference and assign it to a
3232 // temporary variable (that we'll use as replacement for the
3233 // target variable reference). It will look like this:
3234 //
23dc94f6
DS
3235 // _entry_tvar_{name}_{num}_tmp
3236 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3237 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3238
3239 arrayindex* ai_tvar_base = new arrayindex;
3240 ai_tvar_base->tok = e->tok;
3241
3242 symbol* sym = new symbol;
3243 sym->name = aname;
3244 sym->tok = e->tok;
3245 ai_tvar_base->base = sym;
3246
3247 ai_tvar_base->indexes.push_back(tidsym);
3248
3249 // We need to create a copy of the array index in its current
3250 // state so we can have 2 variants of it (the original and one
3251 // that post-decrements the second index).
3252 arrayindex* ai_tvar = new arrayindex;
3253 arrayindex* ai_tvar_postdec = new arrayindex;
3254 *ai_tvar = *ai_tvar_base;
3255 *ai_tvar_postdec = *ai_tvar_base;
3256
3257 // Synthesize the
23dc94f6 3258 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3259 // second index into the array.
3260 arrayindex* ai_ctr = new arrayindex;
3261 ai_ctr->tok = e->tok;
3262
3263 sym = new symbol;
3264 sym->name = ctrname;
3265 sym->tok = e->tok;
3266 ai_ctr->base = sym;
3267 ai_ctr->indexes.push_back(tidsym);
3268 ai_tvar->indexes.push_back(ai_ctr);
3269
3270 symbol* tmpsym = new symbol;
3271 tmpsym->name = aname + "_tmp";
3272 tmpsym->tok = e->tok;
3273
3274 assignment* a = new assignment;
3275 a->tok = e->tok;
3276 a->op = "=";
3277 a->left = tmpsym;
3278 a->right = ai_tvar;
3279
3280 expr_statement* es = new expr_statement;
3281 es->tok = e->tok;
3282 es->value = a;
3283
3284 add_block->statements.push_back (es);
3285
3286 // (2c) Add a post-decrement to the second array index and
3287 // delete the array value. It will look like this:
3288 //
23dc94f6
DS
3289 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3290 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3291
3292 post_crement* pc = new post_crement;
3293 pc->tok = e->tok;
3294 pc->op = "--";
3295 pc->operand = ai_ctr;
3296 ai_tvar_postdec->indexes.push_back(pc);
3297
3298 delete_statement* ds = new delete_statement;
3299 ds->tok = e->tok;
3300 ds->value = ai_tvar_postdec;
3301
3302 add_block->statements.push_back (ds);
3303
3304 // (2d) Delete the counter value if it is 0. It will look like
3305 // this:
23dc94f6
DS
3306 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3307 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3308
3309 ds = new delete_statement;
3310 ds->tok = e->tok;
3311 ds->value = ai_ctr;
3312
3313 unary_expression *ue = new unary_expression;
3314 ue->tok = e->tok;
3315 ue->op = "!";
3316 ue->operand = ai_ctr;
3317
3318 if_statement *ifs = new if_statement;
3319 ifs->tok = e->tok;
3320 ifs->condition = ue;
3321 ifs->thenblock = ds;
3322 ifs->elseblock = NULL;
3323
3324 add_block->statements.push_back (ifs);
3325
3326 // (3) We need an entry probe that saves the value for us in the
3327 // global array we created. Create the entry probe, which will
3328 // look like this:
3329 //
2260f4e3 3330 // probe kernel.function("{function}").call {
23dc94f6
DS
3331 // _entry_tvar_tid = tid()
3332 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3333 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3334 // = ${param}
3335 // }
3336
2260f4e3 3337 if (add_call_probe == NULL)
a7999c82 3338 {
2260f4e3
FCE
3339 add_call_probe = new block;
3340 add_call_probe->tok = e->tok;
8cc799a5 3341 }
4baf0e53 3342
8cc799a5
JS
3343 if (!add_call_probe_tid)
3344 {
a7999c82
JS
3345 // Synthesize a functioncall to grab the thread id.
3346 functioncall* fc = new functioncall;
3347 fc->tok = e->tok;
3348 fc->function = string("tid");
4baf0e53 3349
23dc94f6 3350 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3351 assignment* a = new assignment;
8fc05e57
DS
3352 a->tok = e->tok;
3353 a->op = "=";
a7999c82
JS
3354 a->left = tidsym;
3355 a->right = fc;
8fc05e57 3356
a7999c82 3357 expr_statement* es = new expr_statement;
8fc05e57
DS
3358 es->tok = e->tok;
3359 es->value = a;
2260f4e3 3360 add_call_probe = new block(add_call_probe, es);
8cc799a5 3361 add_call_probe_tid = true;
85ecf79a 3362 }
cf2a1f85 3363
a7999c82 3364 // Save the value, like this:
23dc94f6
DS
3365 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3366 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3367 // = ${param}
3368 arrayindex* ai_tvar_preinc = new arrayindex;
3369 *ai_tvar_preinc = *ai_tvar_base;
3370
3371 pre_crement* preinc = new pre_crement;
3372 preinc->tok = e->tok;
3373 preinc->op = "++";
3374 preinc->operand = ai_ctr;
3375 ai_tvar_preinc->indexes.push_back(preinc);
3376
3377 a = new assignment;
3378 a->tok = e->tok;
3379 a->op = "=";
3380 a->left = ai_tvar_preinc;
3381 a->right = e;
3382
3383 es = new expr_statement;
3384 es->tok = e->tok;
3385 es->value = a;
3386
2260f4e3 3387 add_call_probe = new block(add_call_probe, es);
a7999c82 3388
23dc94f6 3389 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3390 // our parent so it can be used as a substitute for the target
3391 // symbol.
3f803f9e 3392 delete ai_tvar_base;
af234c40
JS
3393 return tmpsym;
3394}
a7999c82 3395
af234c40 3396
23dc94f6
DS
3397expression*
3398dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3399 const string& name)
3400{
3401 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3402 add_block_tid, add_call_probe,
3403 add_call_probe_tid);
3404}
3405
3406
af234c40 3407expression*
140be17a 3408dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3409{
3410 // The code for this is simple.
3411 //
3412 // .call:
3413 // _set_kretprobe_long(index, $value)
3414 //
3415 // .return:
3416 // _get_kretprobe_long(index)
3417 //
3418 // (or s/long/string/ for things like $$parms)
3419
3420 unsigned index;
3421 string setfn, getfn;
3422
140be17a
JS
3423 // We need the caller to predetermine the type of the expression!
3424 switch (e->type)
af234c40 3425 {
140be17a 3426 case pe_string:
af234c40
JS
3427 index = saved_strings++;
3428 setfn = "_set_kretprobe_string";
3429 getfn = "_get_kretprobe_string";
140be17a
JS
3430 break;
3431 case pe_long:
af234c40
JS
3432 index = saved_longs++;
3433 setfn = "_set_kretprobe_long";
3434 getfn = "_get_kretprobe_long";
140be17a
JS
3435 break;
3436 default:
b530b5b3 3437 throw semantic_error(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3438 }
3439
3440 // Create the entry code
3441 // _set_kretprobe_{long|string}(index, $value)
3442
3443 if (add_call_probe == NULL)
3444 {
3445 add_call_probe = new block;
3446 add_call_probe->tok = e->tok;
3447 }
3448
3449 functioncall* set_fc = new functioncall;
3450 set_fc->tok = e->tok;
3451 set_fc->function = setfn;
3452 set_fc->args.push_back(new literal_number(index));
3453 set_fc->args.back()->tok = e->tok;
3454 set_fc->args.push_back(e);
3455
3456 expr_statement* set_es = new expr_statement;
3457 set_es->tok = e->tok;
3458 set_es->value = set_fc;
3459
3460 add_call_probe->statements.push_back(set_es);
3461
3462 // Create the return code
3463 // _get_kretprobe_{long|string}(index)
3464
3465 functioncall* get_fc = new functioncall;
3466 get_fc->tok = e->tok;
3467 get_fc->function = getfn;
3468 get_fc->args.push_back(new literal_number(index));
3469 get_fc->args.back()->tok = e->tok;
3470
3471 return get_fc;
a7999c82 3472}
a43ba433 3473
2cb3fe26 3474
a7999c82
JS
3475void
3476dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3477{
9aa8ffce 3478 if (null_die(scope_die))
a7999c82 3479 return;
2cb3fe26 3480
5f36109e
JS
3481 target_symbol *tsym = new target_symbol(*e);
3482
fde50242
JS
3483 bool pretty = (!e->components.empty() &&
3484 e->components[0].type == target_symbol::comp_pretty_print);
3485 string format = pretty ? "=%s" : "=%#x";
a43ba433 3486
a7999c82
JS
3487 // Convert $$parms to sprintf of a list of parms and active local vars
3488 // which we recursively evaluate
a43ba433 3489
a7999c82
JS
3490 // NB: we synthesize a new token here rather than reusing
3491 // e->tok, because print_format::print likes to use
3492 // its tok->content.
5f36109e 3493 token* pf_tok = new token(*e->tok);
a7999c82 3494 pf_tok->type = tok_identifier;
b393f6f2 3495 pf_tok->content = "sprintf";
2cb3fe26 3496
d5e178c1 3497 print_format* pf = print_format::create(pf_tok);
a7999c82 3498
277c21bc 3499 if (q.has_return && (e->name == "$$return"))
a7999c82 3500 {
277c21bc 3501 tsym->name = "$return";
a7999c82
JS
3502
3503 // Ignore any variable that isn't accessible.
3504 tsym->saved_conversion_error = 0;
3505 expression *texp = tsym;
8b095b45 3506 replace (texp); // NB: throws nothing ...
a7999c82 3507 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3508 {
2cb3fe26 3509
a43ba433
FCE
3510 }
3511 else
3512 {
a7999c82 3513 pf->raw_components += "return";
5f36109e 3514 pf->raw_components += format;
a7999c82
JS
3515 pf->args.push_back(texp);
3516 }
3517 }
3518 else
3519 {
3520 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3521 bool first = true;
a7999c82 3522 Dwarf_Die result;
d48bc7eb
JS
3523 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3524 for (unsigned i = 0; i < scopes.size(); ++i)
3525 {
3526 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3527 break; // we don't want file-level variables
3528 if (dwarf_child (&scopes[i], &result) == 0)
3529 do
00cf3709 3530 {
d48bc7eb
JS
3531 switch (dwarf_tag (&result))
3532 {
3533 case DW_TAG_variable:
3534 if (e->name == "$$parms")
3535 continue;
3536 break;
3537 case DW_TAG_formal_parameter:
3538 if (e->name == "$$locals")
3539 continue;
3540 break;
3541
3542 default:
3543 continue;
3544 }
41c262f3 3545
d48bc7eb
JS
3546 const char *diename = dwarf_diename (&result);
3547 if (! diename) continue;
f76427a2 3548
d48bc7eb
JS
3549 if (! first)
3550 pf->raw_components += " ";
3551 pf->raw_components += diename;
fde50242
JS
3552 first = false;
3553
3554 // Write a placeholder for ugly aggregates
3555 Dwarf_Die type;
3556 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3557 {
3558 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3559 switch (dwarf_tag(&type))
3560 {
3561 case DW_TAG_union_type:
3562 case DW_TAG_structure_type:
3563 case DW_TAG_class_type:
3564 pf->raw_components += "={...}";
3565 continue;
3566
3567 case DW_TAG_array_type:
3568 pf->raw_components += "=[...]";
3569 continue;
3570 }
3571 }
345bbb3d 3572
d48bc7eb
JS
3573 tsym->name = "$";
3574 tsym->name += diename;
41c262f3 3575
d48bc7eb
JS
3576 // Ignore any variable that isn't accessible.
3577 tsym->saved_conversion_error = 0;
3578 expression *texp = tsym;
3579 replace (texp); // NB: throws nothing ...
3580 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3581 {
d48bc7eb
JS
3582 if (q.sess.verbose>2)
3583 {
e26c2f83 3584 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb
JS
3585 c != 0;
3586 c = c->chain) {
4c5d9906 3587 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3588 }
3589 }
3590
3591 pf->raw_components += "=?";
a43ba433 3592 }
d48bc7eb
JS
3593 else
3594 {
3595 pf->raw_components += format;
3596 pf->args.push_back(texp);
3597 }
a7999c82 3598 }
d48bc7eb
JS
3599 while (dwarf_siblingof (&result, &result) == 0);
3600 }
a7999c82 3601 }
2cb3fe26 3602
a7999c82 3603 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3604 pf->type = pe_string;
a7999c82
JS
3605 provide (pf);
3606}
3607
2cb3fe26 3608
a7999c82
JS
3609void
3610dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3611{
cc9001af
MW
3612 assert(e->name.size() > 0
3613 && ((e->name[0] == '$' && e->target_name == "")
3614 || (e->name == "@var" && e->target_name != "")));
a7999c82 3615 visited = true;
30263a73
FCE
3616 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3617 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3618
70208613 3619 try
a7999c82 3620 {
c69a87e0
FCE
3621 bool lvalue = is_active_lvalue(e);
3622 if (lvalue && !q.sess.guru_mode)
b3741c9d 3623 throw semantic_error(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3624
100a540e 3625 // XXX: process $context vars should be writable
70208613 3626
c69a87e0
FCE
3627 // See if we need to generate a new probe to save/access function
3628 // parameters from a return probe. PR 1382.
3629 if (q.has_return
3630 && !defined_being_checked
277c21bc
JS
3631 && e->name != "$return" // not the special return-value variable handled below
3632 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3633 {
3634 if (lvalue)
b530b5b3 3635 throw semantic_error(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3636 visit_target_symbol_saved_return(e);
3637 return;
3638 }
e57b735a 3639
277c21bc
JS
3640 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3641 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3642 {
3643 if (lvalue)
b530b5b3 3644 throw semantic_error(_("cannot write to context variable"), e->tok);
70208613 3645
c69a87e0 3646 if (e->addressof)
b530b5b3 3647 throw semantic_error(_("cannot take address of context variable"), e->tok);
70208613 3648
5f36109e
JS
3649 e->assert_no_components("dwarf", true);
3650
c69a87e0
FCE
3651 visit_target_symbol_context(e);
3652 return;
3653 }
70208613 3654
5f36109e
JS
3655 if (!e->components.empty() &&
3656 e->components.back().type == target_symbol::comp_pretty_print)
3657 {
3658 if (lvalue)
b530b5b3 3659 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3660
277c21bc 3661 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3662 {
3663 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3664 q.has_process, *e);
3665 dpp.expand()->visit(this);
3666 }
3667 else
3668 {
3669 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3670 e->sym_name(),
5f36109e
JS
3671 q.has_process, *e);
3672 dpp.expand()->visit(this);
3673 }
3674 return;
3675 }
3676
c69a87e0
FCE
3677 // Synthesize a function.
3678 functiondecl *fdecl = new functiondecl;
59de45f1 3679 fdecl->synthetic = true;
c69a87e0
FCE
3680 fdecl->tok = e->tok;
3681 embeddedcode *ec = new embeddedcode;
3682 ec->tok = e->tok;
70208613 3683
c69a87e0 3684 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3685 + "_" + e->sym_name()
c69a87e0 3686 + "_" + lex_cast(tick++));
70208613 3687
a5ce5211 3688 ec->code += EMBEDDED_FETCH_DEREF(q.has_process);
70208613 3689
277c21bc 3690 if (q.has_return && (e->name == "$return"))
e19fda4e 3691 {
b5a0dd41 3692 ec->code += q.dw.literal_stmt_for_return (scope_die,
e19fda4e 3693 addr,
b4c34c26 3694 e,
e19fda4e
DS
3695 lvalue,
3696 fdecl->type);
3697 }
3698 else
3699 {
b5a0dd41 3700 ec->code += q.dw.literal_stmt_for_local (getscopes(e),
e19fda4e 3701 addr,
cc9001af 3702 e->sym_name(),
b4c34c26 3703 e,
e19fda4e
DS
3704 lvalue,
3705 fdecl->type);
3706 }
3707
1b07c728
FCE
3708 if (! lvalue)
3709 ec->code += "/* pure */";
64211010
DB
3710
3711 ec->code += "/* unprivileged */";
a5ce5211 3712 ec->code += EMBEDDED_FETCH_DEREF_DONE;
c69a87e0
FCE
3713
3714 fdecl->name = fname;
3715 fdecl->body = ec;
70208613 3716
c69a87e0
FCE
3717 // Any non-literal indexes need to be passed in too.
3718 for (unsigned i = 0; i < e->components.size(); ++i)
3719 if (e->components[i].type == target_symbol::comp_expression_array_index)
3720 {
3721 vardecl *v = new vardecl;
3722 v->type = pe_long;
3723 v->name = "index" + lex_cast(i);
3724 v->tok = e->tok;
3725 fdecl->formal_args.push_back(v);
3726 }
70208613 3727
c69a87e0
FCE
3728 if (lvalue)
3729 {
3730 // Modify the fdecl so it carries a single pe_long formal
3731 // argument called "value".
70208613 3732
c69a87e0
FCE
3733 // FIXME: For the time being we only support setting target
3734 // variables which have base types; these are 'pe_long' in
3735 // stap's type vocabulary. Strings and pointers might be
3736 // reasonable, some day, but not today.
70208613 3737
c69a87e0
FCE
3738 vardecl *v = new vardecl;
3739 v->type = pe_long;
3740 v->name = "value";
3741 v->tok = e->tok;
3742 fdecl->formal_args.push_back(v);
3743 }
f8809d54 3744 fdecl->join (q.sess);
70208613 3745
c69a87e0
FCE
3746 // Synthesize a functioncall.
3747 functioncall* n = new functioncall;
3748 n->tok = e->tok;
3749 n->function = fname;
140be17a 3750 n->type = fdecl->type;
70208613 3751
c69a87e0
FCE
3752 // Any non-literal indexes need to be passed in too.
3753 for (unsigned i = 0; i < e->components.size(); ++i)
3754 if (e->components[i].type == target_symbol::comp_expression_array_index)
3755 n->args.push_back(require(e->components[i].expr_index));
70208613 3756
c69a87e0
FCE
3757 if (lvalue)
3758 {
3759 // Provide the functioncall to our parent, so that it can be
3760 // used to substitute for the assignment node immediately above
3761 // us.
3762 assert(!target_symbol_setter_functioncalls.empty());
3763 *(target_symbol_setter_functioncalls.top()) = n;
3764 }
70208613 3765
c69a87e0 3766 provide (n);
66d284f4
FCE
3767 }
3768 catch (const semantic_error& er)
3769 {
9fab2262
JS
3770 // We suppress this error message, and pass the unresolved
3771 // target_symbol to the next pass. We hope that this value ends
3772 // up not being referenced after all, so it can be optimized out
3773 // quietly.
1af1e62d 3774 e->chain (er);
9fab2262 3775 provide (e);
66d284f4 3776 }
77de5e9e
GH
3777}
3778
3779
c24447be
JS
3780void
3781dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3782{
3783 // Fill in our current module context if needed
3784 if (e->module.empty())
3785 e->module = q.dw.module_name;
3786
3787 var_expanding_visitor::visit_cast_op(e);
3788}
3789
3790
8cc799a5
JS
3791void
3792dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3793{
3794 expression *repl = e;
3795 if (q.has_return)
3796 {
3797 // expand the operand as if it weren't a return probe
3798 q.has_return = false;
3799 replace (e->operand);
3800 q.has_return = true;
3801
3802 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3803 // but it requires knowing the types already, which is problematic for
3804 // arbitrary expressons.
cc9001af 3805 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3806 }
3807 provide (repl);
3808}
3809
bfa7e523
MW
3810vector<Dwarf_Die>&
3811dwarf_var_expanding_visitor::getcuscope(target_symbol *e)
3812{
54e9f062
MW
3813 Dwarf_Off cu_off = 0;
3814 const char *cu_name = NULL;
bfa7e523
MW
3815
3816 string prefixed_srcfile = string("*/") + e->cu_name;
3817
3818 Dwarf_Off off = 0;
3819 size_t cuhl;
3820 Dwarf_Off noff;
3821 Dwarf_Off module_bias;
3822 Dwarf *dw = dwfl_module_getdwarf(q.dw.module, &module_bias);
54e9f062 3823 while (dwarf_nextcu (dw, off, &noff, &cuhl, NULL, NULL, NULL) == 0)
bfa7e523
MW
3824 {
3825 Dwarf_Die die_mem;
3826 Dwarf_Die *die;
3827 die = dwarf_offdie (dw, off + cuhl, &die_mem);
54e9f062 3828
dee830d9
MW
3829 /* We are not interested in partial units. */
3830 if (dwarf_tag (die) == DW_TAG_compile_unit)
54e9f062 3831 {
dee830d9
MW
3832 const char *die_name = dwarf_diename (die);
3833 if (strcmp (die_name, e->cu_name.c_str()) == 0) // Perfect match.
3834 {
3835 cu_name = die_name;
3836 cu_off = off + cuhl;
3837 break;
3838 }
3839
3840 if (fnmatch(prefixed_srcfile.c_str(), die_name, 0) == 0)
3841 if (cu_name == NULL || strlen (die_name) < strlen (cu_name))
3842 {
3843 cu_name = die_name;
3844 cu_off = off + cuhl;
3845 }
54e9f062 3846 }
bfa7e523
MW
3847 off = noff;
3848 }
3849
54e9f062 3850 if (cu_name == NULL)
bfa7e523
MW
3851 throw semantic_error ("unable to find CU '" + e->cu_name + "'"
3852 + " while searching for '" + e->target_name + "'",
3853 e->tok);
3854
3855 vector<Dwarf_Die> *cu_scope = new vector<Dwarf_Die>;
54e9f062
MW
3856 Dwarf_Die cu_die;
3857 dwarf_offdie (dw, cu_off, &cu_die);
3858 cu_scope->push_back(cu_die);
bfa7e523
MW
3859 return *cu_scope;
3860}
8cc799a5 3861
729455a7
JS
3862vector<Dwarf_Die>&
3863dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3864{
bfa7e523
MW
3865 // "static globals" can only be found in the top-level CU.
3866 if (e->name == "@var" && e->cu_name != "")
3867 return this->getcuscope(e);
3868
729455a7
JS
3869 if (scopes.empty())
3870 {
f25a9197
CM
3871 if(scope_die != NULL)
3872 scopes = q.dw.getscopes(scope_die);
729455a7 3873 if (scopes.empty())
b530b5b3
LB
3874 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3875 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
729455a7
JS
3876 throw semantic_error ("unable to find any scopes containing "
3877 + lex_cast_hex(addr)
3878 + ((scope_die == NULL) ? ""
3879 : (string (" in ")
3880 + (dwarf_diename(scope_die) ?: "<unknown>")
3881 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3882 + ")"))
3883 + " while searching for local '"
cc9001af 3884 + e->sym_name() + "'",
729455a7
JS
3885 e->tok);
3886 }
3887 return scopes;
3888}
3889
3890
5f36109e
JS
3891struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3892{
3893 systemtap_session& s;
3894 dwarf_builder& db;
3895
3896 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3897 s(s), db(db) {}
3898 void visit_cast_op (cast_op* e);
3899 void filter_special_modules(string& module);
3900};
3901
3902
c4ce66a1
JS
3903struct dwarf_cast_query : public base_query
3904{
946e1a48 3905 cast_op& e;
c4ce66a1 3906 const bool lvalue;
5f36109e
JS
3907 const bool userspace_p;
3908 functioncall*& result;
c4ce66a1 3909
5f36109e
JS
3910 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3911 const bool userspace_p, functioncall*& result):
abb41d92 3912 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3913 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3914
3915 void handle_query_module();
822a6a3d 3916 void query_library (const char *) {}
576eaefe 3917 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3918};
3919
3920
c4ce66a1
JS
3921void
3922dwarf_cast_query::handle_query_module()
3923{
5f36109e
JS
3924 static unsigned tick = 0;
3925
3926 if (result)
c4ce66a1
JS
3927 return;
3928
ea1e477a 3929 // look for the type in any CU
a44a7cb5
JS
3930 Dwarf_Die* type_die = NULL;
3931 if (startswith(e.type_name, "class "))
3932 {
3933 // normalize to match dwflpp::global_alias_caching_callback
3934 string struct_name = "struct " + e.type_name.substr(6);
3935 type_die = dw.declaration_resolve_other_cus(struct_name);
3936 }
3937 else
3938 type_die = dw.declaration_resolve_other_cus(e.type_name);
3939
3940 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3941 // just "name". But since we didn't require users to be explicit before, and
3942 // actually sort of discouraged it, we must be flexible now. So if a lookup
3943 // fails with a bare name, try augmenting it.
3944 if (!type_die &&
3945 !startswith(e.type_name, "class ") &&
3946 !startswith(e.type_name, "struct ") &&
3947 !startswith(e.type_name, "union ") &&
3948 !startswith(e.type_name, "enum "))
3949 {
3950 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3951 if (!type_die)
3952 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3953 if (!type_die)
3954 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3955 }
3956
ea1e477a
JS
3957 if (!type_die)
3958 return;
c4ce66a1 3959
5f36109e
JS
3960 string code;
3961 exp_type type = pe_long;
3962
ea1e477a 3963 try
c4ce66a1 3964 {
ea1e477a
JS
3965 Dwarf_Die cu_mem;
3966 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
3967
3968 if (!e.components.empty() &&
3969 e.components.back().type == target_symbol::comp_pretty_print)
3970 {
3971 if (lvalue)
b530b5b3 3972 throw semantic_error(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 3973
d19a9a82 3974 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
3975 result = dpp.expand();
3976 return;
3977 }
3978
3979 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
3980 }
3981 catch (const semantic_error& er)
3982 {
3983 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
3984 // may be attempted using several different modules:
3985 // @cast(ptr, "type", "module1:module2:...")
3986 e.chain (er);
c4ce66a1 3987 }
c4ce66a1 3988
5f36109e
JS
3989 if (code.empty())
3990 return;
c4ce66a1 3991
5f36109e 3992 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 3993 + "_" + e.sym_name()
5f36109e 3994 + "_" + lex_cast(tick++));
c4ce66a1 3995
5f36109e
JS
3996 // Synthesize a function.
3997 functiondecl *fdecl = new functiondecl;
3998 fdecl->synthetic = true;
3999 fdecl->tok = e.tok;
4000 fdecl->type = type;
4001 fdecl->name = fname;
4002
4003 embeddedcode *ec = new embeddedcode;
4004 ec->tok = e.tok;
4005 fdecl->body = ec;
4006
a5ce5211 4007 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
5f36109e
JS
4008 ec->code += code;
4009
4010 // Give the fdecl an argument for the pointer we're trying to cast
4011 vardecl *v1 = new vardecl;
4012 v1->type = pe_long;
4013 v1->name = "pointer";
4014 v1->tok = e.tok;
4015 fdecl->formal_args.push_back(v1);
4016
4017 // Any non-literal indexes need to be passed in too.
4018 for (unsigned i = 0; i < e.components.size(); ++i)
4019 if (e.components[i].type == target_symbol::comp_expression_array_index)
4020 {
4021 vardecl *v = new vardecl;
4022 v->type = pe_long;
4023 v->name = "index" + lex_cast(i);
4024 v->tok = e.tok;
4025 fdecl->formal_args.push_back(v);
4026 }
4027
4028 if (lvalue)
4029 {
4030 // Modify the fdecl so it carries a second pe_long formal
4031 // argument called "value".
4032
4033 // FIXME: For the time being we only support setting target
4034 // variables which have base types; these are 'pe_long' in
4035 // stap's type vocabulary. Strings and pointers might be
4036 // reasonable, some day, but not today.
4037
4038 vardecl *v2 = new vardecl;
4039 v2->type = pe_long;
4040 v2->name = "value";
4041 v2->tok = e.tok;
4042 fdecl->formal_args.push_back(v2);
4043 }
4044 else
4045 ec->code += "/* pure */";
4046
4047 ec->code += "/* unprivileged */";
a5ce5211 4048 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e 4049
f8809d54 4050 fdecl->join (dw.sess);
5f36109e
JS
4051
4052 // Synthesize a functioncall.
4053 functioncall* n = new functioncall;
4054 n->tok = e.tok;
4055 n->function = fname;
5f36109e
JS
4056 n->args.push_back(e.operand);
4057
4058 // Any non-literal indexes need to be passed in too.
4059 for (unsigned i = 0; i < e.components.size(); ++i)
4060 if (e.components[i].type == target_symbol::comp_expression_array_index)
4061 n->args.push_back(e.components[i].expr_index);
4062
4063 result = n;
4064}
c4ce66a1
JS
4065
4066
fb0274bc
JS
4067void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4068{
d90053e7 4069 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4070 // for those cases, build a module including that header
d90053e7 4071 if (module[module.size() - 1] == '>' &&
60d98537 4072 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4073 {
4074 string cached_module;
4075 if (s.use_cache)
4076 {
4077 // see if the cached module exists
a2639cb7 4078 cached_module = find_typequery_hash(s, module);
d105f664 4079 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4080 {
4081 int fd = open(cached_module.c_str(), O_RDONLY);
4082 if (fd != -1)
4083 {
4084 if (s.verbose > 2)
b530b5b3
LB
4085 //TRANSLATORS: Here we're using a cached module.
4086 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4087 module = cached_module;
4088 close(fd);
4089 return;
4090 }
4091 }
4092 }
4093
4094 // no cached module, time to make it
d90053e7 4095 if (make_typequery(s, module) == 0)
fb0274bc 4096 {
e16dc041 4097 // try to save typequery in the cache
fb0274bc 4098 if (s.use_cache)
e16dc041 4099 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4100 }
4101 }
4102}
4103
4104
c4ce66a1
JS
4105void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4106{
4107 bool lvalue = is_active_lvalue(e);
4108 if (lvalue && !s.guru_mode)
b3741c9d 4109 throw semantic_error(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4110
4111 if (e->module.empty())
4112 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4113
5f36109e 4114 functioncall* result = NULL;
8b31197b
JS
4115
4116 // split the module string by ':' for alternatives
4117 vector<string> modules;
4118 tokenize(e->module, modules, ":");
b5a0dd41 4119 bool userspace_p=false; // PR10601
5f36109e 4120 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4121 {
8b31197b 4122 string& module = modules[i];
fb0274bc 4123 filter_special_modules(module);
abb41d92 4124
c4ce66a1
JS
4125 // NB: This uses '/' to distinguish between kernel modules and userspace,
4126 // which means that userspace modules won't get any PATH searching.
4127 dwflpp* dw;
707bf35e
JS
4128 try
4129 {
b5a0dd41
FCE
4130 userspace_p=is_user_module (module);
4131 if (! userspace_p)
707bf35e
JS
4132 {
4133 // kernel or kernel module target
ae2552da 4134 dw = db.get_kern_dw(s, module);
707bf35e
JS
4135 }
4136 else
4137 {
05fb3e0c 4138 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4139 dw = db.get_user_dw(s, module);
4140 }
4141 }
4142 catch (const semantic_error& er)
4143 {
4144 /* ignore and go to the next module */
4145 continue;
4146 }
c4ce66a1 4147
5f36109e 4148 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 4149 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 4150 }
abb41d92 4151
5f36109e 4152 if (!result)
c4ce66a1 4153 {
946e1a48
JS
4154 // We pass the unresolved cast_op to the next pass, and hope
4155 // that this value ends up not being referenced after all, so
4156 // it can be optimized out quietly.
c4ce66a1
JS
4157 provide (e);
4158 return;
4159 }
4160
c4ce66a1
JS
4161 if (lvalue)
4162 {
4163 // Provide the functioncall to our parent, so that it can be
4164 // used to substitute for the assignment node immediately above
4165 // us.
4166 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4167 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4168 }
4169
5f36109e 4170 result->visit (this);
77de5e9e
GH
4171}
4172
4173
b8da0ad1
FCE
4174void
4175dwarf_derived_probe::printsig (ostream& o) const
4176{
4177 // Instead of just printing the plain locations, we add a PC value
4178 // as a comment as a way of telling e.g. apart multiple inlined
4179 // function instances. This is distinct from the verbose/clog
4180 // output, since this part goes into the cache hash calculations.
4181 sole_location()->print (o);
6d0f3f0c 4182 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4183 printsig_nested (o);
4184}
4185
4186
4187
dc38c0ae 4188void
b20febf3
FCE
4189dwarf_derived_probe::join_group (systemtap_session& s)
4190{
af234c40
JS
4191 // skip probes which are paired entry-handlers
4192 if (!has_return && (saved_longs || saved_strings))
4193 return;
4194
b20febf3
FCE
4195 if (! s.dwarf_derived_probes)
4196 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4197 s.dwarf_derived_probes->enroll (this);
4198}
4199
4200
2b69faaf
JS
4201static bool
4202kernel_supports_inode_uprobes(systemtap_session& s)
4203{
4204 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4205 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4206 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4207 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4208 && s.kernel_config["CONFIG_UPROBES"] == "y");
4209}
4210
4211
3667d615
JS
4212static bool
4213kernel_supports_inode_uretprobes(systemtap_session& s)
4214{
4215 // We need inode-uprobes first, then look for uretprobe_register either as a
4216 // real export or in the list possibly accessible by kallsyms.
4217 return kernel_supports_inode_uprobes(s) &&
4218 (s.kernel_exports.count("uretprobe_register") > 0 ||
4219 s.kernel_functions.count("uretprobe_register") > 0);
4220}
4221
4222
5261f7ab
DS
4223void
4224check_process_probe_kernel_support(systemtap_session& s)
4225{
4226 // If we've got utrace, we're good to go.
4227 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4228 return;
4229
8c021542
DS
4230 // We don't have utrace. For process probes that aren't
4231 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4232 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4233 // specific autoconf test for its needs.
8c021542
DS
4234 //
4235 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4236 // approximation.
4237 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4238 return;
4239
d3e959b0
DS
4240 // For uprobes-based process probes, we need the task_finder plus
4241 // the builtin inode-uprobes.
8c021542
DS
4242 if (s.need_uprobes
4243 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4244 && kernel_supports_inode_uprobes(s))
8c021542
DS
4245 return;
4246
4247 throw semantic_error (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4248}
4249
4250
b20febf3
FCE
4251dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4252 const string& filename,
4253 int line,
91af0778 4254 // module & section specify a relocation
b20febf3
FCE
4255 // base for <addr>, unless section==""
4256 // (equivalently module=="kernel")
4257 const string& module,
4258 const string& section,
4259 // NB: dwfl_addr is the virtualized
4260 // address for this symbol.
4261 Dwarf_Addr dwfl_addr,
4262 // addr is the section-offset for
4263 // actual relocation.
4264 Dwarf_Addr addr,
4265 dwarf_query& q,
37ebca01 4266 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4267 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4268 module (module), section (section), addr (addr),
63b4fd14 4269 path (q.path),
27dc09b1 4270 has_process (q.has_process),
c9bad430
DS
4271 has_return (q.has_return),
4272 has_maxactive (q.has_maxactive),
c57ea854 4273 has_library (q.has_library),
6b66b9f7 4274 maxactive_val (q.maxactive_val),
b642c901
SC
4275 user_path (q.user_path),
4276 user_lib (q.user_lib),
af234c40 4277 access_vars(false),
c57ea854 4278 saved_longs(0), saved_strings(0),
af234c40 4279 entry_handler(0)
bd2b1e68 4280{
b642c901
SC
4281 if (user_lib.size() != 0)
4282 has_library = true;
4283
6b66b9f7
JS
4284 if (q.has_process)
4285 {
4286 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4287 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4288 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4289 // by the incoming section value (".absolute" vs. ".dynamic").
4290 // XXX Assert invariants here too?
2b69faaf
JS
4291
4292 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4293 // ditto for userspace runtimes (dyninst)
ac3af990 4294 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4295 section == ".absolute" && addr == dwfl_addr &&
4296 addr >= q.dw.module_start && addr < q.dw.module_end)
4297 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4298 }
4299 else
4300 {
4301 // Assert kernel relocation invariants
4302 if (section == "" && dwfl_addr != addr) // addr should be absolute
ce0f6648 4303 throw semantic_error (_("missing relocation basis"), tok);
6b66b9f7 4304 if (section != "" && dwfl_addr == addr) // addr should be an offset
b530b5b3 4305 throw semantic_error (_("inconsistent relocation address"), tok);
6b66b9f7 4306 }
2930abc7 4307
21beacc9
FCE
4308 // XXX: hack for strange g++/gcc's
4309#ifndef USHRT_MAX
4310#define USHRT_MAX 32767
4311#endif
4312
606fd9c8 4313 // Range limit maxactive() value
6b66b9f7 4314 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
b530b5b3
LB
4315 throw semantic_error (_F("maxactive value out of range [0,%s]",
4316 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4317
de688825 4318 // Expand target variables in the probe body
5f0a03a6 4319 if (!null_die(scope_die))
8fc05e57 4320 {
6b66b9f7 4321 // XXX: user-space deref's for q.has_process!
de688825 4322 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4323 v.replace (this->body);
6b66b9f7
JS
4324 if (!q.has_process)
4325 access_vars = v.visited;
37ebca01
FCE
4326
4327 // If during target-variable-expanding the probe, we added a new block
4328 // of code, add it to the start of the probe.
4329 if (v.add_block)
ba6f838d 4330 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4331
4332 // If when target-variable-expanding the probe, we need to synthesize a
4333 // sibling function-entry probe. We don't go through the whole probe derivation
4334 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4335 // dwarf-induced duplication.
4336 if (v.add_call_probe)
37ebca01 4337 {
2260f4e3
FCE
4338 assert (q.has_return && !q.has_call);
4339
4340 // We temporarily replace q.base_probe.
4341 statement* old_body = q.base_probe->body;
4342 q.base_probe->body = v.add_call_probe;
4343 q.has_return = false;
4344 q.has_call = true;
af234c40 4345
da23eceb 4346 if (q.has_process)
af234c40
JS
4347 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4348 module, section, dwfl_addr,
4349 addr, q, scope_die);
da23eceb 4350 else
af234c40
JS
4351 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4352 module, section, dwfl_addr,
4353 addr, q, scope_die);
4354
4355 saved_longs = entry_handler->saved_longs = v.saved_longs;
4356 saved_strings = entry_handler->saved_strings = v.saved_strings;
4357
4358 q.results.push_back (entry_handler);
2260f4e3
FCE
4359
4360 q.has_return = true;
4361 q.has_call = false;
4362 q.base_probe->body = old_body;
37ebca01 4363 }
f10534c6
WH
4364 // Save the local variables for listing mode
4365 if (q.sess.listing_mode_vars)
8c67c337 4366 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4367 }
37ebca01 4368 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4369
f10534c6 4370 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4371
5d23847d 4372 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4373 // "reverse-engineered" form of the incoming (q.base_loc) probe
4374 // point. This allows a user to see what function / file / line
4375 // number any particular match of the wildcards.
2930abc7 4376
a229fcd7 4377 vector<probe_point::component*> comps;
91af0778
FCE
4378 if (q.has_kernel)
4379 comps.push_back (new probe_point::component(TOK_KERNEL));
4380 else if(q.has_module)
4381 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4382 else if(q.has_process)
4383 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4384 else
4385 assert (0);
b5d77020 4386
db520b00
FCE
4387 string fn_or_stmt;
4388 if (q.has_function_str || q.has_function_num)
4389 fn_or_stmt = "function";
4390 else
4391 fn_or_stmt = "statement";
a229fcd7 4392
b8da0ad1 4393 if (q.has_function_str || q.has_statement_str)
db520b00 4394 {
4cd232e4 4395 string retro_name = funcname;
b20febf3 4396 if (filename != "")
cee35f73 4397 {
fb84c077 4398 retro_name += ("@" + string (filename));
cee35f73 4399 if (line > 0)
aca66a36 4400 retro_name += (":" + lex_cast (line));
cee35f73 4401 }
db520b00
FCE
4402 comps.push_back
4403 (new probe_point::component
4404 (fn_or_stmt, new literal_string (retro_name)));
4405 }
b8da0ad1 4406 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4407 {
4408 Dwarf_Addr retro_addr;
4409 if (q.has_function_num)
4410 retro_addr = q.function_num_val;
4411 else
4412 retro_addr = q.statement_num_val;
db520b00
FCE
4413 comps.push_back (new probe_point::component
4414 (fn_or_stmt,
9ea68eb9 4415 new literal_number(retro_addr, true)));
37ebca01
FCE
4416
4417 if (q.has_absolute)
4418 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4419 }
4420
b8da0ad1
FCE
4421 if (q.has_call)
4422 comps.push_back (new probe_point::component(TOK_CALL));
4bda987e
SC
4423 if (q.has_exported)
4424 comps.push_back (new probe_point::component(TOK_EXPORTED));
b8da0ad1
FCE
4425 if (q.has_inline)
4426 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4427 if (has_return)
b8da0ad1
FCE
4428 comps.push_back (new probe_point::component(TOK_RETURN));
4429 if (has_maxactive)
4430 comps.push_back (new probe_point::component
4431 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4432
5d23847d
FCE
4433 // Overwrite it.
4434 this->sole_location()->components = comps;
2930abc7
FCE
4435}
4436
bd2b1e68 4437
0a98fd42 4438void
8c67c337
JS
4439dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4440 Dwarf_Addr dwfl_addr)
0a98fd42 4441{
9aa8ffce 4442 if (null_die(scope_die))
0a98fd42 4443 return;
0a98fd42 4444
8c67c337 4445 bool verbose = q.sess.verbose > 2;
0a98fd42 4446
8c67c337 4447 if (verbose)
b530b5b3 4448 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4449
8c67c337
JS
4450 if (has_return)
4451 {
4452 /* Only save the return value if it has a type. */
4453 string type_name;
4454 Dwarf_Die type_die;
4455 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4456 dwarf_type_name(&type_die, type_name))
4457 args.push_back("$return:"+type_name);
4458
4459 else if (verbose)
b530b5b3
LB
4460 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4461 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4462 }
d87623a1 4463
0a98fd42 4464 Dwarf_Die arg;
4ef35696
JS
4465 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4466 for (unsigned i = 0; i < scopes.size(); ++i)
4467 {
4468 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4469 break; // we don't want file-level variables
4470 if (dwarf_child (&scopes[i], &arg) == 0)
4471 do
0a98fd42 4472 {
4ef35696
JS
4473 switch (dwarf_tag (&arg))
4474 {
4475 case DW_TAG_variable:
4476 case DW_TAG_formal_parameter:
4477 break;
0a98fd42 4478
4ef35696
JS
4479 default:
4480 continue;
4481 }
0a98fd42 4482
4ef35696
JS
4483 /* Ignore this local if it has no name. */
4484 const char *arg_name = dwarf_diename (&arg);
4485 if (!arg_name)
8c67c337
JS
4486 {
4487 if (verbose)
b530b5b3
LB
4488 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4489 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4490 continue;
4491 }
4ef35696
JS
4492
4493 if (verbose)
b530b5b3
LB
4494 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4495 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4496
4497 /* Ignore this local if it has no location (or not at this PC). */
4498 /* NB: It still may not be directly accessible, e.g. if it is an
4499 * aggregate type, implicit_pointer, etc., but the user can later
4500 * figure out how to access the interesting parts. */
4501 Dwarf_Attribute attr_mem;
4502 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4503 {
4504 Dwarf_Op *expr;
4505 size_t len;
4506 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4507 {
4508 if (verbose)
b530b5b3
LB
4509 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4510 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4511 continue;
4512 }
4513 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4514 &len, 1) == 1 && len > 0))
4515 {
4516 if (verbose)
b530b5b3
LB
4517 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4518 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4ef35696
JS
4519 continue;
4520 }
4521 }
4522
4523 /* Ignore this local if it has no type. */
4524 string type_name;
4525 Dwarf_Die type_die;
4526 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4527 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4528 {
4529 if (verbose)
b530b5b3
LB
4530 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4531 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4532 continue;
4533 }
8c67c337 4534
4ef35696
JS
4535 /* This local looks good -- save it! */
4536 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4537 }
4ef35696
JS
4538 while (dwarf_siblingof (&arg, &arg) == 0);
4539 }
0a98fd42
JS
4540}
4541
4542
4543void
d0bfd2ac 4544dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4545{
d0bfd2ac 4546 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4547}
4548
4549
27dc09b1 4550void
42e38653 4551dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4552{
4553 if (has_process)
4554 {
4555 // These probes are allowed for unprivileged users, but only in the
4556 // context of processes which they own.
4557 emit_process_owner_assertion (o);
4558 return;
4559 }
4560
4561 // Other probes must contain the default assertion which aborts
4562 // if executed by an unprivileged user.
42e38653 4563 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4564}
4565
4566
4567void
4568dwarf_derived_probe::print_dupe_stamp(ostream& o)
4569{
4570 if (has_process)
4571 {
4572 // These probes are allowed for unprivileged users, but only in the
4573 // context of processes which they own.
4574 print_dupe_stamp_unprivileged_process_owner (o);
4575 return;
4576 }
4577
4578 // Other probes must contain the default dupe stamp
4579 derived_probe::print_dupe_stamp (o);
4580}
4581
64211010 4582
7a053d3b 4583void
20c6c071 4584dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4585 dwarf_builder * dw,
42e38653 4586 privilege_t privilege)
bd2b1e68 4587{
27dc09b1 4588 root
42e38653 4589 ->bind_privilege(privilege)
27dc09b1 4590 ->bind(dw);
54efe513
GH
4591}
4592
7a053d3b 4593void
fd6602a0 4594dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4595 dwarf_builder * dw,
42e38653 4596 privilege_t privilege)
2865d17a 4597{
27dc09b1 4598 root
42e38653 4599 ->bind_privilege(privilege)
27dc09b1 4600 ->bind(dw);
27dc09b1 4601 root->bind(TOK_CALL)
42e38653 4602 ->bind_privilege(privilege)
27dc09b1 4603 ->bind(dw);
4bda987e
SC
4604 root->bind(TOK_EXPORTED)
4605 ->bind_privilege(privilege)
4606 ->bind(dw);
27dc09b1 4607 root->bind(TOK_RETURN)
42e38653 4608 ->bind_privilege(privilege)
27dc09b1 4609 ->bind(dw);
1e035395 4610
f6be7c06
DB
4611 // For process probes / uprobes, .maxactive() is unused.
4612 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4613 {
4614 root->bind(TOK_RETURN)
1e035395
FCE
4615 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4616 }
bd2b1e68
GH
4617}
4618
7a053d3b 4619void
27dc09b1 4620dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4621 systemtap_session& s,
27dc09b1
DB
4622 match_node * root,
4623 dwarf_builder * dw,
42e38653 4624 privilege_t privilege
27dc09b1 4625)
bd2b1e68
GH
4626{
4627 // Here we match 4 forms:
4628 //
4629 // .function("foo")
4630 // .function(0xdeadbeef)
4631 // .statement("foo")
4632 // .statement(0xdeadbeef)
4633
440d9b00 4634 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4635 register_function_variants(fv_root, dw, privilege);
7f02ca94 4636 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4637 fv_root->bind(TOK_INLINE)
42e38653 4638 ->bind_privilege(privilege)
440d9b00 4639 ->bind(dw);
7f02ca94
JS
4640 fv_root->bind_str(TOK_LABEL)
4641 ->bind_privilege(privilege)
440d9b00
DB
4642 ->bind(dw);
4643
4644 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 4645 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
4646 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4647 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4648 {
4649 fv_root->bind(TOK_INLINE)
42e38653 4650 ->bind_privilege(privilege)
440d9b00
DB
4651 ->bind(dw);
4652 }
4653
42e38653
DB
4654 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
4655 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
4656}
4657
b1615c74
JS
4658void
4659dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
4660 match_node * root,
4661 dwarf_builder * dw)
4662{
4663 root->bind_str(TOK_MARK)
f66bb29a 4664 ->bind_privilege(pr_all)
b1615c74
JS
4665 ->bind(dw);
4666 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 4667 ->bind_privilege(pr_all)
b1615c74
JS
4668 ->bind(dw);
4669}
4670
4671void
4672dwarf_derived_probe::register_plt_variants(systemtap_session& s,
4673 match_node * root,
4674 dwarf_builder * dw)
4675{
4676 root->bind(TOK_PLT)
f66bb29a 4677 ->bind_privilege(pr_all)
b1615c74
JS
4678 ->bind(dw);
4679 root->bind_str(TOK_PLT)
f66bb29a 4680 ->bind_privilege(pr_all)
b1615c74
JS
4681 ->bind(dw);
4682 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4683 ->bind_privilege(pr_all)
b1615c74
JS
4684 ->bind(dw);
4685 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4686 ->bind_privilege(pr_all)
b1615c74 4687 ->bind(dw);
bd2b1e68
GH
4688}
4689
4690void
c4ce66a1 4691dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4692{
c4ce66a1 4693 match_node* root = s.pattern_root;
bd2b1e68
GH
4694 dwarf_builder *dw = new dwarf_builder();
4695
c4ce66a1
JS
4696 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4697 s.code_filters.push_back(filter);
4698
73f52eb4
DB
4699 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
4700 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
4701 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4702 ->bind(dw);
2cab6244 4703
7f02ca94
JS
4704 match_node* uprobes[] = {
4705 root->bind(TOK_PROCESS),
4706 root->bind_str(TOK_PROCESS),
4707 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4708 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4709 };
4710 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
4711 {
f66bb29a 4712 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
4713 register_sdt_variants(s, uprobes[i], dw);
4714 register_plt_variants(s, uprobes[i], dw);
4715 }
bd2b1e68
GH
4716}
4717
9020300d
FCE
4718void
4719dwarf_derived_probe::emit_probe_local_init(translator_output * o)
4720{
b95e2b79
MH
4721 if (access_vars)
4722 {
4723 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4724 o->newline() << "#if defined __ia64__";
d9aed31e 4725 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4726 o->newline() << "#endif";
b95e2b79 4727 }
9020300d 4728}
2930abc7 4729
b20febf3 4730// ------------------------------------------------------------------------
46b84a80
DS
4731
4732void
b20febf3 4733dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4734{
b20febf3 4735 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4736
4737 // XXX: probes put at the same address should all share a
4738 // single kprobe/kretprobe, and have their handlers executed
4739 // sequentially.
b55bc428
FCE
4740}
4741
7a053d3b 4742void
775d51e5 4743dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4744{
b20febf3 4745 if (probes_by_module.empty()) return;
2930abc7 4746
775d51e5
DS
4747 s.op->newline() << "/* ---- dwarf probes ---- */";
4748
4749 // Warn of misconfigured kernels
f41595cc
FCE
4750 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4751 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4752 s.op->newline() << "#endif";
775d51e5 4753 s.op->newline();
f41595cc 4754
f07c3b68 4755 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4756 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4757 s.op->newline() << "#endif";
4758
14cf7e42 4759 // Forward decls
2ba1736a 4760 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 4761
b20febf3
FCE
4762 // Forward declare the master entry functions
4763 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4764 s.op->line() << " struct pt_regs *regs);";
4765 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4766 s.op->line() << " struct pt_regs *regs);";
4767
42cb22bd
MH
4768 // Emit an array of kprobe/kretprobe pointers
4769 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4770 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4771 s.op->newline() << "#endif";
4772
b20febf3 4773 // Emit the actual probe list.
606fd9c8
FCE
4774
4775 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4776 // struct stap_dwarf_probe, but it being initialized data makes it add
4777 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4778 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4779 // NB: bss!
4780
4c2732a1 4781 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4782 s.op->newline(1) << "const unsigned return_p:1;";
4783 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4784 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4785 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4786 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4787
af234c40
JS
4788 // data saved in the kretprobe_instance packet
4789 s.op->newline() << "const unsigned short saved_longs;";
4790 s.op->newline() << "const unsigned short saved_strings;";
4791
faea5e16 4792 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
4793 // are small and uniform enough to justify putting char[MAX]'s into
4794 // the array instead of relocated char*'s.
faea5e16
JS
4795 size_t module_name_max = 0, section_name_max = 0;
4796 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
4797 size_t all_name_cnt = probes_by_module.size(); // for average
4798 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
4799 {
4800 dwarf_derived_probe* p = it->second;
4801#define DOIT(var,expr) do { \
4802 size_t var##_size = (expr) + 1; \
4803 var##_max = max (var##_max, var##_size); \
4804 var##_tot += var##_size; } while (0)
4805 DOIT(module_name, p->module.size());
4806 DOIT(section_name, p->section.size());
606fd9c8
FCE
4807#undef DOIT
4808 }
4809
4810 // Decide whether it's worthwhile to use char[] or char* by comparing
4811 // the amount of average waste (max - avg) to the relocation data size
4812 // (3 native long words).
4813#define CALCIT(var) \
4814 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
4815 { \
4816 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
4817 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
4818 << "[" << var##_name_max << "]" << endl; \
4819 } \
4820 else \
4821 { \
b0986e7a 4822 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
4823 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
4824 }
4825
4826 CALCIT(module);
4827 CALCIT(section);
e6fe60e7 4828#undef CALCIT
606fd9c8 4829
b0986e7a 4830 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
4831 s.op->newline() << "const struct stap_probe * const probe;";
4832 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
4833 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
4834 s.op->indent(1);
4835
4836 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 4837 {
b20febf3
FCE
4838 dwarf_derived_probe* p = it->second;
4839 s.op->newline() << "{";
4840 if (p->has_return)
4841 s.op->line() << " .return_p=1,";
c9bad430 4842 if (p->has_maxactive)
606fd9c8
FCE
4843 {
4844 s.op->line() << " .maxactive_p=1,";
4845 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
4846 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
4847 }
af234c40
JS
4848 if (p->saved_longs || p->saved_strings)
4849 {
4850 if (p->saved_longs)
4851 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
4852 if (p->saved_strings)
4853 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
4854 if (p->entry_handler)
c87ae2c1 4855 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 4856 }
b350f56b
JS
4857 if (p->locations[0]->optional)
4858 s.op->line() << " .optional_p=1,";
dc38c256 4859 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
4860 s.op->line() << " .module=\"" << p->module << "\",";
4861 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 4862 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 4863 s.op->line() << " },";
2930abc7 4864 }
2930abc7 4865
b20febf3
FCE
4866 s.op->newline(-1) << "};";
4867
4868 // Emit the kprobes callback function
4869 s.op->newline();
4870 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4871 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
4872 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
4873 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
4874 // Check that the index is plausible
4875 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4876 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4877 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4878 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4879 s.op->line() << "];";
71db462b 4880 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 4881 "stp_probe_type_kprobe");
d9aed31e 4882 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
4883
4884 // Make it look like the IP is set as it wouldn't have been replaced
4885 // by a breakpoint instruction when calling real probe handler. Reset
4886 // IP regs on return, so we don't confuse kprobes. PR10458
4887 s.op->newline() << "{";
4888 s.op->indent(1);
d9aed31e 4889 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 4890 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 4891 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 4892 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4893 s.op->newline(-1) << "}";
4894
f887a8c9 4895 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
4896 s.op->newline() << "return 0;";
4897 s.op->newline(-1) << "}";
4898
4899 // Same for kretprobes
4900 s.op->newline();
af234c40
JS
4901 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
4902 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 4903 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
4904
4905 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 4906 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
4907 // Check that the index is plausible
4908 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4909 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4910 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4911 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4912 s.op->line() << "];";
4913
7c3e97f4 4914 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
4915 s.op->newline() << "if (sp) {";
4916 s.op->indent(1);
71db462b 4917 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 4918 "stp_probe_type_kretprobe");
d9aed31e 4919 s.op->newline() << "c->kregs = regs;";
af234c40
JS
4920
4921 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
4922 s.op->newline() << "c->ips.krp.pi = inst;";
4923 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
4924
4925 // Make it look like the IP is set as it wouldn't have been replaced
4926 // by a breakpoint instruction when calling real probe handler. Reset
4927 // IP regs on return, so we don't confuse kprobes. PR10458
4928 s.op->newline() << "{";
d9aed31e 4929 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
4930 s.op->newline() << "if (entry)";
4931 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
4932 s.op->newline(-1) << "else";
4933 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
4934 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 4935 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4936 s.op->newline(-1) << "}";
4937
f887a8c9 4938 common_probe_entryfn_epilogue (s, true);
c87ae2c1 4939 s.op->newline(-1) << "}";
b20febf3
FCE
4940 s.op->newline() << "return 0;";
4941 s.op->newline(-1) << "}";
af234c40
JS
4942
4943 s.op->newline();
4944 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4945 s.op->line() << " struct pt_regs *regs) {";
4946 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
4947 s.op->newline(-1) << "}";
4948
4949 s.op->newline();
4950 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
4951 s.op->line() << " struct pt_regs *regs) {";
4952 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
4953 s.op->newline(-1) << "}";
b642c901 4954
14cf7e42 4955 s.op->newline();
20c6c071 4956}
ec4373ff 4957
20c6c071 4958
dc38c0ae 4959void
b20febf3
FCE
4960dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
4961{
4962 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4963 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4964 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 4965 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 4966 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 4967 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 4968 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 4969 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 4970 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 4971 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 4972 s.op->newline(-1) << "} else {";
f07c3b68 4973 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 4974 s.op->newline(-1) << "}";
606fd9c8 4975 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 4976 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 4977 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
4978 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4979 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4980 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4981 s.op->newline(-1) << "}";
4982 s.op->newline() << "#endif";
e4cb375f
MH
4983 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4984 s.op->newline() << "#ifdef __ia64__";
4985 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4986 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4987 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4988 s.op->newline() << "if (rc == 0) {";
4989 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4990 s.op->newline() << "if (rc != 0)";
4991 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4992 s.op->newline(-2) << "}";
4993 s.op->newline() << "#else";
606fd9c8 4994 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 4995 s.op->newline() << "#endif";
b20febf3 4996 s.op->newline(-1) << "} else {";
e4cb375f 4997 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
4998 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4999 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5000 s.op->newline() << "#ifdef __ia64__";
5001 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5002 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5003 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5004 s.op->newline() << "if (rc == 0) {";
5005 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5006 s.op->newline() << "if (rc != 0)";
5007 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5008 s.op->newline(-2) << "}";
5009 s.op->newline() << "#else";
606fd9c8 5010 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5011 s.op->newline() << "#endif";
b20febf3 5012 s.op->newline(-1) << "}";
9063462a
FCE
5013 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5014 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5015 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5016 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5017 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5018 // XXX: shall we increment numskipped?
5019 s.op->newline(-1) << "}";
5020
5021#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5022 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5023 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5024 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5025 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5026 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5027 s.op->newline() << "#ifdef __ia64__";
5028 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5029 s.op->newline() << "#endif";
c48cb0cc
FCE
5030 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5031 // not run for this early-abort case.
5032 s.op->newline(-1) << "}";
5033 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5034 s.op->newline(-1) << "}";
9063462a
FCE
5035#endif
5036
b20febf3
FCE
5037 s.op->newline() << "else sdp->registered_p = 1;";
5038 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5039}
5040
5041
b4be7cbc
FCE
5042void
5043dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5044{
5045 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5046 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5047 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5048 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5049 s.op->newline() << "int rc;";
5050
5051 // new module arrived?
5052 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5053 s.op->newline(1) << "if (sdp->return_p) {";
5054 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5055 s.op->newline() << "if (sdp->maxactive_p) {";
5056 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5057 s.op->newline(-1) << "} else {";
5058 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5059 s.op->newline(-1) << "}";
5060 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5061 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5062 s.op->newline() << "if (sdp->entry_probe) {";
5063 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5064 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5065 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5066 s.op->newline(-1) << "}";
5067 s.op->newline() << "#endif";
5068 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5069 s.op->newline() << "#ifdef __ia64__";
5070 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5071 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5072 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5073 s.op->newline() << "if (rc == 0) {";
5074 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5075 s.op->newline() << "if (rc != 0)";
5076 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5077 s.op->newline(-2) << "}";
5078 s.op->newline() << "#else";
5079 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5080 s.op->newline() << "#endif";
5081 s.op->newline(-1) << "} else {";
5082 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5083 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5084 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5085 s.op->newline() << "#ifdef __ia64__";
5086 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5087 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5088 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5089 s.op->newline() << "if (rc == 0) {";
5090 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5091 s.op->newline() << "if (rc != 0)";
5092 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5093 s.op->newline(-2) << "}";
5094 s.op->newline() << "#else";
5095 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5096 s.op->newline() << "#endif";
5097 s.op->newline(-1) << "}";
5098 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5099
5100 // old module disappeared?
5101 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5102 s.op->newline(1) << "if (sdp->return_p) {";
5103 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5104 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5105 s.op->newline() << "#ifdef STP_TIMING";
5106 s.op->newline() << "if (kp->u.krp.nmissed)";
5107 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5108 s.op->newline(-1) << "#endif";
065d5567 5109 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5110 s.op->newline() << "#ifdef STP_TIMING";
5111 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5112 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5113 s.op->newline(-1) << "#endif";
5114 s.op->newline(-1) << "} else {";
5115 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5116 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5117 s.op->newline() << "#ifdef STP_TIMING";
5118 s.op->newline() << "if (kp->u.kp.nmissed)";
5119 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5120 s.op->newline(-1) << "#endif";
5121 s.op->newline(-1) << "}";
5122 s.op->newline() << "#if defined(__ia64__)";
5123 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5124 s.op->newline() << "#endif";
5125 s.op->newline() << "sdp->registered_p = 0;";
5126 s.op->newline(-1) << "}";
5127
5128 s.op->newline(-1) << "}"; // for loop
5129}
5130
5131
5132
5133
46b84a80 5134void
b20febf3 5135dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5136{
42cb22bd
MH
5137 //Unregister kprobes by batch interfaces.
5138 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5139 s.op->newline() << "j = 0;";
5140 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5141 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5142 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5143 s.op->newline() << "if (! sdp->registered_p) continue;";
5144 s.op->newline() << "if (!sdp->return_p)";
5145 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5146 s.op->newline(-2) << "}";
5147 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5148 s.op->newline() << "j = 0;";
5149 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5150 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5151 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5152 s.op->newline() << "if (! sdp->registered_p) continue;";
5153 s.op->newline() << "if (sdp->return_p)";
5154 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5155 s.op->newline(-2) << "}";
5156 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5157 s.op->newline() << "#ifdef __ia64__";
5158 s.op->newline() << "j = 0;";
5159 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5160 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5161 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5162 s.op->newline() << "if (! sdp->registered_p) continue;";
5163 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5164 s.op->newline(-1) << "}";
5165 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5166 s.op->newline() << "#endif";
42cb22bd
MH
5167 s.op->newline() << "#endif";
5168
b20febf3
FCE
5169 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5170 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5171 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5172 s.op->newline() << "if (! sdp->registered_p) continue;";
5173 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5174 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5175 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5176 s.op->newline() << "#endif";
065d5567 5177 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5178 s.op->newline() << "#ifdef STP_TIMING";
5179 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5180 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5181 s.op->newline(-1) << "#endif";
065d5567 5182 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5183 s.op->newline() << "#ifdef STP_TIMING";
5184 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5185 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 5186 s.op->newline(-1) << "#endif";
557fb7a8 5187 s.op->newline(-1) << "} else {";
42cb22bd 5188 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5189 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5190 s.op->newline() << "#endif";
065d5567 5191 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5192 s.op->newline() << "#ifdef STP_TIMING";
5193 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5194 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5195 s.op->newline(-1) << "#endif";
b20febf3 5196 s.op->newline(-1) << "}";
e4cb375f
MH
5197 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5198 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5199 s.op->newline() << "#endif";
b20febf3
FCE
5200 s.op->newline() << "sdp->registered_p = 0;";
5201 s.op->newline(-1) << "}";
46b84a80
DS
5202}
5203
272c9036
WF
5204static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5205{
5206 string::size_type pos;
5207 string::size_type lastPos = str.find_first_not_of(" ", 0);
5208 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5209
5210 if (nextAt == string::npos)
5211 {
5212 // PR13934: Assembly probes are not forced to use the N@OP form.
5213 // In this case, N is inferred to be the native word size. Since we
5214 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5215 // then must not put any spaces in arguments, to avoid ambiguity.
5216 tokenize(str, tokens, " ");
5217 return;
5218 }
5219
272c9036
WF
5220 while (lastPos != string::npos)
5221 {
5222 pos = nextAt + 1;
5223 nextAt = str.find("@", pos);
5224 if (nextAt == string::npos)
5225 pos = string::npos;
5226 else
5227 pos = str.rfind(" ", nextAt);
5228
5229 tokens.push_back(str.substr(lastPos, pos - lastPos));
5230 lastPos = str.find_first_not_of(" ", pos);
5231 }
5232}
8aabf152 5233
8aabf152 5234
aff5d390 5235struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5236{
ae1418f0 5237 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
5238 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
5239 int elf_machine,
5240 const string & process_name,
a794dbeb 5241 const string & provider_name,
aff5d390 5242 const string & probe_name,
71e5e13d 5243 stap_sdt_probe_type probe_type,
aff5d390 5244 const string & arg_string,
8aabf152 5245 int ac):
332ba7e7 5246 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
5247 provider_name (provider_name), probe_name (probe_name),
5248 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5249 {
f83336a5
FCE
5250 /* Register name mapping table depends on the elf machine of this particular
5251 probe target process/file, not upon the host. So we can't just
5252 #ifdef _i686_ etc. */
ae1418f0
FCE
5253
5254#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5255 if (elf_machine == EM_X86_64) {
46a94997
SC
5256 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5257 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5258 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5259 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5260 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5261 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5262 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5263 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5264 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5265 DRI ("%sil", 4, QI);
5266 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5267 DRI ("%dil", 5, QI);
5268 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5269 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5270 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5271 DRI ("%r8b", 8, QI);
5272 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5273 DRI ("%r9b", 9, QI);
5274 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5275 DRI ("%r10b", 10, QI);
5276 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5277 DRI ("%r11b", 11, QI);
5278 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5279 DRI ("%r12b", 12, QI);
5280 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5281 DRI ("%r13b", 13, QI);
5282 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5283 DRI ("%r14b", 14, QI);
5284 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5285 DRI ("%r15b", 15, QI);
f83336a5 5286 } else if (elf_machine == EM_386) {
46a94997
SC
5287 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5288 DRI ("%ah", 0, QIh);
5289 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5290 DRI ("%ch", 1, QIh);
5291 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5292 DRI ("%dh", 2, QIh);
5293 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5294 DRI ("%bh", 3, QIh);
5295 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5296 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5297 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5298 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5299 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5300 DRI ("%r0", 0, DI);
5301 DRI ("%r1", 1, DI);
5302 DRI ("%r2", 2, DI);
5303 DRI ("%r3", 3, DI);
5304 DRI ("%r4", 4, DI);
5305 DRI ("%r5", 5, DI);
5306 DRI ("%r6", 6, DI);
5307 DRI ("%r7", 7, DI);
5308 DRI ("%r8", 8, DI);
5309 DRI ("%r9", 9, DI);
5310 DRI ("%r10", 10, DI);
5311 DRI ("%r11", 11, DI);
5312 DRI ("%r12", 12, DI);
5313 DRI ("%r13", 13, DI);
5314 DRI ("%r14", 14, DI);
5315 DRI ("%r15", 15, DI);
5316 DRI ("%r16", 16, DI);
5317 DRI ("%r17", 17, DI);
5318 DRI ("%r18", 18, DI);
5319 DRI ("%r19", 19, DI);
5320 DRI ("%r20", 20, DI);
5321 DRI ("%r21", 21, DI);
5322 DRI ("%r22", 22, DI);
5323 DRI ("%r23", 23, DI);
5324 DRI ("%r24", 24, DI);
5325 DRI ("%r25", 25, DI);
5326 DRI ("%r26", 26, DI);
5327 DRI ("%r27", 27, DI);
5328 DRI ("%r28", 28, DI);
5329 DRI ("%r29", 29, DI);
5330 DRI ("%r30", 30, DI);
5331 DRI ("%r31", 31, DI);
8aabf152 5332 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5333 DRI ("0", 0, DI);
5334 DRI ("1", 1, DI);
5335 DRI ("2", 2, DI);
5336 DRI ("3", 3, DI);
5337 DRI ("4", 4, DI);
5338 DRI ("5", 5, DI);
5339 DRI ("6", 6, DI);
5340 DRI ("7", 7, DI);
5341 DRI ("8", 8, DI);
5342 DRI ("9", 9, DI);
5343 DRI ("10", 10, DI);
5344 DRI ("11", 11, DI);
5345 DRI ("12", 12, DI);
5346 DRI ("13", 13, DI);
5347 DRI ("14", 14, DI);
5348 DRI ("15", 15, DI);
5349 DRI ("16", 16, DI);
5350 DRI ("17", 17, DI);
5351 DRI ("18", 18, DI);
5352 DRI ("19", 19, DI);
5353 DRI ("20", 20, DI);
5354 DRI ("21", 21, DI);
5355 DRI ("22", 22, DI);
5356 DRI ("23", 23, DI);
5357 DRI ("24", 24, DI);
5358 DRI ("25", 25, DI);
5359 DRI ("26", 26, DI);
5360 DRI ("27", 27, DI);
5361 DRI ("28", 28, DI);
5362 DRI ("29", 29, DI);
5363 DRI ("30", 30, DI);
5364 DRI ("31", 31, DI);
14900130 5365 } else if (elf_machine == EM_S390) {
46a94997
SC
5366 DRI ("%r0", 0, DI);
5367 DRI ("%r1", 1, DI);
5368 DRI ("%r2", 2, DI);
5369 DRI ("%r3", 3, DI);
5370 DRI ("%r4", 4, DI);
5371 DRI ("%r5", 5, DI);
5372 DRI ("%r6", 6, DI);
5373 DRI ("%r7", 7, DI);
5374 DRI ("%r8", 8, DI);
5375 DRI ("%r9", 9, DI);
5376 DRI ("%r10", 10, DI);
5377 DRI ("%r11", 11, DI);
5378 DRI ("%r12", 12, DI);
5379 DRI ("%r13", 13, DI);
5380 DRI ("%r14", 14, DI);
5381 DRI ("%r15", 15, DI);
272c9036
WF
5382 } else if (elf_machine == EM_ARM) {
5383 DRI ("r0", 0, SI);
5384 DRI ("r1", 1, SI);
5385 DRI ("r2", 2, SI);
5386 DRI ("r3", 3, SI);
5387 DRI ("r4", 4, SI);
5388 DRI ("r5", 5, SI);
5389 DRI ("r6", 6, SI);
5390 DRI ("r7", 7, SI);
5391 DRI ("r8", 8, SI);
5392 DRI ("r9", 9, SI);
5393 DRI ("sl", 10, SI);
5394 DRI ("fp", 11, SI);
5395 DRI ("ip", 12, SI);
5396 DRI ("sp", 13, SI);
5397 DRI ("lr", 14, SI);
5398 DRI ("pc", 15, SI);
14900130 5399 } else if (arg_count) {
8aabf152 5400 /* permit this case; just fall back to dwarf */
f83336a5 5401 }
ae1418f0 5402#undef DRI
f83336a5 5403
ebbd2b45 5404 need_debug_info = false;
88e39987 5405 if (probe_type == uprobe3_type)
272c9036
WF
5406 {
5407 sdt_v3_tokenize(arg_string, arg_tokens);
5408 assert(arg_count <= 12);
5409 }
88e39987 5410 else
272c9036
WF
5411 {
5412 tokenize(arg_string, arg_tokens, " ");
5413 assert(arg_count <= 10);
5414 }
a8ec7719 5415 }
8aabf152 5416
f83336a5 5417 systemtap_session& session;
332ba7e7 5418 int elf_machine;
aff5d390 5419 const string & process_name;
a794dbeb 5420 const string & provider_name;
aff5d390 5421 const string & probe_name;
71e5e13d 5422 stap_sdt_probe_type probe_type;
8aabf152 5423 unsigned arg_count;
aff5d390 5424 vector<string> arg_tokens;
46a94997 5425 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5426 bool need_debug_info;
aff5d390
SC
5427
5428 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5429 void visit_target_symbol_arg (target_symbol* e);
5430 void visit_target_symbol_context (target_symbol* e);
40a0c64e 5431 void visit_cast_op (cast_op* e);
aff5d390
SC
5432};
5433
7a05f484
SC
5434
5435void
6ef331c8 5436sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5437{
6ef331c8 5438 if (e->addressof)
b530b5b3 5439 throw semantic_error(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5440
5441 if (e->name == "$$name")
7a05f484 5442 {
6ef331c8
SC
5443 literal_string *myname = new literal_string (probe_name);
5444 myname->tok = e->tok;
5445 provide(myname);
5446 return;
5447 }
7a05f484 5448
6ef331c8
SC
5449 else if (e->name == "$$provider")
5450 {
5451 literal_string *myname = new literal_string (provider_name);
5452 myname->tok = e->tok;
5453 provide(myname);
5454 return;
5455 }
a794dbeb 5456
6ef331c8
SC
5457 else if (e->name == "$$vars" || e->name == "$$parms")
5458 {
5459 e->assert_no_components("sdt", true);
6ef331c8
SC
5460
5461 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
5462 // NB: we synthesize a new token here rather than reusing
5463 // e->tok, because print_format::print likes to use
5464 // its tok->content.
5465 token* pf_tok = new token(*e->tok);
5466 pf_tok->content = "sprintf";
63ea4244 5467
6ef331c8
SC
5468 print_format* pf = print_format::create(pf_tok);
5469
5470 for (unsigned i = 1; i <= arg_count; ++i)
5471 {
5472 if (i > 1)
5473 pf->raw_components += " ";
5474 target_symbol *tsym = new target_symbol;
5475 tsym->tok = e->tok;
5476 tsym->name = "$arg" + lex_cast(i);
5477 pf->raw_components += tsym->name;
5478 tsym->components = e->components;
5479
5480 expression *texp = require (tsym);
5481 if (!e->components.empty() &&
5482 e->components[0].type == target_symbol::comp_pretty_print)
5483 pf->raw_components += "=%s";
5484 else
5485 pf->raw_components += "=%#x";
5486 pf->args.push_back(texp);
5487 }
5488
5489 pf->components = print_format::string_to_components(pf->raw_components);
5490 provide (pf);
5491 }
5492 else
5493 assert(0); // shouldn't get here
5494}
5495
5496
5497void
5498sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5499{
5500 try
5501 {
8aabf152 5502 unsigned argno = 0; // the N in $argN
c69a87e0 5503 try
aff5d390 5504 {
5ecaa5a7 5505 if (startswith(e->name, "$arg"))
8aabf152 5506 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5507 }
c69a87e0 5508 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5509 {
8aabf152 5510 argno = 0;
aff5d390 5511 }
5ecaa5a7 5512
8aabf152
FCE
5513 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5514 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5515 {
8aabf152
FCE
5516 // NB: Either
5517 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5518 // 2) uprobe2_type $FOO (no probe args)
5519 // both of which get resolved later.
73d53dd2 5520 // Throw it now, and it might be resolved by DWARF later.
8aabf152 5521 need_debug_info = true;
73d53dd2 5522 throw semantic_error(_("target-symbol requires debuginfo"), e->tok);
aff5d390 5523 }
277c21bc 5524
8aabf152
FCE
5525 assert (arg_tokens.size() >= argno);
5526 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5527
8aabf152
FCE
5528 // Now we try to parse this thing, which is an assembler operand
5529 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5530 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5531 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157
FCE
5532 //
5533 // literal reg reg reg + base+index*size+offset
b874bd52 5534 // indirect offset
8095a157 5535 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S)
b874bd52
SC
5536 // power iN R (R) N(R)
5537 // ia64 N rR [r16]
5538 // s390 N %rR 0(rR) N(r15)
5539 // arm #N rR [rR] [rR, #N]
5540
8aabf152
FCE
5541 expression* argexpr = 0; // filled in in case of successful parse
5542
5543 string percent_regnames;
5544 string regnames;
5545 vector<string> matches;
71e5e13d 5546 long precision;
8aabf152
FCE
5547 int rc;
5548
40fe32e0
SC
5549 // Parse the leading length
5550
5551 if (asmarg.find('@') != string::npos)
5552 {
5553 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5554 asmarg = asmarg.substr(asmarg.find('@')+1);
5555 }
71e5e13d
SC
5556 else
5557 {
5558 // V1/V2 do not have precision field so default to signed long
5559 // V3 asm does not have precision field so default to unsigned long
5560 if (probe_type == uprobe3_type)
5561 precision = sizeof(long); // this is an asm probe
5562 else
5563 precision = -sizeof(long);
5564 }
40fe32e0 5565
8aabf152
FCE
5566 // test for a numeric literal.
5567 // Only accept (signed) decimals throughout. XXX
5568
5569 // PR11821. NB: on powerpc, literals are not prefixed with $,
5570 // so this regex does not match. But that's OK, since without
5571 // -mregnames, we can't tell them apart from register numbers
5572 // anyway. With -mregnames, we could, if gcc somehow
5573 // communicated to us the presence of that option, but alas it
5574 // doesn't. http://gcc.gnu.org/PR44995.
272c9036 5575 rc = regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5576 if (! rc)
5577 {
75a371ce
JS
5578 string sn = matches[0].substr(1);
5579 int64_t n;
5580 try
5581 {
5582 // We have to pay attention to the size & sign, as gcc sometimes
5583 // propagates constants that don't quite match, like a negative
5584 // value to fill an unsigned type.
5585 switch (precision)
5586 {
5587 case -1: n = lex_cast< int8_t>(sn); break;
5588 case 1: n = lex_cast< uint8_t>(sn); break;
5589 case -2: n = lex_cast< int16_t>(sn); break;
5590 case 2: n = lex_cast<uint16_t>(sn); break;
5591 case -4: n = lex_cast< int32_t>(sn); break;
5592 case 4: n = lex_cast<uint32_t>(sn); break;
5593 default:
5594 case -8: n = lex_cast< int64_t>(sn); break;
5595 case 8: n = lex_cast<uint64_t>(sn); break;
5596 }
5597 }
5598 catch (std::runtime_error&)
5599 {
5600 goto not_matched;
5601 }
5602 literal_number* ln = new literal_number(n);
8aabf152
FCE
5603 ln->tok = e->tok;
5604 argexpr = ln;
5605 goto matched;
5606 }
5607
14900130
SC
5608 if (dwarf_regs.empty())
5609 goto not_matched;
d5b83cee 5610
8aabf152
FCE
5611 // Build regex pieces out of the known dwarf_regs. We keep two separate
5612 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5613 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5614 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5615 {
5616 string regname = ri->first;
5617 assert (regname != "");
5618 regnames += string("|")+regname;
5619 if (regname[0]=='%')
5620 percent_regnames += string("|")+regname;
5621 }
5622 // clip off leading |
5623 regnames = regnames.substr(1);
272c9036
WF
5624 if (percent_regnames != "")
5625 percent_regnames = percent_regnames.substr(1);
8aabf152
FCE
5626
5627 // test for REGISTER
5628 // NB: Because PR11821, we must use percent_regnames here.
272c9036 5629 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
9109f487
SC
5630 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5631 else
332ba7e7 5632 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5633 if (! rc)
5634 {
5635 string regname = matches[1];
46a94997
SC
5636 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5637 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5638 {
5639 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5640 string width_adjust;
46a94997 5641 switch (ri->second.second)
19c22e1f 5642 {
892ec39a
SC
5643 case QI: width_adjust = ") & 0xff)"; break;
5644 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5645 case HI:
71e5e13d 5646 // preserve 16 bit register signness
892ec39a
SC
5647 width_adjust = ") & 0xffff)";
5648 if (precision < 0)
55b377f4 5649 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5650 break;
5651 case SI:
5652 // preserve 32 bit register signness
892ec39a
SC
5653 width_adjust = ") & 0xffffffff)";
5654 if (precision < 0)
55b377f4 5655 width_adjust += " << 32 >> 32";
19c22e1f 5656 break;
892ec39a 5657 default: width_adjust = "))";
19c22e1f 5658 }
55b377f4
SC
5659 string type = "";
5660 if (probe_type == uprobe3_type)
5661 type = (precision < 0
5662 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5663 type = type + "((";
8aabf152
FCE
5664 get_arg1->tok = e->tok;
5665 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5666 + string(" ((int64_t)") + type
8aabf152
FCE
5667 + (is_user_module (process_name)
5668 ? string("u_fetch_register(")
5669 : string("k_fetch_register("))
46a94997 5670 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5671 + width_adjust;
8aabf152
FCE
5672 argexpr = get_arg1;
5673 goto matched;
5674 }
5675 // invalid register name, fall through
5676 }
40fe32e0 5677
272c9036 5678 int reg, offset1;
e5b7b83f 5679 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5680 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 5681 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
5682 // On ARM test for [REGISTER, OFFSET]
5683 if (elf_machine == EM_ARM)
5684 {
5685 rc = regexp_match (asmarg, string("^\\[(")+regnames+string("), #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?\\]$"), matches);
5686 reg = 1;
5687 offset1 = 2;
5688 }
5689 else
5690 {
5691 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
5692 reg = 4;
5693 offset1 = 1;
5694 }
8aabf152
FCE
5695 if (! rc)
5696 {
e5b7b83f 5697 string regname;
8aabf152 5698 int64_t disp = 0;
272c9036
WF
5699 if (matches[reg].length())
5700 regname = matches[reg];
8095a157
FCE
5701 if (dwarf_regs.find (regname) == dwarf_regs.end())
5702 goto not_matched;
5703
272c9036 5704 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
5705 if (matches[i].length())
5706 try
5707 {
5708 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5709 }
8aabf152
FCE
5710 catch (const runtime_error& f) // unparseable offset
5711 {
5712 goto not_matched; // can't just 'break' out of
5713 // this case or use a sentinel
5714 // value, unfortunately
5715 }
5716
8aabf152 5717 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
5718 embedded_expr *get_arg1 = new embedded_expr;
5719 get_arg1->tok = e->tok;
5720 get_arg1->code = string("/* unprivileged */ /* pure */")
5721 + (is_user_module (process_name)
5722 ? string("u_fetch_register(")
5723 : string("k_fetch_register("))
46a94997 5724 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5725 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5726
8aabf152
FCE
5727 literal_number* inc = new literal_number(disp);
5728 inc->tok = e->tok;
40fe32e0 5729
8aabf152
FCE
5730 binary_expression *be = new binary_expression;
5731 be->tok = e->tok;
5732 be->left = get_arg1;
5733 be->op = "+";
5734 be->right = inc;
40fe32e0 5735
8aabf152 5736 functioncall *fc = new functioncall;
40fe32e0
SC
5737 switch (precision)
5738 {
7f6ce9ab
SC
5739 case 1: case -1:
5740 fc->function = "user_int8"; break;
5741 case 2:
5742 fc->function = "user_uint16"; break;
5743 case -2:
5744 fc->function = "user_int16"; break;
5745 case 4:
5746 fc->function = "user_uint32"; break;
5747 case -4:
5748 fc->function = "user_int32"; break;
5749 case 8: case -8:
5750 fc->function = "user_int64"; break;
40fe32e0
SC
5751 default: fc->function = "user_long";
5752 }
8aabf152
FCE
5753 fc->tok = e->tok;
5754 fc->args.push_back(be);
366af4e7 5755
8aabf152
FCE
5756 argexpr = fc;
5757 goto matched;
5758 }
8095a157
FCE
5759
5760 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
5761 // NB: Despite PR11821, we can use regnames here, since the parentheses
5762 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 5763 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
5764 if (! rc)
5765 {
5766 string baseregname;
5767 string indexregname;
5768 int64_t disp = 0;
5769 short scale = 1;
5770
5771 if (matches[6].length())
5772 try
5773 {
5774 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
5775 // We could verify that scale is one of 1,2,4,8,
5776 // but it doesn't really matter. An erroneous
5777 // address merely results in run-time errors.
8aabf152 5778 }
8095a157
FCE
5779 catch (const runtime_error &f) // unparseable scale
5780 {
5781 goto not_matched;
5782 }
5783
5784 if (matches[4].length())
5785 baseregname = matches[4];
5786 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
5787 goto not_matched;
5788
5789 if (matches[5].length())
5790 indexregname = matches[5];
5791 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
5792 goto not_matched;
5793
f7719b3d 5794 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
5795 if (matches[i].length())
5796 try
5797 {
5798 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5799 }
5800 catch (const runtime_error& f) // unparseable offset
5801 {
5802 goto not_matched; // can't just 'break' out of
5803 // this case or use a sentinel
5804 // value, unfortunately
5805 }
5806
5807 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
5808
5809 embedded_expr *get_arg1 = new embedded_expr;
5810 string regfn = is_user_module (process_name)
5811 ? string("u_fetch_register")
5812 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
5813
5814 get_arg1->tok = e->tok;
5815 get_arg1->code = string("/* unprivileged */ /* pure */")
5816 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
5817 + string("+(")
5818 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
5819 + string("*")
5820 + lex_cast(scale)
5821 + string(")");
5822
5823 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
5824 literal_number* inc = new literal_number(disp);
5825 inc->tok = e->tok;
5826
5827 binary_expression *be = new binary_expression;
5828 be->tok = e->tok;
5829 be->left = get_arg1;
5830 be->op = "+";
5831 be->right = inc;
5832
5833 functioncall *fc = new functioncall;
5834 switch (precision)
5835 {
5836 case 1: case -1:
5837 fc->function = "user_int8"; break;
5838 case 2:
5839 fc->function = "user_uint16"; break;
5840 case -2:
5841 fc->function = "user_int16"; break;
5842 case 4:
5843 fc->function = "user_uint32"; break;
5844 case -4:
5845 fc->function = "user_int32"; break;
5846 case 8: case -8:
5847 fc->function = "user_int64"; break;
5848 default: fc->function = "user_long";
5849 }
5850 fc->tok = e->tok;
5851 fc->args.push_back(be);
5852
5853 argexpr = fc;
5854 goto matched;
8aabf152
FCE
5855 }
5856
8aabf152
FCE
5857
5858 not_matched:
5859 // The asmarg operand was not recognized. Back down to dwarf.
5860 if (! session.suppress_warnings)
84fef8ee
FCE
5861 {
5862 if (probe_type == UPROBE3_TYPE)
5863 session.print_warning (_F("Can't parse SDT_V3 operand '%s'", asmarg.c_str()), e->tok);
5864 else // must be *PROBE2; others don't get asm operands
5865 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s'",
5866 asmarg.c_str()), e->tok);
5867 }
8aabf152
FCE
5868 assert (argexpr == 0);
5869 need_debug_info = true;
73d53dd2 5870 throw semantic_error(_("SDT asm not understood, requires debuginfo"), e->tok);
366af4e7 5871
8aabf152
FCE
5872 matched:
5873 assert (argexpr != 0);
366af4e7
RM
5874
5875 if (session.verbose > 2)
1e41115c 5876 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 5877 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 5878
aff5d390 5879 if (e->components.empty()) // We have a scalar
8aabf152
FCE
5880 {
5881 if (e->addressof)
b530b5b3 5882 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
5883 provide (argexpr);
5884 return;
5885 }
5886 else // $var->foo
5887 {
5888 cast_op *cast = new cast_op;
5889 cast->name = "@cast";
5890 cast->tok = e->tok;
5891 cast->operand = argexpr;
5892 cast->components = e->components;
5893 cast->type_name = probe_name + "_arg" + lex_cast(argno);
5894 cast->module = process_name;
5895 cast->visit(this);
5896 return;
5897 }
366af4e7 5898
8aabf152 5899 /* NOTREACHED */
aff5d390
SC
5900 }
5901 catch (const semantic_error &er)
5902 {
5903 e->chain (er);
5904 provide (e);
5905 }
5906}
5907
5908
6ef331c8
SC
5909void
5910sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
5911{
5912 try
5913 {
49131a6d
MW
5914 assert(e->name.size() > 0
5915 && ((e->name[0] == '$' && e->target_name == "")
5916 || (e->name == "@var" && e->target_name != "")));
6ef331c8
SC
5917
5918 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
5919 visit_target_symbol_context (e);
5920 else
5921 visit_target_symbol_arg (e);
5922 }
5923 catch (const semantic_error &er)
5924 {
5925 e->chain (er);
5926 provide (e);
5927 }
5928}
5929
5930
40a0c64e
JS
5931void
5932sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
5933{
5934 // Fill in our current module context if needed
5935 if (e->module.empty())
5936 e->module = process_name;
5937
5938 var_expanding_visitor::visit_cast_op(e);
5939}
5940
5941
576eaefe
SC
5942void
5943plt_expanding_visitor::visit_target_symbol (target_symbol *e)
5944{
5945 try
5946 {
5947 if (e->name == "$$name")
5948 {
5949 literal_string *myname = new literal_string (entry);
5950 myname->tok = e->tok;
5951 provide(myname);
5952 return;
5953 }
3d69c03f
JS
5954
5955 // variable not found -> throw a semantic error
5956 // (only to be caught right away, but this may be more complex later...)
5957 string alternatives = "$$name";
5958 throw semantic_error(_F("unable to find plt variable '%s' (alternatives: %s)",
5959 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
5960 }
5961 catch (const semantic_error &er)
5962 {
5963 e->chain (er);
5964 provide (e);
5965 }
5966}
5967
5968
edce5b67
JS
5969struct sdt_query : public base_query
5970{
5971 sdt_query(probe * base_probe, probe_point * base_loc,
5972 dwflpp & dw, literal_map_t const & params,
51d6bda3 5973 vector<derived_probe *> & results, const string user_lib);
edce5b67 5974
51d6bda3 5975 void query_library (const char *data);
576eaefe 5976 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
5977 void handle_query_module();
5978
5979private:
15284963 5980 stap_sdt_probe_type probe_type;
d61ea602 5981 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
5982 probe * base_probe;
5983 probe_point * base_loc;
6846cfc8 5984 literal_map_t const & params;
edce5b67 5985 vector<derived_probe *> & results;
a794dbeb
FCE
5986 string pp_mark;
5987 string pp_provider;
51d6bda3 5988 string user_lib;
edce5b67
JS
5989
5990 set<string> probes_handled;
5991
5992 Elf_Data *pdata;
5993 size_t probe_scn_offset;
5994 size_t probe_scn_addr;
aff5d390 5995 uint64_t arg_count;
40fe32e0 5996 GElf_Addr base;
c57ea854 5997 GElf_Addr pc;
aff5d390 5998 string arg_string;
edce5b67 5999 string probe_name;
a794dbeb 6000 string provider_name;
79a0ca08 6001 Dwarf_Addr semaphore;
edce5b67
JS
6002
6003 bool init_probe_scn();
6b51ee12 6004 bool get_next_probe();
c57ea854
SC
6005 void iterate_over_probe_entries();
6006 void handle_probe_entry();
edce5b67 6007
40fe32e0
SC
6008 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
6009 void setup_note_probe_entry (int type, const char *data, size_t len);
6010
edce5b67 6011 void convert_probe(probe *base);
4ddb6dd0 6012 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6013 probe* convert_location();
40fe32e0 6014 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6015 bool have_debuginfo_uprobe(bool need_debug_info)
6016 {return probe_type == uprobe1_type
40fe32e0 6017 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6018 && need_debug_info);}
40fe32e0 6019 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6020};
6021
6022
6023sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6024 dwflpp & dw, literal_map_t const & params,
51d6bda3 6025 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6026 base_query(dw, params), probe_type(unknown_probe_type),
6027 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6028 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6029 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
6030 semaphore(0)
edce5b67 6031{
a794dbeb
FCE
6032 assert(get_string_param(params, TOK_MARK, pp_mark));
6033 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6034
ef428667
FCE
6035 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6036 // map it to double-underscores.
6037 size_t pos = 0;
6038 while (1) // there may be more than one
6039 {
a794dbeb 6040 size_t i = pp_mark.find("-", pos);
ef428667 6041 if (i == string::npos) break;
a794dbeb 6042 pp_mark.replace (i, 1, "__");
ef428667
FCE
6043 pos = i+1; // resume searching after the inserted __
6044 }
a794dbeb
FCE
6045
6046 // XXX: same for pp_provider?
edce5b67
JS
6047}
6048
6049
6050void
c57ea854 6051sdt_query::handle_probe_entry()
edce5b67 6052{
c57ea854
SC
6053 if (! have_uprobe()
6054 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6055 return;
6056
6057 if (sess.verbose > 3)
c57ea854 6058 {
b530b5b3
LB
6059 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
6060 //TRANSLATORS: is matched to.
6061 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6062 switch (probe_type)
6063 {
6064 case uprobe1_type:
6065 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6066 break;
6067 case uprobe2_type:
6068 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6069 break;
40fe32e0
SC
6070 case uprobe3_type:
6071 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6072 break;
d61ea602
JS
6073 default:
6074 clog << "unknown!" << endl;
6075 break;
c57ea854
SC
6076 }
6077 }
edce5b67 6078
c57ea854
SC
6079 // Extend the derivation chain
6080 probe *new_base = convert_location();
6081 probe_point *new_location = new_base->locations[0];
6082
c57ea854
SC
6083 bool need_debug_info = false;
6084
7d395255
JS
6085 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6086 // or dwfl_module_getelf(...). We only need it for the machine type, which
6087 // should be the same. The bias is used for relocating debuginfoless probes,
6088 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6089 Dwarf_Addr bias;
7d395255 6090 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6091
1cc41cd6
DS
6092 /* Figure out the architecture of this particular ELF file. The
6093 dwarfless register-name mappings depend on it. */
6094 GElf_Ehdr ehdr_mem;
6095 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
6096 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6097 assert(em);
1cc41cd6
DS
6098 int elf_machine = em->e_machine;
6099 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine, module_val,
6100 provider_name, probe_name,
6101 probe_type, arg_string, arg_count);
6102 svv.replace (new_base->body);
6103 need_debug_info = svv.need_debug_info;
c57ea854 6104
1cc41cd6
DS
6105 // XXX: why not derive_probes() in the uprobes case too?
6106 literal_map_t params;
6107 for (unsigned i = 0; i < new_location->components.size(); ++i)
6108 {
6109 probe_point::component *c = new_location->components[i];
6110 params[c->functor] = c->arg;
6111 }
c57ea854 6112
73d53dd2 6113 unsigned prior_results_size = results.size();
1cc41cd6
DS
6114 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6115 q.has_mark = true; // enables mid-statement probing
30263a73 6116
73d53dd2
JS
6117 // V1 probes always need dwarf info
6118 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6
DS
6119 if (have_debuginfo_uprobe(need_debug_info))
6120 dw.iterate_over_modules(&query_module, &q);
73d53dd2
JS
6121
6122 // For V2+ probes, if variable references weren't used or failed (PR14369),
6123 // then try with the more direct approach. Unresolved $vars might still
6124 // cause their own error, but this gives them a chance to be optimized out.
6125 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6126 {
6127 string section;
6128 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6129 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6130 {
6131 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6132 section = ".dynamic";
6133 }
6134 else
6135 section = ".absolute";
edce5b67 6136
1cc41cd6
DS
6137 uprobe_derived_probe* p =
6138 new uprobe_derived_probe ("", "", 0,
6139 path_remove_sysroot(sess,q.module_val),
6140 section,
6141 q.statement_num_val, reloc_addr, q, 0);
6142 p->saveargs (arg_count);
6143 results.push_back (p);
c57ea854 6144 }
487bf4e2 6145 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6146 record_semaphore(results, prior_results_size);
c57ea854 6147}
edce5b67 6148
4ddb6dd0 6149
c57ea854
SC
6150void
6151sdt_query::handle_query_module()
6152{
6153 if (!init_probe_scn())
6154 return;
edce5b67 6155
c57ea854
SC
6156 if (sess.verbose > 3)
6157 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6158
40fe32e0
SC
6159 if (probe_loc == note_section)
6160 {
6161 GElf_Shdr shdr_mem;
6162 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6163
6164 if (shdr)
6165 base = shdr->sh_addr;
6166 else
6167 base = 0;
6168 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
6169 }
d61ea602 6170 else if (probe_loc == probe_section)
40fe32e0 6171 iterate_over_probe_entries ();
edce5b67
JS
6172}
6173
6174
6175bool
6176sdt_query::init_probe_scn()
6177{
448a86b7 6178 Elf* elf;
edce5b67 6179 GElf_Shdr shdr_mem;
40fe32e0
SC
6180
6181 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6182 if (shdr)
6183 {
6184 probe_loc = note_section;
6185 return true;
6186 }
edce5b67 6187
448a86b7 6188 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6189 if (shdr)
edce5b67 6190 {
fea74777
SC
6191 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6192 probe_scn_offset = 0;
6193 probe_scn_addr = shdr->sh_addr;
6194 assert (pdata != NULL);
6195 if (sess.verbose > 4)
ce0f6648
LB
6196 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6197 << pdata->d_size << endl;
40fe32e0 6198 probe_loc = probe_section;
fea74777 6199 return true;
edce5b67 6200 }
fea74777 6201 else
edce5b67 6202 return false;
edce5b67
JS
6203}
6204
40fe32e0
SC
6205void
6206sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
6207{
6208 sdt_query *me = (sdt_query*)object;
6209 me->setup_note_probe_entry (type, data, len);
6210}
6211
6212
6213void
6214sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
6215{
6216 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
6217 // && !memcmp (data->d_buf + name_off,
6218 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
6219
6220 // probes are in the .note.stapsdt section
6221#define _SDT_NOTE_TYPE 3
6222 if (type != _SDT_NOTE_TYPE)
6223 return;
6224
6225 union
6226 {
6227 Elf64_Addr a64[3];
6228 Elf32_Addr a32[3];
6229 } buf;
6230 Dwarf_Addr bias;
6231 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6232 Elf_Data dst =
6233 {
6234 &buf, ELF_T_ADDR, EV_CURRENT,
6235 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6236 };
6237 assert (dst.d_size <= sizeof buf);
6238
6239 if (len < dst.d_size + 3)
6240 return;
6241
6242 Elf_Data src =
6243 {
6244 (void *) data, ELF_T_ADDR, EV_CURRENT,
6245 dst.d_size, 0, 0
6246 };
6247
6248 if (gelf_xlatetom (elf, &dst, &src,
6249 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6250 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6251
6252 probe_type = uprobe3_type;
6253 const char * provider = data + dst.d_size;
3f803f9e 6254
40fe32e0 6255 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6256 if(name++ == NULL)
6257 return;
6258
6259 const char *args = (const char*)memchr (name, '\0', data + len - name);
6260 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6261 return;
6262
6263 provider_name = provider;
6264 probe_name = name;
6265 arg_string = args;
40fe32e0
SC
6266
6267 // Did we find a matching probe?
6268 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6269 && ((pp_provider == "")
6270 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6271 return;
6272
e9a90eee
JS
6273 // PR13934: Assembly probes are not forced to use the N@OP form.
6274 // If we have '@' then great, else count based on space-delimiters.
6275 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6276 if (!arg_count && !arg_string.empty())
6277 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6278
40fe32e0
SC
6279 GElf_Addr base_ref;
6280 if (gelf_getclass (elf) == ELFCLASS32)
6281 {
6282 pc = buf.a32[0];
6283 base_ref = buf.a32[1];
6284 semaphore = buf.a32[2];
6285 }
6286 else
6287 {
6288 pc = buf.a64[0];
6289 base_ref = buf.a64[1];
6290 semaphore = buf.a64[2];
6291 }
6292
6293 semaphore += base - base_ref;
6294 pc += base - base_ref;
6295
7d395255
JS
6296 // The semaphore also needs the ELF bias added now, so
6297 // record_semaphore can properly relocate it later.
6298 semaphore += bias;
6299
40fe32e0 6300 if (sess.verbose > 4)
b530b5b3 6301 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
6302
6303 handle_probe_entry();
6304}
6305
6306
c57ea854
SC
6307void
6308sdt_query::iterate_over_probe_entries()
edce5b67 6309{
c57ea854 6310 // probes are in the .probe section
edce5b67
JS
6311 while (probe_scn_offset < pdata->d_size)
6312 {
aff5d390
SC
6313 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6314 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6315 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6316 if (! have_uprobe())
edce5b67
JS
6317 {
6318 // Unless this is a mangled .probes section, this happens
6319 // because the name of the probe comes first, followed by
6320 // the sentinel.
6321 if (sess.verbose > 5)
b530b5b3 6322 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6323 probe_scn_offset += sizeof(__uint32_t);
6324 continue;
6325 }
aff5d390
SC
6326 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6327 {
6328 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6329 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6330 continue;
6331 }
6332
1cc41cd6 6333 if (probe_type == uprobe1_type)
aff5d390 6334 {
79a0ca08 6335 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6336 return;
79a0ca08 6337 semaphore = 0;
aff5d390 6338 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6339 provider_name = ""; // unknown
1cc41cd6
DS
6340 pc = pbe_v1->arg;
6341 arg_count = 0;
aff5d390
SC
6342 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6343 }
08b5a50c 6344 else if (probe_type == uprobe2_type)
aff5d390 6345 {
79a0ca08 6346 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6347 return;
79a0ca08 6348 semaphore = pbe_v2->semaphore;
aff5d390 6349 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6350 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6351 arg_count = pbe_v2->arg_count;
6352 pc = pbe_v2->pc;
6353 if (pbe_v2->arg_string)
6354 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6355 // skip over pbe_v2, probe_name text and provider text
6356 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6357 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6358 }
edce5b67 6359 if (sess.verbose > 4)
b530b5b3 6360 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6361 << "@0x" << hex << pc << dec << endl;
edce5b67 6362
a794dbeb
FCE
6363 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6364 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6365 handle_probe_entry ();
edce5b67 6366 }
edce5b67
JS
6367}
6368
6369
6846cfc8 6370void
4ddb6dd0 6371sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6372{
a794dbeb
FCE
6373 for (unsigned i=0; i<2; i++) {
6374 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6375 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6376 // XXX: multiple addresses?
6377 if (sess.verbose > 2)
b530b5b3 6378 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6379
79a0ca08
SC
6380 Dwarf_Addr addr;
6381 if (this->semaphore)
6382 addr = this->semaphore;
6383 else
6384 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6385 if (addr)
6386 {
7d395255 6387 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6388 dwfl_module_relocate_address (dw.module, &addr);
6389 // XXX: relocation basis?
6390 for (unsigned i = start; i < results.size(); ++i)
6391 results[i]->sdt_semaphore_addr = addr;
6392 if (sess.verbose > 2)
b530b5b3 6393 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6394 return;
6395 }
6396 else
6397 if (sess.verbose > 2)
b530b5b3 6398 clog << _(", not found") << endl;
a794dbeb 6399 }
6846cfc8
SC
6400}
6401
6402
edce5b67
JS
6403void
6404sdt_query::convert_probe (probe *base)
6405{
6406 block *b = new block;
6407 b->tok = base->body->tok;
6408
edce5b67
JS
6409 // Generate: if (arg1 != mark("label")) next;
6410 functioncall *fc = new functioncall;
bbafcb1e 6411 fc->function = "ulong_arg";
edce5b67 6412 fc->tok = b->tok;
bbafcb1e 6413 literal_number* num = new literal_number(1);
edce5b67
JS
6414 num->tok = b->tok;
6415 fc->args.push_back(num);
6416
6417 functioncall *fcus = new functioncall;
6418 fcus->function = "user_string";
6419 fcus->type = pe_string;
6420 fcus->tok = b->tok;
6421 fcus->args.push_back(fc);
6422
6423 if_statement *is = new if_statement;
6424 is->thenblock = new next_statement;
6425 is->elseblock = NULL;
6426 is->tok = b->tok;
63ea4244 6427 is->thenblock->tok = b->tok;
edce5b67
JS
6428 comparison *be = new comparison;
6429 be->op = "!=";
6430 be->tok = b->tok;
6431 be->left = fcus;
6432 be->right = new literal_string(probe_name);
63ea4244 6433 be->right->tok = b->tok;
edce5b67
JS
6434 is->condition = be;
6435 b->statements.push_back(is);
6436
6437 // Now replace the body
6438 b->statements.push_back(base->body);
6439 base->body = b;
6440}
6441
6442
c72aa911
JS
6443probe*
6444sdt_query::convert_location ()
edce5b67 6445{
c72aa911 6446 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6447 vector<probe_point::component*> derived_comps;
edce5b67 6448
662539d9
JS
6449 vector<probe_point::component*>::iterator it;
6450 for (it = specific_loc->components.begin();
6451 it != specific_loc->components.end(); ++it)
6452 if ((*it)->functor == TOK_PROCESS)
6453 {
1cc41cd6
DS
6454 // copy the process name
6455 derived_comps.push_back(*it);
662539d9
JS
6456 }
6457 else if ((*it)->functor == TOK_LIBRARY)
6458 {
1cc41cd6
DS
6459 // copy the library name for process probes
6460 derived_comps.push_back(*it);
662539d9
JS
6461 }
6462 else if ((*it)->functor == TOK_PROVIDER)
6463 {
6464 // replace the possibly wildcarded arg with the specific provider name
6465 *it = new probe_point::component(TOK_PROVIDER,
6466 new literal_string(provider_name));
6467 }
6468 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6469 {
6470 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6471 *it = new probe_point::component(TOK_MARK,
6472 new literal_string(probe_name));
a794dbeb 6473
aff5d390
SC
6474 if (sess.verbose > 3)
6475 switch (probe_type)
6476 {
6477 case uprobe1_type:
b530b5b3 6478 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6479 << hex << pc << dec << endl;
6480 break;
6481 case uprobe2_type:
b530b5b3 6482 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6483 << hex << pc << dec << endl;
6484 break;
40fe32e0 6485 case uprobe3_type:
b530b5b3 6486 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6487 << hex << pc << dec << endl;
6488 break;
aff5d390 6489 default:
b530b5b3
LB
6490 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6491 pp_mark.c_str()) << endl;
aff5d390
SC
6492 }
6493
c72aa911
JS
6494 switch (probe_type)
6495 {
aff5d390
SC
6496 case uprobe1_type:
6497 case uprobe2_type:
40fe32e0 6498 case uprobe3_type:
c72aa911 6499 // process("executable").statement(probe_arg)
662539d9
JS
6500 derived_comps.push_back
6501 (new probe_point::component(TOK_STATEMENT,
6502 new literal_number(pc, true)));
c72aa911
JS
6503 break;
6504
a794dbeb 6505 default: // deprecated
c72aa911 6506 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6507 derived_comps.push_back
6508 (new probe_point::component(TOK_FUNCTION,
6509 new literal_string("*")));
6510 derived_comps.push_back
c72aa911 6511 (new probe_point::component(TOK_LABEL,
a794dbeb 6512 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6513 break;
6514 }
6515 }
edce5b67 6516
662539d9
JS
6517 probe_point* derived_loc = new probe_point(*specific_loc);
6518 derived_loc->components = derived_comps;
c72aa911 6519 return base_probe->create_alias(derived_loc, specific_loc);
edce5b67
JS
6520}
6521
6522
51d6bda3
SC
6523void
6524sdt_query::query_library (const char *library)
6525{
6526 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6527}
6528
6529
20c6c071 6530void
5227f1ea 6531dwarf_builder::build(systemtap_session & sess,
7a053d3b 6532 probe * base,
20c6c071 6533 probe_point * location,
86bf665e 6534 literal_map_t const & parameters,
20c6c071
GH
6535 vector<derived_probe *> & finished_results)
6536{
b20febf3
FCE
6537 // NB: the kernel/user dwlfpp objects are long-lived.
6538 // XXX: but they should be per-session, as this builder object
6539 // may be reused if we try to cross-instrument multiple targets.
84048984 6540
7a24d422 6541 dwflpp* dw = 0;
6d5d594e 6542 literal_map_t filled_parameters = parameters;
7a24d422 6543
7a24d422 6544 string module_name;
ae2552da
FCE
6545 if (has_null_param (parameters, TOK_KERNEL))
6546 {
6547 dw = get_kern_dw(sess, "kernel");
6548 }
6549 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6550 {
c523a015
LB
6551 size_t dash_pos = 0;
6552 while((dash_pos=module_name.find('-'))!=string::npos)
6553 module_name.replace(int(dash_pos),1,"_");
6554 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6555 // NB: glob patterns get expanded later, during the offline
6556 // elfutils module listing.
ae2552da 6557 dw = get_kern_dw(sess, module_name);
b8da0ad1 6558 }
6d5d594e 6559 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6560 {
05fb3e0c 6561 module_name = sess.sysroot + module_name;
6d5d594e
LB
6562 if(has_null_param(filled_parameters, TOK_PROCESS))
6563 {
6564 wordexp_t words;
6565 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6566 if(rc || words.we_wordc <= 0)
6567 throw semantic_error(_("unspecified process probe is invalid without a -c COMMAND"));
05fb3e0c 6568 module_name = sess.sysroot + words.we_wordv[0];
6d5d594e
LB
6569 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6570 // in the case of TOK_MARK we need to modify locations as well
6571 if(location->components[0]->functor==TOK_PROCESS &&
6572 location->components[0]->arg == 0)
6573 location->components[0]->arg = new literal_string(module_name);
6574 wordfree (& words);
6575 }
5750ecc6 6576
37001baa
FCE
6577 // PR6456 process("/bin/*") glob handling
6578 if (contains_glob_chars (module_name))
6579 {
6580 // Expand glob via rewriting the probe-point process("....")
6581 // parameter, asserted to be the first one.
6582
6583 assert (location->components.size() > 0);
6584 assert (location->components[0]->functor == TOK_PROCESS);
6585 assert (location->components[0]->arg);
6586 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6587 assert (lit);
6588
6589 // Evaluate glob here, and call derive_probes recursively with each match.
6590 glob_t the_blob;
6591 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3
LB
6592 if (rc)
6593 throw semantic_error (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
37001baa
FCE
6594 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6595 {
e19ebcf7 6596 assert_no_interrupts();
37001baa
FCE
6597
6598 const char* globbed = the_blob.gl_pathv[i];
6599 struct stat st;
6600
6601 if (access (globbed, X_OK) == 0
6602 && stat (globbed, &st) == 0
6603 && S_ISREG (st.st_mode)) // see find_executable()
6604 {
7977a734
FCE
6605 // Need to call canonicalize here, in order to path-expand
6606 // patterns like process("stap*"). Otherwise it may go through
6607 // to the next round of expansion as ("stap"), leading to a $PATH
6608 // search that's not consistent with the glob search already done.
6609
6610 char *cf = canonicalize_file_name (globbed);
6611 if (cf) globbed = cf;
6612
37001baa
FCE
6613 // synthesize a new probe_point, with the glob-expanded string
6614 probe_point *pp = new probe_point (*location);
5750ecc6
FCE
6615 // PR13338: quote results to prevent recursion
6616 string eglobbed = escape_glob_chars (globbed);
6617
6618 if (sess.verbose > 1)
6619 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6620 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 6621 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 6622
37001baa 6623 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6624 new literal_string (eglobbed_tgt));
37001baa
FCE
6625 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6626 pp->components[0] = ppc;
6627
7977a734
FCE
6628 probe* new_probe = new probe (*base, pp);
6629
6630 // We override "optional = true" here, as if the
6631 // wildcarded probe point was given a "?" suffix.
6632
6633 // This is because wildcard probes will be expected
6634 // by users to apply only to some subset of the
6635 // matching binaries, in the sense of "any", rather
6636 // than "all", sort of similarly how
6637 // module("*").function("...") patterns work.
6638
6639 derive_probes (sess, new_probe, finished_results,
6640 true /* NB: not location->optional */ );
37001baa
FCE
6641 }
6642 }
6643
6644 globfree (& the_blob);
6645 return; // avoid falling through
6646 }
6647
5750ecc6
FCE
6648 // PR13338: unquote glob results
6649 module_name = unescape_glob_chars (module_name);
05fb3e0c 6650 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
6651
6652 // if the executable starts with "#!", we look for the interpreter of the script
6653 {
6654 ifstream script_file (user_path.c_str () );
6655
6656 if (script_file.good ())
6657 {
6658 string line;
6659
6660 getline (script_file, line);
6661
6662 if (line.compare (0, 2, "#!") == 0)
6663 {
6664 string path_head = line.substr(2);
6665
6666 // remove white spaces at the beginning of the string
6667 size_t p2 = path_head.find_first_not_of(" \t");
6668
6669 if (p2 != string::npos)
6670 {
6671 string path = path_head.substr(p2);
6672
6673 // remove white spaces at the end of the string
6674 p2 = path.find_last_not_of(" \t\n");
6675 if (string::npos != p2)
6676 path.erase(p2+1);
6677
8e13c1a1
RH
6678 // handle "#!/usr/bin/env" redirect
6679 size_t offset = 0;
6680 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
6681 {
6682 offset = sizeof("/bin/env")-1;
6683 }
6684 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
6685 {
6686 offset = sizeof("/usr/bin/env")-1;
6687 }
6688
6689 if (offset != 0)
6690 {
6691 size_t p3 = path.find_first_not_of(" \t", offset);
6692
6693 if (p3 != string::npos)
6694 {
6695 string env_path = path.substr(p3);
05fb3e0c
WF
6696 user_path = find_executable (env_path, sess.sysroot,
6697 sess.sysenv);
8e13c1a1
RH
6698 }
6699 }
6700 else
6701 {
05fb3e0c 6702 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 6703 }
d1bcbe71
RH
6704
6705 struct stat st;
6706
6707 if (access (user_path.c_str(), X_OK) == 0
6708 && stat (user_path.c_str(), &st) == 0
6709 && S_ISREG (st.st_mode)) // see find_executable()
6710 {
6711 if (sess.verbose > 1)
b530b5b3
LB
6712 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6713 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
6714
6715 assert (location->components.size() > 0);
6716 assert (location->components[0]->functor == TOK_PROCESS);
6717 assert (location->components[0]->arg);
6718 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6719 assert (lit);
6720
6721 // synthesize a new probe_point, with the expanded string
6722 probe_point *pp = new probe_point (*location);
05fb3e0c 6723 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 6724 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6725 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
6726 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6727 pp->components[0] = ppc;
6728
6729 probe* new_probe = new probe (*base, pp);
6730
6731 derive_probes (sess, new_probe, finished_results);
6732
6733 script_file.close();
6734 return;
6735 }
6736 }
6737 }
6738 }
6739 script_file.close();
6740 }
6741
47e226ed 6742 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 6743 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
6744 {
6745 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
6746 "LD_LIBRARY_PATH");
6747 if (module_name.find('/') == string::npos)
6748 // We didn't find user_lib so use iterate_over_libraries
6749 module_name = user_path;
6750 }
63b4fd14 6751 else
b642c901 6752 module_name = user_path; // canonicalize it
d0a7f5a9 6753
3667d615 6754 // uretprobes aren't available everywhere
536f1261 6755 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 6756 {
3667d615
JS
6757 if (kernel_supports_inode_uprobes(sess) &&
6758 !kernel_supports_inode_uretprobes(sess))
2b69faaf 6759 throw semantic_error
3ffeaf3c 6760 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 6761 }
3667d615 6762
f4000852
MW
6763 // There is a similar check in pass 4 (buildrun), but it is
6764 // needed here too to make sure alternatives for optional
6765 // (? or !) process probes are disposed and/or alternatives
6766 // are selected.
3667d615
JS
6767 if (!sess.runtime_usermode_p())
6768 check_process_probe_kernel_support(sess);
e34d5d13 6769
7a24d422
FCE
6770 // user-space target; we use one dwflpp instance per module name
6771 // (= program or shared library)
707bf35e 6772 dw = get_user_dw(sess, module_name);
c8959a29 6773 }
20c6c071 6774
5896cd05 6775 if (sess.verbose > 3)
b530b5b3 6776 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 6777
a794dbeb
FCE
6778 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
6779 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 6780 {
d8f31d0a 6781 assert(dw);
51d6bda3 6782 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
6783 dw->iterate_over_modules(&query_module, &sdtq);
6784 return;
7a05f484 6785 }
20c6c071 6786
8f14e444 6787 unsigned results_pre = finished_results.size();
6d5d594e 6788 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
6789
6790 // XXX: kernel.statement.absolute is a special case that requires no
6791 // dwfl processing. This code should be in a separate builder.
7a24d422 6792 if (q.has_kernel && q.has_absolute)
37ebca01 6793 {
4baf0e53 6794 // assert guru mode for absolute probes
37ebca01
FCE
6795 if (! q.base_probe->privileged)
6796 {
e3bbc038 6797 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 6798 q.base_probe->tok);
37ebca01
FCE
6799 }
6800
6801 // For kernel.statement(NUM).absolute probe points, we bypass
6802 // all the debuginfo stuff: We just wire up a
6803 // dwarf_derived_probe right here and now.
4baf0e53 6804 dwarf_derived_probe* p =
b8da0ad1
FCE
6805 new dwarf_derived_probe ("", "", 0, "kernel", "",
6806 q.statement_num_val, q.statement_num_val,
6807 q, 0);
37ebca01 6808 finished_results.push_back (p);
1a0dbc5a 6809 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
6810 return;
6811 }
6812
51178501 6813 dw->iterate_over_modules(&query_module, &q);
8f14e444
FCE
6814
6815
6816 // PR11553 special processing: .return probes requested, but
6817 // some inlined function instances matched.
6818 unsigned i_n_r = q.inlined_non_returnable.size();
6819 unsigned results_post = finished_results.size();
6820 if (i_n_r > 0)
6821 {
6822 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
6823 {
6824 string quicklist;
6825 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6826 it != q.inlined_non_returnable.end();
6827 it++)
6828 {
6829 quicklist += " " + (*it);
6830 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
6831 {
6832 quicklist += " ...";
6833 break;
6834 }
6835 }
c57ea854 6836
b530b5b3
LB
6837 sess.print_warning (_F(ngettext("cannot probe .return of %u inlined function %s",
6838 "cannot probe .return of %u inlined functions %s",
6839 quicklist.size()), i_n_r, quicklist.c_str()));
8f14e444
FCE
6840 // There will be also a "no matches" semantic error generated.
6841 }
6842 if (sess.verbose > 1)
b530b5b3
LB
6843 clog << _F(ngettext("skipped .return probe of %u inlined function",
6844 "skipped .return probe of %u inlined functions", i_n_r), i_n_r) << endl;
8f14e444
FCE
6845 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
6846 {
6847 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6848 it != q.inlined_non_returnable.end();
6849 it++)
6850 clog << (*it) << " ";
6851 clog << endl;
6852 }
6853 } // i_n_r > 0
5f0a03a6
JK
6854}
6855
6856symbol_table::~symbol_table()
6857{
c9efa5c9 6858 delete_map(map_by_addr);
5f0a03a6
JK
6859}
6860
6861void
2867a2a1 6862symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
822a6a3d 6863 Dwarf_Addr addr, Dwarf_Addr */*high_addr*/)
5f0a03a6 6864{
ab91b232
JK
6865#ifdef __powerpc__
6866 // Map ".sys_foo" to "sys_foo".
6867 if (name[0] == '.')
6868 name++;
6869#endif
5f0a03a6
JK
6870 func_info *fi = new func_info();
6871 fi->addr = addr;
6872 fi->name = name;
ab91b232 6873 fi->weak = weak;
2867a2a1 6874 fi->descriptor = descriptor;
5f0a03a6
JK
6875 map_by_name[fi->name] = fi;
6876 // TODO: Use a multimap in case there are multiple static
6877 // functions with the same name?
1c6b77e5 6878 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
6879}
6880
6881enum info_status
6882symbol_table::read_symbols(FILE *f, const string& path)
6883{
6884 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
6885 int ret;
2e67a43b
TM
6886 char *name = 0;
6887 char *mod = 0;
5f0a03a6
JK
6888 char type;
6889 unsigned long long addr;
6890 Dwarf_Addr high_addr = 0;
6891 int line = 0;
6892
62a4021d
FCE
6893#if __GLIBC__ >2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)
6894#define MS_FMT "%ms"
6895#else
6896#define MS_FMT "%as"
6897#endif
6898 // %ms (newer than %as) mallocs space for the string and stores its address.
6899 while ((ret = fscanf(f, "%llx %c " MS_FMT " [" MS_FMT, &addr, &type, &name, &mod)) > 0)
5f0a03a6 6900 {
2e67a43b
TM
6901 auto_free free_name(name);
6902 auto_free free_mod(mod);
5f0a03a6
JK
6903 line++;
6904 if (ret < 3)
6905 {
3d372d6b 6906 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 6907 line, path.c_str());
5f0a03a6
JK
6908 // Caller should delete symbol_table object.
6909 return info_absent;
6910 }
2e67a43b 6911 else if (ret > 3)
5f0a03a6
JK
6912 {
6913 // Modules are loaded above the kernel, so if we're getting
6914 // modules, we're done.
2e67a43b 6915 break;
5f0a03a6 6916 }
ab91b232 6917 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 6918 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
6919 }
6920
1c6b77e5 6921 if (map_by_addr.size() < 1)
5f0a03a6 6922 {
3d372d6b 6923 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 6924 path.c_str()) << endl;
5f0a03a6
JK
6925 return info_absent;
6926 }
6927 return info_present;
6928}
6929
6930// NB: This currently unused. We use get_from_elf() instead because
6931// that gives us raw addresses -- which we need for modules -- whereas
6932// nm provides the address relative to the beginning of the section.
6933enum info_status
83ca3872 6934symbol_table::read_from_elf_file(const string &path,
2713ea24 6935 systemtap_session &sess)
5f0a03a6 6936{
58502ae4
JS
6937 vector<string> cmd;
6938 cmd.push_back("/usr/bin/nm");
6939 cmd.push_back("-n");
6940 cmd.push_back("--defined-only");
6941 cmd.push_back("path");
6942
5f0a03a6 6943 FILE *f;
58502ae4
JS
6944 int child_fd;
6945 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
6946 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 6947 {
58502ae4 6948 // nm failures are detected by stap_waitpid
3d372d6b 6949 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 6950 path.c_str(), strerror(errno));
5f0a03a6
JK
6951 return info_absent;
6952 }
6953 enum info_status status = read_symbols(f, path);
58502ae4 6954 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 6955 {
2713ea24
CM
6956 if (status == info_present)
6957 sess.print_warning("nm cannot read symbol table from " + path);
5f0a03a6
JK
6958 return info_absent;
6959 }
6960 return status;
6961}
6962
6963enum info_status
83ca3872 6964symbol_table::read_from_text_file(const string& path,
2713ea24 6965 systemtap_session &sess)
5f0a03a6
JK
6966{
6967 FILE *f = fopen(path.c_str(), "r");
6968 if (!f)
6969 {
2713ea24 6970 sess.print_warning("cannot read symbol table from " + path + " -- " + strerror(errno));
5f0a03a6
JK
6971 return info_absent;
6972 }
6973 enum info_status status = read_symbols(f, path);
6974 (void) fclose(f);
6975 return status;
6976}
6977
46f7b6be 6978void
f98c6346 6979symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
6980{
6981#ifdef __powerpc__
6982 /*
6983 * The .opd section contains function descriptors that can look
6984 * just like function entry points. For example, there's a function
6985 * descriptor called "do_exit" that links to the entry point ".do_exit".
6986 * Reject all symbols in .opd.
6987 */
6988 opd_section = SHN_UNDEF;
6989 Dwarf_Addr bias;
6990 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
6991 ?: dwfl_module_getelf (mod, &bias));
6992 Elf_Scn* scn = 0;
6993 size_t shstrndx;
6994
6995 if (!elf)
6996 return;
fcc30d6d 6997 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
6998 return;
6999 while ((scn = elf_nextscn(elf, scn)) != NULL)
7000 {
7001 GElf_Shdr shdr_mem;
7002 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7003 if (!shdr)
7004 continue;
7005 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7006 if (!strcmp(name, ".opd"))
7007 {
7008 opd_section = elf_ndxscn(scn);
7009 return;
7010 }
7011 }
7012#endif
7013}
7014
7015bool
7016symbol_table::reject_section(GElf_Word section)
7017{
7018 if (section == SHN_UNDEF)
7019 return true;
7020#ifdef __powerpc__
7021 if (section == opd_section)
7022 return true;
7023#endif
7024 return false;
7025}
7026
5f0a03a6
JK
7027enum info_status
7028symbol_table::get_from_elf()
7029{
7030 Dwarf_Addr high_addr = 0;
7031 Dwfl_Module *mod = mod_info->mod;
7032 int syments = dwfl_module_getsymtab(mod);
7033 assert(syments);
46f7b6be 7034 prepare_section_rejection(mod);
5f0a03a6
JK
7035 for (int i = 1; i < syments; ++i)
7036 {
7037 GElf_Sym sym;
ab91b232
JK
7038 GElf_Word section;
7039 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 7040 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7041 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 7042 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
7043 }
7044 return info_present;
7045}
7046
5f0a03a6
JK
7047func_info *
7048symbol_table::get_func_containing_address(Dwarf_Addr addr)
7049{
1c6b77e5
JS
7050 iterator_t iter = map_by_addr.upper_bound(addr);
7051 if (iter == map_by_addr.begin())
5f0a03a6 7052 return NULL;
2e67a43b 7053 else
1c6b77e5 7054 return (--iter)->second;
5f0a03a6
JK
7055}
7056
3d372d6b
SC
7057func_info *
7058symbol_table::get_first_func()
7059{
7060 iterator_t iter = map_by_addr.begin();
7061 return (iter)->second;
7062}
7063
5f0a03a6
JK
7064func_info *
7065symbol_table::lookup_symbol(const string& name)
7066{
7067 map<string, func_info*>::iterator i = map_by_name.find(name);
7068 if (i == map_by_name.end())
7069 return NULL;
7070 return i->second;
7071}
7072
7073Dwarf_Addr
7074symbol_table::lookup_symbol_address(const string& name)
7075{
7076 func_info *fi = lookup_symbol(name);
7077 if (fi)
7078 return fi->addr;
7079 return 0;
7080}
7081
ab91b232
JK
7082// This is the kernel symbol table. The kernel macro cond_syscall creates
7083// a weak symbol for each system call and maps it to sys_ni_syscall.
7084// For system calls not implemented elsewhere, this weak symbol shows up
7085// in the kernel symbol table. Following the precedent of dwarfful stap,
7086// we refuse to consider such symbols. Here we delete them from our
7087// symbol table.
7088// TODO: Consider generalizing this and/or making it part of blacklist
7089// processing.
7090void
7091symbol_table::purge_syscall_stubs()
7092{
7093 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7094 if (stub_addr == 0)
7095 return;
1c6b77e5 7096 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7097 for (iterator_t iter = purge_range.first;
7098 iter != purge_range.second;
1c6b77e5 7099 )
ab91b232 7100 {
1c6b77e5 7101 func_info *fi = iter->second;
2e67a43b 7102 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7103 {
2e67a43b 7104 map_by_name.erase(fi->name);
1c6b77e5 7105 map_by_addr.erase(iter++);
2e67a43b 7106 delete fi;
2e67a43b 7107 }
1c6b77e5
JS
7108 else
7109 iter++;
ab91b232
JK
7110 }
7111}
7112
5f0a03a6
JK
7113void
7114module_info::get_symtab(dwarf_query *q)
7115{
1c6b77e5
JS
7116 if (symtab_status != info_unknown)
7117 return;
7118
5f0a03a6
JK
7119 sym_table = new symbol_table(this);
7120 if (!elf_path.empty())
7121 {
5f0a03a6
JK
7122 symtab_status = sym_table->get_from_elf();
7123 }
7124 else
7125 {
7126 assert(name == TOK_KERNEL);
ab3ed72d
DS
7127 symtab_status = info_absent;
7128 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
7129 }
7130 if (symtab_status == info_absent)
7131 {
7132 delete sym_table;
7133 sym_table = NULL;
7134 return;
7135 }
7136
ab91b232
JK
7137 if (name == TOK_KERNEL)
7138 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7139}
7140
1c6b77e5
JS
7141// update_symtab reconciles data between the elf symbol table and the dwarf
7142// function enumeration. It updates the symbol table entries with the dwarf
7143// die that describes the function, which also signals to query_module_symtab
7144// that a statement probe isn't needed. In return, it also adds aliases to the
7145// function table for names that share the same addr/die.
7146void
7147module_info::update_symtab(cu_function_cache_t *funcs)
7148{
7149 if (!sym_table)
7150 return;
7151
7152 cu_function_cache_t new_funcs;
7153
7154 for (cu_function_cache_t::iterator func = funcs->begin();
7155 func != funcs->end(); func++)
7156 {
7157 // optimization: inlines will never be in the symbol table
7158 if (dwarf_func_inline(&func->second) != 0)
7159 continue;
7160
1ffb8bd1
JS
7161 // XXX We may want to make additional efforts to match mangled elf names
7162 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
7163 // missing, so we may also need to try matching by address. See also the
7164 // notes about _Z in dwflpp::iterate_over_functions().
7165
1c6b77e5
JS
7166 func_info *fi = sym_table->lookup_symbol(func->first);
7167 if (!fi)
7168 continue;
7169
7170 // iterate over all functions at the same address
7171 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
7172 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
7173 {
7174 // update this function with the dwarf die
7175 it->second->die = func->second;
7176
7177 // if this function is a new alias, then
7178 // save it to merge into the function cache
7179 if (it->second != fi)
b7478964 7180 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
7181 }
7182 }
7183
7184 // add all discovered aliases back into the function cache
7185 // NB: this won't replace any names that dwarf may have already found
7186 funcs->insert(new_funcs.begin(), new_funcs.end());
7187}
7188
5f0a03a6
JK
7189module_info::~module_info()
7190{
7191 if (sym_table)
7192 delete sym_table;
b55bc428
FCE
7193}
7194
935447c8 7195// ------------------------------------------------------------------------
888af770 7196// user-space probes
935447c8
DS
7197// ------------------------------------------------------------------------
7198
935447c8 7199
888af770 7200struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7201{
89ba3085
FCE
7202private:
7203 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 7204 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
7205 }
7206
cfcab6c7
JS
7207 void emit_module_maxuprobes (systemtap_session& s);
7208
2b69faaf
JS
7209 // Using our own utrace-based uprobes
7210 void emit_module_utrace_decls (systemtap_session& s);
7211 void emit_module_utrace_init (systemtap_session& s);
7212 void emit_module_utrace_exit (systemtap_session& s);
7213
7214 // Using the upstream inode-based uprobes
7215 void emit_module_inode_decls (systemtap_session& s);
7216 void emit_module_inode_init (systemtap_session& s);
7217 void emit_module_inode_exit (systemtap_session& s);
7218
3a894f7e
JS
7219 // Using the dyninst backend (via stapdyn)
7220 void emit_module_dyninst_decls (systemtap_session& s);
7221 void emit_module_dyninst_init (systemtap_session& s);
7222 void emit_module_dyninst_exit (systemtap_session& s);
7223
935447c8 7224public:
888af770 7225 void emit_module_decls (systemtap_session& s);
935447c8
DS
7226 void emit_module_init (systemtap_session& s);
7227 void emit_module_exit (systemtap_session& s);
7228};
7229
7230
888af770
FCE
7231void
7232uprobe_derived_probe::join_group (systemtap_session& s)
7233{
7234 if (! s.uprobe_derived_probes)
7235 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7236 s.uprobe_derived_probes->enroll (this);
ac3af990 7237 if (!s.runtime_usermode_p())
4441e344 7238 enable_task_finder(s);
a96d1db0 7239
8a03658e 7240 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
7241 // signal staprun to load that module. If we're using the builtin
7242 // inode-uprobes, we still need to know that it is required.
8a03658e 7243 s.need_uprobes = true;
a96d1db0
DN
7244}
7245
888af770 7246
c0f84e7b
SC
7247void
7248uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7249{
7250 dwarf_derived_probe::getargs(arg_set);
7251 arg_set.insert(arg_set.end(), args.begin(), args.end());
7252}
7253
7254
7255void
7256uprobe_derived_probe::saveargs(int nargs)
7257{
7258 for (int i = 1; i <= nargs; i++)
7259 args.push_back("$arg" + lex_cast (i) + ":long");
7260}
7261
7262
2865d17a 7263void
42e38653 7264uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
7265{
7266 // These probes are allowed for unprivileged users, but only in the
7267 // context of processes which they own.
7268 emit_process_owner_assertion (o);
7269}
7270
7271
888af770 7272struct uprobe_builder: public derived_probe_builder
a96d1db0 7273{
888af770 7274 uprobe_builder() {}
2b69faaf 7275 virtual void build(systemtap_session & sess,
a96d1db0
DN
7276 probe * base,
7277 probe_point * location,
86bf665e 7278 literal_map_t const & parameters,
a96d1db0
DN
7279 vector<derived_probe *> & finished_results)
7280 {
888af770 7281 int64_t process, address;
a96d1db0 7282
2b69faaf 7283 if (kernel_supports_inode_uprobes(sess))
3ffeaf3c 7284 throw semantic_error (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 7285
888af770 7286 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7287 (void) b1;
888af770 7288 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7289 (void) b2;
888af770
FCE
7290 bool rr = has_null_param (parameters, TOK_RETURN);
7291 assert (b1 && b2); // by pattern_root construction
a96d1db0 7292
0973d815 7293 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7294 }
7295};
7296
7297
7298void
cfcab6c7 7299uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 7300{
43241c44
FCE
7301 // We'll probably need at least this many:
7302 unsigned minuprobes = probes.size();
7303 // .. but we don't want so many that .bss is inflated (PR10507):
7304 unsigned uprobesize = 64;
7305 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7306 unsigned maxuprobes = maxuprobesmem / uprobesize;
7307
aaf7ffe8
FCE
7308 // Let's choose a value on the geometric middle. This should end up
7309 // between minuprobes and maxuprobes. It's OK if this number turns
7310 // out to be < minuprobes or > maxuprobes. At worst, we get a
7311 // run-time error of one kind (too few: missed uprobe registrations)
7312 // or another (too many: vmalloc errors at module load time).
7313 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7314
6d0f3f0c 7315 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7316 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7317 s.op->newline() << "#endif";
cfcab6c7
JS
7318}
7319
7320
7321void
7322uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
7323{
7324 if (probes.empty()) return;
7325 s.op->newline() << "/* ---- utrace uprobes ---- */";
7326 // If uprobes isn't in the kernel, pull it in from the runtime.
7327
7328 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7329 s.op->newline() << "#include <linux/uprobes.h>";
7330 s.op->newline() << "#else";
2ba1736a 7331 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
7332 s.op->newline() << "#endif";
7333 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7334 s.op->newline() << "#define UPROBES_API_VERSION 1";
7335 s.op->newline() << "#endif";
7336
7337 emit_module_maxuprobes (s);
a96d1db0 7338
cc52276b 7339 // Forward decls
2ba1736a 7340 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 7341
5e112f92
FCE
7342 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7343 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7344 // XXX: consider a slab cache or somesuch for stap_uprobes
7345 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 7346 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7347
89ba3085
FCE
7348 s.op->assert_0_indent();
7349
89ba3085
FCE
7350 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7351 // This means we process probes[] in two passes.
7352 map <string,unsigned> module_index;
7353 unsigned module_index_ctr = 0;
7354
cc52276b
WC
7355 // not const since embedded task_finder_target struct changes
7356 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7357 s.op->indent(1);
7358 for (unsigned i=0; i<probes.size(); i++)
7359 {
7360 uprobe_derived_probe *p = probes[i];
7361 string pbmkey = make_pbm_key (p);
7362 if (module_index.find (pbmkey) == module_index.end())
7363 {
7364 module_index[pbmkey] = module_index_ctr++;
7365
7366 s.op->newline() << "{";
7367 // NB: it's essential that make_pbm_key() use all of and
7368 // only the same fields as we're about to emit.
7369 s.op->line() << " .finder={";
1af100fc 7370 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 7371 if (p->pid != 0)
68910c97
JK
7372 s.op->line() << " .pid=" << p->pid << ",";
7373
7374 if (p->section == "") // .statement(addr).absolute
7375 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7376 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7377 {
7378 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7379 s.op->line() << " .callback=&stap_uprobe_process_found,";
7380 }
68910c97 7381 else if (p->section != ".absolute") // ET_DYN
89ba3085 7382 {
4ad95bbc
SC
7383 if (p->has_library)
7384 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7385 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7386 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7387 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7388 }
89ba3085 7389 s.op->line() << " },";
68910c97
JK
7390 if (p->module != "")
7391 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7392 s.op->line() << " },";
7393 }
c57ea854 7394 else
822a6a3d 7395 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7396 }
7397 s.op->newline(-1) << "};";
7398
7399 s.op->assert_0_indent();
7400
cc52276b
WC
7401 // NB: read-only structure
7402 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7403 s.op->indent(1);
888af770
FCE
7404 for (unsigned i =0; i<probes.size(); i++)
7405 {
7406 uprobe_derived_probe* p = probes[i];
7407 s.op->newline() << "{";
89ba3085
FCE
7408 string key = make_pbm_key (p);
7409 unsigned value = module_index[key];
759e1d76
FCE
7410 if (value != 0)
7411 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7412 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7413 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7414
038c38c6 7415 if (p->sdt_semaphore_addr != 0)
63b4fd14 7416 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7417 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0
JS
7418
7419 if (p->has_return)
7420 s.op->line() << " .return_p=1,";
888af770
FCE
7421 s.op->line() << " },";
7422 }
7423 s.op->newline(-1) << "};";
a96d1db0 7424
89ba3085
FCE
7425 s.op->assert_0_indent();
7426
48e685da 7427 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7428 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7429 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7430 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7431 "stp_probe_type_uprobe");
0e090c74 7432 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7433 << "sup->spec_index >= " << probes.size() << ") {";
7434 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7435 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7436 s.op->newline() << "atomic_dec (&c->busy);";
7437 s.op->newline() << "goto probe_epilogue;";
7438 s.op->newline(-1) << "}";
d9aed31e 7439 s.op->newline() << "c->uregs = regs;";
e04b5d74 7440 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7441
7442 // Make it look like the IP is set as it would in the actual user
7443 // task when calling real probe handler. Reset IP regs on return, so
7444 // we don't confuse uprobes. PR10458
7445 s.op->newline() << "{";
7446 s.op->indent(1);
d9aed31e 7447 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7448 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7449 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7450 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7451 s.op->newline(-1) << "}";
7452
f887a8c9 7453 common_probe_entryfn_epilogue (s, true);
888af770 7454 s.op->newline(-1) << "}";
a96d1db0 7455
48e685da 7456 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7457 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7458 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7459 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7460 "stp_probe_type_uretprobe");
6dceb5c9 7461 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7462 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7463 << "sup->spec_index >= " << probes.size() << ") {";
7464 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7465 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7466 s.op->newline() << "atomic_dec (&c->busy);";
7467 s.op->newline() << "goto probe_epilogue;";
7468 s.op->newline(-1) << "}";
7469
d9aed31e 7470 s.op->newline() << "c->uregs = regs;";
e04b5d74 7471 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7472
7473 // Make it look like the IP is set as it would in the actual user
7474 // task when calling real probe handler. Reset IP regs on return, so
7475 // we don't confuse uprobes. PR10458
7476 s.op->newline() << "{";
7477 s.op->indent(1);
d9aed31e 7478 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7479 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7480 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7481 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7482 s.op->newline(-1) << "}";
7483
f887a8c9 7484 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
7485 s.op->newline(-1) << "}";
7486
89ba3085 7487 s.op->newline();
2ba1736a 7488 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 7489 s.op->newline();
888af770 7490}
935447c8
DS
7491
7492
888af770 7493void
2b69faaf 7494uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 7495{
888af770 7496 if (probes.empty()) return;
935447c8 7497
2b69faaf 7498 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 7499
01b05e2e 7500 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
7501 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
7502 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
7503 // NB: we assume the rest of the struct (specificaly, sup->up) is
7504 // initialized to zero. This is so that we can use
7505 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
7506 s.op->newline(-1) << "}";
7507 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 7508
89ba3085
FCE
7509 // Set up the task_finders
7510 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
7511 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 7512 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 7513 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 7514
5e112f92
FCE
7515 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
7516 // finders already registered, since mere registration does not
7517 // cause any utrace or memory allocation actions. That happens only
7518 // later, once the task finder engine starts running. So, for a
7519 // partial initialization requiring unwind, we need do nothing.
7520 s.op->newline() << "if (rc) break;";
a7a68293 7521
888af770
FCE
7522 s.op->newline(-1) << "}";
7523}
d0ea46ce 7524
d0a7f5a9 7525
888af770 7526void
2b69faaf 7527uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
7528{
7529 if (probes.empty()) return;
2b69faaf 7530 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 7531
6d0f3f0c
FCE
7532 // NB: there is no stap_unregister_task_finder_target call;
7533 // important stuff like utrace cleanups are done by
d41d451c
FCE
7534 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7535 //
7536 // This function blocks until all callbacks are completed, so there
7537 // is supposed to be no possibility of any registration-related code starting
7538 // to run in parallel with our shutdown here. So we don't need to protect the
7539 // stap_uprobes[] array with the mutex.
d0a7f5a9 7540
01b05e2e 7541 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7542 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7543 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7544 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7545
8faa1fc5 7546 // PR10655: decrement that ENABLED semaphore
c116c31b 7547 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7548 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7549 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7550 s.op->newline() << "struct task_struct *tsk;";
7551 s.op->newline() << "rcu_read_lock();";
6846cfc8 7552
86229a55
DS
7553 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7554 // that the pid is always in the global namespace, not in any
7555 // private namespace.
8faa1fc5 7556 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7557 // We'd like to call find_task_by_pid_ns() here, but it isn't
7558 // exported. So, we call what it calls...
7559 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7560 s.op->newline() << "#else";
7561 s.op->newline() << " tsk = find_task_by_pid (pid);";
7562 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7563
7564 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7565 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7566 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7567 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7568 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7569 s.op->newline() << "#endif";
3c5b8e2b 7570 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7571 s.op->newline(-1) << "}";
8faa1fc5
FCE
7572 // XXX: need to analyze possibility of race condition
7573 s.op->newline(-1) << "}";
7574 s.op->newline() << "rcu_read_unlock();";
7575 s.op->newline(-1) << "}";
6846cfc8 7576
3568f1dd
FCE
7577 s.op->newline() << "if (sups->return_p) {";
7578 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7579 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 7580 s.op->newline() << "#endif";
80b4ad8b
FCE
7581 // NB: PR6829 does not change that we still need to unregister at
7582 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7583 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7584 s.op->newline(-1) << "} else {";
7585 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7586 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
7587 s.op->newline() << "#endif";
7588 s.op->newline() << "unregister_uprobe (& sup->up);";
7589 s.op->newline(-1) << "}";
935447c8 7590
6d0f3f0c 7591 s.op->newline() << "sup->spec_index = -1;";
935447c8 7592
3568f1dd
FCE
7593 // XXX: uprobe missed counts?
7594
6d0f3f0c 7595 s.op->newline(-1) << "}";
935447c8 7596
5e112f92 7597 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
7598}
7599
2b69faaf
JS
7600
7601void
7602uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
7603{
7604 if (probes.empty()) return;
7605 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 7606 emit_module_maxuprobes (s);
2ba1736a 7607 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
7608
7609 // Write the probe handler.
79af55c3
JS
7610 s.op->newline() << "static int stapiu_probe_handler "
7611 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
7612 s.op->newline(1);
71db462b 7613 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
cda141c2 7614 "stp_probe_type_uprobe");
3bff6634 7615 s.op->newline() << "c->uregs = regs;";
e04b5d74 7616 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 7617 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 7618 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 7619
f887a8c9 7620 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
7621 s.op->newline() << "return 0;";
7622 s.op->newline(-1) << "}";
7623 s.op->assert_0_indent();
7624
7625 // Index of all the modules for which we need inodes.
7626 map<string, unsigned> module_index;
7627 unsigned module_index_ctr = 0;
7628
7629 // Discover and declare targets for each unique path.
cfcab6c7 7630 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
7631 << "stap_inode_uprobe_targets[] = {";
7632 s.op->indent(1);
7633 for (unsigned i=0; i<probes.size(); i++)
7634 {
7635 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
7636 const string key = make_pbm_key(p);
7637 if (module_index.find (key) == module_index.end())
2b69faaf 7638 {
cfcab6c7
JS
7639 module_index[key] = module_index_ctr++;
7640 s.op->newline() << "{";
7641 s.op->line() << " .finder={";
1af100fc 7642 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
7643 if (p->pid != 0)
7644 s.op->line() << " .pid=" << p->pid << ",";
7645
7646 if (p->section == "") // .statement(addr).absolute XXX?
7647 s.op->line() << " .callback=&stapiu_process_found,";
7648 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7649 {
7650 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7651 s.op->line() << " .callback=&stapiu_process_found,";
7652 }
7653 else if (p->section != ".absolute") // ET_DYN
7654 {
7655 if (p->has_library)
7656 s.op->line() << " .procname=\"" << p->path << "\", ";
7657 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
7658 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
7659 s.op->line() << " .callback=&stapiu_process_munmap,";
7660 }
7661 s.op->line() << " },";
7662 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
7663 s.op->line() << " },";
2b69faaf
JS
7664 }
7665 }
7666 s.op->newline(-1) << "};";
7667 s.op->assert_0_indent();
7668
7669 // Declare the actual probes.
cfcab6c7 7670 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
7671 << "stap_inode_uprobe_consumers[] = {";
7672 s.op->indent(1);
7673 for (unsigned i=0; i<probes.size(); i++)
7674 {
7675 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
7676 unsigned index = module_index[make_pbm_key(p)];
7677 s.op->newline() << "{";
79af55c3
JS
7678 if (p->has_return)
7679 s.op->line() << " .return_p=1,";
cfcab6c7
JS
7680 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
7681 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
7682 if (p->sdt_semaphore_addr)
7683 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
7684 << hex << p->sdt_semaphore_addr << dec << "ULL,";
7685 s.op->line() << " .probe=" << common_probe_init (p) << ",";
7686 s.op->line() << " },";
2b69faaf
JS
7687 }
7688 s.op->newline(-1) << "};";
7689 s.op->assert_0_indent();
7690}
7691
7692
7693void
7694uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
7695{
7696 if (probes.empty()) return;
7697 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
7698 // Let stapiu_init() handle reporting errors by setting probe_point
7699 // to NULL.
7700 s.op->newline() << "probe_point = NULL;";
cfcab6c7 7701 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
7702 << "stap_inode_uprobe_targets, "
7703 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
7704 << "stap_inode_uprobe_consumers, "
7705 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
7706}
7707
7708
7709void
7710uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
7711{
7712 if (probes.empty()) return;
7713 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 7714 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
7715 << "stap_inode_uprobe_targets, "
7716 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
7717 << "stap_inode_uprobe_consumers, "
7718 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
7719}
7720
7721
3a894f7e
JS
7722void
7723uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
7724{
7725 if (probes.empty()) return;
7726 s.op->newline() << "/* ---- dyninst uprobes ---- */";
7727 emit_module_maxuprobes (s);
e00f3fb7 7728 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 7729
e00f3fb7
JS
7730 // Assign "task-finder" numbers as we build up the stapdu_target table.
7731 // This means we process probes[] in two passes.
7732 map <string,unsigned> module_index;
7733 unsigned module_index_ctr = 0;
7734
7735 // Discover and declare file targets
7736 s.op->newline() << "static const struct stapdu_target stapdu_targets[] = {";
3a894f7e
JS
7737 s.op->indent(1);
7738 for (unsigned i=0; i<probes.size(); i++)
7739 {
7740 uprobe_derived_probe *p = probes[i];
e00f3fb7
JS
7741 string pbmkey = make_pbm_key (p);
7742 if (module_index.find (pbmkey) == module_index.end())
7743 {
7744 module_index[pbmkey] = module_index_ctr++;
7745
7746 s.op->newline() << "{";
7747 // NB: it's essential that make_pbm_key() use all of and
7748 // only the same fields as we're about to emit.
7749 s.op->line() << " .path=" << lex_cast_qstring(p->module) << ",";
7750 // XXX pid/procname filtering?
7751 s.op->line() << " },";
7752 }
3a894f7e
JS
7753 }
7754 s.op->newline(-1) << "};";
7755 s.op->assert_0_indent();
7756
874d38bf
JS
7757 // loc2c-generated code assumes pt_regs are available, so use this to make
7758 // sure we always have *something* for it to dereference...
7759 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs = {0};";
7760
e00f3fb7
JS
7761 // Declare the individual probes
7762 s.op->newline() << "static struct stapdu_probe stapdu_probes[] = {";
3a894f7e
JS
7763 s.op->indent(1);
7764 for (unsigned i=0; i<probes.size(); i++)
7765 {
7766 uprobe_derived_probe *p = probes[i];
e00f3fb7 7767 unsigned index = module_index[make_pbm_key(p)];
3a894f7e 7768 s.op->newline() << "{";
e00f3fb7
JS
7769 s.op->line() << " .target=" << index << ",";
7770 s.op->line() << " .offset=" << lex_cast_hex(p->addr) << "ULL,";
7771 if (p->sdt_semaphore_addr)
7772 s.op->line() << " .semaphore="
7773 << lex_cast_hex(p->sdt_semaphore_addr) << "ULL,";
536f1261
JS
7774
7775 s.op->line() << " .flags=0";
7776 if (p->has_return)
7777 s.op->line() << "|STAPDYN_PROBE_FLAG_RETURN";
7778 s.op->line() << ",";
7779
3a894f7e
JS
7780 s.op->line() << " .probe=" << common_probe_init (p) << ",";
7781 s.op->line() << " },";
7782 }
7783 s.op->newline(-1) << "};";
7784 s.op->assert_0_indent();
7785
e00f3fb7
JS
7786 s.op->newline() << "#include \"dyninst/uprobes.c\"";
7787
3a894f7e
JS
7788 // Write the probe handler.
7789 // NB: not static, so dyninst can find it
7790 s.op->newline() << "int enter_dyninst_uprobe "
7791 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 7792 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
71db462b 7793 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
cda141c2 7794 "stp_probe_type_uprobe");
874d38bf 7795 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 7796 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
7797 // XXX: once we have regs, check how dyninst sets the IP
7798 // XXX: the way that dyninst rewrites stuff is probably going to be
7799 // ... very confusing to our backtracer (at least if we stay in process)
7800 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 7801 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
7802 s.op->newline() << "return 0;";
7803 s.op->newline(-1) << "}";
7804 s.op->assert_0_indent();
7805}
7806
7807
7808void
7809uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
7810{
7811 if (probes.empty()) return;
7812
7813 /* stapdyn handles the dirty work via dyninst */
7814 s.op->newline() << "/* ---- dyninst uprobes ---- */";
7815 s.op->newline() << "/* this section left intentionally blank */";
7816}
7817
7818
7819void
7820uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
7821{
7822 if (probes.empty()) return;
7823
7824 /* stapdyn handles the dirty work via dyninst */
7825 s.op->newline() << "/* ---- dyninst uprobes ---- */";
7826 s.op->newline() << "/* this section left intentionally blank */";
7827}
7828
7829
2b69faaf
JS
7830void
7831uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
7832{
ac3af990 7833 if (s.runtime_usermode_p())
4441e344
JS
7834 emit_module_dyninst_decls (s);
7835 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
7836 emit_module_inode_decls (s);
7837 else
7838 emit_module_utrace_decls (s);
7839}
7840
7841
7842void
7843uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
7844{
ac3af990 7845 if (s.runtime_usermode_p())
4441e344
JS
7846 emit_module_dyninst_init (s);
7847 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
7848 emit_module_inode_init (s);
7849 else
7850 emit_module_utrace_init (s);
7851}
7852
7853
7854void
7855uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
7856{
ac3af990 7857 if (s.runtime_usermode_p())
4441e344
JS
7858 emit_module_dyninst_exit (s);
7859 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
7860 emit_module_inode_exit (s);
7861 else
7862 emit_module_utrace_exit (s);
7863}
7864
7865
e6fe60e7
AM
7866// ------------------------------------------------------------------------
7867// Kprobe derived probes
7868// ------------------------------------------------------------------------
7869
4627ed58 7870static const string TOK_KPROBE("kprobe");
935447c8 7871
bae55db9 7872struct kprobe_derived_probe: public derived_probe
d0ea46ce 7873{
23dc94f6
DS
7874 kprobe_derived_probe (systemtap_session& sess,
7875 vector<derived_probe *> & results,
7876 probe *base,
bae55db9
JS
7877 probe_point *location,
7878 const string& name,
7879 int64_t stmt_addr,
7880 bool has_return,
7881 bool has_statement,
7882 bool has_maxactive,
b642c901
SC
7883 bool has_path,
7884 bool has_library,
7885 long maxactive_val,
7886 const string& path,
7887 const string& library
bae55db9
JS
7888 );
7889 string symbol_name;
7890 Dwarf_Addr addr;
7891 bool has_return;
7892 bool has_statement;
7893 bool has_maxactive;
b642c901
SC
7894 bool has_path;
7895 bool has_library;
bae55db9 7896 long maxactive_val;
b642c901
SC
7897 string path;
7898 string library;
bae55db9
JS
7899 bool access_var;
7900 void printsig (std::ostream &o) const;
7901 void join_group (systemtap_session& s);
7902};
d0ea46ce 7903
bae55db9
JS
7904struct kprobe_derived_probe_group: public derived_probe_group
7905{
7906private:
7907 multimap<string,kprobe_derived_probe*> probes_by_module;
7908 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 7909
bae55db9
JS
7910public:
7911 void enroll (kprobe_derived_probe* probe);
7912 void emit_module_decls (systemtap_session& s);
7913 void emit_module_init (systemtap_session& s);
7914 void emit_module_exit (systemtap_session& s);
7915};
d0ea46ce 7916
23dc94f6
DS
7917struct kprobe_var_expanding_visitor: public var_expanding_visitor
7918{
7919 systemtap_session& sess;
7920 block *add_block;
7921 block *add_call_probe; // synthesized from .return probes with saved $vars
7922 bool add_block_tid, add_call_probe_tid;
bd5b25e1 7923 bool has_return;
23dc94f6 7924
bd5b25e1 7925 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 7926 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
7927 add_block_tid(false), add_call_probe_tid(false),
7928 has_return(has_return) {}
23dc94f6
DS
7929
7930 void visit_entry_op (entry_op* e);
7931};
7932
7933
7934kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
7935 vector<derived_probe *> & results,
7936 probe *base,
e6fe60e7 7937 probe_point *location,
b6371390 7938 const string& name,
e6fe60e7 7939 int64_t stmt_addr,
b6371390
JS
7940 bool has_return,
7941 bool has_statement,
7942 bool has_maxactive,
b642c901
SC
7943 bool has_path,
7944 bool has_library,
7945 long maxactive_val,
7946 const string& path,
7947 const string& library
b6371390 7948 ):
4c5d1300 7949 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 7950 symbol_name (name), addr (stmt_addr),
b6371390 7951 has_return (has_return), has_statement (has_statement),
b642c901
SC
7952 has_maxactive (has_maxactive), has_path (has_path),
7953 has_library (has_library),
7954 maxactive_val (maxactive_val),
7955 path (path), library (library)
e6fe60e7
AM
7956{
7957 this->tok = base->tok;
7958 this->access_var = false;
d0ea46ce 7959
e6fe60e7
AM
7960#ifndef USHRT_MAX
7961#define USHRT_MAX 32767
7962#endif
d0ea46ce 7963
46856d8d
JS
7964 // Expansion of $target variables in the probe body produces an error during
7965 // translate phase, since we're not using debuginfo
d0ea46ce 7966
e6fe60e7 7967 vector<probe_point::component*> comps;
46856d8d 7968 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 7969
46856d8d
JS
7970 if (has_statement)
7971 {
9ea68eb9
JS
7972 comps.push_back (new probe_point::component(TOK_STATEMENT,
7973 new literal_number(addr, true)));
46856d8d
JS
7974 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
7975 }
7976 else
7977 {
7978 size_t pos = name.find(':');
7979 if (pos != string::npos)
d0ea46ce 7980 {
46856d8d
JS
7981 string module = name.substr(0, pos);
7982 string function = name.substr(pos + 1);
7983 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
7984 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
7985 }
7986 else
7987 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 7988 }
d0ea46ce 7989
b6371390
JS
7990 if (has_return)
7991 comps.push_back (new probe_point::component(TOK_RETURN));
7992 if (has_maxactive)
7993 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 7994
bd5b25e1 7995 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
7996 v.replace (this->body);
7997
7998 // If during target-variable-expanding the probe, we added a new block
7999 // of code, add it to the start of the probe.
8000 if (v.add_block)
8001 this->body = new block(v.add_block, this->body);
8002
8003 // If when target-variable-expanding the probe, we need to
8004 // synthesize a sibling function-entry probe. We don't go through
8005 // the whole probe derivation business (PR10642) that could lead to
8006 // wildcard/alias resolution, or for that dwarf-induced duplication.
8007 if (v.add_call_probe)
8008 {
8009 assert (has_return);
8010
8011 // We temporarily replace base.
8012 statement* old_body = base->body;
8013 base->body = v.add_call_probe;
8014
8015 derived_probe *entry_handler
8016 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8017 false, has_statement, has_maxactive,
8018 has_path, has_library, maxactive_val,
8019 path, library);
8020 results.push_back (entry_handler);
8021
8022 base->body = old_body;
8023 }
8024
e6fe60e7
AM
8025 this->sole_location()->components = comps;
8026}
d0ea46ce 8027
e6fe60e7
AM
8028void kprobe_derived_probe::printsig (ostream& o) const
8029{
8030 sole_location()->print (o);
8031 o << " /* " << " name = " << symbol_name << "*/";
8032 printsig_nested (o);
8033}
d0ea46ce 8034
e6fe60e7
AM
8035void kprobe_derived_probe::join_group (systemtap_session& s)
8036{
d0ea46ce 8037
e6fe60e7
AM
8038 if (! s.kprobe_derived_probes)
8039 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8040 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8041
e6fe60e7 8042}
d0ea46ce 8043
e6fe60e7
AM
8044void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8045{
8046 probes_by_module.insert (make_pair (p->symbol_name, p));
8047 // probes of same symbol should share single kprobe/kretprobe
8048}
d0ea46ce 8049
e6fe60e7
AM
8050void
8051kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8052{
8053 if (probes_by_module.empty()) return;
d0ea46ce 8054
e6fe60e7 8055 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8056
e6fe60e7
AM
8057 // Warn of misconfigured kernels
8058 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8059 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8060 s.op->newline() << "#endif";
8061 s.op->newline();
d0ea46ce 8062
f07c3b68 8063 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8064 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8065 s.op->newline() << "#endif";
8066
e6fe60e7 8067 // Forward declare the master entry functions
88747011 8068 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8069 s.op->line() << " struct pt_regs *regs);";
88747011 8070 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8071 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8072
e6fe60e7
AM
8073 // Emit an array of kprobe/kretprobe pointers
8074 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8075 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8076 s.op->newline() << "#endif";
d0ea46ce 8077
e6fe60e7 8078 // Emit the actual probe list.
d0ea46ce 8079
e6fe60e7
AM
8080 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8081 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8082 s.op->newline() << "#ifdef __ia64__";
8083 s.op->newline() << "struct kprobe dummy;";
8084 s.op->newline() << "#endif";
8085 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8086 // NB: bss!
d0ea46ce 8087
e6fe60e7
AM
8088 s.op->newline() << "static struct stap_dwarfless_probe {";
8089 s.op->newline(1) << "const unsigned return_p:1;";
8090 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8091 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8092 s.op->newline() << "unsigned registered_p:1;";
8093 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 8094
e6fe60e7
AM
8095 // Function Names are mostly small and uniform enough to justify putting
8096 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 8097
faea5e16
JS
8098 size_t symbol_string_name_max = 0;
8099 size_t symbol_string_name_tot = 0;
e6fe60e7 8100 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 8101 {
e6fe60e7
AM
8102 kprobe_derived_probe* p = it->second;
8103#define DOIT(var,expr) do { \
8104 size_t var##_size = (expr) + 1; \
8105 var##_max = max (var##_max, var##_size); \
8106 var##_tot += var##_size; } while (0)
e6fe60e7
AM
8107 DOIT(symbol_string_name, p->symbol_name.size());
8108#undef DOIT
6270adc1
MH
8109 }
8110
e6fe60e7
AM
8111#define CALCIT(var) \
8112 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 8113
e6fe60e7
AM
8114 CALCIT(symbol_string);
8115#undef CALCIT
6270adc1 8116
bd659351 8117 s.op->newline() << "unsigned long address;";
7c3e97f4 8118 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
8119 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
8120 s.op->indent(1);
6270adc1 8121
e6fe60e7
AM
8122 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
8123 {
8124 kprobe_derived_probe* p = it->second;
8125 s.op->newline() << "{";
8126 if (p->has_return)
8127 s.op->line() << " .return_p=1,";
6270adc1 8128
e6fe60e7
AM
8129 if (p->has_maxactive)
8130 {
8131 s.op->line() << " .maxactive_p=1,";
8132 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
8133 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
8134 }
6270adc1 8135
b350f56b
JS
8136 if (p->locations[0]->optional)
8137 s.op->line() << " .optional_p=1,";
8138
e6fe60e7 8139 if (p->has_statement)
c8d9d15e 8140 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 8141 else
c8d9d15e 8142 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 8143
faea5e16 8144 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 8145 s.op->line() << " },";
935447c8
DS
8146 }
8147
e6fe60e7 8148 s.op->newline(-1) << "};";
5d67b47c 8149
e6fe60e7
AM
8150 // Emit the kprobes callback function
8151 s.op->newline();
88747011 8152 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
8153 s.op->line() << " struct pt_regs *regs) {";
8154 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8155 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8156 // Check that the index is plausible
8157 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8158 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8159 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8160 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8161 s.op->line() << "];";
71db462b 8162 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8163 "stp_probe_type_kprobe");
d9aed31e 8164 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
8165
8166 // Make it look like the IP is set as it wouldn't have been replaced
8167 // by a breakpoint instruction when calling real probe handler. Reset
8168 // IP regs on return, so we don't confuse kprobes. PR10458
8169 s.op->newline() << "{";
8170 s.op->indent(1);
d9aed31e 8171 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8172 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 8173 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8174 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8175 s.op->newline(-1) << "}";
8176
f887a8c9 8177 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8178 s.op->newline() << "return 0;";
8179 s.op->newline(-1) << "}";
935447c8 8180
e6fe60e7
AM
8181 // Same for kretprobes
8182 s.op->newline();
88747011 8183 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
8184 s.op->line() << " struct pt_regs *regs) {";
8185 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 8186
e6fe60e7
AM
8187 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8188 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8189 // Check that the index is plausible
8190 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8191 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8192 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8193 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8194 s.op->line() << "];";
935447c8 8195
71db462b 8196 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8197 "stp_probe_type_kretprobe");
d9aed31e 8198 s.op->newline() << "c->kregs = regs;";
6dceb5c9 8199 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
8200
8201 // Make it look like the IP is set as it wouldn't have been replaced
8202 // by a breakpoint instruction when calling real probe handler. Reset
8203 // IP regs on return, so we don't confuse kprobes. PR10458
8204 s.op->newline() << "{";
8205 s.op->indent(1);
d9aed31e 8206 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8207 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 8208 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8209 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8210 s.op->newline(-1) << "}";
8211
f887a8c9 8212 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8213 s.op->newline() << "return 0;";
8214 s.op->newline(-1) << "}";
bd659351 8215
03a4ec63 8216 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8217 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
8218 s.op->newline() << " struct module *owner,";
8219 s.op->newline() << " unsigned long val) {";
8220 s.op->newline(1) << "int i;";
fc1d2aa2
MW
8221 s.op->newline() << "int *p = (int *) data;";
8222 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
8223 << " && *p > 0; i++) {";
bd659351
MW
8224 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8225 s.op->newline() << "if (! sdp->address)";
fc1d2aa2 8226 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 8227 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
8228 s.op->newline() << "(*p)--;";
8229 s.op->newline(-1) << "}";
8230 s.op->newline(-2) << "}";
8231 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 8232 s.op->newline(-1) << "}";
03a4ec63 8233 s.op->newline() << "#endif";
935447c8
DS
8234}
8235
e6fe60e7 8236
6270adc1 8237void
e6fe60e7 8238kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 8239{
03a4ec63 8240 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
8241 s.op->newline() << "{";
8242 s.op->newline(1) << "int p = 0;";
8243 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
8244 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8245 s.op->newline() << "if (! sdp->address)";
8246 s.op->newline(1) << "p++;";
8247 s.op->newline(-2) << "}";
8248 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
8249 s.op->newline(-1) << "}";
03a4ec63 8250 s.op->newline() << "#endif";
bd659351 8251
e6fe60e7 8252 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 8253 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 8254 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 8255 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
8256 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
8257
8258 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8259 s.op->newline() << "if (! addr) {";
8260 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
8261 s.op->newline() << "if (!sdp->optional_p)";
8262 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
8263 s.op->newline(-1) << "continue;";
bd659351 8264 s.op->newline(-1) << "}";
03a4ec63
MW
8265 s.op->newline() << "#endif";
8266
26e63673 8267 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 8268 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 8269 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 8270 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8271 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 8272 s.op->newline() << "#endif";
e6fe60e7
AM
8273 s.op->newline() << "if (sdp->maxactive_p) {";
8274 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
8275 s.op->newline(-1) << "} else {";
f07c3b68 8276 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 8277 s.op->newline(-1) << "}";
88747011 8278 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
8279 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
8280 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8281 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 8282 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8283 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 8284 s.op->newline() << "#endif";
c8d9d15e 8285 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
8286 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8287 s.op->newline() << "if (rc == 0) {";
8288 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
8289 s.op->newline() << "if (rc != 0)";
8290 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8291 s.op->newline(-2) << "}";
8292 s.op->newline() << "#else";
8293 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
8294 s.op->newline() << "#endif";
8295 s.op->newline(-1) << "} else {";
8296 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 8297 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 8298 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8299 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 8300 s.op->newline() << "#endif";
88747011 8301 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 8302 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8303 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 8304 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 8305 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8306 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 8307 s.op->newline() << "#endif";
e6fe60e7
AM
8308 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8309 s.op->newline() << "if (rc == 0) {";
8310 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
8311 s.op->newline() << "if (rc != 0)";
8312 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8313 s.op->newline(-2) << "}";
8314 s.op->newline() << "#else";
8315 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
8316 s.op->newline() << "#endif";
8317 s.op->newline(-1) << "}";
8318 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
8319 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 8320 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 8321 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 8322 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
8323 // XXX: shall we increment numskipped?
8324 s.op->newline(-1) << "}";
6270adc1 8325
e6fe60e7
AM
8326 s.op->newline() << "else sdp->registered_p = 1;";
8327 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
8328}
8329
b4be7cbc 8330
e6fe60e7
AM
8331void
8332kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 8333{
e6fe60e7
AM
8334 //Unregister kprobes by batch interfaces.
8335 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
8336 s.op->newline() << "j = 0;";
8337 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8338 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8339 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8340 s.op->newline() << "if (! sdp->registered_p) continue;";
8341 s.op->newline() << "if (!sdp->return_p)";
c9116e99 8342 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 8343 s.op->newline(-2) << "}";
c9116e99 8344 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8345 s.op->newline() << "j = 0;";
8346 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8347 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8348 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8349 s.op->newline() << "if (! sdp->registered_p) continue;";
8350 s.op->newline() << "if (sdp->return_p)";
c9116e99 8351 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 8352 s.op->newline(-2) << "}";
c9116e99 8353 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8354 s.op->newline() << "#ifdef __ia64__";
8355 s.op->newline() << "j = 0;";
8356 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8357 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8358 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8359 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 8360 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 8361 s.op->newline(-1) << "}";
c9116e99 8362 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8363 s.op->newline() << "#endif";
8364 s.op->newline() << "#endif";
3e3bd7b6 8365
e6fe60e7
AM
8366 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8367 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8368 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8369 s.op->newline() << "if (! sdp->registered_p) continue;";
8370 s.op->newline() << "if (sdp->return_p) {";
8371 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8372 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
8373 s.op->newline() << "#endif";
065d5567 8374 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
8375 s.op->newline() << "#ifdef STP_TIMING";
8376 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 8377 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 8378 s.op->newline(-1) << "#endif";
065d5567 8379 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
8380 s.op->newline() << "#ifdef STP_TIMING";
8381 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 8382 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
8383 s.op->newline(-1) << "#endif";
8384 s.op->newline(-1) << "} else {";
8385 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8386 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
8387 s.op->newline() << "#endif";
065d5567 8388 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
8389 s.op->newline() << "#ifdef STP_TIMING";
8390 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 8391 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
8392 s.op->newline(-1) << "#endif";
8393 s.op->newline(-1) << "}";
8394 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
8395 s.op->newline() << "unregister_kprobe (&kp->dummy);";
8396 s.op->newline() << "#endif";
8397 s.op->newline() << "sdp->registered_p = 0;";
8398 s.op->newline(-1) << "}";
f8a968bc
JS
8399}
8400
e6fe60e7 8401struct kprobe_builder: public derived_probe_builder
3c1b3d06 8402{
9fdf787d 8403public:
2a639817 8404 kprobe_builder() {}
9fdf787d 8405
2a639817 8406 void build_no_more (systemtap_session &s) {}
9fdf787d 8407
e6fe60e7
AM
8408 virtual void build(systemtap_session & sess,
8409 probe * base,
8410 probe_point * location,
8411 literal_map_t const & parameters,
8412 vector<derived_probe *> & finished_results);
8413};
3c1b3d06
FCE
8414
8415
79189b84 8416void
05fb3e0c 8417kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
8418 probe * base,
8419 probe_point * location,
8420 literal_map_t const & parameters,
8421 vector<derived_probe *> & finished_results)
79189b84 8422{
e6fe60e7 8423 string function_string_val, module_string_val;
05fb3e0c 8424 string path, library, path_tgt, library_tgt;
b6371390
JS
8425 int64_t statement_num_val = 0, maxactive_val = 0;
8426 bool has_function_str, has_module_str, has_statement_num;
8427 bool has_absolute, has_return, has_maxactive;
b642c901 8428 bool has_path, has_library;
79189b84 8429
b6371390
JS
8430 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
8431 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
8432 has_return = has_null_param (parameters, TOK_RETURN);
8433 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
8434 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
8435 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
8436 has_path = get_param (parameters, TOK_PROCESS, path);
8437 has_library = get_param (parameters, TOK_LIBRARY, library);
8438
8439 if (has_path)
05fb3e0c
WF
8440 {
8441 path = find_executable (path, sess.sysroot, sess.sysenv);
8442 path_tgt = path_remove_sysroot(sess, path);
8443 }
b642c901 8444 if (has_library)
05fb3e0c
WF
8445 {
8446 library = find_executable (library, sess.sysroot, sess.sysenv,
8447 "LD_LIBRARY_PATH");
8448 library_tgt = path_remove_sysroot(sess, library);
8449 }
c57ea854 8450
b6371390 8451 if (has_function_str)
6fb70fb7 8452 {
2a639817 8453 if (has_module_str)
9fdf787d
DS
8454 {
8455 function_string_val = module_string_val + ":" + function_string_val;
8456 derived_probe *dp
23dc94f6
DS
8457 = new kprobe_derived_probe (sess, finished_results, base,
8458 location, function_string_val,
9fdf787d
DS
8459 0, has_return, has_statement_num,
8460 has_maxactive, has_path, has_library,
8461 maxactive_val, path_tgt, library_tgt);
8462 finished_results.push_back (dp);
8463 }
8464 else
8465 {
2a639817
JS
8466 vector<string> matches;
8467
8468 // Simple names can be found directly
8469 if (function_string_val.find_first_of("*?[") == string::npos)
8470 {
8471 if (sess.kernel_functions.count(function_string_val))
8472 matches.push_back(function_string_val);
8473 }
8474 else // Search function name list for matching names
8475 {
8476 for (set<string>::const_iterator it = sess.kernel_functions.begin();
8477 it != sess.kernel_functions.end(); it++)
8478 // fnmatch returns zero for matching.
8479 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
8480 matches.push_back(*it);
8481 }
86758d5f 8482
2a639817
JS
8483 for (vector<string>::const_iterator it = matches.begin();
8484 it != matches.end(); it++)
9fdf787d 8485 {
2a639817
JS
8486 derived_probe *dp
8487 = new kprobe_derived_probe (sess, finished_results, base,
8488 location, *it, 0, has_return,
8489 has_statement_num,
8490 has_maxactive, has_path,
8491 has_library, maxactive_val,
8492 path_tgt, library_tgt);
8493 finished_results.push_back (dp);
9fdf787d
DS
8494 }
8495 }
6fb70fb7 8496 }
e6fe60e7 8497 else
b6371390
JS
8498 {
8499 // assert guru mode for absolute probes
8500 if ( has_statement_num && has_absolute && !base->privileged )
e3bbc038 8501 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 8502
23dc94f6
DS
8503 finished_results.push_back (new kprobe_derived_probe (sess,
8504 finished_results,
8505 base,
b6371390
JS
8506 location, "",
8507 statement_num_val,
8508 has_return,
8509 has_statement_num,
8510 has_maxactive,
b642c901
SC
8511 has_path,
8512 has_library,
8513 maxactive_val,
05fb3e0c
WF
8514 path_tgt,
8515 library_tgt));
96b030fe 8516 }
79189b84
JS
8517}
8518
23dc94f6
DS
8519
8520void
8521kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
8522{
8523 expression *repl = e;
8524
bd5b25e1
JS
8525 if (has_return)
8526 {
8527 // expand the operand as if it weren't a return probe
8528 has_return = false;
8529 replace (e->operand);
8530 has_return = true;
23dc94f6 8531
bd5b25e1
JS
8532 // XXX it would be nice to use gen_kretprobe_saved_return when
8533 // available, but it requires knowing the types already, which is
8534 // problematic for arbitrary expressons.
8535 repl = gen_mapped_saved_return (sess, e->operand, "entry",
8536 add_block, add_block_tid,
8537 add_call_probe, add_call_probe_tid);
8538 }
23dc94f6
DS
8539 provide (repl);
8540}
8541
8542
dd225250
PS
8543// ------------------------------------------------------------------------
8544// Hardware breakpoint based probes.
8545// ------------------------------------------------------------------------
8546
8547static const string TOK_HWBKPT("data");
8548static const string TOK_HWBKPT_WRITE("write");
8549static const string TOK_HWBKPT_RW("rw");
8550static const string TOK_LENGTH("length");
8551
8552#define HWBKPT_READ 0
8553#define HWBKPT_WRITE 1
8554#define HWBKPT_RW 2
8555struct hwbkpt_derived_probe: public derived_probe
8556{
8557 hwbkpt_derived_probe (probe *base,
8558 probe_point *location,
8559 uint64_t addr,
8560 string symname,
8561 unsigned int len,
8562 bool has_only_read_access,
8563 bool has_only_write_access,
8564 bool has_rw_access
8565 );
8566 Dwarf_Addr hwbkpt_addr;
8567 string symbol_name;
8568 unsigned int hwbkpt_access,hwbkpt_len;
8569
8570 void printsig (std::ostream &o) const;
8571 void join_group (systemtap_session& s);
8572};
8573
8574struct hwbkpt_derived_probe_group: public derived_probe_group
8575{
dd225250 8576private:
dac77b80 8577 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
8578
8579public:
8580 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
8581 void emit_module_decls (systemtap_session& s);
8582 void emit_module_init (systemtap_session& s);
8583 void emit_module_exit (systemtap_session& s);
8584};
8585
8586hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
8587 probe_point *location,
8588 uint64_t addr,
8589 string symname,
8590 unsigned int len,
8591 bool has_only_read_access,
8592 bool has_only_write_access,
822a6a3d 8593 bool):
4c5d1300 8594 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
8595 hwbkpt_addr (addr),
8596 symbol_name (symname),
8597 hwbkpt_len (len)
8598{
8599 this->tok = base->tok;
8600
8601 vector<probe_point::component*> comps;
8602 comps.push_back (new probe_point::component(TOK_KERNEL));
8603
8604 if (hwbkpt_addr)
9ea68eb9
JS
8605 comps.push_back (new probe_point::component (TOK_HWBKPT,
8606 new literal_number(hwbkpt_addr, true)));
8607 else if (symbol_name.size())
8608 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
8609
8610 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
8611
8612 if (has_only_read_access)
9ea68eb9 8613 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
8614//TODO add code for comps.push_back for read, since this flag is not for x86
8615
8616 else
9ea68eb9
JS
8617 {
8618 if (has_only_write_access)
8619 {
8620 this->hwbkpt_access = HWBKPT_WRITE ;
8621 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
8622 }
8623 else
8624 {
8625 this->hwbkpt_access = HWBKPT_RW ;
8626 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
8627 }
8628 }
dd225250
PS
8629
8630 this->sole_location()->components = comps;
8631}
8632
8633void hwbkpt_derived_probe::printsig (ostream& o) const
8634{
8635 sole_location()->print (o);
8636 printsig_nested (o);
8637}
8638
8639void hwbkpt_derived_probe::join_group (systemtap_session& s)
8640{
dac77b80
FCE
8641 if (! s.hwbkpt_derived_probes)
8642 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
8643 s.hwbkpt_derived_probes->enroll (this, s);
8644}
8645
8646void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
8647{
dac77b80
FCE
8648 hwbkpt_probes.push_back (p);
8649
8650 unsigned max_hwbkpt_probes_by_arch = 0;
8651 if (s.architecture == "i386" || s.architecture == "x86_64")
8652 max_hwbkpt_probes_by_arch = 4;
8653 else if (s.architecture == "s390")
8654 max_hwbkpt_probes_by_arch = 1;
8655
c57ea854 8656 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 8657 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 8658 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
8659}
8660
8661void
8662hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
8663{
dac77b80 8664 if (hwbkpt_probes.empty()) return;
dd225250
PS
8665
8666 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
8667
8668 s.op->newline() << "#include <linux/perf_event.h>";
8669 s.op->newline() << "#include <linux/hw_breakpoint.h>";
8670 s.op->newline();
8671
8672 // Forward declare the master entry functions
8673 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8674 s.op->line() << " int nmi,";
8675 s.op->line() << " struct perf_sample_data *data,";
8676 s.op->line() << " struct pt_regs *regs);";
79189b84 8677
dd225250
PS
8678 // Emit the actual probe list.
8679
8680 s.op->newline() << "static struct perf_event_attr ";
dac77b80 8681 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8682
8683 s.op->newline() << "static struct perf_event **";
dac77b80 8684 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8685 s.op->newline() << "static struct stap_hwbkpt_probe {";
8686 s.op->newline() << "int registered_p:1;";
43650b10 8687// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
8688// registered_p = 1 signifies a probe that got registered successfully
8689
faea5e16 8690 // Symbol Names are mostly small and uniform enough
dd225250 8691 // to justify putting const char*.
dac77b80 8692 s.op->newline() << "const char * const symbol;";
dd225250
PS
8693
8694 s.op->newline() << "const unsigned long address;";
8695 s.op->newline() << "uint8_t atype;";
bb0a4e12 8696 s.op->newline() << "unsigned int len;";
7c3e97f4 8697 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
8698 s.op->newline() << "} stap_hwbkpt_probes[] = {";
8699 s.op->indent(1);
8700
dac77b80 8701 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 8702 {
dac77b80 8703 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 8704 s.op->newline() << "{";
dd225250
PS
8705 if (p->symbol_name.size())
8706 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
8707 else
8708 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
8709 switch(p->hwbkpt_access){
8710 case HWBKPT_READ:
8711 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 8712 break;
dd225250
PS
8713 case HWBKPT_WRITE:
8714 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 8715 break;
dd225250
PS
8716 case HWBKPT_RW:
8717 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 8718 break;
dd225250
PS
8719 };
8720 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 8721 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 8722 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
8723 s.op->line() << " },";
8724 }
dac77b80 8725 s.op->newline(-1) << "};";
dd225250
PS
8726
8727 // Emit the hwbkpt callback function
8728 s.op->newline() ;
8729 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8730 s.op->line() << " int nmi,";
8731 s.op->line() << " struct perf_sample_data *data,";
8732 s.op->line() << " struct pt_regs *regs) {";
dac77b80
FCE
8733 s.op->newline(1) << "unsigned int i;";
8734 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
8735 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
8736 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8737 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
8738 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) {";
8739 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 8740 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8741 "stp_probe_type_hwbkpt");
d9aed31e 8742 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 8743 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
8744 s.op->newline() << "c->uregs = regs;";
8745 s.op->newline(-1) << "} else {";
8746 s.op->newline(1) << "c->kregs = regs;";
8747 s.op->newline(-1) << "}";
26e63673 8748 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 8749 common_probe_entryfn_epilogue (s, true);
dac77b80 8750 s.op->newline(-1) << "}";
dd225250
PS
8751 s.op->newline(-1) << "}";
8752 s.op->newline() << "return 0;";
dac77b80 8753 s.op->newline(-1) << "}";
dd225250
PS
8754}
8755
8756void
8757hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
8758{
dac77b80 8759 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
8760 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
8761 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8762 s.op->newline() << "void *addr = (void *) sdp->address;";
8763 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
8764 s.op->newline() << "hw_breakpoint_init(hp);";
8765 s.op->newline() << "if (addr)";
8766 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
8767 s.op->newline(-1) << "else { ";
8768 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
8769 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 8770 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
8771 s.op->newline() << "continue;";
8772 s.op->newline(-1) << "}";
8773 s.op->newline(-1) << "}";
8774 s.op->newline() << "hp->bp_type = sdp->atype;";
8775
8776 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 8777 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
8778 {
8779 s.op->newline() << "switch(sdp->len) {";
8780 s.op->newline() << "case 1:";
8781 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
8782 s.op->newline() << "break;";
8783 s.op->newline(-1) << "case 2:";
8784 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
8785 s.op->newline() << "break;";
8786 s.op->newline(-1) << "case 3:";
8787 s.op->newline() << "case 4:";
8788 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
8789 s.op->newline() << "break;";
8790 s.op->newline(-1) << "case 5:";
8791 s.op->newline() << "case 6:";
8792 s.op->newline() << "case 7:";
8793 s.op->newline() << "case 8:";
8794 s.op->newline() << "default:"; // XXX: could instead reject
8795 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
8796 s.op->newline() << "break;";
8797 s.op->newline(-1) << "}";
8798 }
8799 else // other architectures presumed straightforward
8800 s.op->newline() << "hp->bp_len = sdp->len;";
8801
26e63673 8802 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
8803 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
8804 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
8805 s.op->newline() << "#else";
dac77b80 8806 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 8807 s.op->newline() << "#endif";
43650b10 8808 s.op->newline() << "rc = 0;";
dac77b80 8809 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
8810 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
8811 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
8812 s.op->newline(-1) << "}";
217ef1f4
WC
8813 s.op->newline() << "if (rc) {";
8814 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 8815 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 8816 s.op->newline(-1) << "}";
dd225250 8817 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
8818 s.op->newline(-1) << "}"; // for loop
8819}
8820
8821void
8822hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
8823{
8824 //Unregister hwbkpt probes.
dac77b80 8825 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 8826 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
8827 s.op->newline() << "if (sdp->registered_p == 0) continue;";
8828 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
8829 s.op->newline() << "sdp->registered_p = 0;";
8830 s.op->newline(-1) << "}";
8831}
8832
8833struct hwbkpt_builder: public derived_probe_builder
8834{
8835 hwbkpt_builder() {}
8836 virtual void build(systemtap_session & sess,
8837 probe * base,
8838 probe_point * location,
8839 literal_map_t const & parameters,
8840 vector<derived_probe *> & finished_results);
8841};
8842
8843void
8844hwbkpt_builder::build(systemtap_session & sess,
8845 probe * base,
8846 probe_point * location,
8847 literal_map_t const & parameters,
8848 vector<derived_probe *> & finished_results)
8849{
8850 string symbol_str_val;
8851 int64_t hwbkpt_address, len;
8852 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
8853
b47f3a55 8854 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
b530b5b3 8855 throw semantic_error (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
8856 location->components[0]->tok);
8857 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
b530b5b3 8858 throw semantic_error (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
8859 location->components[0]->tok);
8860
dd225250
PS
8861 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
8862 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
8863 has_len = get_param (parameters, TOK_LENGTH, len);
8864 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
8865 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
8866
8867 if (!has_len)
8868 len = 1;
8869
8870 if (has_addr)
8871 finished_results.push_back (new hwbkpt_derived_probe (base,
8872 location,
8873 hwbkpt_address,
8874 "",len,0,
8875 has_write,
8876 has_rw));
5d8a0aea 8877 else if (has_symbol_str)
dd225250
PS
8878 finished_results.push_back (new hwbkpt_derived_probe (base,
8879 location,
8880 0,
8881 symbol_str_val,len,0,
8882 has_write,
8883 has_rw));
5d8a0aea
FCE
8884 else
8885 assert (0);
dd225250 8886}
342d3f96 8887
0a6f5a3f
JS
8888// ------------------------------------------------------------------------
8889// statically inserted kernel-tracepoint derived probes
8890// ------------------------------------------------------------------------
8891
6fb70fb7 8892struct tracepoint_arg
79189b84 8893{
ad370dcc 8894 string name, c_type, typecast;
dcaa1a65 8895 bool usable, used, isptr;
f8a968bc 8896 Dwarf_Die type_die;
dcaa1a65 8897 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 8898};
79189b84 8899
0a6f5a3f
JS
8900struct tracepoint_derived_probe: public derived_probe
8901{
79189b84
JS
8902 tracepoint_derived_probe (systemtap_session& s,
8903 dwflpp& dw, Dwarf_Die& func_die,
8904 const string& tracepoint_name,
8905 probe* base_probe, probe_point* location);
bc9a523d 8906
79189b84 8907 systemtap_session& sess;
6fb70fb7
JS
8908 string tracepoint_name, header;
8909 vector <struct tracepoint_arg> args;
bc9a523d 8910
6fb70fb7 8911 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 8912 void getargs (std::list<std::string> &arg_set) const;
79189b84 8913 void join_group (systemtap_session& s);
3e3bd7b6 8914 void print_dupe_stamp(ostream& o);
0a6f5a3f 8915};
79189b84
JS
8916
8917
0a6f5a3f 8918struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 8919{
79189b84
JS
8920 void emit_module_decls (systemtap_session& s);
8921 void emit_module_init (systemtap_session& s);
8922 void emit_module_exit (systemtap_session& s);
0a6f5a3f 8923};
79189b84 8924
bc9a523d 8925
f8a968bc
JS
8926struct tracepoint_var_expanding_visitor: public var_expanding_visitor
8927{
8928 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
8929 vector <struct tracepoint_arg>& args):
8930 dw (dw), probe_name (probe_name), args (args) {}
8931 dwflpp& dw;
8932 const string& probe_name;
8933 vector <struct tracepoint_arg>& args;
bc9a523d 8934
f8a968bc
JS
8935 void visit_target_symbol (target_symbol* e);
8936 void visit_target_symbol_arg (target_symbol* e);
8937 void visit_target_symbol_context (target_symbol* e);
8938};
79189b84
JS
8939
8940
f8a968bc
JS
8941void
8942tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 8943{
cc9001af 8944 string argname = e->sym_name();
75ead1f7 8945
f8a968bc
JS
8946 // search for a tracepoint parameter matching this name
8947 tracepoint_arg *arg = NULL;
8948 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 8949 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
8950 {
8951 arg = &args[i];
8952 arg->used = true;
8953 break;
8954 }
75ead1f7 8955
f8a968bc
JS
8956 if (arg == NULL)
8957 {
8958 stringstream alternatives;
8959 for (unsigned i = 0; i < args.size(); ++i)
8960 alternatives << " $" << args[i].name;
046e7190 8961 alternatives << " $$name $$parms $$vars";
75ead1f7 8962
f8a968bc
JS
8963 // We hope that this value ends up not being referenced after all, so it
8964 // can be optimized out quietly.
b530b5b3
LB
8965 throw semantic_error(_F("unable to find tracepoint variable '%s' (alternatives: %s)",
8966 e->name.c_str(), alternatives.str().c_str()), e->tok);
f8a968bc
JS
8967 // NB: we can have multiple errors, since a target variable
8968 // may be expanded in several different contexts:
8969 // trace ("*") { $foo->bar }
f8a968bc 8970 }
75ead1f7 8971
f8a968bc 8972 // make sure we're not dereferencing base types
dc5a09fc 8973 if (!arg->isptr)
d19a9a82 8974 e->assert_no_components("tracepoint", true);
75ead1f7 8975
f8a968bc
JS
8976 // we can only write to dereferenced fields, and only if guru mode is on
8977 bool lvalue = is_active_lvalue(e);
8978 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
b3741c9d 8979 throw semantic_error(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 8980
ad370dcc
JS
8981 // XXX: if a struct/union arg is passed by value, then writing to its fields
8982 // is also meaningless until you dereference past a pointer member. It's
8983 // harder to detect and prevent that though...
75ead1f7 8984
f8a968bc
JS
8985 if (e->components.empty())
8986 {
03c75a4a 8987 if (e->addressof)
b530b5b3 8988 throw semantic_error(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 8989
3e3bd7b6 8990 // Just grab the value from the probe locals
a45664f4
JS
8991 symbol* sym = new symbol;
8992 sym->tok = e->tok;
8993 sym->name = "__tracepoint_arg_" + arg->name;
8994 provide (sym);
f8a968bc
JS
8995 }
8996 else
8997 {
5f36109e
JS
8998 // make a copy of the original as a bare target symbol for the tracepoint
8999 // value, which will be passed into the dwarf dereferencing code
9000 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9001 e2->components.clear();
9002
9003 if (e->components.back().type == target_symbol::comp_pretty_print)
9004 {
9005 if (lvalue)
b530b5b3 9006 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9007
d19a9a82 9008 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9009 dpp.expand()->visit (this);
9010 return;
9011 }
9012
f8a968bc
JS
9013 // Synthesize a function to dereference the dwarf fields,
9014 // with a pointer parameter that is the base tracepoint variable
9015 functiondecl *fdecl = new functiondecl;
59de45f1 9016 fdecl->synthetic = true;
f8a968bc
JS
9017 fdecl->tok = e->tok;
9018 embeddedcode *ec = new embeddedcode;
9019 ec->tok = e->tok;
75ead1f7 9020
f8a968bc 9021 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9022 + "_" + e->sym_name()
aca66a36 9023 + "_" + lex_cast(tick++));
75ead1f7 9024
f8a968bc
JS
9025 fdecl->name = fname;
9026 fdecl->body = ec;
75ead1f7 9027
a5ce5211 9028 ec->code += EMBEDDED_FETCH_DEREF(false);
c69a87e0 9029 ec->code += dw.literal_stmt_for_pointer (&arg->type_die, e,
f8a968bc 9030 lvalue, fdecl->type);
75ead1f7 9031
f8a968bc
JS
9032 // Give the fdecl an argument for the raw tracepoint value
9033 vardecl *v1 = new vardecl;
9034 v1->type = pe_long;
9035 v1->name = "pointer";
9036 v1->tok = e->tok;
9037 fdecl->formal_args.push_back(v1);
75ead1f7 9038
6fda2dff
JS
9039 // Any non-literal indexes need to be passed in too.
9040 for (unsigned i = 0; i < e->components.size(); ++i)
9041 if (e->components[i].type == target_symbol::comp_expression_array_index)
9042 {
9043 vardecl *v = new vardecl;
9044 v->type = pe_long;
aca66a36 9045 v->name = "index" + lex_cast(i);
6fda2dff
JS
9046 v->tok = e->tok;
9047 fdecl->formal_args.push_back(v);
9048 }
9049
f8a968bc
JS
9050 if (lvalue)
9051 {
9052 // Modify the fdecl so it carries a pe_long formal
9053 // argument called "value".
75ead1f7 9054
f8a968bc
JS
9055 // FIXME: For the time being we only support setting target
9056 // variables which have base types; these are 'pe_long' in
9057 // stap's type vocabulary. Strings and pointers might be
9058 // reasonable, some day, but not today.
9059
9060 vardecl *v2 = new vardecl;
9061 v2->type = pe_long;
9062 v2->name = "value";
9063 v2->tok = e->tok;
9064 fdecl->formal_args.push_back(v2);
9065 }
9066 else
9067 ec->code += "/* pure */";
9068
64211010 9069 ec->code += "/* unprivileged */";
a5ce5211 9070 ec->code += EMBEDDED_FETCH_DEREF_DONE;
aff5d390 9071
f8809d54 9072 fdecl->join (dw.sess);
75ead1f7 9073
f8a968bc
JS
9074 // Synthesize a functioncall.
9075 functioncall* n = new functioncall;
9076 n->tok = e->tok;
9077 n->function = fname;
6fda2dff
JS
9078 n->args.push_back(require(e2));
9079
9080 // Any non-literal indexes need to be passed in too.
9081 for (unsigned i = 0; i < e->components.size(); ++i)
9082 if (e->components[i].type == target_symbol::comp_expression_array_index)
9083 n->args.push_back(require(e->components[i].expr_index));
75ead1f7 9084
f8a968bc
JS
9085 if (lvalue)
9086 {
9087 // Provide the functioncall to our parent, so that it can be
9088 // used to substitute for the assignment node immediately above
9089 // us.
9090 assert(!target_symbol_setter_functioncalls.empty());
9091 *(target_symbol_setter_functioncalls.top()) = n;
9092 }
75ead1f7 9093
f8a968bc
JS
9094 provide (n);
9095 }
75ead1f7
JS
9096}
9097
9098
f8a968bc
JS
9099void
9100tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9101{
03c75a4a 9102 if (e->addressof)
b530b5b3 9103 throw semantic_error(_("cannot take address of context variable"), e->tok);
03c75a4a 9104
f8a968bc 9105 if (is_active_lvalue (e))
b530b5b3 9106 throw semantic_error(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 9107
277c21bc 9108 if (e->name == "$$name")
f8a968bc 9109 {
5f36109e
JS
9110 e->assert_no_components("tracepoint");
9111
bfdaad1e
DS
9112 // Synthesize an embedded expression.
9113 embedded_expr *expr = new embedded_expr;
9114 expr->tok = e->tok;
9115 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 9116 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 9117 provide (expr);
f8a968bc 9118 }
277c21bc 9119 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 9120 {
5f36109e
JS
9121 e->assert_no_components("tracepoint", true);
9122
f8a968bc
JS
9123 token* pf_tok = new token(*e->tok);
9124 pf_tok->content = "sprintf";
0a6f5a3f 9125
d5e178c1 9126 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 9127
f8a968bc 9128 for (unsigned i = 0; i < args.size(); ++i)
b278033a 9129 {
dcaa1a65
JS
9130 if (!args[i].usable)
9131 continue;
f8a968bc
JS
9132 if (i > 0)
9133 pf->raw_components += " ";
9134 pf->raw_components += args[i].name;
3e3bd7b6 9135 target_symbol *tsym = new target_symbol;
f8a968bc 9136 tsym->tok = e->tok;
277c21bc 9137 tsym->name = "$" + args[i].name;
5f36109e 9138 tsym->components = e->components;
b278033a 9139
f8a968bc
JS
9140 // every variable should always be accessible!
9141 tsym->saved_conversion_error = 0;
9142 expression *texp = require (tsym); // NB: throws nothing ...
14a97852
JS
9143 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
9144 {
9145 if (dw.sess.verbose>2)
e26c2f83 9146 for (const semantic_error *c = tsym->saved_conversion_error;
14a97852 9147 c != 0; c = c->chain)
4c5d9906 9148 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
9149 pf->raw_components += "=?";
9150 continue;
9151 }
b278033a 9152
5f36109e
JS
9153 if (!e->components.empty() &&
9154 e->components[0].type == target_symbol::comp_pretty_print)
9155 pf->raw_components += "=%s";
9156 else
9157 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
9158 pf->args.push_back(texp);
9159 }
0a6f5a3f 9160
f8a968bc
JS
9161 pf->components = print_format::string_to_components(pf->raw_components);
9162 provide (pf);
b278033a 9163 }
f8a968bc
JS
9164 else
9165 assert(0); // shouldn't get here
0a6f5a3f
JS
9166}
9167
0a6f5a3f 9168void
f8a968bc 9169tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 9170{
aff5d390 9171 try
c69a87e0 9172 {
8fa5f271
MW
9173 assert(e->name.size() > 0
9174 && ((e->name[0] == '$' && e->target_name == "")
9175 || (e->name == "@var" && e->target_name != "")));
aff5d390 9176
277c21bc 9177 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 9178 visit_target_symbol_context (e);
8fa5f271
MW
9179 else if (e->name == "@var")
9180 throw semantic_error(_("cannot use @var DWARF variables in tracepoints"), e->tok);
c69a87e0
FCE
9181 else
9182 visit_target_symbol_arg (e);
9183 }
9184 catch (const semantic_error &er)
9185 {
1af1e62d 9186 e->chain (er);
c69a87e0
FCE
9187 provide (e);
9188 }
0a6f5a3f
JS
9189}
9190
9191
9192
79189b84
JS
9193tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
9194 dwflpp& dw, Dwarf_Die& func_die,
9195 const string& tracepoint_name,
9196 probe* base, probe_point* loc):
4c5d1300 9197 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 9198 sess (s), tracepoint_name (tracepoint_name)
56894e91 9199{
79189b84
JS
9200 // create synthetic probe point name; preserve condition
9201 vector<probe_point::component*> comps;
9202 comps.push_back (new probe_point::component (TOK_KERNEL));
9203 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
9204 this->sole_location()->components = comps;
9205
6fb70fb7
JS
9206 // fill out the available arguments in this tracepoint
9207 build_args(dw, func_die);
56894e91 9208
6fb70fb7
JS
9209 // determine which header defined this tracepoint
9210 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
9211 header = decl_file;
9212
9213#if 0 /* This convention is not enforced. */
6fb70fb7
JS
9214 size_t header_pos = decl_file.rfind("trace/");
9215 if (header_pos == string::npos)
9216 throw semantic_error ("cannot parse header location for tracepoint '"
9217 + tracepoint_name + "' in '"
9218 + decl_file + "'");
9219 header = decl_file.substr(header_pos);
d4393459 9220#endif
56894e91 9221
6fb70fb7
JS
9222 // tracepoints from FOO_event_types.h should really be included from FOO.h
9223 // XXX can dwarf tell us the include hierarchy? it would be better to
9224 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 9225 // XXX: see also PR9993.
d4393459 9226 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
9227 if (header_pos != string::npos)
9228 header.erase(header_pos, 12);
56894e91 9229
f8a968bc
JS
9230 // Now expand the local variables in the probe body
9231 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 9232 v.replace (this->body);
a45664f4
JS
9233 for (unsigned i = 0; i < args.size(); i++)
9234 if (args[i].used)
9235 {
9236 vardecl* v = new vardecl;
9237 v->name = "__tracepoint_arg_" + args[i].name;
9238 v->tok = this->tok;
58701b78 9239 v->set_arity(0, this->tok);
a45664f4 9240 v->type = pe_long;
69aa668e 9241 v->synthetic = true;
a45664f4
JS
9242 this->locals.push_back (v);
9243 }
56894e91 9244
79189b84 9245 if (sess.verbose > 2)
ce0f6648 9246 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 9247}
dc38c0ae 9248
56894e91 9249
f8a968bc 9250static bool
dcaa1a65 9251resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 9252{
d19a9a82 9253 Dwarf_Die type;
dcaa1a65 9254 switch (dwarf_tag(&arg.type_die))
b20febf3 9255 {
f8a968bc
JS
9256 case DW_TAG_typedef:
9257 case DW_TAG_const_type:
9258 case DW_TAG_volatile_type:
9259 // iterate on the referent type
3d1ad340 9260 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 9261 && resolve_tracepoint_arg_type(arg));
f8a968bc 9262 case DW_TAG_base_type:
a52d2ac0 9263 case DW_TAG_enumeration_type:
f8a968bc 9264 // base types will simply be treated as script longs
dcaa1a65 9265 arg.isptr = false;
f8a968bc
JS
9266 return true;
9267 case DW_TAG_pointer_type:
dcaa1a65
JS
9268 // pointers can be treated as script longs,
9269 // and if we know their type, they can also be dereferenced
d19a9a82
JS
9270 type = arg.type_die;
9271 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
9272 {
9273 // It still might be a non-type, e.g. const void,
9274 // so we need to strip away all qualifiers.
9275 int tag = dwarf_tag(&arg.type_die);
9276 if (tag != DW_TAG_typedef &&
9277 tag != DW_TAG_const_type &&
9278 tag != DW_TAG_volatile_type)
9279 {
9280 arg.isptr = true;
9281 break;
9282 }
9283 }
9284 if (!arg.isptr)
9285 arg.type_die = type;
ad370dcc
JS
9286 arg.typecast = "(intptr_t)";
9287 return true;
9288 case DW_TAG_structure_type:
9289 case DW_TAG_union_type:
9290 // for structs/unions which are passed by value, we turn it into
9291 // a pointer that can be dereferenced.
9292 arg.isptr = true;
9293 arg.typecast = "(intptr_t)&";
dcaa1a65 9294 return true;
f8a968bc
JS
9295 default:
9296 // should we consider other types too?
9297 return false;
b20febf3 9298 }
56894e91
JS
9299}
9300
9301
9302void
822a6a3d 9303tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 9304{
6fb70fb7
JS
9305 Dwarf_Die arg;
9306 if (dwarf_child(&func_die, &arg) == 0)
9307 do
9308 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
9309 {
9310 // build a tracepoint_arg for this parameter
9311 tracepoint_arg tparg;
23d106b9 9312 tparg.name = dwarf_diename(&arg);
56894e91 9313
6fb70fb7 9314 // read the type of this parameter
3d1ad340 9315 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 9316 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
ce0f6648
LB
9317 throw semantic_error (_F("cannot get type of parameter '%s' of tracepoint '%s'",
9318 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 9319
dcaa1a65 9320 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
9321 args.push_back(tparg);
9322 if (sess.verbose > 4)
a52d2ac0
JS
9323 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
9324 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
9325 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
9326 }
9327 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
9328}
9329
dc38c0ae 9330void
d0bfd2ac 9331tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 9332{
dcaa1a65
JS
9333 for (unsigned i = 0; i < args.size(); ++i)
9334 if (args[i].usable)
d0bfd2ac 9335 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
9336}
9337
79189b84
JS
9338void
9339tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 9340{
79189b84
JS
9341 if (! s.tracepoint_derived_probes)
9342 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
9343 s.tracepoint_derived_probes->enroll (this);
9344}
e38d6504 9345
56894e91 9346
197a4d62 9347void
3e3bd7b6 9348tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 9349{
3e3bd7b6
JS
9350 for (unsigned i = 0; i < args.size(); i++)
9351 if (args[i].used)
9352 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 9353}
56894e91 9354
3e3bd7b6 9355
c9ccb642 9356static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 9357{
3c1b3d06
FCE
9358 vector<string> they_live;
9359 // PR 9993
9360 // XXX: may need this to be configurable
d4393459 9361 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
9362
9363 // PR11649: conditional extra header
9364 // for kvm tracepoints in 2.6.33ish
9365 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
9366 they_live.push_back ("#include <linux/kvm_host.h>");
9367 }
9368
50b72692 9369 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 9370 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
9371 if (s.kernel_source_tree != "")
9372 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
9373 they_live.push_back ("struct xfs_mount;");
9374 they_live.push_back ("struct xfs_inode;");
9375 they_live.push_back ("struct xfs_buf;");
9376 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 9377 they_live.push_back ("struct xfs_trans;");
9e0cd21a 9378 }
d4393459 9379
50b72692 9380 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
9381 they_live.push_back ("struct rpc_task;");
9382 }
b64d65e2
FCE
9383 // RHEL6.3
9384 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
9385 they_live.push_back ("struct rpc_clnt;");
9386 they_live.push_back ("struct rpc_wait_queue;");
9387 }
d4393459
FCE
9388
9389 they_live.push_back ("#include <asm/cputime.h>");
9390
c2cf1b87
FCE
9391 // linux 3.0
9392 they_live.push_back ("struct cpu_workqueue_struct;");
9393
50b72692 9394 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
9395 if (s.kernel_source_tree != "")
9396 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
9397
50b72692
HP
9398 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
9399 they_live.push_back ("struct ext3_reserve_window_node;");
9400
3c1b3d06
FCE
9401 return they_live;
9402}
47dd066d
WC
9403
9404
9405void
79189b84 9406tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 9407{
79189b84
JS
9408 if (probes.empty())
9409 return;
47dd066d 9410
96b030fe
JS
9411 s.op->newline() << "/* ---- tracepoint probes ---- */";
9412 s.op->newline();
79189b84 9413
47dd066d 9414
a4b9c3b3
FCE
9415 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
9416 // to be separately compiled. That's because kernel tracepoint headers sometimes
9417 // conflict. PR13155.
9418
9419 map<string,translator_output*> per_header_aux;
9420 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 9421
6fb70fb7
JS
9422 for (unsigned i = 0; i < probes.size(); ++i)
9423 {
9424 tracepoint_derived_probe *p = probes[i];
75ae2ec9 9425 string header = p->header;
5f73a260 9426
a4b9c3b3
FCE
9427 // We cache the auxiliary output files on a per-header basis. We don't
9428 // need one aux file per tracepoint, only one per tracepoint-header.
9429 translator_output *tpop = per_header_aux[header];
9430 if (tpop == 0)
9431 {
9432 tpop = s.op_create_auxiliary();
9433 per_header_aux[header] = tpop;
9434
9435 // PR9993: Add extra headers to work around undeclared types in individual
9436 // include/trace/foo.h files
9437 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
9438 for (unsigned z=0; z<extra_decls.size(); z++)
9439 tpop->newline() << extra_decls[z] << "\n";
720c435f 9440
a4b9c3b3
FCE
9441 // strip include/ substring, the same way as done in get_tracequery_module()
9442 size_t root_pos = header.rfind("include/");
9443 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443
FCE
9444
9445 tpop->newline() << "#include <linux/tracepoint.h>" << endl;
a4b9c3b3 9446 tpop->newline() << "#include <" << header << ">";
720c435f 9447
a4b9c3b3
FCE
9448 // Starting in 2.6.35, at the same time NOARGS was added, the callback
9449 // always has a void* as the first parameter. PR11599
9450 tpop->newline() << "#ifdef DECLARE_TRACE_NOARGS";
9451 tpop->newline() << "#define STAP_TP_DATA , NULL";
9452 tpop->newline() << "#define STAP_TP_PROTO void *cb_data"
9453 << " __attribute__ ((unused))";
9454 if (!p->args.empty())
9455 tpop->line() << ",";
9456 tpop->newline() << "#else";
9457 tpop->newline() << "#define STAP_TP_DATA";
9458 tpop->newline() << "#define STAP_TP_PROTO";
9459 if (p->args.empty())
9460 tpop->line() << " void";
9461 tpop->newline() << "#endif";
720c435f
JS
9462
9463 tpop->newline() << "#define intptr_t long";
a4b9c3b3
FCE
9464 }
9465
720c435f
JS
9466 // collect the args that are actually in use
9467 vector<const tracepoint_arg*> used_args;
6fb70fb7 9468 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
9469 if (p->args[j].used)
9470 used_args.push_back(&p->args[j]);
9471
a4b9c3b3
FCE
9472 // forward-declare the generated-side tracepoint callback
9473 tpop->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9474 tpop->indent(2);
9475 if (used_args.empty())
9476 tpop->line() << "void";
9477 for (unsigned j = 0; j < used_args.size(); ++j)
6fb70fb7
JS
9478 {
9479 if (j > 0)
a4b9c3b3
FCE
9480 tpop->line() << ", ";
9481 tpop->line() << "int64_t";
6fb70fb7 9482 }
720c435f
JS
9483 tpop->line() << ");";
9484 tpop->indent(-2);
5f73a260 9485
a4b9c3b3
FCE
9486 // define the generated-side tracepoint callback - in the main translator-output
9487 s.op->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9488 s.op->indent(2);
9489 if (used_args.empty())
9490 s.op->newline() << "void";
9491 for (unsigned j = 0; j < used_args.size(); ++j)
a4b9c3b3 9492 {
a4b9c3b3
FCE
9493 if (j > 0)
9494 s.op->line() << ", ";
720c435f 9495 s.op->newline() << "int64_t __tracepoint_arg_" << used_args[j]->name;
6fb70fb7 9496 }
5f73a260
JS
9497 s.op->newline() << ")";
9498 s.op->newline(-2) << "{";
7c3e97f4 9499 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 9500 << common_probe_init (p) << ";";
71db462b 9501 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 9502 "stp_probe_type_tracepoint");
6dceb5c9 9503 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
9504 << lex_cast_qstring (p->tracepoint_name)
9505 << ";";
720c435f
JS
9506 for (unsigned j = 0; j < used_args.size(); ++j)
9507 {
9508 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 9509 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
9510 << " = __tracepoint_arg_" << used_args[j]->name << ";";
9511 }
26e63673 9512 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 9513 common_probe_entryfn_epilogue (s, true);
6fb70fb7 9514 s.op->newline(-1) << "}";
47dd066d 9515
a4b9c3b3 9516 // define the real tracepoint callback function
720c435f 9517 tpop->newline() << "static void enter_tracepoint_probe_" << i << "(";
a4b9c3b3
FCE
9518 tpop->newline(2) << "STAP_TP_PROTO";
9519 for (unsigned j = 0; j < p->args.size(); ++j)
9520 {
9521 if (j > 0)
9522 tpop->line() << ", ";
9523 tpop->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
9524 }
9525 tpop->newline() << ")";
9526 tpop->newline(-2) << "{";
720c435f
JS
9527 tpop->newline(1) << "enter_real_tracepoint_probe_" << i << "(";
9528 tpop->indent(2);
9529 for (unsigned j = 0; j < used_args.size(); ++j)
9530 {
9531 if (j > 0)
9532 tpop->line() << ", ";
9533 tpop->newline() << "(int64_t)" << used_args[j]->typecast
9534 << "__tracepoint_arg_" << used_args[j]->name;
9535 }
9536 tpop->newline() << ");";
9537 tpop->newline(-3) << "}";
a4b9c3b3
FCE
9538
9539
96b030fe 9540 // emit normalized registration functions
720c435f 9541 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9542 tpop->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 9543 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3 9544 tpop->newline(-1) << "}";
47dd066d 9545
86758d5f
JS
9546 // NB: we're not prepared to deal with unreg failures. However, failures
9547 // can only occur if the tracepoint doesn't exist (yet?), or if we
9548 // weren't even registered. The former should be OKed by the initial
9549 // registration call, and the latter is safe to ignore.
720c435f 9550 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9551 tpop->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 9552 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3
FCE
9553 tpop->newline(-1) << "}";
9554 tpop->newline();
5f73a260 9555
720c435f
JS
9556 // declare normalized registration functions
9557 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
9558 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 9559
a4b9c3b3 9560 tpop->assert_0_indent();
af304783
DS
9561 }
9562
96b030fe
JS
9563 // emit an array of registration functions for easy init/shutdown
9564 s.op->newline() << "static struct stap_tracepoint_probe {";
9565 s.op->newline(1) << "int (*reg)(void);";
86758d5f 9566 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
9567 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
9568 s.op->indent(1);
9569 for (unsigned i = 0; i < probes.size(); ++i)
9570 {
9571 s.op->newline () << "{";
9572 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
9573 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
9574 s.op->line() << " },";
9575 }
9576 s.op->newline(-1) << "};";
9577 s.op->newline();
47dd066d
WC
9578}
9579
9580
79189b84
JS
9581void
9582tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 9583{
79189b84
JS
9584 if (probes.size () == 0)
9585 return;
47dd066d 9586
79189b84 9587 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
9588 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
9589 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
9590 s.op->newline() << "if (rc) {";
9591 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
9592 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
9593 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
9594 s.op->newline(-1) << "}";
9595 s.op->newline(-1) << "}";
47dd066d 9596
bc9a523d
FCE
9597 // This would be technically proper (on those autoconf-detectable
9598 // kernels that include this function in tracepoint.h), however we
9599 // already make several calls to synchronze_sched() during our
9600 // shutdown processes.
47dd066d 9601
bc9a523d
FCE
9602 // s.op->newline() << "if (rc)";
9603 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
9604 // s.op->indent(-1);
79189b84 9605}
47dd066d
WC
9606
9607
79189b84
JS
9608void
9609tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 9610{
79189b84
JS
9611 if (probes.empty())
9612 return;
47dd066d 9613
96b030fe
JS
9614 s.op->newline() << "/* deregister tracepoint probes */";
9615 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
9616 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
9617 s.op->indent(-1);
47dd066d 9618
bc9a523d 9619 // Not necessary: see above.
47dd066d 9620
bc9a523d 9621 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 9622}
b20febf3 9623
47dd066d 9624
75ead1f7 9625struct tracepoint_query : public base_query
47dd066d 9626{
75ead1f7
JS
9627 tracepoint_query(dwflpp & dw, const string & tracepoint,
9628 probe * base_probe, probe_point * base_loc,
9629 vector<derived_probe *> & results):
9630 base_query(dw, "*"), tracepoint(tracepoint),
9631 base_probe(base_probe), base_loc(base_loc),
9632 results(results) {}
47dd066d 9633
75ead1f7 9634 const string& tracepoint;
47dd066d 9635
75ead1f7
JS
9636 probe * base_probe;
9637 probe_point * base_loc;
9638 vector<derived_probe *> & results;
f982c59b 9639 set<string> probed_names;
47dd066d 9640
75ead1f7
JS
9641 void handle_query_module();
9642 int handle_query_cu(Dwarf_Die * cudie);
9643 int handle_query_func(Dwarf_Die * func);
822a6a3d 9644 void query_library (const char *) {}
576eaefe 9645 void query_plt (const char *entry, size_t addr) {}
b20febf3 9646
75ead1f7
JS
9647 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
9648 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
9649};
47dd066d
WC
9650
9651
9652void
75ead1f7 9653tracepoint_query::handle_query_module()
47dd066d 9654{
75ead1f7 9655 // look for the tracepoints in each CU
337b7c44 9656 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
9657}
9658
9659
75ead1f7
JS
9660int
9661tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 9662{
75ead1f7 9663 dw.focus_on_cu (cudie);
47dd066d 9664
75ead1f7
JS
9665 // look at each function to see if it's a tracepoint
9666 string function = "stapprobe_" + tracepoint;
9667 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
9668}
9669
9670
75ead1f7
JS
9671int
9672tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 9673{
75ead1f7 9674 dw.focus_on_function (func);
47dd066d 9675
60d98537 9676 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 9677 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
9678
9679 // check for duplicates -- sometimes tracepoint headers may be indirectly
9680 // included in more than one of our tracequery modules.
9681 if (!probed_names.insert(tracepoint_instance).second)
9682 return DWARF_CB_OK;
9683
79189b84
JS
9684 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
9685 tracepoint_instance,
9686 base_probe, base_loc);
9687 results.push_back (dp);
75ead1f7 9688 return DWARF_CB_OK;
47dd066d
WC
9689}
9690
9691
75ead1f7
JS
9692int
9693tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 9694{
75ead1f7 9695 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 9696 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9697 return q->handle_query_cu(cudie);
47dd066d
WC
9698}
9699
9700
75ead1f7
JS
9701int
9702tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 9703{
75ead1f7 9704 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 9705 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9706 return q->handle_query_func(func);
47dd066d
WC
9707}
9708
9709
0a6f5a3f 9710struct tracepoint_builder: public derived_probe_builder
47dd066d 9711{
0a6f5a3f
JS
9712private:
9713 dwflpp *dw;
9714 bool init_dw(systemtap_session& s);
c9ccb642
FCE
9715 void get_tracequery_modules(systemtap_session& s,
9716 const vector<string>& headers,
9717 vector<string>& modules);
47dd066d 9718
0a6f5a3f 9719public:
47dd066d 9720
0a6f5a3f
JS
9721 tracepoint_builder(): dw(0) {}
9722 ~tracepoint_builder() { delete dw; }
47dd066d 9723
0a6f5a3f
JS
9724 void build_no_more (systemtap_session& s)
9725 {
9726 if (dw && s.verbose > 3)
b530b5b3 9727 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
9728 delete dw;
9729 dw = NULL;
435f53a7
FCE
9730
9731 delete_session_module_cache (s);
0a6f5a3f 9732 }
47dd066d 9733
0a6f5a3f
JS
9734 void build(systemtap_session& s,
9735 probe *base, probe_point *location,
9736 literal_map_t const& parameters,
9737 vector<derived_probe*>& finished_results);
9738};
47dd066d 9739
47dd066d 9740
c9ccb642 9741
2a0e62a8 9742// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
9743// tracepoint-related header files given. Return the generated or cached
9744// modules[].
9745
9746void
9747tracepoint_builder::get_tracequery_modules(systemtap_session& s,
9748 const vector<string>& headers,
9749 vector<string>& modules)
0a6f5a3f 9750{
c95eddf7 9751 if (s.verbose > 2)
55e50c24 9752 {
ce0f6648 9753 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
9754 for (size_t i = 0; i < headers.size(); ++i)
9755 clog << " " << headers[i] << endl;
9756 }
c95eddf7 9757
2a0e62a8
JS
9758 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
9759 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
9760 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
9761 // so we prefer not to repeat this.
9762 vector<string> uncached_headers;
9763 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 9764 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
9765
9766 // They may be in the cache already.
9767 if (s.use_cache && !s.poison_cache)
9768 for (size_t i=0; i<headers.size(); i++)
9769 {
9770 // see if the cached module exists
2a0e62a8 9771 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
9772 if (!tracequery_path.empty() && file_exists(tracequery_path))
9773 {
9774 if (s.verbose > 2)
9775 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 9776
c252fca2
JS
9777 // an empty file is a cached failure
9778 if (get_file_size(tracequery_path) > 0)
9779 modules.push_back (tracequery_path);
c9ccb642
FCE
9780 }
9781 else
9782 uncached_headers.push_back(headers[i]);
9783 }
9784 else
9785 uncached_headers = headers;
f982c59b 9786
c9ccb642
FCE
9787 // If we have nothing left to search for, quit
9788 if (uncached_headers.empty()) return;
55e50c24 9789
c9ccb642 9790 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 9791
c9ccb642
FCE
9792 // We could query several subsets of headers[] to make this go
9793 // faster, but let's KISS and do one at a time.
9794 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 9795 {
c9ccb642
FCE
9796 const string& header = uncached_headers[i];
9797
9798 // create a tracequery source file
9799 ostringstream osrc;
9800
9801 // PR9993: Add extra headers to work around undeclared types in individual
9802 // include/trace/foo.h files
9803 vector<string> short_decls = tracepoint_extra_decls(s, header);
9804
9805 // add each requested tracepoint header
75ae2ec9 9806 size_t root_pos = header.rfind("include/");
832f100d 9807 short_decls.push_back(string("#include <") +
75ae2ec9 9808 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 9809 string(">"));
f982c59b 9810
c9ccb642
FCE
9811 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
9812 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
9813
9814 // the kernel has changed this naming a few times, previously TPPROTO,
9815 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
9816 osrc << "#ifndef PARAMS" << endl;
9817 osrc << "#define PARAMS(args...) args" << endl;
9818 osrc << "#endif" << endl;
9819
c9ccb642
FCE
9820 // override DECLARE_TRACE to synthesize probe functions for us
9821 osrc << "#undef DECLARE_TRACE" << endl;
9822 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
9823 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 9824
c9ccb642
FCE
9825 // 2.6.35 added the NOARGS variant, but it's the same for us
9826 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
9827 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
9828 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
9829
9830 // 2.6.38 added the CONDITION variant, which can also just redirect
9831 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
9832 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
9833 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
9834
c9ccb642
FCE
9835 // older tracepoints used DEFINE_TRACE, so redirect that too
9836 osrc << "#undef DEFINE_TRACE" << endl;
9837 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
9838 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
9839
c9ccb642
FCE
9840 // add the specified decls/#includes
9841 for (unsigned z=0; z<short_decls.size(); z++)
9842 osrc << "#undef TRACE_INCLUDE_FILE\n"
9843 << "#undef TRACE_INCLUDE_PATH\n"
9844 << short_decls[z] << "\n";
9845
9846 // finish up the module source
9847 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 9848
c9ccb642
FCE
9849 // save the source file away
9850 headers_tracequery_src[header] = osrc.str();
55e50c24 9851 }
f982c59b 9852
c9ccb642 9853 // now build them all together
2a0e62a8 9854 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 9855
c9ccb642 9856 // now plop them into the cache
b278033a 9857 if (s.use_cache)
c9ccb642
FCE
9858 for (size_t i=0; i<uncached_headers.size(); i++)
9859 {
9860 const string& header = uncached_headers[i];
2a0e62a8
JS
9861 const string& tracequery_obj = tracequery_objs[header];
9862 const string& tracequery_path = headers_cache_obj[header];
9863 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 9864 {
2a0e62a8 9865 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
9866 modules.push_back (tracequery_path);
9867 }
c252fca2
JS
9868 else
9869 // cache an empty file for failures
9870 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 9871 }
f982c59b
JS
9872}
9873
9874
d4393459 9875
f982c59b
JS
9876bool
9877tracepoint_builder::init_dw(systemtap_session& s)
9878{
9879 if (dw != NULL)
9880 return true;
9881
9882 vector<string> tracequery_modules;
55e50c24 9883 vector<string> system_headers;
f982c59b
JS
9884
9885 glob_t trace_glob;
d4393459
FCE
9886
9887 // find kernel_source_tree
9888 if (s.kernel_source_tree == "")
f982c59b 9889 {
d4393459
FCE
9890 unsigned found;
9891 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
9892 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
9893 if (found)
9894 {
9895 Dwarf_Die *cudie = 0;
9896 Dwarf_Addr bias;
9897 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
9898 {
e19ebcf7 9899 assert_no_interrupts();
d4393459
FCE
9900 Dwarf_Attribute attr;
9901 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
9902 if (name)
9903 {
61f1a63b 9904 if (s.verbose > 2)
b530b5b3 9905 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
61f1a63b 9906
d4393459
FCE
9907 s.kernel_source_tree = name;
9908 break; // skip others; modern Kbuild uses same comp_dir for them all
9909 }
9910 }
9911 }
9912 }
9913
9914 // prefixes
9915 vector<string> glob_prefixes;
9916 glob_prefixes.push_back (s.kernel_build_tree);
9917 if (s.kernel_source_tree != "")
9918 glob_prefixes.push_back (s.kernel_source_tree);
9919
9920 // suffixes
9921 vector<string> glob_suffixes;
9922 glob_suffixes.push_back("include/trace/events/*.h");
9923 glob_suffixes.push_back("include/trace/*.h");
9924 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
f89ff3e2 9925 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
ca51c2cd 9926 glob_suffixes.push_back("fs/xfs/xfs_trace*.h");
d4393459
FCE
9927
9928 // compute cartesian product
9929 vector<string> globs;
9930 for (unsigned i=0; i<glob_prefixes.size(); i++)
9931 for (unsigned j=0; j<glob_suffixes.size(); j++)
9932 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
9933
8aa43b8d 9934 set<string> duped_headers;
d4393459
FCE
9935 for (unsigned z = 0; z < globs.size(); z++)
9936 {
9937 string glob_str = globs[z];
9938 if (s.verbose > 3)
b530b5b3 9939 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 9940
067cc66f
CM
9941 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
9942 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
9943 throw runtime_error("Error globbing tracepoint");
9944
f982c59b
JS
9945 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
9946 {
9947 string header(trace_glob.gl_pathv[i]);
9948
9949 // filter out a few known "internal-only" headers
60d98537
JS
9950 if (endswith(header, "/define_trace.h") ||
9951 endswith(header, "/ftrace.h") ||
9952 endswith(header, "/trace_events.h") ||
9953 endswith(header, "_event_types.h"))
f982c59b
JS
9954 continue;
9955
8aa43b8d
JS
9956 // skip identical headers from the build and source trees.
9957 size_t root_pos = header.rfind("include/");
9958 if (root_pos != string::npos &&
9959 !duped_headers.insert(header.substr(root_pos + 8)).second)
9960 continue;
9961
55e50c24 9962 system_headers.push_back(header);
f982c59b
JS
9963 }
9964 globfree(&trace_glob);
9965 }
9966
c9ccb642
FCE
9967 // Build tracequery modules
9968 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 9969
f982c59b
JS
9970 // TODO: consider other sources of tracepoint headers too, like from
9971 // a command-line parameter or some environment or .systemtaprc
47dd066d 9972
59c11f91 9973 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
9974 return true;
9975}
47dd066d 9976
0a6f5a3f
JS
9977void
9978tracepoint_builder::build(systemtap_session& s,
9979 probe *base, probe_point *location,
9980 literal_map_t const& parameters,
9981 vector<derived_probe*>& finished_results)
9982{
9983 if (!init_dw(s))
9984 return;
47dd066d 9985
75ead1f7
JS
9986 string tracepoint;
9987 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 9988
75ead1f7 9989 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 9990 dw->iterate_over_modules(&query_module, &q);
47dd066d 9991}
47dd066d 9992
e6fe60e7 9993
b55bc428 9994// ------------------------------------------------------------------------
bd2b1e68 9995// Standard tapset registry.
b55bc428
FCE
9996// ------------------------------------------------------------------------
9997
7a053d3b 9998void
f8220a7b 9999register_standard_tapsets(systemtap_session & s)
b55bc428 10000{
47e0478e 10001 register_tapset_been(s);
93646f4d 10002 register_tapset_itrace(s);
dd0e4fa7 10003 register_tapset_mark(s);
7a212aa8 10004 register_tapset_procfs(s);
912e8c59 10005 register_tapset_timers(s);
8d9609f5 10006 register_tapset_netfilter(s);
b84779a5 10007 register_tapset_utrace(s);
b98a8d73 10008
7a24d422 10009 // dwarf-based kprobe/uprobe parts
c4ce66a1 10010 dwarf_derived_probe::register_patterns(s);
30a279be 10011
888af770
FCE
10012 // XXX: user-space starter set
10013 s.pattern_root->bind_num(TOK_PROCESS)
10014 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10015 ->bind_privilege(pr_all)
888af770
FCE
10016 ->bind(new uprobe_builder ());
10017 s.pattern_root->bind_num(TOK_PROCESS)
10018 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10019 ->bind_privilege(pr_all)
888af770
FCE
10020 ->bind(new uprobe_builder ());
10021
0a6f5a3f
JS
10022 // kernel tracepoint probes
10023 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10024 ->bind(new tracepoint_builder());
10025
e6fe60e7
AM
10026 // Kprobe based probe
10027 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10028 ->bind(new kprobe_builder());
10029 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10030 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
10031 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10032 ->bind(new kprobe_builder());
b6371390
JS
10033 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10034 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10035 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10036 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10037 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10038 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10039 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10040 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10041 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
10042
10043 //Hwbkpt based probe
b47f3a55
FCE
10044 // NB: we formerly registered the probe point types only if the kernel configuration
10045 // allowed it. However, we get better error messages if we allow probes to resolve.
10046 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10047 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10048 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10049 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10050 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10051 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10052 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10053 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10054 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10055 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10056 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10057 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10058 // length supported with address only, not symbol names
83ea76b1
WC
10059
10060 //perf event based probe
4763f713 10061 register_tapset_perf(s);
b55bc428 10062}
dc38c0ae
DS
10063
10064
b20febf3
FCE
10065vector<derived_probe_group*>
10066all_session_groups(systemtap_session& s)
dc38c0ae 10067{
b20febf3 10068 vector<derived_probe_group*> g;
912e8c59
JS
10069
10070#define DOONE(x) \
10071 if (s. x##_derived_probes) \
10072 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
10073
10074 // Note that order *is* important here. We want to make sure we
10075 // register (actually run) begin probes before any other probe type
10076 // is run. Similarly, when unregistering probes, we want to
10077 // unregister (actually run) end probes after every other probe type
10078 // has be unregistered. To do the latter,
10079 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
10080 DOONE(be);
10081 DOONE(dwarf);
888af770 10082 DOONE(uprobe);
b20febf3
FCE
10083 DOONE(timer);
10084 DOONE(profile);
10085 DOONE(mark);
0a6f5a3f 10086 DOONE(tracepoint);
e6fe60e7 10087 DOONE(kprobe);
dd225250 10088 DOONE(hwbkpt);
83ea76b1 10089 DOONE(perf);
b20febf3 10090 DOONE(hrtimer);
ce82316f 10091 DOONE(procfs);
8d9609f5 10092 DOONE(netfilter);
935447c8
DS
10093
10094 // Another "order is important" item. We want to make sure we
10095 // "register" the dummy task_finder probe group after all probe
10096 // groups that use the task_finder.
10097 DOONE(utrace);
a96d1db0 10098 DOONE(itrace);
935447c8 10099 DOONE(task_finder);
b20febf3
FCE
10100#undef DOONE
10101 return g;
46b84a80 10102}
73267b89
JS
10103
10104/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.389323 seconds and 5 git commands to generate.