]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
sdt_query: set well-formed intermediate probe
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
ef36f781 2// Copyright (C) 2005-2014 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"
f31a77f5 16#include "tapset-dynprobe.h"
56e12059 17#include "translate.h"
dc38c0ae 18#include "session.h"
72dbc915 19#include "util.h"
0a6f5a3f 20#include "buildrun.h"
86bf665e 21#include "dwarf_wrappers.h"
2e67a43b 22#include "auto_free.h"
b278033a 23#include "hash.h"
440f755a 24#include "dwflpp.h"
5f8ca04f 25#include "setupdwfl.h"
6b51ee12 26#include <gelf.h>
22d737e8 27
4d0d9e8a 28#include "sdt_types.h"
bd2b1e68 29
3b579393
FCE
30#include <cstdlib>
31#include <algorithm>
bd2b1e68 32#include <deque>
56e12059 33#include <iostream>
d1bcbe71 34#include <fstream>
bd2b1e68 35#include <map>
ec4373ff 36#include <set>
56e12059 37#include <sstream>
bd2b1e68 38#include <stdexcept>
b55bc428 39#include <vector>
67959c62 40#include <stack>
e36387d7 41#include <cstdarg>
29e64872 42#include <cassert>
1969b5bc 43#include <iomanip>
f781f849 44#include <cerrno>
bd2b1e68
GH
45
46extern "C" {
df8fadee 47#include <fcntl.h>
bd2b1e68 48#include <elfutils/libdwfl.h>
7a053d3b 49#include <elfutils/libdw.h>
77de5e9e
GH
50#include <dwarf.h>
51#include <elf.h>
52#include <obstack.h>
b20febf3 53#include <glob.h>
30a279be 54#include <fnmatch.h>
5f0a03a6 55#include <stdio.h>
349dc70e 56#include <sys/types.h>
37001baa 57#include <sys/stat.h>
aaf7ffe8 58#include <math.h>
aff5d390 59#include <regex.h>
37001baa 60#include <unistd.h>
4b1ad75e
RM
61
62#define __STDC_FORMAT_MACROS
63#include <inttypes.h>
bd2b1e68 64}
77de5e9e 65
508059f0
MW
66// Old elf.h doesn't know about this machine type.
67#ifndef EM_AARCH64
68#define EM_AARCH64 183
69#endif
70
56e12059
FCE
71
72using namespace std;
2171f774 73using namespace __gnu_cxx;
56e12059 74
47dd066d 75
b20febf3
FCE
76
77// ------------------------------------------------------------------------
faea5e16
JS
78
79string
80common_probe_init (derived_probe* p)
81{
26e63673
JS
82 assert(p->session_index != (unsigned)-1);
83 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
84}
85
86
b20febf3 87void
71db462b
DS
88common_probe_entryfn_prologue (systemtap_session& s,
89 string statestr, string probe,
90 string probe_type, bool overload_processing)
b20febf3 91{
944c9a7a 92 if (s.runtime_usermode_p())
ac34f2aa
JS
93 {
94 // If session_state() is NULL, then we haven't even initialized shm yet,
95 // and there's *nothing* for the probe to do. (even alibi is in shm)
96 // So failure skips this whole block through the end of the epilogue.
97 s.op->newline() << "if (likely(session_state())) {";
e481ab2e 98 s.op->indent(1);
ac34f2aa
JS
99 }
100
71db462b 101 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 102 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 103 s.op->newline() << "#else";
653e6a9a 104
e481ab2e
JS
105 if (s.runtime_usermode_p())
106 s.op->newline() << "int _stp_saved_errno = errno;";
107
fee09ad5 108 s.op->newline() << "struct context* __restrict__ c = NULL;";
71db462b
DS
109 s.op->newline() << "#if !INTERRUPTIBLE";
110 s.op->newline() << "unsigned long flags;";
111 s.op->newline() << "#endif";
b20febf3 112
f887a8c9 113 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 114 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
115 s.op->newline() << "#endif";
116 if (overload_processing && !s.runtime_usermode_p())
71db462b 117 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 118 else
71db462b 119 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 120
f887a8c9
DS
121 if (! s.runtime_usermode_p())
122 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
123 else
124 {
125 s.op->newline() << "struct timespec timespec_atstart;";
45639d96 126 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atstart);";
f887a8c9 127 }
71db462b 128 s.op->newline() << "#endif";
994aac0e 129
d2d39de6 130 s.op->newline() << "#if !INTERRUPTIBLE";
71db462b
DS
131 s.op->newline() << "local_irq_save (flags);";
132 s.op->newline() << "#endif";
b20febf3 133
ac3af990 134 if (! s.runtime_usermode_p())
71db462b
DS
135 {
136 // Check for enough free enough stack space
137 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
138 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
139 // XXX: may need porting to platforms where task_struct is not
140 // at bottom of kernel stack NB: see also
141 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 142 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 143 s.op->newline() << "#ifdef STP_TIMING";
065d5567 144 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
145 s.op->newline() << "#endif";
146 s.op->newline() << "goto probe_epilogue;";
147 s.op->newline(-1) << "}";
148 }
c931ec8a 149
065d5567 150 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
151 s.op->newline(1) << "goto probe_epilogue;";
152 s.op->indent(-1);
9a604fac 153
1d0e697d 154 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
d2d39de6 155 s.op->newline() << "if (!c) {";
71db462b 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 161 s.op->newline() << "#endif";
71db462b
DS
162 s.op->newline() << "goto probe_epilogue;";
163 s.op->newline(-1) << "}";
d2d39de6 164
71db462b
DS
165 s.op->newline();
166 s.op->newline() << "c->last_stmt = 0;";
167 s.op->newline() << "c->last_error = 0;";
168 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
169 s.op->newline() << "c->uregs = 0;";
170 s.op->newline() << "c->kregs = 0;";
171 s.op->newline() << "#if defined __ia64__";
172 s.op->newline() << "c->unwaddr = 0;";
173 s.op->newline() << "#endif";
f4d70a33
JS
174 if (s.runtime_usermode_p())
175 s.op->newline() << "c->probe_index = " << probe << "->index;";
71db462b
DS
176 s.op->newline() << "c->probe_point = " << probe << "->pp;";
177 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
178 s.op->newline() << "c->probe_name = " << probe << "->pn;";
179 s.op->newline() << "#endif";
180 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 181 // reset Individual Probe State union
71db462b 182 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 183 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
184 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
185 s.op->newline() << "c->regparm = 0;";
186 s.op->newline() << "#endif";
e0a17418 187
152fa051
LB
188 if(!s.suppress_time_limits){
189 s.op->newline() << "#if INTERRUPTIBLE";
190 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
191 s.op->newline() << "#else";
192 s.op->newline() << "c->actionremaining = MAXACTION;";
193 s.op->newline() << "#endif";
194 }
9915575b
FCE
195 // NB: The following would actually be incorrect.
196 // That's because cycles_sum/cycles_base values are supposed to survive
197 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
198 // cycles), the values will be reset.
199 /*
71db462b
DS
200 s.op->newline() << "#ifdef STP_OVERLOAD";
201 s.op->newline() << "c->cycles_sum = 0;";
202 s.op->newline() << "c->cycles_base = 0;";
203 s.op->newline() << "#endif";
9915575b 204 */
44cfbe25
SM
205
206 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
207 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
208 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
209 s.op->newline() << "#endif";
b20febf3 210}
9a604fac 211
a44a0785 212
b20febf3 213void
f887a8c9
DS
214common_probe_entryfn_epilogue (systemtap_session& s,
215 bool overload_processing)
b20febf3 216{
f887a8c9
DS
217 if (overload_processing && !s.runtime_usermode_p())
218 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 219 else
f887a8c9
DS
220 s.op->newline() << "#ifdef STP_TIMING";
221 s.op->newline() << "{";
222 s.op->indent(1);
223 if (! s.runtime_usermode_p())
224 {
225 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
226 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
227 // fewer, if the hardware counter rolls over really quickly. We
228 // handle 32-bit wraparound here.
229 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
230 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
231 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
232 s.op->indent(-1);
233 }
234 else
235 {
236 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
237 s.op->newline() << "long cycles_elapsed;";
45639d96 238 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atend);";
f887a8c9
DS
239 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
240 // 'cycles_elapsed' is really elapsed nanoseconds
241 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
242 }
243
244 s.op->newline() << "#ifdef STP_TIMING";
245 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
246 s.op->newline() << "#endif";
247
248 if (overload_processing && !s.runtime_usermode_p())
249 {
250 s.op->newline() << "#ifdef STP_OVERLOAD";
251 s.op->newline() << "{";
a58d79d0
DS
252 // If the cycle count has wrapped (cycles_atend > cycles_base),
253 // let's go ahead and pretend the interval has been reached.
254 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
255 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
256 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
257 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
258 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
259
260 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
261 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
262 // has overloaded the system and we need to quit.
7baf48e9
FCE
263 // NB: this is not suppressible via --suppress-runtime-errors,
264 // because this is a system safety metric that we cannot trust
265 // unprivileged users to override.
f887a8c9
DS
266 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
267 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
268 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
269 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
270 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
271 s.op->newline(-1) << "}";
272
273 s.op->newline() << "c->cycles_base = cycles_atend;";
274 s.op->newline() << "c->cycles_sum = 0;";
275 s.op->newline(-1) << "}";
276 s.op->newline(-1) << "}";
277 s.op->newline() << "#endif";
a58d79d0 278 }
e57b735a 279
f887a8c9
DS
280 s.op->newline(-1) << "}";
281 s.op->newline() << "#endif";
e57b735a 282
f887a8c9
DS
283 s.op->newline() << "c->probe_point = 0;"; // vacated
284 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
285 s.op->newline() << "c->probe_name = 0;";
286 s.op->newline() << "#endif";
287 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
288
289
f887a8c9
DS
290 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
291 s.op->indent(1);
292 if (s.suppress_handler_errors) // PR 13306
b78a0fbb 293 {
065d5567 294 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
295 }
296 else
297 {
f887a8c9
DS
298 s.op->newline() << "if (c->last_stmt != NULL)";
299 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
300 s.op->newline(-1) << "else";
301 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
302 s.op->indent(-1);
065d5567
JS
303 s.op->newline() << "atomic_inc (error_count());";
304 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
305 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
306 s.op->newline() << "_stp_exit ();";
307 s.op->newline(-1) << "}";
7baf48e9
FCE
308 }
309
f887a8c9 310 s.op->newline(-1) << "}";
7baf48e9
FCE
311
312
f887a8c9
DS
313 s.op->newline(-1) << "probe_epilogue:"; // context is free
314 s.op->indent(1);
e57b735a 315
f887a8c9 316 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
317 {
318 // Check for excessive skip counts.
065d5567
JS
319 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
320 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
321 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
322 s.op->newline(-1) << "}";
7baf48e9 323 }
e57b735a 324
d2d39de6
JS
325 // We mustn't release the context until after all _stp_error(), so dyninst
326 // mode can still access the log buffers stored therein.
327 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
328
329 s.op->newline() << "#if !INTERRUPTIBLE";
f887a8c9
DS
330 s.op->newline() << "local_irq_restore (flags);";
331 s.op->newline() << "#endif";
653e6a9a 332
944c9a7a 333 if (s.runtime_usermode_p())
ac34f2aa
JS
334 {
335 s.op->newline() << "errno = _stp_saved_errno;";
ac34f2aa 336 }
e481ab2e
JS
337
338 s.op->newline() << "#endif // STP_ALIBI";
339
340 if (s.runtime_usermode_p())
341 s.op->newline(-1) << "}";
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");
e7d4410d
LB
368static const string TOK_METHOD("method");
369static const string TOK_CLASS("class");;
c31add50
JL
370static const string TOK_CALLEE("callee");;
371static const string TOK_CALLEES("callees");;
e57b735a 372
440f755a
JS
373// Can we handle this query with just symbol-table info?
374enum dbinfo_reqt
375{
376 dbr_unknown,
377 dbr_none, // kernel.statement(NUM).absolute
378 dbr_need_symtab, // can get by with symbol table if there's no dwarf
379 dbr_need_dwarf
380};
e57b735a 381
20e4a32c 382
673d0add 383struct dwarf_query; // forward decl
20e4a32c 384
45582cbc
JL
385static int query_cu (Dwarf_Die * cudie, dwarf_query *q);
386static void query_addr(Dwarf_Addr addr, dwarf_query *q);
387static void query_plt_statement(dwarf_query *q);
a781f401 388
440f755a
JS
389struct
390symbol_table
391{
392 module_info *mod_info; // associated module
393 map<string, func_info*> map_by_name;
1c6b77e5 394 multimap<Dwarf_Addr, func_info*> map_by_addr;
2a4acb09
JL
395 map<string, Dwarf_Addr> globals;
396 map<string, Dwarf_Addr> locals;
1c6b77e5 397 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
398 typedef pair<iterator_t, iterator_t> range_t;
399#ifdef __powerpc__
400 GElf_Word opd_section;
401#endif
2867a2a1
JS
402 void add_symbol(const char *name, bool weak, bool descriptor,
403 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a
JS
404 enum info_status get_from_elf();
405 void prepare_section_rejection(Dwfl_Module *mod);
406 bool reject_section(GElf_Word section);
440f755a
JS
407 void purge_syscall_stubs();
408 func_info *lookup_symbol(const string& name);
409 Dwarf_Addr lookup_symbol_address(const string& name);
410 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 411 func_info *get_first_func();
7a053d3b 412
440f755a
JS
413 symbol_table(module_info *mi) : mod_info(mi) {}
414 ~symbol_table();
415};
77de5e9e 416
440f755a
JS
417static bool null_die(Dwarf_Die *die)
418{
822a6a3d 419 static Dwarf_Die null;
440f755a
JS
420 return (!die || !memcmp(die, &null, sizeof(null)));
421}
c4ce66a1
JS
422
423
7a053d3b 424enum
bd2b1e68 425function_spec_type
7a053d3b 426 {
bd2b1e68
GH
427 function_alone,
428 function_and_file,
7a053d3b 429 function_file_and_line
bd2b1e68
GH
430 };
431
ec4373ff 432
bd2b1e68 433struct dwarf_builder;
f10534c6 434struct dwarf_var_expanding_visitor;
77de5e9e 435
2930abc7 436
b20febf3
FCE
437// XXX: This class is a candidate for subclassing to separate
438// the relocation vs non-relocation variants. Likewise for
439// kprobe vs kretprobe variants.
440
441struct dwarf_derived_probe: public derived_probe
b55bc428 442{
b20febf3
FCE
443 dwarf_derived_probe (const string& function,
444 const string& filename,
445 int line,
446 const string& module,
447 const string& section,
448 Dwarf_Addr dwfl_addr,
2930abc7 449 Dwarf_Addr addr,
b20febf3
FCE
450 dwarf_query & q,
451 Dwarf_Die* scope_die);
20e4a32c 452
b20febf3
FCE
453 string module;
454 string section;
455 Dwarf_Addr addr;
63b4fd14 456 string path;
27dc09b1 457 bool has_process;
2930abc7 458 bool has_return;
c9bad430 459 bool has_maxactive;
63b4fd14 460 bool has_library;
c9bad430 461 long maxactive_val;
4ad95bbc 462 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
463 string user_path;
464 string user_lib;
b95e2b79 465 bool access_vars;
2930abc7 466
af234c40
JS
467 unsigned saved_longs, saved_strings;
468 dwarf_derived_probe* entry_handler;
469
b8da0ad1 470 void printsig (std::ostream &o) const;
6b66b9f7 471 virtual void join_group (systemtap_session& s);
3689db05 472 void emit_probe_local_init(systemtap_session& s, translator_output * o);
d0bfd2ac 473 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 474
42e38653 475 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
476 void print_dupe_stamp(ostream& o);
477
bd2b1e68 478 // Pattern registration helpers.
7a053d3b 479 static void register_statement_variants(match_node * root,
27dc09b1 480 dwarf_builder * dw,
42e38653 481 privilege_t privilege);
fd6602a0 482 static void register_function_variants(match_node * root,
27dc09b1 483 dwarf_builder * dw,
42e38653 484 privilege_t privilege);
440d9b00
DB
485 static void register_function_and_statement_variants(systemtap_session& s,
486 match_node * root,
27dc09b1 487 dwarf_builder * dw,
42e38653 488 privilege_t privilege);
b1615c74
JS
489 static void register_sdt_variants(systemtap_session& s,
490 match_node * root,
491 dwarf_builder * dw);
492 static void register_plt_variants(systemtap_session& s,
493 match_node * root,
494 dwarf_builder * dw);
c4ce66a1 495 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
496
497protected:
498 dwarf_derived_probe(probe *base,
499 probe_point *location,
500 Dwarf_Addr addr,
501 bool has_return):
74fe61bc
LB
502 derived_probe(base, location), addr(addr), has_process(0),
503 has_return(has_return), has_maxactive(0), has_library(0),
504 maxactive_val(0), access_vars(false), saved_longs(0),
505 saved_strings(0), entry_handler(0)
6b66b9f7
JS
506 {}
507
508private:
d0bfd2ac 509 list<string> args;
8c67c337 510 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
511};
512
dc38c0ae 513
6b66b9f7 514struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 515{
6d0f3f0c 516 int pid; // 0 => unrestricted
0973d815 517
6d0f3f0c
FCE
518 uprobe_derived_probe (const string& function,
519 const string& filename,
520 int line,
521 const string& module,
6d0f3f0c
FCE
522 const string& section,
523 Dwarf_Addr dwfl_addr,
524 Dwarf_Addr addr,
525 dwarf_query & q,
6b66b9f7
JS
526 Dwarf_Die* scope_die):
527 dwarf_derived_probe(function, filename, line, module, section,
528 dwfl_addr, addr, q, scope_die), pid(0)
529 {}
6d0f3f0c 530
0973d815
FCE
531 // alternate constructor for process(PID).statement(ADDR).absolute
532 uprobe_derived_probe (probe *base,
533 probe_point *location,
534 int pid,
535 Dwarf_Addr addr,
6b66b9f7
JS
536 bool has_return):
537 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
538 {}
9ace370f 539
6d0f3f0c 540 void join_group (systemtap_session& s);
2865d17a 541
42e38653 542 void emit_privilege_assertion (translator_output*);
8f6d8c2b 543 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
544 void getargs(std::list<std::string> &arg_set) const;
545 void saveargs(int nargs);
546private:
547 list<string> args;
6d0f3f0c
FCE
548};
549
dc38c0ae
DS
550struct dwarf_derived_probe_group: public derived_probe_group
551{
552private:
b20febf3
FCE
553 multimap<string,dwarf_derived_probe*> probes_by_module;
554 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
555
556public:
08b5a50c 557 dwarf_derived_probe_group() {}
b20febf3
FCE
558 void enroll (dwarf_derived_probe* probe);
559 void emit_module_decls (systemtap_session& s);
560 void emit_module_init (systemtap_session& s);
b4be7cbc 561 void emit_module_refresh (systemtap_session& s);
b20febf3 562 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
563};
564
565
20c6c071 566// Helper struct to thread through the dwfl callbacks.
2c384610 567struct base_query
20c6c071 568{
c4ce66a1
JS
569 base_query(dwflpp & dw, literal_map_t const & params);
570 base_query(dwflpp & dw, const string & module_val);
2c384610 571 virtual ~base_query() {}
bd2b1e68 572
5227f1ea 573 systemtap_session & sess;
2c384610 574 dwflpp & dw;
5227f1ea 575
070764c0
JL
576 // Used to keep track of which modules were visited during
577 // iterate_over_modules()
578 set<string> visited_modules;
579
bd2b1e68 580 // Parameter extractors.
86bf665e 581 static bool has_null_param(literal_map_t const & params,
888af770 582 string const & k);
86bf665e 583 static bool get_string_param(literal_map_t const & params,
bd2b1e68 584 string const & k, string & v);
86bf665e 585 static bool get_number_param(literal_map_t const & params,
bd2b1e68 586 string const & k, long & v);
86bf665e 587 static bool get_number_param(literal_map_t const & params,
c239d28c 588 string const & k, Dwarf_Addr & v);
bbbc7241 589 static void query_library_callback (base_query *me, const char *data);
45cdb40e 590 static void query_plt_callback (base_query *me, const char *link, size_t addr);
f301a9ff 591 virtual void query_library (const char *data) = 0;
576eaefe 592 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 593
b55bc428 594
2c384610
DS
595 // Extracted parameters.
596 bool has_kernel;
91af0778
FCE
597 bool has_module;
598 bool has_process;
63b4fd14 599 bool has_library;
576eaefe
SC
600 bool has_plt;
601 bool has_statement;
2c384610 602 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 603 string path; // executable path if module is a .so
576eaefe 604 string plt_val; // has_plt => plt wildcard
2c384610
DS
605
606 virtual void handle_query_module() = 0;
607};
608
609
c4ce66a1 610base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 611 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 612{
91af0778 613 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
614 if (has_kernel)
615 module_val = "kernel";
91af0778
FCE
616
617 has_module = get_string_param (params, TOK_MODULE, module_val);
618 if (has_module)
619 has_process = false;
4baf0e53 620 else
d0a7f5a9 621 {
63b4fd14 622 string library_name;
576eaefe 623 long statement_num_val;
d0a7f5a9 624 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 625 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
626 if ((has_plt = has_null_param (params, TOK_PLT)))
627 plt_val = "*";
628 else has_plt = get_string_param (params, TOK_PLT, plt_val);
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
e2941743
JL
747 // Used in .callee[s] probes, when calling iterate_over_callees() (which
748 // provides the actual stack). Retains the addrs of the callers unwind addr
749 // where the callee is found. Specifies multiple callers. E.g. when a callee
750 // at depth 2 is found, callers[1] has the addr of the caller, and callers[0]
751 // has the addr of the caller's caller.
752 stack<Dwarf_Addr> *callers;
753
20c6c071
GH
754 bool has_function_str;
755 bool has_statement_str;
756 bool has_function_num;
757 bool has_statement_num;
7a053d3b
RM
758 string statement_str_val;
759 string function_str_val;
c239d28c
GH
760 Dwarf_Addr statement_num_val;
761 Dwarf_Addr function_num_val;
20c6c071 762
b8da0ad1 763 bool has_call;
4bda987e 764 bool has_exported;
b8da0ad1 765 bool has_inline;
20c6c071
GH
766 bool has_return;
767
c9bad430
DS
768 bool has_maxactive;
769 long maxactive_val;
770
20c6c071
GH
771 bool has_label;
772 string label_val;
773
c31add50
JL
774 bool has_callee;
775 string callee_val;
776
777 bool has_callees_num;
778 long callees_num_val;
779
20c6c071
GH
780 bool has_relative;
781 long relative_val;
782
37ebca01
FCE
783 bool has_absolute;
784
467bea43
SC
785 bool has_mark;
786
5f0a03a6
JK
787 enum dbinfo_reqt dbinfo_reqt;
788 enum dbinfo_reqt assess_dbinfo_reqt();
789
7d6d0afc 790 void parse_function_spec(const string & spec);
20c6c071 791 function_spec_type spec_type;
7d6d0afc 792 vector<string> scopes;
20c6c071
GH
793 string function;
794 string file;
4a81c0d9
JL
795 lineno_t lineno_type;
796 int linenos[2];
5f0a03a6 797 bool query_done; // Found exact match
20c6c071 798
5a617dc6
JL
799 // Holds the prologue end of the current function
800 Dwarf_Addr prologue_end;
801
bd25380d 802 set<string> filtered_srcfiles;
7e1279ea
FCE
803
804 // Map official entrypc -> func_info object
86bf665e
TM
805 inline_instance_map_t filtered_inlines;
806 func_info_map_t filtered_functions;
4df79aaf 807
959ccfed
JL
808 // Helper when we want to iterate over both
809 base_func_info_map_t filtered_all();
810
4df79aaf 811 void query_module_functions ();
e772a6e7
JL
812
813 string final_function_name(const string& final_func,
814 const string& final_file,
815 int final_line);
b55bc428
FCE
816};
817
98afd80e 818
435f53a7
FCE
819static void delete_session_module_cache (systemtap_session& s); // forward decl
820
821
98afd80e 822struct dwarf_builder: public derived_probe_builder
b55bc428 823{
665e1256 824 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 825 map <string,dwflpp*> user_dw;
b642c901
SC
826 string user_path;
827 string user_lib;
44ffe90c
JL
828
829 // Holds modules to suggest functions from. NB: aggregates over
830 // recursive calls to build() when deriving globby probes.
831 set <string> modules_seen;
832
ae2552da 833 dwarf_builder() {}
aa30ccd3 834
ae2552da 835 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 836 {
ea14cf67
FCE
837 if (kern_dw[module] == 0)
838 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 839 return kern_dw[module];
707bf35e
JS
840 }
841
842 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
843 {
ea14cf67
FCE
844 if (user_dw[module] == 0)
845 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
846 return user_dw[module];
847 }
7a24d422
FCE
848
849 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 850 void dwarf_build_no_more (bool)
aa30ccd3 851 {
435f53a7
FCE
852 delete_map(kern_dw);
853 delete_map(user_dw);
7a24d422
FCE
854 }
855
856 void build_no_more (systemtap_session &s)
857 {
858 dwarf_build_no_more (s.verbose > 3);
435f53a7 859 delete_session_module_cache (s);
aa30ccd3
FCE
860 }
861
e38d6504
RM
862 ~dwarf_builder()
863 {
7a24d422 864 dwarf_build_no_more (false);
c8959a29 865 }
aa30ccd3 866
5227f1ea 867 virtual void build(systemtap_session & sess,
7a053d3b 868 probe * base,
20c6c071 869 probe_point * location,
86bf665e 870 literal_map_t const & parameters,
20c6c071 871 vector<derived_probe *> & finished_results);
b55bc428
FCE
872};
873
5111fc3e 874
e1278bd4 875dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
876 probe_point * base_loc,
877 dwflpp & dw,
86bf665e 878 literal_map_t const & params,
b642c901
SC
879 vector<derived_probe *> & results,
880 const string user_path,
881 const string user_lib)
e2941743
JL
882 : base_query(dw, params), results(results), base_probe(base_probe),
883 base_loc(base_loc), user_path(user_path), user_lib(user_lib),
5a617dc6 884 callers(NULL), has_relative(false), relative_val(0), prologue_end(0)
bd2b1e68
GH
885{
886 // Reduce the query to more reasonable semantic values (booleans,
887 // extracted strings, numbers, etc).
bd2b1e68
GH
888 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
889 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
890
891 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
892 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
893
0f336e95 894 has_label = get_string_param(params, TOK_LABEL, label_val);
c31add50
JL
895 has_callee = get_string_param(params, TOK_CALLEE, callee_val);
896 if (has_null_param(params, TOK_CALLEES))
897 { // .callees ==> .callees(1) (also equivalent to .callee("*"))
898 has_callees_num = true;
899 callees_num_val = 1;
900 }
901 else
902 {
903 has_callees_num = get_number_param(params, TOK_CALLEES, callees_num_val);
904 if (has_callees_num && callees_num_val < 1)
905 throw SEMANTIC_ERROR(_(".callees(N) only acceptable for N >= 1"),
906 base_probe->tok);
907 }
0f336e95 908
b8da0ad1 909 has_call = has_null_param(params, TOK_CALL);
4bda987e 910 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 911 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 912 has_return = has_null_param(params, TOK_RETURN);
c9bad430 913 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 914 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 915 has_mark = false;
37ebca01 916
bd2b1e68 917 if (has_function_str)
7d6d0afc 918 parse_function_spec(function_str_val);
bd2b1e68 919 else if (has_statement_str)
7d6d0afc 920 parse_function_spec(statement_str_val);
0daad364 921
5f0a03a6
JK
922 dbinfo_reqt = assess_dbinfo_reqt();
923 query_done = false;
0daad364
JS
924}
925
926
2c384610 927void
5f0a03a6 928dwarf_query::query_module_dwarf()
2c384610
DS
929{
930 if (has_function_num || has_statement_num)
931 {
932 // If we have module("foo").function(0xbeef) or
933 // module("foo").statement(0xbeef), the address is relative
934 // to the start of the module, so we seek the function
935 // number plus the module's bias.
6b517475
JS
936 Dwarf_Addr addr = has_function_num ?
937 function_num_val : statement_num_val;
08d1d520
MW
938
939 // These are raw addresses, we need to know what the elf_bias
940 // is to feed it to libdwfl based functions.
941 Dwarf_Addr elf_bias;
942 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
943 assert(elf);
944 addr += elf_bias;
6b517475 945 query_addr(addr, this);
2c384610
DS
946 }
947 else
948 {
949 // Otherwise if we have a function("foo") or statement("foo")
950 // specifier, we have to scan over all the CUs looking for
951 // the function(s) in question
952 assert(has_function_str || has_statement_str);
4df79aaf
JS
953
954 // For simple cases, no wildcard and no source:line, we can do a very
955 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
956 if (spec_type == function_alone &&
957 !dw.name_has_wildcard(function) &&
958 !startswith(function, "_Z"))
4df79aaf
JS
959 query_module_functions();
960 else
337b7c44 961 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
962 }
963}
964
5f0a03a6
JK
965static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
966 dwarf_query * q);
967
91bb9081
LB
968static void
969query_symtab_func_info (func_info & fi, dwarf_query * q)
970{
971 assert(null_die(&fi.die));
972
973 Dwarf_Addr addr = fi.addr;
974
975 // Now compensate for the dw bias because the addresses come
976 // from dwfl_module_symtab, so fi->addr is NOT a normal dw address.
977 q->dw.get_module_dwarf(false, false);
978 addr -= q->dw.module_bias;
979
980 // If there are already probes in this module, lets not duplicate.
981 // This can come from other weak symbols/aliases or existing
a41f2ad7
JS
982 // matches from Dwarf DIE functions. Try to add this addr to the
983 // collection, and only continue if it was new.
984 if (q->alias_dupes.insert(addr).second)
985 query_func_info(addr, fi, q);
91bb9081
LB
986}
987
5f0a03a6
JK
988void
989dwarf_query::query_module_symtab()
990{
991 // Get the symbol table if it's necessary, sufficient, and not already got.
992 if (dbinfo_reqt == dbr_need_dwarf)
993 return;
994
995 module_info *mi = dw.mod_info;
996 if (dbinfo_reqt == dbr_need_symtab)
997 {
998 if (mi->symtab_status == info_unknown)
5f52fafe 999 mi->get_symtab();
5f0a03a6
JK
1000 if (mi->symtab_status == info_absent)
1001 return;
1002 }
1003
1004 func_info *fi = NULL;
1005 symbol_table *sym_table = mi->sym_table;
1006
1007 if (has_function_str)
1008 {
1009 // Per dwarf_query::assess_dbinfo_reqt()...
1010 assert(spec_type == function_alone);
1011 if (dw.name_has_wildcard(function_str_val))
1012 {
2e67a43b 1013 symbol_table::iterator_t iter;
1c6b77e5
JS
1014 for (iter = sym_table->map_by_addr.begin();
1015 iter != sym_table->map_by_addr.end();
2e67a43b 1016 ++iter)
5f0a03a6 1017 {
1c6b77e5 1018 fi = iter->second;
5f0a03a6
JK
1019 if (!null_die(&fi->die))
1020 continue; // already handled in query_module_dwarf()
1021 if (dw.function_name_matches_pattern(fi->name, function_str_val))
91bb9081 1022 query_symtab_func_info(*fi, this);
5f0a03a6
JK
1023 }
1024 }
1025 else
1026 {
1027 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1028 if (fi && !fi->descriptor && null_die(&fi->die))
91bb9081 1029 query_symtab_func_info(*fi, this);
5f0a03a6 1030 }
5f0a03a6
JK
1031 }
1032}
1033
1034void
1035dwarf_query::handle_query_module()
1036{
f4faaf86
JS
1037 if (has_plt && has_statement_num)
1038 {
1039 query_plt_statement (this);
1040 return;
1041 }
1042
0035051e 1043 bool report = dbinfo_reqt == dbr_need_dwarf;
1c6b77e5
JS
1044 dw.get_module_dwarf(false, report);
1045
1046 // prebuild the symbol table to resolve aliases
5f52fafe 1047 dw.mod_info->get_symtab();
1c6b77e5 1048
857bdfd1
JS
1049 // reset the dupe-checking for each new module
1050 alias_dupes.clear();
7fdd3e2c 1051 inline_dupes.clear();
857bdfd1 1052
5f0a03a6
JK
1053 if (dw.mod_info->dwarf_status == info_present)
1054 query_module_dwarf();
1c6b77e5 1055
91bb9081
LB
1056 // Consult the symbol table, asm and weak functions can show up
1057 // in the symbol table but not in dwarf and minidebuginfo is
1058 // located in the gnu_debugdata section, alias_dupes checking
1059 // is done before adding any probe points
1060 if (!query_done && !pending_interrupts)
5f0a03a6
JK
1061 query_module_symtab();
1062}
1063
2c384610 1064
7d6d0afc
JS
1065void
1066dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1067{
4a81c0d9
JL
1068 lineno_type = ABSOLUTE;
1069 linenos[0] = linenos[1] = 0;
1d12a9b2 1070
91699a70 1071 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1072
7d6d0afc 1073 // look for named scopes
91699a70
JS
1074 scope_pos = spec.rfind("::");
1075 if (scope_pos != string::npos)
bd2b1e68 1076 {
91699a70
JS
1077 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1078 scope_pos += 2;
bd2b1e68 1079 }
91699a70
JS
1080 else
1081 scope_pos = 0;
bd2b1e68 1082
7d6d0afc
JS
1083 // look for a source separator
1084 src_pos = spec.find('@', scope_pos);
1085 if (src_pos == string::npos)
bd2b1e68 1086 {
7d6d0afc
JS
1087 function = spec.substr(scope_pos);
1088 spec_type = function_alone;
bd2b1e68 1089 }
7d6d0afc 1090 else
879eb9e9 1091 {
7d6d0afc 1092 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1093
7d6d0afc
JS
1094 // look for a line-number separator
1095 line_pos = spec.find_first_of(":+", src_pos);
1096 if (line_pos == string::npos)
1097 {
1098 file = spec.substr(src_pos + 1);
1099 spec_type = function_and_file;
1100 }
1101 else
1102 {
1103 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1104
1105 // classify the line spec
1106 spec_type = function_file_and_line;
1107 if (spec[line_pos] == '+')
4a81c0d9 1108 lineno_type = RELATIVE;
7d6d0afc
JS
1109 else if (spec[line_pos + 1] == '*' &&
1110 spec.length() == line_pos + 2)
4a81c0d9 1111 lineno_type = WILDCARD;
7d6d0afc 1112 else
4a81c0d9 1113 lineno_type = ABSOLUTE;
7d6d0afc 1114
4a81c0d9 1115 if (lineno_type != WILDCARD)
7d6d0afc
JS
1116 try
1117 {
1118 // try to parse either N or N-M
1119 dash_pos = spec.find('-', line_pos + 1);
1120 if (dash_pos == string::npos)
4a81c0d9 1121 linenos[0] = linenos[1] = lex_cast<int>(spec.substr(line_pos + 1));
7d6d0afc
JS
1122 else
1123 {
4a81c0d9
JL
1124 lineno_type = RANGE;
1125 linenos[0] = lex_cast<int>(spec.substr(line_pos + 1,
7d6d0afc 1126 dash_pos - line_pos - 1));
4a81c0d9
JL
1127 linenos[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1128 if (linenos[0] > linenos[1])
1129 throw runtime_error("bad range");
7d6d0afc
JS
1130 }
1131 }
1132 catch (runtime_error & exn)
1133 {
1134 goto bad;
1135 }
1136 }
bd2b1e68
GH
1137 }
1138
7d6d0afc
JS
1139 if (function.empty() ||
1140 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1141 goto bad;
1142
7d6d0afc 1143 if (sess.verbose > 2)
bd2b1e68 1144 {
b530b5b3
LB
1145 //clog << "parsed '" << spec << "'";
1146 clog << _F("parse '%s'", spec.c_str());
41c262f3 1147
7d6d0afc
JS
1148 if (!scopes.empty())
1149 clog << ", scope '" << scopes[0] << "'";
1150 for (unsigned i = 1; i < scopes.size(); ++i)
1151 clog << "::'" << scopes[i] << "'";
41c262f3 1152
7d6d0afc
JS
1153 clog << ", func '" << function << "'";
1154
1155 if (spec_type != function_alone)
1156 clog << ", file '" << file << "'";
1157
1158 if (spec_type == function_file_and_line)
1159 {
1160 clog << ", line ";
4a81c0d9 1161 switch (lineno_type)
7d6d0afc
JS
1162 {
1163 case ABSOLUTE:
4a81c0d9 1164 clog << linenos[0];
7d6d0afc
JS
1165 break;
1166
1167 case RELATIVE:
4a81c0d9 1168 clog << "+" << linenos[0];
7d6d0afc
JS
1169 break;
1170
1171 case RANGE:
4a81c0d9 1172 clog << linenos[0] << " - " << linenos[1];
7d6d0afc
JS
1173 break;
1174
1175 case WILDCARD:
1176 clog << "*";
1177 break;
1178 }
1179 }
1180
1181 clog << endl;
bd2b1e68
GH
1182 }
1183
7d6d0afc
JS
1184 return;
1185
1186bad:
dc09353a 1187 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1188 base_probe->tok);
bd2b1e68
GH
1189}
1190
05fb3e0c
WF
1191string path_remove_sysroot(const systemtap_session& sess, const string& path)
1192{
1193 size_t pos;
1194 string retval = path;
1195 if (!sess.sysroot.empty() &&
1196 (pos = retval.find(sess.sysroot)) != string::npos)
1197 retval.replace(pos, sess.sysroot.length(), "/");
1198 return retval;
1199}
bd2b1e68 1200
36f9dd1d 1201void
1ffb8bd1 1202dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1203 const char* filename,
36f9dd1d 1204 int line,
b20febf3 1205 Dwarf_Die* scope_die,
36f9dd1d
FCE
1206 Dwarf_Addr addr)
1207{
b20febf3 1208 string reloc_section; // base section for relocation purposes
27646582 1209 Dwarf_Addr reloc_addr; // relocated
b20febf3 1210 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1211 string funcname = dw_funcname;
36f9dd1d 1212
37ebca01
FCE
1213 assert (! has_absolute); // already handled in dwarf_builder::build()
1214
f4faaf86 1215 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1216
1ffb8bd1 1217 // If we originally used the linkage name, then let's call it that way
1ffb8bd1 1218 const char* linkage_name;
91bb9081 1219 if (!null_die(scope_die) && startswith (this->function, "_Z")
f450a7e3 1220 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1221 funcname = linkage_name;
1222
7f9f3386
FCE
1223 if (sess.verbose > 1)
1224 {
b530b5b3 1225 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1226 if (string(module) == TOK_KERNEL)
b530b5b3 1227 clog << _(" kernel");
91af0778 1228 else if (has_module)
b530b5b3 1229 clog << _(" module=") << module;
91af0778 1230 else if (has_process)
b530b5b3 1231 clog << _(" process=") << module;
b20febf3 1232 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1233 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1234 }
4baf0e53 1235
2f18e69b
JL
1236 dwflpp::blacklisted_type blacklisted = dw.blacklisted_p (funcname, filename,
1237 line, module, addr,
1238 has_return);
b20febf3
FCE
1239 if (sess.verbose > 1)
1240 clog << endl;
7f9f3386 1241
84048984
FCE
1242 if (module == TOK_KERNEL)
1243 {
1244 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1245 reloc_addr = addr - sess.sym_stext;
37ebca01 1246 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1247 }
1248
2f18e69b 1249 if (!blacklisted)
b20febf3 1250 {
1a0dbc5a 1251 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1252
1253 if (has_process)
1254 {
05fb3e0c 1255 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1256 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1257 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1258 *this, scope_die));
1259 }
1260 else
1261 {
1262 assert (has_kernel || has_module);
1263 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1264 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1265 *this, scope_die));
1266 }
b20febf3 1267 }
2f18e69b
JL
1268 else
1269 {
1270 switch (blacklisted)
1271 {
1272 case dwflpp::blacklisted_section:
1273 sess.print_warning(_F("function %s is in blacklisted section",
1274 funcname.c_str()), base_probe->tok);
1275 break;
1276 case dwflpp::blacklisted_kprobes:
1277 sess.print_warning(_F("kprobes function %s is blacklisted",
1278 funcname.c_str()), base_probe->tok);
1279 break;
1280 case dwflpp::blacklisted_function_return:
1281 sess.print_warning(_F("function %s return probe is blacklisted",
1282 funcname.c_str()), base_probe->tok);
1283 break;
1284 case dwflpp::blacklisted_file:
1285 sess.print_warning(_F("function %s is in blacklisted file",
1286 funcname.c_str()), base_probe->tok);
1287 break;
1288 case dwflpp::blacklisted_function:
1289 default:
1290 sess.print_warning(_F("function %s is blacklisted",
1291 funcname.c_str()), base_probe->tok);
1292 break;
1293 }
1294 }
2930abc7
FCE
1295}
1296
5f0a03a6
JK
1297enum dbinfo_reqt
1298dwarf_query::assess_dbinfo_reqt()
1299{
1300 if (has_absolute)
1301 {
1302 // kernel.statement(NUM).absolute
1303 return dbr_none;
1304 }
c31add50 1305 if (has_inline || has_label || has_callee || has_callees_num)
5f0a03a6
JK
1306 {
1307 // kernel.function("f").inline or module("m").function("f").inline
1308 return dbr_need_dwarf;
1309 }
1310 if (has_function_str && spec_type == function_alone)
1311 {
1312 // kernel.function("f") or module("m").function("f")
1313 return dbr_need_symtab;
1314 }
1315 if (has_statement_num)
1316 {
1317 // kernel.statement(NUM) or module("m").statement(NUM)
1318 // Technically, all we need is the module offset (or _stext, for
1319 // the kernel). But for that we need either the ELF file or (for
1320 // _stext) the symbol table. In either case, the symbol table
1321 // is available, and that allows us to map the NUM (address)
1322 // to a function, which is goodness.
1323 return dbr_need_symtab;
1324 }
1325 if (has_function_num)
1326 {
1327 // kernel.function(NUM) or module("m").function(NUM)
1328 // Need the symbol table so we can back up from NUM to the
1329 // start of the function.
1330 return dbr_need_symtab;
1331 }
1332 // Symbol table tells us nothing about source files or line numbers.
1333 return dbr_need_dwarf;
1334}
2930abc7 1335
e772a6e7
JL
1336string
1337dwarf_query::final_function_name(const string& final_func,
1338 const string& final_file,
1339 int final_line)
1340{
1341 string final_name = final_func;
1342 if (final_file != "")
1343 {
1344 final_name += ("@" + final_file);
1345 if (final_line > 0)
1346 final_name += (":" + lex_cast(final_line));
1347 }
1348 return final_name;
1349}
2930abc7 1350
959ccfed
JL
1351base_func_info_map_t
1352dwarf_query::filtered_all(void)
1353{
1354 vector<base_func_info> r;
1355 func_info_map_t::const_iterator f;
1356 for (f = filtered_functions.begin();
1357 f != filtered_functions.end(); ++f)
1358 r.push_back(*f);
1359 inline_instance_map_t::const_iterator i;
1360 for (i = filtered_inlines.begin();
1361 i != filtered_inlines.end(); ++i)
1362 r.push_back(*i);
1363 return r;
1364}
1365
b8da0ad1
FCE
1366// The critical determining factor when interpreting a pattern
1367// string is, perhaps surprisingly: "presence of a lineno". The
1368// presence of a lineno changes the search strategy completely.
1369//
1370// Compare the two cases:
1371//
1372// 1. {statement,function}(foo@file.c:lineno)
1373// - find the files matching file.c
1374// - in each file, find the functions matching foo
1375// - query the file for line records matching lineno
1376// - iterate over the line records,
1377// - and iterate over the functions,
1378// - if(haspc(function.DIE, line.addr))
1379// - if looking for statements: probe(lineno.addr)
1380// - if looking for functions: probe(function.{entrypc,return,etc.})
1381//
1382// 2. {statement,function}(foo@file.c)
1383// - find the files matching file.c
1384// - in each file, find the functions matching foo
1385// - probe(function.{entrypc,return,etc.})
1386//
1387// Thus the first decision we make is based on the presence of a
1388// lineno, and we enter entirely different sets of callbacks
1389// depending on that decision.
1390//
1391// Note that the first case is a generalization fo the second, in that
1392// we could theoretically search through line records for matching
1393// file names (a "table scan" in rdbms lingo). Luckily, file names
1394// are already cached elsewhere, so we can do an "index scan" as an
1395// optimization.
7e1279ea 1396
bd2b1e68 1397static void
4cd232e4 1398query_statement (string const & func,
20e4a32c 1399 char const * file,
4cd232e4 1400 int line,
bcc12710 1401 Dwarf_Die *scope_die,
20e4a32c 1402 Dwarf_Addr stmt_addr,
4cd232e4 1403 dwarf_query * q)
bd2b1e68 1404{
39bcd429
FCE
1405 try
1406 {
cee35f73 1407 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1408 line, scope_die, stmt_addr);
39bcd429
FCE
1409 }
1410 catch (const semantic_error& e)
1411 {
1412 q->sess.print_error (e);
1413 }
bd2b1e68
GH
1414}
1415
6b517475
JS
1416static void
1417query_addr(Dwarf_Addr addr, dwarf_query *q)
1418{
1419 dwflpp &dw = q->dw;
1420
08d1d520
MW
1421 if (q->sess.verbose > 2)
1422 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1423
1424 // First pick which CU contains this address
1425 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1426 if (!cudie) // address could be wildly out of range
1427 return;
1428 dw.focus_on_cu(cudie);
1429
1430 // Now compensate for the dw bias
1431 addr -= dw.module_bias;
1432
1433 // Per PR5787, we look up the scope die even for
1434 // statement_num's, for blacklist sensitivity and $var
1435 // resolution purposes.
1436
1437 // Find the scopes containing this address
1438 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1439 if (scopes.empty())
1440 return;
1441
1442 // Look for the innermost containing function
1443 Dwarf_Die *fnscope = NULL;
1444 for (size_t i = 0; i < scopes.size(); ++i)
1445 {
1446 int tag = dwarf_tag(&scopes[i]);
1447 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1448 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1449 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1450 {
1451 fnscope = &scopes[i];
1452 break;
1453 }
1454 }
1455 if (!fnscope)
1456 return;
1457 dw.focus_on_function(fnscope);
1458
1459 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1460
1461 const char *file = dwarf_decl_file(fnscope);
1462 int line;
1463 dwarf_decl_line(fnscope, &line);
1464
1465 // Function probes should reset the addr to the function entry
1466 // and possibly perform prologue searching
1467 if (q->has_function_num)
1468 {
1bbf3f90
JS
1469 if (!dw.die_entrypc(fnscope, &addr))
1470 return;
6b517475 1471 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
b5b9879f
JL
1472 (q->sess.prologue_searching ||
1473 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
6b517475
JS
1474 {
1475 func_info func;
1476 func.die = *fnscope;
1477 func.name = dw.function_name;
1478 func.decl_file = file;
1479 func.decl_line = line;
1480 func.entrypc = addr;
1481
1482 func_info_map_t funcs(1, func);
1483 dw.resolve_prologue_endings (funcs);
5a617dc6
JL
1484 q->prologue_end = funcs[0].prologue_end;
1485
1486 // PR13200: if it's a .return probe, we need to emit a *retprobe based
1487 // on the entrypc so here we only use prologue_end for non .return
1488 // probes (note however that .return probes still take advantage of
1489 // prologue_end: PR14436)
1490 if (!q->has_return)
1491 addr = funcs[0].prologue_end;
6b517475
JS
1492 }
1493 }
1494 else
1495 {
de797211
JL
1496 Dwarf_Line *address_line = dwarf_getsrc_die(cudie, addr);
1497 Dwarf_Addr address_line_addr = addr;
6b517475
JS
1498 if (address_line)
1499 {
bf5974d6
JL
1500 file = DWARF_LINESRC(address_line);
1501 line = DWARF_LINENO(address_line);
1502 address_line_addr = DWARF_LINEADDR(address_line);
6b517475
JS
1503 }
1504
1505 // Verify that a raw address matches the beginning of a
1506 // statement. This is a somewhat lame check that the address
1507 // is at the start of an assembly instruction. Mark probes are in the
1508 // middle of a macro and thus not strictly at a statement beginning.
1509 // Guru mode may override this check.
de797211 1510 if (!q->has_mark && (!address_line || address_line_addr != addr))
6b517475
JS
1511 {
1512 stringstream msg;
2a97f50b 1513 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1514 addr);
6b517475 1515 if (address_line)
de797211 1516 msg << _F(" (try %#" PRIx64 ")", address_line_addr);
6b517475 1517 else
b530b5b3
LB
1518 msg << _F(" (no line info found for '%s', in module '%s')",
1519 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475 1520 if (! q->sess.guru_mode)
dc09353a 1521 throw SEMANTIC_ERROR(msg.str());
2713ea24 1522 else
6b517475
JS
1523 q->sess.print_warning(msg.str());
1524 }
1525 }
1526
1527 // Build a probe at this point
1528 query_statement(dw.function_name, file, line, scope, addr, q);
1529}
1530
f4faaf86
JS
1531static void
1532query_plt_statement(dwarf_query *q)
1533{
1534 assert (q->has_plt && q->has_statement_num);
1535
1536 Dwarf_Addr addr = q->statement_num_val;
1537 if (q->sess.verbose > 2)
1538 clog << "query_plt_statement 0x" << hex << addr << dec << endl;
1539
1540 // First adjust the raw address to dwfl's elf bias.
1541 Dwarf_Addr elf_bias;
1542 Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
1543 assert(elf);
1544 addr += elf_bias;
1545
1546 // Now compensate for the dw bias
1547 q->dw.get_module_dwarf(false, false);
1548 addr -= q->dw.module_bias;
1549
1550 // Build a probe at this point
1551 query_statement(q->plt_val, NULL, -1, NULL, addr, q);
1552}
1553
8096dd7d
JS
1554static void
1555query_label (string const & func,
1556 char const * label,
1557 char const * file,
1558 int line,
1559 Dwarf_Die *scope_die,
1560 Dwarf_Addr stmt_addr,
1561 dwarf_query * q)
1562{
6b517475
JS
1563 assert (q->has_statement_str || q->has_function_str);
1564
8096dd7d
JS
1565 // weed out functions whose decl_file isn't one of
1566 // the source files that we actually care about
6b517475 1567 if (q->spec_type != function_alone &&
8096dd7d
JS
1568 q->filtered_srcfiles.count(file) == 0)
1569 return;
1570
9891c543
JL
1571 // To help users, we create an intermediate probe point containing the final
1572 // function name, as well as the matched label. See query_callee() for
1573 // something similar, but with more comments.
1574 string canon_func = q->final_function_name(func, file, line);
1575
1576 string module = q->dw.module_name;
1577 if (q->has_process)
1578 module = path_remove_sysroot(q->sess, module);
8096dd7d 1579
9891c543
JL
1580 probe_point *pp = new probe_point(*q->base_loc);
1581 vector<probe_point::component*> pp_comps;
1582 vector<probe_point::component*>::iterator it;
1583 for (it = pp->components.begin(); it != pp->components.end(); ++it)
c72aa911 1584 {
9891c543
JL
1585 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1586 pp_comps.push_back(new probe_point::component((*it)->functor,
1587 new literal_string(module)));
1588 else if ((*it)->functor == TOK_FUNCTION)
1589 pp_comps.push_back(new probe_point::component(TOK_FUNCTION,
1590 new literal_string(canon_func)));
1591 else if ((*it)->functor == TOK_LABEL)
1592 pp_comps.push_back(new probe_point::component(TOK_LABEL,
1593 new literal_string(label)));
1594 else
1595 pp_comps.push_back(*it);
c72aa911 1596 }
9891c543
JL
1597
1598 pp->components = pp_comps;
1599 dwarf_query q_label(*q);
1600 q_label.base_loc = pp;
1601 q_label.base_probe = new probe(q->base_probe, pp);
1602
1603 query_statement(func, file, line, scope_die, stmt_addr, &q_label);
8096dd7d
JS
1604}
1605
67959c62 1606static void
e772a6e7
JL
1607query_callee (base_func_info& callee,
1608 base_func_info& caller,
67959c62
JL
1609 stack<Dwarf_Addr> *callers,
1610 dwarf_query * q)
1611{
1612 assert (q->has_function_str);
e772a6e7
JL
1613 assert (q->has_callee || q->has_callees_num);
1614
1615 // OK, we found a callee for a targeted caller. To help users see the
1616 // derivation, let's add an intermediate probe to the chain. E.g. right now we
1617 // have .function(pattern).callee(pattern) (or .callees) and we want to add as
1618 // the next step .function(caller).callee(callee). This is the step that will
1619 // show up as well when in listing mode.
1620
1621 // To add this intermediate probe, we first create it and then create a new
1622 // dwarf_query with that probe as base.
1623
1624 // Build final names for caller and callee
1625 string canon_caller = q->final_function_name(caller.name, caller.decl_file,
1626 caller.decl_line);
1627 string canon_callee = q->final_function_name(callee.name, callee.decl_file,
1628 callee.decl_line);
1629
1630 // Build the intermediate probe. We replace the function arg with the final
1631 // caller, and the callee arg with the final callee. Also, since the
1632 // process(str) or module(str) currently in the base_loc is still the one the
1633 // user typed in (not necessarily the same as the absolute path we get in the
1634 // sole location), we also replace that (otherwise, function(str).* will
1635 // return a mishmash of absolute and relative paths in listing mode).
1636
1637 string module = q->dw.module_name;
1638 if (q->has_process)
1639 module = path_remove_sysroot(q->sess, module);
1640
1641 probe_point *pp = new probe_point(*q->base_loc);
1642 vector<probe_point::component*> pp_comps;
1643 vector<probe_point::component*>::iterator it;
1644 for (it = pp->components.begin(); it != pp->components.end(); ++it)
1645 {
1646 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1647 pp_comps.push_back(new probe_point::component((*it)->functor,
1648 new literal_string(module)));
1649 else if ((*it)->functor == TOK_FUNCTION)
1650 pp_comps.push_back(new probe_point::component(TOK_FUNCTION,
1651 new literal_string(canon_caller)));
1652 else if ((*it)->functor == TOK_CALLEE || (*it)->functor == TOK_CALLEES)
1653 pp_comps.push_back(new probe_point::component(TOK_CALLEE,
1654 new literal_string(canon_callee)));
1655 else
1656 pp_comps.push_back(*it);
1657 }
1658
1659 // Finally create the new probe and the new query (use copy-constructor
1660 // instead of creating from scratch so we don't have to rebuild param map)
1661 pp->components = pp_comps;
1662 dwarf_query q_callee(*q);
1663 q_callee.base_loc = pp;
1664 q_callee.base_probe = new probe(q->base_probe, pp);
1665
1666 // Pass on the callers we'll need to add checks for
1667 q_callee.callers = callers;
1668
1669 query_statement(callee.name, callee.decl_file, callee.decl_line,
1670 &callee.die, callee.entrypc, &q_callee);
67959c62
JL
1671}
1672
7e1279ea 1673static void
3e961ba6 1674query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1675 dwarf_query * q)
1676{
b6581717 1677 try
7e1279ea 1678 {
8f14e444
FCE
1679 assert (! q->has_return); // checked by caller already
1680 if (q->sess.verbose>2)
b530b5b3
LB
1681 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1682 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1683 query_statement (ii.name, ii.decl_file, ii.decl_line,
1684 &ii.die, ii.entrypc, q);
7e1279ea 1685 }
b6581717 1686 catch (semantic_error &e)
7e1279ea 1687 {
b6581717 1688 q->sess.print_error (e);
7e1279ea
FCE
1689 }
1690}
1691
1692static void
1693query_func_info (Dwarf_Addr entrypc,
bcc12710 1694 func_info & fi,
7e1279ea
FCE
1695 dwarf_query * q)
1696{
b6581717 1697 try
7e1279ea 1698 {
5a617dc6
JL
1699 // If it's a .return probe, we need to emit a *retprobe based on the
1700 // entrypc (PR13200). Note however that if prologue_end is valid,
1701 // dwarf_derived_probe will still take advantage of it by creating a new
1702 // probe there if necessary to pick up target vars (PR14436).
1703 if (fi.prologue_end == 0 || q->has_return)
1704 {
170ccf10 1705 q->prologue_end = fi.prologue_end;
5a617dc6
JL
1706 query_statement (fi.name, fi.decl_file, fi.decl_line,
1707 &fi.die, entrypc, q);
1708 }
b6581717 1709 else
5a617dc6 1710 {
5a617dc6
JL
1711 query_statement (fi.name, fi.decl_file, fi.decl_line,
1712 &fi.die, fi.prologue_end, q);
1713 }
7e1279ea 1714 }
b6581717 1715 catch (semantic_error &e)
7e1279ea 1716 {
b6581717 1717 q->sess.print_error (e);
7e1279ea
FCE
1718 }
1719}
1720
1721
bd4b874d 1722static void
de797211 1723query_srcfile_label (Dwarf_Addr addr, int lineno, dwarf_query * q)
bd4b874d 1724{
959ccfed
JL
1725 base_func_info_map_t bfis = q->filtered_all();
1726 base_func_info_map_t::iterator i;
1727 for (i = bfis.begin(); i != bfis.end(); ++i)
f09d0d1e
JS
1728 if (q->dw.die_has_pc (i->die, addr))
1729 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1730 q, query_label);
bd4b874d
SC
1731}
1732
7e1279ea 1733static void
de797211 1734query_srcfile_line (Dwarf_Addr addr, int lineno, dwarf_query * q)
7e1279ea 1735{
8fb810d7
JL
1736 assert (q->has_statement_str || q->has_function_str);
1737 assert (q->spec_type == function_file_and_line);
1738
959ccfed
JL
1739 base_func_info_map_t bfis = q->filtered_all();
1740 base_func_info_map_t::iterator i;
1741 for (i = bfis.begin(); i != bfis.end(); ++i)
897820ca 1742 {
3e961ba6 1743 if (q->dw.die_has_pc (i->die, addr))
959ccfed
JL
1744 {
1745 if (q->sess.verbose>3)
1746 clog << _("filtered DIE lands on srcfile\n");
1747 Dwarf_Die scope;
1748 q->dw.inner_die_containing_pc(i->die, addr, scope);
1749 query_statement (i->name, i->decl_file,
1750 lineno, // NB: not q->line !
1751 &scope, addr, q);
1752 }
20e4a32c 1753 }
7e1279ea
FCE
1754}
1755
7fdd3e2c
JS
1756bool
1757inline_instance_info::operator<(const inline_instance_info& other) const
1758{
1759 if (entrypc != other.entrypc)
1760 return entrypc < other.entrypc;
1761
1762 if (decl_line != other.decl_line)
1763 return decl_line < other.decl_line;
1764
1765 int cmp = name.compare(other.name);
c60517ca
FCE
1766
1767 if (!cmp)
1768 {
1769 assert (decl_file);
1770 assert (other.decl_file);
1771 cmp = strcmp(decl_file, other.decl_file);
1772 }
1773
7fdd3e2c
JS
1774 return cmp < 0;
1775}
1776
1777
4fa7b22b 1778static int
3956fccb 1779query_dwarf_inline_instance (Dwarf_Die * die, dwarf_query * q)
4fa7b22b 1780{
6b517475 1781 assert (q->has_statement_str || q->has_function_str);
4bda987e 1782 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1783
39bcd429 1784 try
7a053d3b 1785 {
b0ee93c4 1786 if (q->sess.verbose>2)
b530b5b3 1787 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1788
6b517475
JS
1789 Dwarf_Addr entrypc;
1790 if (q->dw.die_entrypc (die, &entrypc))
1791 {
1792 inline_instance_info inl;
1793 inl.die = *die;
1794 inl.name = q->dw.function_name;
1795 inl.entrypc = entrypc;
1796 q->dw.function_file (&inl.decl_file);
1797 q->dw.function_line (&inl.decl_line);
1798
1799 // make sure that this inline hasn't already
1800 // been matched from a different CU
1801 if (q->inline_dupes.insert(inl).second)
1802 q->filtered_inlines.push_back(inl);
1803 }
7e1279ea
FCE
1804 return DWARF_CB_OK;
1805 }
1806 catch (const semantic_error& e)
1807 {
1808 q->sess.print_error (e);
1809 return DWARF_CB_ABORT;
1810 }
1811}
bb788f9f 1812
7e1279ea 1813static int
7d007451 1814query_dwarf_func (Dwarf_Die * func, dwarf_query * q)
7e1279ea 1815{
6b517475 1816 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1817
bd25380d
JS
1818 // weed out functions whose decl_file isn't one of
1819 // the source files that we actually care about
6b517475 1820 if (q->spec_type != function_alone &&
bd25380d 1821 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1822 return DWARF_CB_OK;
bd25380d 1823
7e1279ea
FCE
1824 try
1825 {
7e1279ea
FCE
1826 q->dw.focus_on_function (func);
1827
7d6d0afc
JS
1828 if (!q->dw.function_scope_matches(q->scopes))
1829 return DWARF_CB_OK;
1830
857bdfd1
JS
1831 // make sure that this function address hasn't
1832 // already been matched under an aliased name
1833 Dwarf_Addr addr;
1834 if (!q->dw.func_is_inline() &&
1835 dwarf_entrypc(func, &addr) == 0 &&
1836 !q->alias_dupes.insert(addr).second)
1837 return DWARF_CB_OK;
1838
4bda987e 1839 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1840 {
4bda987e 1841 if (q->sess.verbose>3)
b530b5b3 1842 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1843 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1844 }
8f14e444
FCE
1845 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1846 {
1847 q->inlined_non_returnable.insert (q->dw.function_name);
1848 }
396afcee 1849 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1850 {
4bda987e
SC
1851 if (q->has_exported && !q->dw.func_is_exported ())
1852 return DWARF_CB_OK;
6b517475 1853 if (q->sess.verbose>2)
b530b5b3 1854 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1855
1856 func_info func;
1857 q->dw.function_die (&func.die);
1858 func.name = q->dw.function_name;
1859 q->dw.function_file (&func.decl_file);
1860 q->dw.function_line (&func.decl_line);
1861
1862 Dwarf_Addr entrypc;
1863 if (q->dw.function_entrypc (&entrypc))
1864 {
1865 func.entrypc = entrypc;
1866 q->filtered_functions.push_back (func);
1867 }
1868 /* else this function is fully inlined, just ignore it */
7e1279ea 1869 }
39bcd429 1870 return DWARF_CB_OK;
bd2b1e68 1871 }
39bcd429 1872 catch (const semantic_error& e)
bd2b1e68 1873 {
39bcd429
FCE
1874 q->sess.print_error (e);
1875 return DWARF_CB_ABORT;
bd2b1e68 1876 }
bd2b1e68
GH
1877}
1878
1879static int
5c378838 1880query_cu (Dwarf_Die * cudie, dwarf_query * q)
bd2b1e68 1881{
6b517475
JS
1882 assert (q->has_statement_str || q->has_function_str);
1883
85007c04 1884 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1885
39bcd429 1886 try
bd2b1e68 1887 {
7e1279ea 1888 q->dw.focus_on_cu (cudie);
b5d77020 1889
b0ee93c4 1890 if (false && q->sess.verbose>2)
b530b5b3
LB
1891 clog << _F("focused on CU '%s', in module '%s'\n",
1892 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1893
6b517475
JS
1894 q->filtered_srcfiles.clear();
1895 q->filtered_functions.clear();
1896 q->filtered_inlines.clear();
1897
1898 // In this path, we find "abstract functions", record
1899 // information about them, and then (depending on lineno
1900 // matching) possibly emit one or more of the function's
1901 // associated addresses. Unfortunately the control of this
1902 // cannot easily be turned inside out.
1903
1904 if (q->spec_type != function_alone)
39bcd429 1905 {
6b517475
JS
1906 // If we have a pattern string with a filename, we need
1907 // to elaborate the srcfile mask in question first.
1908 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1909
1910 // If we have a file pattern and *no* srcfile matches, there's
1911 // no need to look further into this CU, so skip.
1912 if (q->filtered_srcfiles.empty())
1913 return DWARF_CB_OK;
1914 }
e4c58386 1915
6b517475
JS
1916 // Pick up [entrypc, name, DIE] tuples for all the functions
1917 // matching the query, and fill in the prologue endings of them
1918 // all in a single pass.
5898b6e1 1919 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1920 if (rc != DWARF_CB_OK)
1921 q->query_done = true;
1922
277a2b96
JL
1923 if (!q->filtered_functions.empty() &&
1924 !q->has_statement_str && // PR 2608
1925 (q->sess.prologue_searching ||
1926 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
1927 q->dw.resolve_prologue_endings (q->filtered_functions);
6b517475
JS
1928
1929 if (q->spec_type == function_file_and_line)
1930 {
58b070fb 1931 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1932 if (q->has_function_str)
b530b5b3 1933 q->sess.print_warning (_("For probing a particular line, use a "
b78a0fbb 1934 ".statement() probe, not .function()"),
af2e341f 1935 q->base_probe->tok);
58b070fb 1936
de797211 1937 void (* callback) (Dwarf_Addr, int, dwarf_query*) =
6b517475 1938 q->has_label ? query_srcfile_label : query_srcfile_line;
516e1e2c
JL
1939
1940 base_func_info_map_t bfis = q->filtered_all();
1941
1942 set<string>::const_iterator srcfile;
1943 for (srcfile = q->filtered_srcfiles.begin();
1944 srcfile != q->filtered_srcfiles.end(); ++srcfile)
1945 q->dw.iterate_over_srcfile_lines(srcfile->c_str(), q->linenos,
1946 q->lineno_type, bfis, callback, q);
6b517475
JS
1947 }
1948 else if (q->has_label)
1949 {
959ccfed
JL
1950 base_func_info_map_t bfis = q->filtered_all();
1951 base_func_info_map_t::iterator i;
1952 for (i = bfis.begin(); i != bfis.end(); ++i)
6b517475
JS
1953 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1954 q, query_label);
39bcd429 1955 }
67959c62
JL
1956 else if (q->has_callee || q->has_callees_num)
1957 {
1958 // .callee(str) --> str, .callees[(N)] --> "*"
1959 string callee_val = q->has_callee ? q->callee_val : "*";
1960 long callees_num_val = q->has_callees_num ? q->callees_num_val : 1;
1961
1962 // NB: We filter functions that do not match the file here rather than
1963 // in query_callee because we only want the filtering to apply to the
1964 // first level, not to callees that are recursed into if
1965 // callees_num_val > 1.
959ccfed
JL
1966 base_func_info_map_t bfis = q->filtered_all();
1967 base_func_info_map_t::iterator i;
1968 for (i = bfis.begin(); i != bfis.end(); ++i)
67959c62
JL
1969 {
1970 if (q->spec_type != function_alone &&
1971 q->filtered_srcfiles.count(i->decl_file) == 0)
1972 continue;
1973 q->dw.iterate_over_callees (&i->die, callee_val,
1974 callees_num_val,
e772a6e7 1975 q, query_callee, *i);
67959c62
JL
1976 }
1977 }
6b517475
JS
1978 else
1979 {
1980 // Otherwise, simply probe all resolved functions.
1981 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1982 i != q->filtered_functions.end(); ++i)
1983 query_func_info (i->entrypc, *i, q);
1984
1985 // And all inline instances (if we're not excluding inlines with ".call")
1986 if (! q->has_call)
1987 for (inline_instance_map_t::iterator i
1988 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1989 query_inline_instance_info (*i, q);
e772a6e7 1990 }
39bcd429 1991 return DWARF_CB_OK;
bd2b1e68 1992 }
39bcd429 1993 catch (const semantic_error& e)
bd2b1e68 1994 {
39bcd429
FCE
1995 q->sess.print_error (e);
1996 return DWARF_CB_ABORT;
bd2b1e68 1997 }
bd2b1e68
GH
1998}
1999
0ce64fb8 2000
4df79aaf
JS
2001void
2002dwarf_query::query_module_functions ()
2003{
2004 try
2005 {
2006 filtered_srcfiles.clear();
2007 filtered_functions.clear();
2008 filtered_inlines.clear();
2009
2010 // Collect all module functions so we know which CUs are interesting
2011 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
2012 if (rc != DWARF_CB_OK)
2013 {
2014 query_done = true;
2015 return;
2016 }
2017
2018 set<void*> used_cus; // by cu->addr
2019 vector<Dwarf_Die> cus;
2020 Dwarf_Die cu_mem;
2021
959ccfed
JL
2022 base_func_info_map_t bfis = filtered_all();
2023 base_func_info_map_t::iterator i;
2024 for (i = bfis.begin(); i != bfis.end(); ++i)
4df79aaf
JS
2025 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
2026 used_cus.insert(cu_mem.addr).second)
2027 cus.push_back(cu_mem);
2028
2029 // Reset the dupes since we didn't actually collect them the first time
2030 alias_dupes.clear();
2031 inline_dupes.clear();
2032
2033 // Run the query again on the individual CUs
91bb9081
LB
2034 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i){
2035 rc = query_cu(&*i, this);
2036 if (rc != DWARF_CB_OK)
2037 {
2038 query_done = true;
2039 return;
2040 }
2041 }
4df79aaf
JS
2042 }
2043 catch (const semantic_error& e)
2044 {
2045 sess.print_error (e);
2046 }
2047}
2048
2049
5f0a03a6
JK
2050static void
2051validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
2052{
2053 // Validate the machine code in this elf file against the
2054 // session machine. This is important, in case the wrong kind
2055 // of debuginfo is being automagically processed by elfutils.
2056 // While we can tell i686 apart from x86-64, unfortunately
2057 // we can't help confusing i586 vs i686 (both EM_386).
2058
2059 Dwarf_Addr bias;
2060 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
2061 // because dwfl_module_getelf can force costly section relocations
2062 // we don't really need, while either will do for this purpose.
2063 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
2064 ?: dwfl_module_getelf (mod, &bias));
2065
2066 GElf_Ehdr ehdr_mem;
2067 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 2068 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 2069 assert(em);
5f0a03a6
JK
2070 int elf_machine = em->e_machine;
2071 const char* debug_filename = "";
2072 const char* main_filename = "";
2073 (void) dwfl_module_info (mod, NULL, NULL,
2074 NULL, NULL, NULL,
2075 & main_filename,
2076 & debug_filename);
2077 const string& sess_machine = q->sess.architecture;
756c9462
FCE
2078
2079 string expect_machine; // to match sess.machine (i.e., kernel machine)
2080 string expect_machine2;
5f0a03a6 2081
d27e6fd5 2082 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
2083 switch (elf_machine)
2084 {
756c9462
FCE
2085 // x86 and ppc are bi-architecture; a 64-bit kernel
2086 // can normally run either 32-bit or 64-bit *userspace*.
2087 case EM_386:
2088 expect_machine = "i?86";
2089 if (! q->has_process) break; // 32-bit kernel/module
2090 /* FALLSTHROUGH */
2091 case EM_X86_64:
2092 expect_machine2 = "x86_64";
2093 break;
2094 case EM_PPC:
756c9462 2095 case EM_PPC64:
5a1c472e 2096 expect_machine = "powerpc";
756c9462 2097 break;
3fe7d888 2098 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2099 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2100 case EM_ARM: expect_machine = "arm*"; break;
86aae990 2101 case EM_AARCH64: expect_machine = "arm64"; break;
5f0a03a6
JK
2102 // XXX: fill in some more of these
2103 default: expect_machine = "?"; break;
2104 }
2105
2106 if (! debug_filename) debug_filename = main_filename;
2107 if (! debug_filename) debug_filename = name;
2108
756c9462
FCE
2109 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2110 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2111 {
2112 stringstream msg;
b530b5b3
LB
2113 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2114 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2115 sess_machine.c_str(), debug_filename);
dc09353a 2116 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2117 }
2118
b57082de 2119 if (q->sess.verbose>1)
b78a0fbb 2120 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2121 " file %s ELF machine %s|%s (code %d)\n",
2122 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2123 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2124 expect_machine2.c_str(), elf_machine);
5f0a03a6 2125}
1d3a40b6 2126
91af0778
FCE
2127
2128
2129static Dwarf_Addr
2130lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2131{
2132 int syments = dwfl_module_getsymtab(m);
2133 assert(syments);
2134 for (int i = 1; i < syments; ++i)
2135 {
2136 GElf_Sym sym;
2137 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2138 if (name != NULL && strcmp(name, wanted) == 0)
2139 return sym.st_value;
2140 }
2141
2142 return 0;
2143}
2144
2145
2146
bd2b1e68 2147static int
b8da0ad1 2148query_module (Dwfl_Module *mod,
91af0778 2149 void **,
b8da0ad1 2150 const char *name,
6f4c1275 2151 Dwarf_Addr addr,
06de3a04 2152 base_query *q)
bd2b1e68 2153{
39bcd429 2154 try
e38d6504 2155 {
91af0778
FCE
2156 module_info* mi = q->sess.module_cache->cache[name];
2157 if (mi == 0)
2158 {
2159 mi = q->sess.module_cache->cache[name] = new module_info(name);
2160
6f4c1275
FCE
2161 mi->mod = mod;
2162 mi->addr = addr;
91af0778 2163
6f4c1275
FCE
2164 const char* debug_filename = "";
2165 const char* main_filename = "";
2166 (void) dwfl_module_info (mod, NULL, NULL,
2167 NULL, NULL, NULL,
2168 & main_filename,
2169 & debug_filename);
2170
ab3ed72d 2171 if (debug_filename || main_filename)
91af0778 2172 {
6f4c1275
FCE
2173 mi->elf_path = debug_filename ?: main_filename;
2174 }
2175 else if (name == TOK_KERNEL)
2176 {
2177 mi->dwarf_status = info_absent;
91af0778 2178 }
91af0778
FCE
2179 }
2180 // OK, enough of that module_info caching business.
2181
5f0a03a6 2182 q->dw.focus_on_module(mod, mi);
d9b516ca 2183
39bcd429
FCE
2184 // If we have enough information in the pattern to skip a module and
2185 // the module does not match that information, return early.
b8da0ad1 2186 if (!q->dw.module_name_matches(q->module_val))
85007c04 2187 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2188
2189 // Don't allow module("*kernel*") type expressions to match the
2190 // elfutils module "kernel", which we refer to in the probe
2191 // point syntax exclusively as "kernel.*".
2192 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2193 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2194
5f0a03a6
JK
2195 if (mod)
2196 validate_module_elf(mod, name, q);
2197 else
91af0778
FCE
2198 assert(q->has_kernel); // and no vmlinux to examine
2199
2200 if (q->sess.verbose>2)
b530b5b3 2201 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2202
2203
2204 // Collect a few kernel addresses. XXX: these belong better
2205 // to the sess.module_info["kernel"] struct.
2206 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2207 {
91af0778
FCE
2208 if (! q->sess.sym_kprobes_text_start)
2209 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2210 if (! q->sess.sym_kprobes_text_end)
2211 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2212 if (! q->sess.sym_stext)
2213 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2214 }
2215
47e226ed
SC
2216 // We either have a wildcard or an unresolved library
2217 if (q->has_library && (contains_glob_chars (q->path)
2218 || q->path.find('/') == string::npos))
84c84ac4
SC
2219 // handle .library(GLOB)
2220 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2221 // .plt is translated to .plt.statement(N). We only want to iterate for the
2222 // .plt case
2223 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2224 {
2225 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2226 q->visited_modules.insert(name);
2227 }
84c84ac4 2228 else
070764c0
JL
2229 {
2230 // search the module for matches of the probe point.
2231 q->handle_query_module();
2232 q->visited_modules.insert(name);
2233 }
bb788f9f 2234
b8da0ad1 2235 // If we know that there will be no more matches, abort early.
85007c04 2236 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2237 return DWARF_CB_ABORT;
2238 else
2239 return DWARF_CB_OK;
7a053d3b 2240 }
39bcd429 2241 catch (const semantic_error& e)
bd2b1e68 2242 {
39bcd429
FCE
2243 q->sess.print_error (e);
2244 return DWARF_CB_ABORT;
bd2b1e68 2245 }
bd2b1e68
GH
2246}
2247
35d4ab18 2248
84c84ac4 2249void
bbbc7241 2250base_query::query_library_callback (base_query *me, const char *data)
84c84ac4 2251{
5d5bd369 2252 me->query_library (data);
84c84ac4
SC
2253}
2254
2255
2cbcfa9c 2256string
51d6bda3
SC
2257query_one_library (const char *library, dwflpp & dw,
2258 const string user_lib, probe * base_probe, probe_point *base_loc,
2259 vector<derived_probe *> & results)
84c84ac4 2260{
47e226ed 2261 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2262 {
05fb3e0c
WF
2263 string library_path = find_executable (library, "", dw.sess.sysenv,
2264 "LD_LIBRARY_PATH");
84c84ac4
SC
2265 probe_point* specific_loc = new probe_point(*base_loc);
2266 specific_loc->optional = true;
ef0943df 2267 specific_loc->from_glob = true;
84c84ac4
SC
2268 vector<probe_point::component*> derived_comps;
2269
5d25dfb6
JL
2270 // Create new probe point for the matching library. This is what will be
2271 // shown in listing mode. Also replace the process(str) with the real
2272 // absolute path rather than keeping what the user typed in.
84c84ac4
SC
2273 vector<probe_point::component*>::iterator it;
2274 for (it = specific_loc->components.begin();
2275 it != specific_loc->components.end(); ++it)
5d25dfb6
JL
2276 if ((*it)->functor == TOK_PROCESS)
2277 derived_comps.push_back(new probe_point::component(TOK_PROCESS,
2278 new literal_string(path_remove_sysroot(dw.sess, dw.module_name))));
2279 else if ((*it)->functor == TOK_LIBRARY)
84c84ac4
SC
2280 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2281 new literal_string(library_path)));
2282 else
2283 derived_comps.push_back(*it);
2284 probe_point* derived_loc = new probe_point(*specific_loc);
2285 derived_loc->components = derived_comps;
8159bf55 2286 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2287 derive_probes(dw.sess, new_base, results);
2288 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2289 clog << _("module=") << library_path << endl;
2290 return library_path;
84c84ac4 2291 }
2cbcfa9c 2292 return "";
84c84ac4
SC
2293}
2294
2295
51d6bda3
SC
2296void
2297dwarf_query::query_library (const char *library)
2298{
2cbcfa9c
JL
2299 string library_path =
2300 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2301 if (!library_path.empty())
2302 visited_modules.insert(library_path);
51d6bda3
SC
2303}
2304
576eaefe
SC
2305struct plt_expanding_visitor: public var_expanding_visitor
2306{
2307 plt_expanding_visitor(const string & entry):
2308 entry (entry)
2309 {
2310 }
2311 const string & entry;
2312
2313 void visit_target_symbol (target_symbol* e);
2314};
2315
2316
2317void
45cdb40e 2318base_query::query_plt_callback (base_query *me, const char *entry, size_t address)
576eaefe 2319{
576eaefe
SC
2320 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2321 me->query_plt (entry, address);
7f4964f1 2322 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2323}
2324
2325
2326void
2327query_one_plt (const char *entry, long addr, dwflpp & dw,
2328 probe * base_probe, probe_point *base_loc,
2329 vector<derived_probe *> & results)
2330{
2331 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2332 vector<probe_point::component*> derived_comps;
2333
2334 if (dw.sess.verbose > 2)
2335 clog << _F("plt entry=%s\n", entry);
2336
576eaefe
SC
2337 vector<probe_point::component*>::iterator it;
2338 for (it = specific_loc->components.begin();
2339 it != specific_loc->components.end(); ++it)
2340 if ((*it)->functor == TOK_PLT)
3d372d6b 2341 {
8159bf55
FCE
2342 *it = new probe_point::component(TOK_PLT,
2343 new literal_string(entry));
3d372d6b
SC
2344 derived_comps.push_back(*it);
2345 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2346 new literal_number(addr, true)));
3d372d6b 2347 }
576eaefe
SC
2348 else
2349 derived_comps.push_back(*it);
2350 probe_point* derived_loc = new probe_point(*specific_loc);
2351 derived_loc->components = derived_comps;
02c34e38
FCE
2352 probe *new_base = new probe (new probe (base_probe, specific_loc),
2353 derived_loc);
576eaefe
SC
2354 string e = string(entry);
2355 plt_expanding_visitor pltv (e);
2356 pltv.replace (new_base->body);
2357 derive_probes(dw.sess, new_base, results);
2358}
2359
2360
2361void
2362dwarf_query::query_plt (const char *entry, size_t address)
2363{
2364 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2365}
51d6bda3 2366
435f53a7
FCE
2367// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2368// but the needed declaration for module_cache is not available there.
2369// Nor for that matter in session.cxx. Only in this CU is that field ever
2370// set (in query_module() above), so we clean it up here too.
2371static void
2372delete_session_module_cache (systemtap_session& s)
2373{
2374 if (s.module_cache) {
2375 if (s.verbose > 3)
b530b5b3 2376 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2377 delete s.module_cache;
2378 s.module_cache = 0;
2379 }
2380}
2381
2382
de688825 2383struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2384{
77de5e9e 2385 dwarf_query & q;
bcc12710 2386 Dwarf_Die *scope_die;
77de5e9e 2387 Dwarf_Addr addr;
8c819921 2388 block *add_block;
2260f4e3 2389 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2390 // NB: tids are not always collected in add_block & add_call_probe, because
2391 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2392 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2393 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2394 unsigned saved_longs, saved_strings; // data saved within kretprobes
2395 map<std::string, expression *> return_ts_map;
729455a7 2396 vector<Dwarf_Die> scopes;
3689db05 2397 // probe counter name -> pointer of associated probe
698de6cc 2398 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2399 bool visited;
77de5e9e 2400
de688825 2401 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2402 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2403 add_block_tid(false), add_call_probe_tid(false),
af234c40 2404 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2405 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2406 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2407 void visit_target_symbol_saved_return (target_symbol* e);
2408 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2409 void visit_target_symbol (target_symbol* e);
bd1fcbad 2410 void visit_atvar_op (atvar_op* e);
c24447be 2411 void visit_cast_op (cast_op* e);
8cc799a5 2412 void visit_entry_op (entry_op* e);
3689db05 2413 void visit_perf_op (perf_op* e);
729455a7
JS
2414private:
2415 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2416};
2417
2418
de688825 2419unsigned var_expanding_visitor::tick = 0;
77de5e9e 2420
a50de939 2421
74fe61bc 2422var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2423{
2424 // FIXME: for the time being, by default we only support plain '$foo
2425 // = bar', not '+=' or any other op= variant. This is fixable, but a
2426 // bit ugly.
2427 //
2428 // If derived classes desire to add additional operator support, add
2429 // new operators to this list in the derived class constructor.
2430 valid_ops.insert ("=");
2431}
2432
2433
87214add
JS
2434bool
2435var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2436 expression*& lvalue, expression*& rvalue)
77de5e9e 2437{
e57b735a
GH
2438 // Our job would normally be to require() the left and right sides
2439 // into a new assignment. What we're doing is slightly trickier:
2440 // we're pushing a functioncall** onto a stack, and if our left
2441 // child sets the functioncall* for that value, we're going to
2442 // assume our left child was a target symbol -- transformed into a
2443 // set_target_foo(value) call, and it wants to take our right child
2444 // as the argument "value".
2445 //
2446 // This is why some people claim that languages with
2447 // constructor-decomposing case expressions have a leg up on
2448 // visitors.
2449
2450 functioncall *fcall = NULL;
d9b516ca 2451
a50de939 2452 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2453 const string* old_op = op;
2454 op = &eop;
a50de939 2455
e57b735a 2456 target_symbol_setter_functioncalls.push (&fcall);
87214add 2457 replace (lvalue);
e57b735a 2458 target_symbol_setter_functioncalls.pop ();
87214add
JS
2459 replace (rvalue);
2460
2461 op = old_op;
e57b735a
GH
2462
2463 if (fcall != NULL)
77de5e9e 2464 {
e57b735a
GH
2465 // Our left child is informing us that it was a target variable
2466 // and it has been replaced with a set_target_foo() function
2467 // call; we are going to provide that function call -- with the
2468 // right child spliced in as sole argument -- in place of
de688825 2469 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2470
87214add 2471 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2472 {
2473 // Build up a list of supported operators.
2474 string ops;
2475 std::set<string>::iterator i;
b530b5b3 2476 int valid_ops_size = 0;
a50de939 2477 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2478 {
a50de939 2479 ops += " " + *i + ",";
b530b5b3
LB
2480 valid_ops_size++;
2481 }
a50de939
DS
2482 ops.resize(ops.size() - 1); // chop off the last ','
2483
2484 // Throw the error.
dc09353a 2485 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2486 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2487 valid_ops_size, ops.c_str()), tok);
b530b5b3 2488
a50de939 2489 }
e57b735a 2490
87214add
JS
2491 assert (lvalue == fcall);
2492 if (rvalue)
2493 fcall->args.push_back (rvalue);
4ed05b15 2494 provide (fcall);
87214add 2495 return true;
77de5e9e 2496 }
e57b735a 2497 else
87214add
JS
2498 return false;
2499}
2500
2501
2502void
2503var_expanding_visitor::visit_assignment (assignment* e)
2504{
2505 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2506 provide (e);
2507}
2508
2509
2510void
2511var_expanding_visitor::visit_pre_crement (pre_crement* e)
2512{
2513 expression *dummy = NULL;
2514 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2515 provide (e);
2516}
2517
2518
2519void
2520var_expanding_visitor::visit_post_crement (post_crement* e)
2521{
2522 expression *dummy = NULL;
2523 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2524 provide (e);
2525}
2526
2527
2528void
2529var_expanding_visitor::visit_delete_statement (delete_statement* s)
2530{
2531 string fakeop = "delete";
2532 expression *dummy = NULL;
2533 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2534 provide (s);
e57b735a 2535}
d9b516ca 2536
d7f3e0c5 2537
30263a73
FCE
2538void
2539var_expanding_visitor::visit_defined_op (defined_op* e)
2540{
2541 bool resolved = true;
2542
2543 defined_ops.push (e);
2544 try {
2545 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2546 // defined with a target_symbol* operand, a subsidiary call may attempt to
2547 // rewrite it to a general expression* instead, and require<> happily
2548 // casts to/from void*, causing possible memory corruption. We use
2549 // expression* here, being the general case of rewritten $variable.
2550 expression *foo1 = e->operand;
2551 foo1 = require (foo1);
2552
c69a87e0 2553 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2554 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2555 // erroneous resolutions. Some would signal a visit_target_symbol failure
2556 // with an exception, with a set flag within the target_symbol, or nothing
2557 // at all.
30263a73 2558 //
c69a87e0
FCE
2559 // Now, failures always have to be signalled with a
2560 // saved_conversion_error being chained to the target_symbol.
2561 // Successes have to result in an attempted rewrite of the
850bfddd 2562 // target_symbol (via provide()).
780f11ff 2563 //
c69a87e0
FCE
2564 // Edna Mode: "no capes". fche: "no exceptions".
2565
30263a73
FCE
2566 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2567 //
2568 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2569 //
2570 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2571 // dwarf probe to take care of it.
2572 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2573 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2574 //
30263a73
FCE
2575 // utrace: success: rewrites to function; failure: semantic_error
2576 //
850bfddd 2577 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2578
2579 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2580 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2581 resolved = false;
a45664f4 2582 else if (foo2) // unresolved but not marked failing
b7aedf26 2583 {
780f11ff
JS
2584 // There are some visitors that won't touch certain target_symbols,
2585 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2586 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2587 e->operand = foo2;
2588 provide (e);
2589 return;
2590 }
30263a73
FCE
2591 else // resolved, rewritten to some other expression type
2592 resolved = true;
780f11ff 2593 } catch (const semantic_error& e) {
c69a87e0 2594 assert (0); // should not happen
30263a73
FCE
2595 }
2596 defined_ops.pop ();
2597
2598 literal_number* ln = new literal_number (resolved ? 1 : 0);
2599 ln->tok = e->tok;
2600 provide (ln);
2601}
2602
2603
5f36109e
JS
2604struct dwarf_pretty_print
2605{
2606 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2607 const string& local, bool userspace_p,
2608 const target_symbol& e):
d19a9a82
JS
2609 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2610 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2611 {
2612 init_ts (e);
2613 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2614 }
2615
2616 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2617 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2618 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2619 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2620 {
2621 init_ts (e);
2622 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2623 }
2624
2625 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2626 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2627 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2628 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2629 {
2630 init_ts (e);
2631 dw.type_die_for_pointer (type_die, ts, &base_type);
2632 }
2633
2634 functioncall* expand ();
ce83ff57 2635 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2636
2637private:
2638 dwflpp& dw;
2639 target_symbol* ts;
7d11d8c9 2640 bool print_full;
5f36109e
JS
2641 Dwarf_Die base_type;
2642
2643 string local;
2644 vector<Dwarf_Die> scopes;
2645 Dwarf_Addr pc;
2646
2647 expression* pointer;
2648 Dwarf_Die pointer_type;
2649
d19a9a82 2650 const bool userspace_p, deref_p;
5f36109e
JS
2651
2652 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2653 print_format* pf, bool top=false);
600551ca
JS
2654 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2655 print_format* pf);
5f36109e 2656 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2657 print_format* pf);
5f36109e 2658 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2659 print_format* pf, bool top);
5f36109e 2660 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2661 print_format* pf, bool top);
5f36109e 2662 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2663 print_format* pf, bool top);
5f36109e 2664 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2665 print_format* pf, int& count);
bbee5bb8 2666 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2667
2668 void init_ts (const target_symbol& e);
2669 expression* deref (target_symbol* e);
c55ea10d 2670 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2671};
2672
2673
2674void
2675dwarf_pretty_print::init_ts (const target_symbol& e)
2676{
2677 // Work with a new target_symbol so we can modify arguments
2678 ts = new target_symbol (e);
2679
2680 if (ts->addressof)
dc09353a 2681 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2682
2683 if (ts->components.empty() ||
2684 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2685 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2686 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2687 ts->components.pop_back();
2688}
2689
2690
2691functioncall*
2692dwarf_pretty_print::expand ()
2693{
2694 static unsigned tick = 0;
2695
2696 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2697 // try {
2698 // return sprintf("{.foo=...}", (ts)->foo, ...)
2699 // } catch {
2700 // return "ERROR"
2701 // }
5f36109e
JS
2702 // }
2703
2704 // Create the function decl and call.
2705
2706 functiondecl *fdecl = new functiondecl;
2707 fdecl->tok = ts->tok;
2708 fdecl->synthetic = true;
2709 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2710 fdecl->type = pe_string;
2711
2712 functioncall* fcall = new functioncall;
2713 fcall->tok = ts->tok;
2714 fcall->function = fdecl->name;
140be17a 2715 fcall->type = pe_string;
5f36109e
JS
2716
2717 // If there's a <pointer>, replace it with a new var and make that
2718 // the first function argument.
2719 if (pointer)
2720 {
2721 vardecl *v = new vardecl;
2722 v->type = pe_long;
2723 v->name = "pointer";
2724 v->tok = ts->tok;
2725 fdecl->formal_args.push_back (v);
2726 fcall->args.push_back (pointer);
2727
2728 symbol* sym = new symbol;
2729 sym->tok = ts->tok;
2730 sym->name = v->name;
5f36109e
JS
2731 pointer = sym;
2732 }
2733
2734 // For each expression argument, replace it with a function argument.
2735 for (unsigned i = 0; i < ts->components.size(); ++i)
2736 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2737 {
2738 vardecl *v = new vardecl;
2739 v->type = pe_long;
2740 v->name = "index" + lex_cast(i);
2741 v->tok = ts->tok;
2742 fdecl->formal_args.push_back (v);
2743 fcall->args.push_back (ts->components[i].expr_index);
2744
2745 symbol* sym = new symbol;
2746 sym->tok = ts->tok;
2747 sym->name = v->name;
5f36109e
JS
2748 ts->components[i].expr_index = sym;
2749 }
2750
2751 // Create the return sprintf.
1c922ad7 2752 print_format* pf = print_format::create(ts->tok, "sprintf");
5f36109e
JS
2753 return_statement* rs = new return_statement;
2754 rs->tok = ts->tok;
2755 rs->value = pf;
5f36109e
JS
2756
2757 // Recurse into the actual values.
7d11d8c9 2758 recurse (&base_type, ts, pf, true);
5f36109e
JS
2759 pf->components = print_format::string_to_components(pf->raw_components);
2760
7d11d8c9
JS
2761 // Create the try-catch net
2762 try_block* tb = new try_block;
2763 tb->tok = ts->tok;
2764 tb->try_block = rs;
2765 tb->catch_error_var = 0;
2766 return_statement* rs2 = new return_statement;
2767 rs2->tok = ts->tok;
2768 rs2->value = new literal_string ("ERROR");
2769 rs2->value->tok = ts->tok;
2770 tb->catch_block = rs2;
2771 fdecl->body = tb;
2772
f8809d54 2773 fdecl->join (dw.sess);
5f36109e
JS
2774 return fcall;
2775}
2776
2777
2778void
2779dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2780 print_format* pf, bool top)
5f36109e
JS
2781{
2782 Dwarf_Die type;
2783 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2784
2785 switch (dwarf_tag(&type))
2786 {
2787 default:
2788 // XXX need a warning?
2789 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2790 // + ") for " + dwarf_type_name(&type), e->tok);
2791 pf->raw_components.append("?");
2792 break;
2793
2794 case DW_TAG_enumeration_type:
2795 case DW_TAG_base_type:
7d11d8c9 2796 recurse_base (&type, e, pf);
5f36109e
JS
2797 break;
2798
2799 case DW_TAG_array_type:
7d11d8c9 2800 recurse_array (&type, e, pf, top);
5f36109e
JS
2801 break;
2802
2803 case DW_TAG_pointer_type:
2804 case DW_TAG_reference_type:
2805 case DW_TAG_rvalue_reference_type:
7d11d8c9 2806 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2807 break;
2808
2809 case DW_TAG_subroutine_type:
c55ea10d 2810 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2811 break;
2812
2813 case DW_TAG_union_type:
5f36109e
JS
2814 case DW_TAG_structure_type:
2815 case DW_TAG_class_type:
7d11d8c9 2816 recurse_struct (&type, e, pf, top);
5f36109e
JS
2817 break;
2818 }
2819}
2820
2821
600551ca
JS
2822// Bit fields are handled as a special-case combination of recurse() and
2823// recurse_base(), only called from recurse_struct_members(). The main
2824// difference is that the value is always printed numerically, even if the
2825// underlying type is a char.
2826void
2827dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2828 print_format* pf)
2829{
2830 Dwarf_Die type;
2831 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2832
2833 int tag = dwarf_tag(&type);
2834 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2835 {
2836 // XXX need a warning?
2837 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2838 // + ") for " + dwarf_type_name(&type), e->tok);
2839 pf->raw_components.append("?");
2840 return;
2841 }
2842
2843 Dwarf_Attribute attr;
2844 Dwarf_Word encoding = (Dwarf_Word) -1;
2845 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2846 &encoding);
2847 switch (encoding)
2848 {
2849 case DW_ATE_float:
2850 case DW_ATE_complex_float:
2851 // XXX need a warning?
2852 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2853 // + ") for " + dwarf_type_name(&type), e->tok);
2854 pf->raw_components.append("?");
2855 break;
2856
2857 case DW_ATE_unsigned:
2858 case DW_ATE_unsigned_char:
2859 push_deref (pf, "%u", e);
2860 break;
2861
2862 case DW_ATE_signed:
2863 case DW_ATE_signed_char:
2864 default:
2865 push_deref (pf, "%i", e);
2866 break;
2867 }
2868}
2869
2870
5f36109e
JS
2871void
2872dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2873 print_format* pf)
5f36109e
JS
2874{
2875 Dwarf_Attribute attr;
2876 Dwarf_Word encoding = (Dwarf_Word) -1;
2877 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2878 &encoding);
5f36109e
JS
2879 switch (encoding)
2880 {
2881 case DW_ATE_float:
2882 case DW_ATE_complex_float:
2883 // XXX need a warning?
2884 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2885 // + ") for " + dwarf_type_name(type), e->tok);
2886 pf->raw_components.append("?");
5f36109e
JS
2887 break;
2888
6561d8d1 2889 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2890 case DW_ATE_signed_char:
2891 case DW_ATE_unsigned_char:
941101c1
JS
2892 // Use escapes to make sure that non-printable characters
2893 // don't interrupt our stream (especially '\0' values).
2894 push_deref (pf, "'%#c'", e);
5f36109e
JS
2895 break;
2896
2897 case DW_ATE_unsigned:
c55ea10d 2898 push_deref (pf, "%u", e);
5f36109e
JS
2899 break;
2900
600551ca 2901 case DW_ATE_signed:
5f36109e 2902 default:
c55ea10d 2903 push_deref (pf, "%i", e);
5f36109e
JS
2904 break;
2905 }
5f36109e
JS
2906}
2907
2908
2909void
2910dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2911 print_format* pf, bool top)
5f36109e 2912{
7d11d8c9
JS
2913 if (!top && !print_full)
2914 {
2915 pf->raw_components.append("[...]");
2916 return;
2917 }
2918
5f36109e
JS
2919 Dwarf_Die childtype;
2920 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2921
2922 if (print_chars (&childtype, e, pf))
2923 return;
2924
5f36109e
JS
2925 pf->raw_components.append("[");
2926
2927 // We print the array up to the first 5 elements.
2928 // XXX how can we determine the array size?
2929 // ... for now, just print the first element
64cddf39 2930 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2931 unsigned i, size = 1;
64cddf39 2932 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2933 {
2934 if (i > 0)
2935 pf->raw_components.append(", ");
2936 target_symbol* e2 = new target_symbol(*e);
2937 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2938 recurse (&childtype, e2, pf);
5f36109e
JS
2939 }
2940 if (i < size || 1/*XXX until real size is known */)
2941 pf->raw_components.append(", ...");
2942 pf->raw_components.append("]");
2943}
2944
2945
2946void
2947dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2948 print_format* pf, bool top)
5f36109e 2949{
7d11d8c9 2950 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2951 bool void_p = true;
7d11d8c9 2952 Dwarf_Die pointee;
bbee5bb8 2953 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2954 {
2955 try
2956 {
2957 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2958 void_p = false;
2959 }
2960 catch (const semantic_error&) {}
2961 }
2962
2963 if (!void_p)
5f36109e 2964 {
bbee5bb8
JS
2965 if (print_chars (&pointee, e, pf))
2966 return;
2967
2968 if (top)
2969 {
2970 recurse (&pointee, e, pf, top);
2971 return;
2972 }
5f36109e 2973 }
bbee5bb8 2974
c55ea10d 2975 push_deref (pf, "%p", e);
5f36109e
JS
2976}
2977
2978
2979void
2980dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2981 print_format* pf, bool top)
5f36109e 2982{
bdec0e18
JS
2983 if (dwarf_hasattr(type, DW_AT_declaration))
2984 {
a44a7cb5 2985 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2986 if (!resolved)
2987 {
2988 // could be an error, but for now just stub it
2989 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2990 pf->raw_components.append("{...}");
2991 return;
2992 }
2993 type = resolved;
2994 }
2995
5f36109e
JS
2996 int count = 0;
2997 pf->raw_components.append("{");
7d11d8c9
JS
2998 if (top || print_full)
2999 recurse_struct_members (type, e, pf, count);
3000 else
3001 pf->raw_components.append("...");
5f36109e
JS
3002 pf->raw_components.append("}");
3003}
3004
3005
3006void
3007dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3008 print_format* pf, int& count)
5f36109e 3009{
a80f28d8
JS
3010 /* With inheritance, a subclass may mask member names of parent classes, so
3011 * our search among the inheritance tree must be breadth-first rather than
3012 * depth-first (recursive). The type die is still our starting point. When
3013 * we encounter a masked name, just skip it. */
3014 set<string> dupes;
3015 deque<Dwarf_Die> inheritees(1, *type);
3016 for (; !inheritees.empty(); inheritees.pop_front())
3017 {
dee830d9 3018 Dwarf_Die child, childtype, import;
a80f28d8
JS
3019 if (dwarf_child (&inheritees.front(), &child) == 0)
3020 do
3021 {
3022 target_symbol* e2 = e;
5f36109e 3023
a80f28d8
JS
3024 // skip static members
3025 if (dwarf_hasattr(&child, DW_AT_declaration))
3026 continue;
5f36109e 3027
a80f28d8 3028 int tag = dwarf_tag (&child);
5f36109e 3029
dee830d9
MW
3030 /* Pretend imported units contain members by recursing into
3031 struct_member printing with the same count. */
3032 if (tag == DW_TAG_imported_unit
3033 && dwarf_attr_die (&child, DW_AT_import, &import))
3034 recurse_struct_members (&import, e2, pf, count);
3035
a80f28d8
JS
3036 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
3037 continue;
5f36109e 3038
a80f28d8 3039 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 3040
a80f28d8
JS
3041 if (tag == DW_TAG_inheritance)
3042 {
3043 inheritees.push_back(childtype);
3044 continue;
3045 }
5f36109e 3046
a80f28d8
JS
3047 int childtag = dwarf_tag (&childtype);
3048 const char *member = dwarf_diename (&child);
3a147004 3049
a80f28d8
JS
3050 // "_vptr.foo" members are C++ virtual function tables,
3051 // which (generally?) aren't interesting for users.
3052 if (member && startswith(member, "_vptr."))
3053 continue;
3a147004 3054
a80f28d8
JS
3055 // skip inheritance-masked duplicates
3056 if (member && !dupes.insert(member).second)
3057 continue;
64cddf39 3058
a80f28d8
JS
3059 if (++count > 1)
3060 pf->raw_components.append(", ");
64cddf39 3061
a80f28d8
JS
3062 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
3063 if (pf->args.size() >= 32)
3064 {
3065 pf->raw_components.append("...");
3066 break;
3067 }
3068
3069 if (member)
3070 {
3071 pf->raw_components.append(".");
3072 pf->raw_components.append(member);
5f36109e 3073
a80f28d8
JS
3074 e2 = new target_symbol(*e);
3075 e2->components.push_back (target_symbol::component(e->tok, member));
3076 }
3077 else if (childtag == DW_TAG_union_type)
3078 pf->raw_components.append("<union>");
3079 else if (childtag == DW_TAG_structure_type)
3080 pf->raw_components.append("<class>");
3081 else if (childtag == DW_TAG_class_type)
3082 pf->raw_components.append("<struct>");
3083 pf->raw_components.append("=");
600551ca
JS
3084
3085 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
3086 recurse_bitfield (&childtype, e2, pf);
3087 else
3088 recurse (&childtype, e2, pf);
5f36109e 3089 }
a80f28d8
JS
3090 while (dwarf_siblingof (&child, &child) == 0);
3091 }
5f36109e
JS
3092}
3093
3094
bbee5bb8
JS
3095bool
3096dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
3097 print_format* pf)
3098{
3099 Dwarf_Die type;
3100 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
3101
3102 Dwarf_Attribute attr;
3103 Dwarf_Word encoding = (Dwarf_Word) -1;
3104 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3105 &encoding);
3106 switch (encoding)
bbee5bb8 3107 {
6561d8d1
JS
3108 case DW_ATE_UTF:
3109 case DW_ATE_signed_char:
3110 case DW_ATE_unsigned_char:
3111 break;
3112 default:
3113 return false;
3114 }
3115
3116 string function = userspace_p ? "user_string2" : "kernel_string2";
3117 Dwarf_Word size = (Dwarf_Word) -1;
3118 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3119 switch (size)
3120 {
3121 case 1:
3122 break;
3123 case 2:
3124 function += "_utf16";
3125 break;
3126 case 4:
3127 function += "_utf32";
3128 break;
3129 default:
3130 return false;
3131 }
3132
3133 if (push_deref (pf, "\"%s\"", e))
3134 {
3135 // steal the last arg for a string access
3136 assert (!pf->args.empty());
3137 functioncall* fcall = new functioncall;
3138 fcall->tok = e->tok;
3139 fcall->function = function;
3140 fcall->args.push_back (pf->args.back());
3141 expression *err_msg = new literal_string ("<unknown>");
3142 err_msg->tok = e->tok;
3143 fcall->args.push_back (err_msg);
3144 pf->args.back() = fcall;
bbee5bb8 3145 }
6561d8d1 3146 return true;
bbee5bb8
JS
3147}
3148
a5ce5211
MW
3149// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3150static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3151 + "#define fetch_register k_fetch_register\n"
3152 + "#define store_register k_store_register\n"
3153 + "#define deref kderef\n"
3154 + "#define store_deref store_kderef\n";
a5ce5211
MW
3155
3156static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3157 + "#define fetch_register u_fetch_register\n"
3158 + "#define store_register u_store_register\n"
3159 + "#define deref uderef\n"
3160 + "#define store_deref store_uderef\n";
a5ce5211
MW
3161
3162#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3163 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3164
3165static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3166 + "#undef fetch_register\n"
3167 + "#undef store_register\n"
3168 + "#undef deref\n"
3169 + "#undef store_deref\n";
bbee5bb8 3170
1c0be8c7
JS
3171static functioncall*
3172synthetic_embedded_deref_call(systemtap_session& session,
3173 const string& function_name,
3174 const string& function_code,
3175 exp_type function_type,
3176 bool userspace_p,
3177 bool lvalue_p,
3178 target_symbol* e,
3179 expression* pointer=NULL)
3180{
3181 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3182 functiondecl *fdecl = new functiondecl;
3183 fdecl->synthetic = true;
3184 fdecl->tok = e->tok;
1c0be8c7
JS
3185 fdecl->name = function_name;
3186 fdecl->type = function_type;
3187
5f36109e
JS
3188 embeddedcode *ec = new embeddedcode;
3189 ec->tok = e->tok;
1c0be8c7
JS
3190 ec->code += "/* unprivileged */";
3191 if (! lvalue_p)
3192 ec->code += "/* pure */";
3193 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3194 ec->code += function_code;
3195 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3196 fdecl->body = ec;
3197
3198 // Synthesize a functioncall.
3199 functioncall* fcall = new functioncall;
3200 fcall->tok = e->tok;
3201 fcall->function = fdecl->name;
1c0be8c7 3202 fcall->type = fdecl->type;
5f36109e 3203
1c0be8c7
JS
3204 // If this code snippet uses a precomputed pointer,
3205 // pass that as the first argument.
5f36109e
JS
3206 if (pointer)
3207 {
5f36109e
JS
3208 vardecl *v = new vardecl;
3209 v->type = pe_long;
3210 v->name = "pointer";
3211 v->tok = e->tok;
3212 fdecl->formal_args.push_back(v);
3213 fcall->args.push_back(pointer);
3214 }
5f36109e 3215
1c0be8c7 3216 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3217 for (unsigned i = 0; i < e->components.size(); ++i)
3218 if (e->components[i].type == target_symbol::comp_expression_array_index)
3219 {
3220 vardecl *v = new vardecl;
3221 v->type = pe_long;
3222 v->name = "index" + lex_cast(i);
3223 v->tok = e->tok;
3224 fdecl->formal_args.push_back(v);
3225 fcall->args.push_back(e->components[i].expr_index);
3226 }
3227
1c0be8c7
JS
3228 // If this code snippet is assigning to an lvalue,
3229 // add a final argument for the rvalue.
3230 if (lvalue_p)
3231 {
3232 // Modify the fdecl so it carries a single pe_long formal
3233 // argument called "value".
5f36109e 3234
1c0be8c7
JS
3235 // FIXME: For the time being we only support setting target
3236 // variables which have base types; these are 'pe_long' in
3237 // stap's type vocabulary. Strings and pointers might be
3238 // reasonable, some day, but not today.
5f36109e 3239
1c0be8c7
JS
3240 vardecl *v = new vardecl;
3241 v->type = pe_long;
3242 v->name = "value";
3243 v->tok = e->tok;
3244 fdecl->formal_args.push_back(v);
3245 // NB: We don't know the value for fcall argument yet.
3246 // (see target_symbol_setter_functioncalls)
3247 }
3248
3249 // Add the synthesized decl to the session, and return the call.
3250 fdecl->join (session);
5f36109e
JS
3251 return fcall;
3252}
3253
1c0be8c7
JS
3254expression*
3255dwarf_pretty_print::deref (target_symbol* e)
3256{
3257 static unsigned tick = 0;
3258
3259 if (!deref_p)
3260 {
3261 assert (pointer && e->components.empty());
3262 return pointer;
3263 }
3264
3265 bool lvalue_p = false;
3266 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3267
3268 string code;
3269 exp_type type = pe_long;
3270 if (pointer)
3271 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3272 else if (!local.empty())
3273 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3274 else
3275 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3276
3277 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3278 userspace_p, lvalue_p, e, pointer);
3279}
3280
5f36109e 3281
c55ea10d
JS
3282bool
3283dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3284 target_symbol* e)
3285{
3286 expression* e2 = NULL;
3287 try
3288 {
3289 e2 = deref (e);
3290 }
3291 catch (const semantic_error&)
3292 {
3293 pf->raw_components.append ("?");
3294 return false;
3295 }
3296 pf->raw_components.append (fmt);
3297 pf->args.push_back (e2);
3298 return true;
3299}
3300
3301
e57b735a 3302void
a7999c82 3303dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3304{
a7999c82
JS
3305 // Get the full name of the target symbol.
3306 stringstream ts_name_stream;
3307 e->print(ts_name_stream);
3308 string ts_name = ts_name_stream.str();
3309
3310 // Check and make sure we haven't already seen this target
3311 // variable in this return probe. If we have, just return our
3312 // last replacement.
af234c40 3313 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3314 if (i != return_ts_map.end())
85ecf79a 3315 {
a7999c82
JS
3316 provide (i->second);
3317 return;
3318 }
85ecf79a 3319
70208613
JS
3320 // Attempt the expansion directly first, so if there's a problem with the
3321 // variable we won't have a bogus entry probe lying around. Like in
3322 // saveargs(), we pretend for a moment that we're not in a .return.
3323 bool saved_has_return = q.has_return;
3324 q.has_return = false;
3325 expression *repl = e;
3326 replace (repl);
3327 q.has_return = saved_has_return;
3328 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3329 if (n && n->saved_conversion_error)
3330 {
3331 provide (repl);
3332 return;
3333 }
3334
af234c40
JS
3335 expression *exp;
3336 if (!q.has_process &&
3337 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3338 exp = gen_kretprobe_saved_return(repl);
af234c40 3339 else
cc9001af 3340 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3341
3342 // Provide the variable to our parent so it can be used as a
3343 // substitute for the target symbol.
3344 provide (exp);
3345
3346 // Remember this replacement since we might be able to reuse
3347 // it later if the same return probe references this target
3348 // symbol again.
3349 return_ts_map[ts_name] = exp;
3350}
3351
4a2970a3 3352static expression*
23dc94f6
DS
3353gen_mapped_saved_return(systemtap_session &sess, expression* e,
3354 const string& name,
3355 block *& add_block, bool& add_block_tid,
3356 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3357{
23dc94f6
DS
3358 static unsigned tick = 0;
3359
a7999c82
JS
3360 // We've got to do several things here to handle target
3361 // variables in return probes.
85ecf79a 3362
a7999c82
JS
3363 // (1) Synthesize two global arrays. One is the cache of the
3364 // target variable and the other contains a thread specific
3365 // nesting level counter. The arrays will look like
3366 // this:
3367 //
23dc94f6
DS
3368 // _entry_tvar_{name}_{num}
3369 // _entry_tvar_{name}_{num}_ctr
a7999c82 3370
23dc94f6 3371 string aname = (string("_entry_tvar_")
cc9001af 3372 + name
aca66a36 3373 + "_" + lex_cast(tick++));
a7999c82
JS
3374 vardecl* vd = new vardecl;
3375 vd->name = aname;
3376 vd->tok = e->tok;
23dc94f6 3377 sess.globals.push_back (vd);
a7999c82
JS
3378
3379 string ctrname = aname + "_ctr";
3380 vd = new vardecl;
3381 vd->name = ctrname;
3382 vd->tok = e->tok;
23dc94f6 3383 sess.globals.push_back (vd);
a7999c82
JS
3384
3385 // (2) Create a new code block we're going to insert at the
3386 // beginning of this probe to get the cached value into a
3387 // temporary variable. We'll replace the target variable
3388 // reference with the temporary variable reference. The code
3389 // will look like this:
3390 //
23dc94f6
DS
3391 // _entry_tvar_tid = tid()
3392 // _entry_tvar_{name}_{num}_tmp
3393 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3394 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3395 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3396 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3397 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3398 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3399
3400 // (2a) Synthesize the tid temporary expression, which will look
3401 // like this:
3402 //
23dc94f6 3403 // _entry_tvar_tid = tid()
a7999c82 3404 symbol* tidsym = new symbol;
23dc94f6 3405 tidsym->name = string("_entry_tvar_tid");
a7999c82 3406 tidsym->tok = e->tok;
85ecf79a 3407
a7999c82
JS
3408 if (add_block == NULL)
3409 {
3410 add_block = new block;
3411 add_block->tok = e->tok;
8cc799a5 3412 }
8c819921 3413
8cc799a5
JS
3414 if (!add_block_tid)
3415 {
a7999c82
JS
3416 // Synthesize a functioncall to grab the thread id.
3417 functioncall* fc = new functioncall;
3418 fc->tok = e->tok;
3419 fc->function = string("tid");
8c819921 3420
23dc94f6 3421 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3422 assignment* a = new assignment;
3423 a->tok = e->tok;
3424 a->op = "=";
a7999c82
JS
3425 a->left = tidsym;
3426 a->right = fc;
8c819921
DS
3427
3428 expr_statement* es = new expr_statement;
3429 es->tok = e->tok;
3430 es->value = a;
8c819921 3431 add_block->statements.push_back (es);
8cc799a5 3432 add_block_tid = true;
a7999c82 3433 }
8c819921 3434
a7999c82
JS
3435 // (2b) Synthesize an array reference and assign it to a
3436 // temporary variable (that we'll use as replacement for the
3437 // target variable reference). It will look like this:
3438 //
23dc94f6
DS
3439 // _entry_tvar_{name}_{num}_tmp
3440 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3441 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3442
3443 arrayindex* ai_tvar_base = new arrayindex;
3444 ai_tvar_base->tok = e->tok;
3445
3446 symbol* sym = new symbol;
3447 sym->name = aname;
3448 sym->tok = e->tok;
3449 ai_tvar_base->base = sym;
3450
3451 ai_tvar_base->indexes.push_back(tidsym);
3452
3453 // We need to create a copy of the array index in its current
3454 // state so we can have 2 variants of it (the original and one
3455 // that post-decrements the second index).
3456 arrayindex* ai_tvar = new arrayindex;
3457 arrayindex* ai_tvar_postdec = new arrayindex;
3458 *ai_tvar = *ai_tvar_base;
3459 *ai_tvar_postdec = *ai_tvar_base;
3460
3461 // Synthesize the
23dc94f6 3462 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3463 // second index into the array.
3464 arrayindex* ai_ctr = new arrayindex;
3465 ai_ctr->tok = e->tok;
3466
3467 sym = new symbol;
3468 sym->name = ctrname;
3469 sym->tok = e->tok;
3470 ai_ctr->base = sym;
3471 ai_ctr->indexes.push_back(tidsym);
3472 ai_tvar->indexes.push_back(ai_ctr);
3473
3474 symbol* tmpsym = new symbol;
3475 tmpsym->name = aname + "_tmp";
3476 tmpsym->tok = e->tok;
3477
3478 assignment* a = new assignment;
3479 a->tok = e->tok;
3480 a->op = "=";
3481 a->left = tmpsym;
3482 a->right = ai_tvar;
3483
3484 expr_statement* es = new expr_statement;
3485 es->tok = e->tok;
3486 es->value = a;
3487
3488 add_block->statements.push_back (es);
3489
3490 // (2c) Add a post-decrement to the second array index and
3491 // delete the array value. It will look like this:
3492 //
23dc94f6
DS
3493 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3494 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3495
3496 post_crement* pc = new post_crement;
3497 pc->tok = e->tok;
3498 pc->op = "--";
3499 pc->operand = ai_ctr;
3500 ai_tvar_postdec->indexes.push_back(pc);
3501
3502 delete_statement* ds = new delete_statement;
3503 ds->tok = e->tok;
3504 ds->value = ai_tvar_postdec;
3505
3506 add_block->statements.push_back (ds);
3507
3508 // (2d) Delete the counter value if it is 0. It will look like
3509 // this:
23dc94f6
DS
3510 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3511 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3512
3513 ds = new delete_statement;
3514 ds->tok = e->tok;
3515 ds->value = ai_ctr;
3516
3517 unary_expression *ue = new unary_expression;
3518 ue->tok = e->tok;
3519 ue->op = "!";
3520 ue->operand = ai_ctr;
3521
3522 if_statement *ifs = new if_statement;
3523 ifs->tok = e->tok;
3524 ifs->condition = ue;
3525 ifs->thenblock = ds;
3526 ifs->elseblock = NULL;
3527
3528 add_block->statements.push_back (ifs);
3529
3530 // (3) We need an entry probe that saves the value for us in the
3531 // global array we created. Create the entry probe, which will
3532 // look like this:
3533 //
2260f4e3 3534 // probe kernel.function("{function}").call {
23dc94f6
DS
3535 // _entry_tvar_tid = tid()
3536 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3537 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3538 // = ${param}
3539 // }
3540
2260f4e3 3541 if (add_call_probe == NULL)
a7999c82 3542 {
2260f4e3
FCE
3543 add_call_probe = new block;
3544 add_call_probe->tok = e->tok;
8cc799a5 3545 }
4baf0e53 3546
8cc799a5
JS
3547 if (!add_call_probe_tid)
3548 {
a7999c82
JS
3549 // Synthesize a functioncall to grab the thread id.
3550 functioncall* fc = new functioncall;
3551 fc->tok = e->tok;
3552 fc->function = string("tid");
4baf0e53 3553
23dc94f6 3554 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3555 assignment* a = new assignment;
8fc05e57
DS
3556 a->tok = e->tok;
3557 a->op = "=";
a7999c82
JS
3558 a->left = tidsym;
3559 a->right = fc;
8fc05e57 3560
a7999c82 3561 expr_statement* es = new expr_statement;
8fc05e57
DS
3562 es->tok = e->tok;
3563 es->value = a;
2260f4e3 3564 add_call_probe = new block(add_call_probe, es);
8cc799a5 3565 add_call_probe_tid = true;
85ecf79a 3566 }
cf2a1f85 3567
a7999c82 3568 // Save the value, like this:
23dc94f6
DS
3569 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3570 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3571 // = ${param}
3572 arrayindex* ai_tvar_preinc = new arrayindex;
3573 *ai_tvar_preinc = *ai_tvar_base;
3574
3575 pre_crement* preinc = new pre_crement;
3576 preinc->tok = e->tok;
3577 preinc->op = "++";
3578 preinc->operand = ai_ctr;
3579 ai_tvar_preinc->indexes.push_back(preinc);
3580
3581 a = new assignment;
3582 a->tok = e->tok;
3583 a->op = "=";
3584 a->left = ai_tvar_preinc;
3585 a->right = e;
3586
3587 es = new expr_statement;
3588 es->tok = e->tok;
3589 es->value = a;
3590
2260f4e3 3591 add_call_probe = new block(add_call_probe, es);
a7999c82 3592
23dc94f6 3593 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3594 // our parent so it can be used as a substitute for the target
3595 // symbol.
3f803f9e 3596 delete ai_tvar_base;
af234c40
JS
3597 return tmpsym;
3598}
a7999c82 3599
af234c40 3600
23dc94f6
DS
3601expression*
3602dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3603 const string& name)
3604{
3605 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3606 add_block_tid, add_call_probe,
3607 add_call_probe_tid);
3608}
3609
3610
af234c40 3611expression*
140be17a 3612dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3613{
3614 // The code for this is simple.
3615 //
3616 // .call:
3617 // _set_kretprobe_long(index, $value)
3618 //
3619 // .return:
3620 // _get_kretprobe_long(index)
3621 //
3622 // (or s/long/string/ for things like $$parms)
3623
3624 unsigned index;
3625 string setfn, getfn;
3626
140be17a
JS
3627 // We need the caller to predetermine the type of the expression!
3628 switch (e->type)
af234c40 3629 {
140be17a 3630 case pe_string:
af234c40
JS
3631 index = saved_strings++;
3632 setfn = "_set_kretprobe_string";
3633 getfn = "_get_kretprobe_string";
140be17a
JS
3634 break;
3635 case pe_long:
af234c40
JS
3636 index = saved_longs++;
3637 setfn = "_set_kretprobe_long";
3638 getfn = "_get_kretprobe_long";
140be17a
JS
3639 break;
3640 default:
dc09353a 3641 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3642 }
3643
3644 // Create the entry code
3645 // _set_kretprobe_{long|string}(index, $value)
3646
3647 if (add_call_probe == NULL)
3648 {
3649 add_call_probe = new block;
3650 add_call_probe->tok = e->tok;
3651 }
3652
3653 functioncall* set_fc = new functioncall;
3654 set_fc->tok = e->tok;
3655 set_fc->function = setfn;
3656 set_fc->args.push_back(new literal_number(index));
3657 set_fc->args.back()->tok = e->tok;
3658 set_fc->args.push_back(e);
3659
3660 expr_statement* set_es = new expr_statement;
3661 set_es->tok = e->tok;
3662 set_es->value = set_fc;
3663
3664 add_call_probe->statements.push_back(set_es);
3665
3666 // Create the return code
3667 // _get_kretprobe_{long|string}(index)
3668
3669 functioncall* get_fc = new functioncall;
3670 get_fc->tok = e->tok;
3671 get_fc->function = getfn;
3672 get_fc->args.push_back(new literal_number(index));
3673 get_fc->args.back()->tok = e->tok;
3674
3675 return get_fc;
a7999c82 3676}
a43ba433 3677
2cb3fe26 3678
a7999c82
JS
3679void
3680dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3681{
b78a0fbb 3682 if (null_die(scope_die)) {
04c8e51b
JL
3683 literal_string *empty = new literal_string("");
3684 empty->tok = e->tok;
3685 provide(empty);
a7999c82 3686 return;
b78a0fbb 3687 }
2cb3fe26 3688
5f36109e
JS
3689 target_symbol *tsym = new target_symbol(*e);
3690
fde50242
JS
3691 bool pretty = (!e->components.empty() &&
3692 e->components[0].type == target_symbol::comp_pretty_print);
3693 string format = pretty ? "=%s" : "=%#x";
a43ba433 3694
a7999c82
JS
3695 // Convert $$parms to sprintf of a list of parms and active local vars
3696 // which we recursively evaluate
a43ba433 3697
1c922ad7 3698 print_format* pf = print_format::create(e->tok, "sprintf");
a7999c82 3699
277c21bc 3700 if (q.has_return && (e->name == "$$return"))
a7999c82 3701 {
277c21bc 3702 tsym->name = "$return";
a7999c82
JS
3703
3704 // Ignore any variable that isn't accessible.
3705 tsym->saved_conversion_error = 0;
3706 expression *texp = tsym;
8b095b45 3707 replace (texp); // NB: throws nothing ...
a7999c82 3708 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3709 {
2cb3fe26 3710
a43ba433
FCE
3711 }
3712 else
3713 {
a7999c82 3714 pf->raw_components += "return";
5f36109e 3715 pf->raw_components += format;
a7999c82
JS
3716 pf->args.push_back(texp);
3717 }
3718 }
3719 else
3720 {
3721 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3722 bool first = true;
a7999c82 3723 Dwarf_Die result;
d48bc7eb
JS
3724 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3725 for (unsigned i = 0; i < scopes.size(); ++i)
3726 {
3727 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3728 break; // we don't want file-level variables
3729 if (dwarf_child (&scopes[i], &result) == 0)
3730 do
00cf3709 3731 {
d48bc7eb
JS
3732 switch (dwarf_tag (&result))
3733 {
3734 case DW_TAG_variable:
3735 if (e->name == "$$parms")
3736 continue;
3737 break;
3738 case DW_TAG_formal_parameter:
3739 if (e->name == "$$locals")
3740 continue;
3741 break;
3742
3743 default:
3744 continue;
3745 }
41c262f3 3746
d48bc7eb
JS
3747 const char *diename = dwarf_diename (&result);
3748 if (! diename) continue;
f76427a2 3749
d48bc7eb
JS
3750 if (! first)
3751 pf->raw_components += " ";
3752 pf->raw_components += diename;
fde50242
JS
3753 first = false;
3754
3755 // Write a placeholder for ugly aggregates
3756 Dwarf_Die type;
3757 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3758 {
3759 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3760 switch (dwarf_tag(&type))
3761 {
3762 case DW_TAG_union_type:
3763 case DW_TAG_structure_type:
3764 case DW_TAG_class_type:
3765 pf->raw_components += "={...}";
3766 continue;
3767
3768 case DW_TAG_array_type:
3769 pf->raw_components += "=[...]";
3770 continue;
3771 }
3772 }
345bbb3d 3773
d48bc7eb
JS
3774 tsym->name = "$";
3775 tsym->name += diename;
41c262f3 3776
d48bc7eb
JS
3777 // Ignore any variable that isn't accessible.
3778 tsym->saved_conversion_error = 0;
3779 expression *texp = tsym;
3780 replace (texp); // NB: throws nothing ...
3781 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3782 {
d48bc7eb
JS
3783 if (q.sess.verbose>2)
3784 {
e26c2f83 3785 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb 3786 c != 0;
c081af73 3787 c = c->get_chain()) {
4c5d9906 3788 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3789 }
3790 }
3791
3792 pf->raw_components += "=?";
a43ba433 3793 }
d48bc7eb
JS
3794 else
3795 {
3796 pf->raw_components += format;
3797 pf->args.push_back(texp);
3798 }
a7999c82 3799 }
d48bc7eb
JS
3800 while (dwarf_siblingof (&result, &result) == 0);
3801 }
a7999c82 3802 }
2cb3fe26 3803
a7999c82 3804 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3805 pf->type = pe_string;
a7999c82
JS
3806 provide (pf);
3807}
3808
2cb3fe26 3809
bd1fcbad
YZ
3810void
3811dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3812{
3813 // Fill in our current module context if needed
3814 if (e->module.empty())
3815 e->module = q.dw.module_name;
3816
3817 if (e->module == q.dw.module_name && e->cu_name.empty())
3818 {
3819 // process like any other local
3820 // e->sym_name() will do the right thing
3821 visit_target_symbol(e);
3822 return;
3823 }
3824
3825 var_expanding_visitor::visit_atvar_op(e);
3826}
3827
3828
a7999c82
JS
3829void
3830dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3831{
bd1fcbad 3832 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3833 visited = true;
30263a73
FCE
3834 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3835 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3836
70208613 3837 try
a7999c82 3838 {
c69a87e0
FCE
3839 bool lvalue = is_active_lvalue(e);
3840 if (lvalue && !q.sess.guru_mode)
dc09353a 3841 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3842
100a540e 3843 // XXX: process $context vars should be writable
70208613 3844
c69a87e0
FCE
3845 // See if we need to generate a new probe to save/access function
3846 // parameters from a return probe. PR 1382.
3847 if (q.has_return
3848 && !defined_being_checked
277c21bc
JS
3849 && e->name != "$return" // not the special return-value variable handled below
3850 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3851 {
3852 if (lvalue)
dc09353a 3853 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3854 visit_target_symbol_saved_return(e);
3855 return;
3856 }
e57b735a 3857
277c21bc
JS
3858 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3859 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3860 {
3861 if (lvalue)
dc09353a 3862 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3863
c69a87e0 3864 if (e->addressof)
dc09353a 3865 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3866
5f36109e
JS
3867 e->assert_no_components("dwarf", true);
3868
c69a87e0
FCE
3869 visit_target_symbol_context(e);
3870 return;
3871 }
70208613 3872
04c8e51b
JL
3873 // Everything else (pretty-printed vars, and context vars) require a
3874 // scope_die in which to search for them. If we don't have that, just
3875 // leave it unresolved; we'll produce an error later on.
3876 if (null_die(scope_die))
3877 {
3878 provide(e);
3879 return;
3880 }
3881
5f36109e
JS
3882 if (!e->components.empty() &&
3883 e->components.back().type == target_symbol::comp_pretty_print)
3884 {
3885 if (lvalue)
dc09353a 3886 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3887
277c21bc 3888 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3889 {
3890 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3891 q.has_process, *e);
3892 dpp.expand()->visit(this);
3893 }
3894 else
3895 {
3896 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3897 e->sym_name(),
5f36109e
JS
3898 q.has_process, *e);
3899 dpp.expand()->visit(this);
3900 }
3901 return;
3902 }
3903
1c0be8c7 3904 bool userspace_p = q.has_process;
c69a87e0 3905 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3906 + "_" + e->sym_name()
c69a87e0 3907 + "_" + lex_cast(tick++));
70208613 3908
70208613 3909
1c0be8c7
JS
3910 exp_type type = pe_long;
3911 string code;
277c21bc 3912 if (q.has_return && (e->name == "$return"))
1c0be8c7 3913 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 3914 else
1c0be8c7
JS
3915 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
3916 e, lvalue, type);
70208613 3917
1c0be8c7
JS
3918 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
3919 userspace_p, lvalue, e);
70208613 3920
c69a87e0
FCE
3921 if (lvalue)
3922 {
3923 // Provide the functioncall to our parent, so that it can be
3924 // used to substitute for the assignment node immediately above
3925 // us.
3926 assert(!target_symbol_setter_functioncalls.empty());
3927 *(target_symbol_setter_functioncalls.top()) = n;
3928 }
70208613 3929
1c0be8c7
JS
3930 // Revisit the functioncall so arguments can be expanded.
3931 n->visit (this);
66d284f4
FCE
3932 }
3933 catch (const semantic_error& er)
3934 {
9fab2262
JS
3935 // We suppress this error message, and pass the unresolved
3936 // target_symbol to the next pass. We hope that this value ends
3937 // up not being referenced after all, so it can be optimized out
3938 // quietly.
1af1e62d 3939 e->chain (er);
9fab2262 3940 provide (e);
66d284f4 3941 }
77de5e9e
GH
3942}
3943
3944
c24447be
JS
3945void
3946dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3947{
3948 // Fill in our current module context if needed
3949 if (e->module.empty())
3950 e->module = q.dw.module_name;
3951
3952 var_expanding_visitor::visit_cast_op(e);
3953}
3954
3955
8cc799a5
JS
3956void
3957dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3958{
3959 expression *repl = e;
3960 if (q.has_return)
3961 {
3962 // expand the operand as if it weren't a return probe
3963 q.has_return = false;
3964 replace (e->operand);
3965 q.has_return = true;
3966
3967 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3968 // but it requires knowing the types already, which is problematic for
3969 // arbitrary expressons.
cc9001af 3970 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3971 }
3972 provide (repl);
3973}
3974
3689db05
SC
3975void
3976dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
3977{
ace7c23f 3978 string e_lit_val = e->operand->value;
b78a0fbb 3979
3689db05 3980 add_block = new block;
9eaaceaa 3981 add_block->tok = e->tok;
3689db05
SC
3982
3983 systemtap_session &s = this->q.sess;
3984 map<string, pair<string,derived_probe*> >::iterator it;
3985 // Find the associated perf.counter probe
3986 for (it=s.perf_counters.begin();
3987 it != s.perf_counters.end();
3988 it++)
3989 if ((*it).first == e_lit_val)
3990 {
3991 // if perf .function("name") omitted, then set it to this process name
3992 if ((*it).second.first.length() == 0)
3993 ((*it).second).first = this->q.user_path;
3994 if (((*it).second).first == this->q.user_path)
3995 break;
3996 }
3997
3998 if (it != s.perf_counters.end())
3999 {
698de6cc 4000 perf_counter_refs.insert((*it).second.second);
3689db05
SC
4001 // __perf_read_N is assigned in the probe prologue
4002 symbol* sym = new symbol;
4653caf1 4003 sym->tok = e->tok;
3689db05
SC
4004 sym->name = "__perf_read_" + (*it).first;
4005 provide (sym);
4006 }
4007 else
dc09353a 4008 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
4009}
4010
8cc799a5 4011
729455a7
JS
4012vector<Dwarf_Die>&
4013dwarf_var_expanding_visitor::getscopes(target_symbol *e)
4014{
4015 if (scopes.empty())
4016 {
04c8e51b 4017 if(!null_die(scope_die))
f25a9197 4018 scopes = q.dw.getscopes(scope_die);
729455a7 4019 if (scopes.empty())
b530b5b3
LB
4020 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
4021 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 4022 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7 4023 + lex_cast_hex(addr)
04c8e51b 4024 + (null_die(scope_die) ? ""
729455a7
JS
4025 : (string (" in ")
4026 + (dwarf_diename(scope_die) ?: "<unknown>")
4027 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
4028 + ")"))
4029 + " while searching for local '"
cc9001af 4030 + e->sym_name() + "'",
729455a7
JS
4031 e->tok);
4032 }
4033 return scopes;
4034}
4035
4036
5f36109e
JS
4037struct dwarf_cast_expanding_visitor: public var_expanding_visitor
4038{
4039 systemtap_session& s;
4040 dwarf_builder& db;
4041
4042 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4043 s(s), db(db) {}
4044 void visit_cast_op (cast_op* e);
4045 void filter_special_modules(string& module);
4046};
4047
4048
c4ce66a1
JS
4049struct dwarf_cast_query : public base_query
4050{
946e1a48 4051 cast_op& e;
c4ce66a1 4052 const bool lvalue;
5f36109e
JS
4053 const bool userspace_p;
4054 functioncall*& result;
c4ce66a1 4055
5f36109e
JS
4056 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
4057 const bool userspace_p, functioncall*& result):
abb41d92 4058 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 4059 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
4060
4061 void handle_query_module();
822a6a3d 4062 void query_library (const char *) {}
576eaefe 4063 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
4064};
4065
4066
c4ce66a1
JS
4067void
4068dwarf_cast_query::handle_query_module()
4069{
5f36109e
JS
4070 static unsigned tick = 0;
4071
4072 if (result)
c4ce66a1
JS
4073 return;
4074
ea1e477a 4075 // look for the type in any CU
a44a7cb5
JS
4076 Dwarf_Die* type_die = NULL;
4077 if (startswith(e.type_name, "class "))
4078 {
4079 // normalize to match dwflpp::global_alias_caching_callback
4080 string struct_name = "struct " + e.type_name.substr(6);
4081 type_die = dw.declaration_resolve_other_cus(struct_name);
4082 }
4083 else
4084 type_die = dw.declaration_resolve_other_cus(e.type_name);
4085
4086 // NB: We now index the types as "struct name"/"union name"/etc. instead of
4087 // just "name". But since we didn't require users to be explicit before, and
4088 // actually sort of discouraged it, we must be flexible now. So if a lookup
4089 // fails with a bare name, try augmenting it.
4090 if (!type_die &&
4091 !startswith(e.type_name, "class ") &&
4092 !startswith(e.type_name, "struct ") &&
4093 !startswith(e.type_name, "union ") &&
4094 !startswith(e.type_name, "enum "))
4095 {
4096 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
4097 if (!type_die)
4098 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
4099 if (!type_die)
4100 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
4101 }
4102
ea1e477a
JS
4103 if (!type_die)
4104 return;
c4ce66a1 4105
5f36109e
JS
4106 string code;
4107 exp_type type = pe_long;
4108
ea1e477a 4109 try
c4ce66a1 4110 {
ea1e477a
JS
4111 Dwarf_Die cu_mem;
4112 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4113
4114 if (!e.components.empty() &&
4115 e.components.back().type == target_symbol::comp_pretty_print)
4116 {
4117 if (lvalue)
dc09353a 4118 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4119
d19a9a82 4120 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4121 result = dpp.expand();
4122 return;
4123 }
4124
4125 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4126 }
4127 catch (const semantic_error& er)
4128 {
4129 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4130 // may be attempted using several different modules:
4131 // @cast(ptr, "type", "module1:module2:...")
4132 e.chain (er);
c4ce66a1 4133 }
c4ce66a1 4134
5f36109e
JS
4135 if (code.empty())
4136 return;
c4ce66a1 4137
5f36109e 4138 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4139 + "_" + e.sym_name()
5f36109e 4140 + "_" + lex_cast(tick++));
c4ce66a1 4141
1c0be8c7
JS
4142 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4143 userspace_p, lvalue, &e, e.operand);
5f36109e 4144}
c4ce66a1
JS
4145
4146
fb0274bc
JS
4147void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4148{
d90053e7 4149 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4150 // for those cases, build a module including that header
d90053e7 4151 if (module[module.size() - 1] == '>' &&
60d98537 4152 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4153 {
4154 string cached_module;
4155 if (s.use_cache)
4156 {
4157 // see if the cached module exists
a2639cb7 4158 cached_module = find_typequery_hash(s, module);
d105f664 4159 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4160 {
4161 int fd = open(cached_module.c_str(), O_RDONLY);
4162 if (fd != -1)
4163 {
4164 if (s.verbose > 2)
b530b5b3
LB
4165 //TRANSLATORS: Here we're using a cached module.
4166 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4167 module = cached_module;
4168 close(fd);
4169 return;
4170 }
4171 }
4172 }
4173
4174 // no cached module, time to make it
d90053e7 4175 if (make_typequery(s, module) == 0)
fb0274bc 4176 {
e16dc041 4177 // try to save typequery in the cache
fb0274bc 4178 if (s.use_cache)
e16dc041 4179 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4180 }
4181 }
4182}
4183
4184
c4ce66a1
JS
4185void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4186{
4187 bool lvalue = is_active_lvalue(e);
4188 if (lvalue && !s.guru_mode)
dc09353a 4189 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4190
4191 if (e->module.empty())
4192 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4193
5f36109e 4194 functioncall* result = NULL;
8b31197b
JS
4195
4196 // split the module string by ':' for alternatives
4197 vector<string> modules;
4198 tokenize(e->module, modules, ":");
b5a0dd41 4199 bool userspace_p=false; // PR10601
5f36109e 4200 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4201 {
8b31197b 4202 string& module = modules[i];
fb0274bc 4203 filter_special_modules(module);
abb41d92 4204
c4ce66a1
JS
4205 // NB: This uses '/' to distinguish between kernel modules and userspace,
4206 // which means that userspace modules won't get any PATH searching.
4207 dwflpp* dw;
707bf35e
JS
4208 try
4209 {
b5a0dd41
FCE
4210 userspace_p=is_user_module (module);
4211 if (! userspace_p)
707bf35e
JS
4212 {
4213 // kernel or kernel module target
ae2552da 4214 dw = db.get_kern_dw(s, module);
707bf35e
JS
4215 }
4216 else
4217 {
05fb3e0c 4218 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4219 dw = db.get_user_dw(s, module);
4220 }
4221 }
4222 catch (const semantic_error& er)
4223 {
4224 /* ignore and go to the next module */
4225 continue;
4226 }
c4ce66a1 4227
5f36109e 4228 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
06de3a04 4229 dw->iterate_over_modules<base_query>(&query_module, &q);
c4ce66a1 4230 }
abb41d92 4231
5f36109e 4232 if (!result)
c4ce66a1 4233 {
946e1a48
JS
4234 // We pass the unresolved cast_op to the next pass, and hope
4235 // that this value ends up not being referenced after all, so
4236 // it can be optimized out quietly.
c4ce66a1
JS
4237 provide (e);
4238 return;
4239 }
4240
c4ce66a1
JS
4241 if (lvalue)
4242 {
4243 // Provide the functioncall to our parent, so that it can be
4244 // used to substitute for the assignment node immediately above
4245 // us.
4246 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4247 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4248 }
4249
5f36109e 4250 result->visit (this);
77de5e9e
GH
4251}
4252
4253
bd1fcbad
YZ
4254struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4255{
4256 systemtap_session& s;
4257 dwarf_builder& db;
4258
4259 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4260 s(s), db(db) {}
4261 void visit_atvar_op (atvar_op* e);
4262};
4263
4264
4265struct dwarf_atvar_query: public base_query
4266{
4267 atvar_op& e;
4268 const bool userspace_p, lvalue;
4269 functioncall*& result;
4270 unsigned& tick;
4271 const string cu_name_pattern;
4272
4273 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4274 const bool userspace_p, const bool lvalue,
4275 functioncall*& result,
4276 unsigned& tick):
4277 base_query(dw, module), e(e),
4278 userspace_p(userspace_p), lvalue(lvalue), result(result),
4279 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4280
4281 void handle_query_module ();
4282 void query_library (const char *) {}
4283 void query_plt (const char *entry, size_t addr) {}
5c378838 4284 static int atvar_query_cu (Dwarf_Die *cudie, dwarf_atvar_query *q);
bd1fcbad
YZ
4285};
4286
4287
4288int
5c378838 4289dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, dwarf_atvar_query *q)
bd1fcbad 4290{
bd1fcbad
YZ
4291 if (! q->e.cu_name.empty())
4292 {
c60517ca 4293 const char *die_name = dwarf_diename(cudie) ?: "";
bd1fcbad
YZ
4294 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4295 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4296 {
4297 return DWARF_CB_OK;
4298 }
4299 }
4300
4301 try
4302 {
4303 vector<Dwarf_Die> scopes(1, *cudie);
4304
4305 q->dw.focus_on_cu (cudie);
4306
4307 if (! q->e.components.empty() &&
4308 q->e.components.back().type == target_symbol::comp_pretty_print)
4309 {
4310 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4311 q->userspace_p, q->e);
4312 q->result = dpp.expand();
4313 return DWARF_CB_ABORT;
4314 }
4315
4316 exp_type type = pe_long;
4317 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4318 &q->e, q->lvalue, type);
4319
4320 if (code.empty())
4321 return DWARF_CB_OK;
4322
4323 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4324 : "_dwarf_tvar_get")
4325 + "_" + q->e.sym_name()
4326 + "_" + lex_cast(q->tick++));
4327
4328 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4329 q->userspace_p, q->lvalue,
4330 &q->e);
4331 }
4332 catch (const semantic_error& er)
4333 {
4334 // Here we suppress the error because we often just have too many
4335 // when scanning all the CUs.
4336 return DWARF_CB_OK;
4337 }
4338
4339 if (q->result) {
4340 return DWARF_CB_ABORT;
4341 }
4342
4343 return DWARF_CB_OK;
4344}
4345
4346
4347void
4348dwarf_atvar_query::handle_query_module ()
4349{
4350
4351 dw.iterate_over_cus(atvar_query_cu, this, false);
4352}
4353
4354
4355void
4356dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4357{
4358 const bool lvalue = is_active_lvalue(e);
4359 if (lvalue && !s.guru_mode)
dc09353a 4360 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4361 "need stap -g"), e->tok);
4362
4363 if (e->module.empty())
4364 e->module = "kernel";
4365
4366 functioncall* result = NULL;
4367
4368 // split the module string by ':' for alternatives
4369 vector<string> modules;
4370 tokenize(e->module, modules, ":");
4371 bool userspace_p = false;
4372 for (unsigned i = 0; !result && i < modules.size(); ++i)
4373 {
4374 string& module = modules[i];
4375
4376 dwflpp* dw;
4377 try
4378 {
4379 userspace_p = is_user_module(module);
4380 if (!userspace_p)
4381 {
4382 // kernel or kernel module target
4383 dw = db.get_kern_dw(s, module);
4384 }
4385 else
4386 {
4387 module = find_executable(module, "", s.sysenv);
4388 dw = db.get_user_dw(s, module);
4389 }
4390 }
4391 catch (const semantic_error& er)
4392 {
4393 /* ignore and go to the next module */
4394 continue;
4395 }
4396
4397 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
06de3a04 4398 dw->iterate_over_modules<base_query>(&query_module, &q);
bd1fcbad
YZ
4399
4400 if (result)
4401 {
4402 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4403
4404 if (lvalue)
4405 {
4406 // Provide the functioncall to our parent, so that it can be
4407 // used to substitute for the assignment node immediately above
4408 // us.
4409 assert(!target_symbol_setter_functioncalls.empty());
4410 *(target_symbol_setter_functioncalls.top()) = result;
4411 }
4412
4413 result->visit(this);
4414 return;
4415 }
4416
4417 /* Unable to find the variable in the current module, so we chain
4418 * an error in atvar_op */
dc09353a 4419 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4420 e->sym_name().c_str(), module.c_str(),
4421 e->cu_name.empty() ? "" : _(", in "),
4422 e->cu_name.c_str()));
4423 e->chain (er);
4424 }
4425
4426 provide(e);
4427}
4428
4429
b8da0ad1
FCE
4430void
4431dwarf_derived_probe::printsig (ostream& o) const
4432{
4433 // Instead of just printing the plain locations, we add a PC value
4434 // as a comment as a way of telling e.g. apart multiple inlined
4435 // function instances. This is distinct from the verbose/clog
4436 // output, since this part goes into the cache hash calculations.
4437 sole_location()->print (o);
6d0f3f0c 4438 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4439 printsig_nested (o);
4440}
4441
4442
4443
dc38c0ae 4444void
b20febf3
FCE
4445dwarf_derived_probe::join_group (systemtap_session& s)
4446{
af234c40
JS
4447 // skip probes which are paired entry-handlers
4448 if (!has_return && (saved_longs || saved_strings))
4449 return;
4450
b20febf3
FCE
4451 if (! s.dwarf_derived_probes)
4452 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4453 s.dwarf_derived_probes->enroll (this);
4454}
4455
4456
2b69faaf
JS
4457static bool
4458kernel_supports_inode_uprobes(systemtap_session& s)
4459{
4460 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4461 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4462 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4463 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4464 && s.kernel_config["CONFIG_UPROBES"] == "y");
4465}
4466
4467
3667d615
JS
4468static bool
4469kernel_supports_inode_uretprobes(systemtap_session& s)
4470{
766013af
JS
4471 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4472 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4473 return kernel_supports_inode_uprobes(s) &&
af9e147f 4474 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4475}
4476
4477
5261f7ab
DS
4478void
4479check_process_probe_kernel_support(systemtap_session& s)
4480{
4481 // If we've got utrace, we're good to go.
4482 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4483 return;
4484
8c021542
DS
4485 // We don't have utrace. For process probes that aren't
4486 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4487 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4488 // specific autoconf test for its needs.
8c021542
DS
4489 //
4490 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4491 // approximation.
4492 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4493 return;
4494
d3e959b0
DS
4495 // For uprobes-based process probes, we need the task_finder plus
4496 // the builtin inode-uprobes.
8c021542
DS
4497 if (s.need_uprobes
4498 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4499 && kernel_supports_inode_uprobes(s))
8c021542
DS
4500 return;
4501
dc09353a 4502 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4503}
4504
4505
b20febf3
FCE
4506dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4507 const string& filename,
4508 int line,
91af0778 4509 // module & section specify a relocation
b20febf3
FCE
4510 // base for <addr>, unless section==""
4511 // (equivalently module=="kernel")
4512 const string& module,
4513 const string& section,
4514 // NB: dwfl_addr is the virtualized
4515 // address for this symbol.
4516 Dwarf_Addr dwfl_addr,
4517 // addr is the section-offset for
4518 // actual relocation.
4519 Dwarf_Addr addr,
4520 dwarf_query& q,
37ebca01 4521 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4522 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4523 module (module), section (section), addr (addr),
63b4fd14 4524 path (q.path),
27dc09b1 4525 has_process (q.has_process),
c9bad430
DS
4526 has_return (q.has_return),
4527 has_maxactive (q.has_maxactive),
c57ea854 4528 has_library (q.has_library),
6b66b9f7 4529 maxactive_val (q.maxactive_val),
b642c901
SC
4530 user_path (q.user_path),
4531 user_lib (q.user_lib),
af234c40 4532 access_vars(false),
c57ea854 4533 saved_longs(0), saved_strings(0),
af234c40 4534 entry_handler(0)
bd2b1e68 4535{
b642c901
SC
4536 if (user_lib.size() != 0)
4537 has_library = true;
4538
6b66b9f7
JS
4539 if (q.has_process)
4540 {
4541 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4542 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4543 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4544 // by the incoming section value (".absolute" vs. ".dynamic").
4545 // XXX Assert invariants here too?
2b69faaf
JS
4546
4547 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4548 // ditto for userspace runtimes (dyninst)
ac3af990 4549 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4550 section == ".absolute" && addr == dwfl_addr &&
4551 addr >= q.dw.module_start && addr < q.dw.module_end)
4552 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4553 }
4554 else
4555 {
4556 // Assert kernel relocation invariants
4557 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4558 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4559 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4560 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4561 }
2930abc7 4562
21beacc9
FCE
4563 // XXX: hack for strange g++/gcc's
4564#ifndef USHRT_MAX
4565#define USHRT_MAX 32767
4566#endif
4567
606fd9c8 4568 // Range limit maxactive() value
6b66b9f7 4569 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4570 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4571 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4572
a7696882
JL
4573 // Expand target variables in the probe body. Even if the scope_die is
4574 // invalid, we still want to expand things such as $$vars/$$parms/etc...
4575 // (PR15999, PR16473). Access to specific context vars e.g. $argc will not be
4576 // expanded and will produce an error during the typeresolution_info pass.
8fc05e57 4577 {
6b66b9f7 4578 // XXX: user-space deref's for q.has_process!
5a617dc6
JL
4579
4580 // PR14436: if we're expanding target variables in the probe body of a
4581 // .return probe, we need to make the expansion at the postprologue addr
4582 // instead (if any), which is then also the spot where the entry handler
4583 // probe is placed. (Note that at this point, a nonzero prologue_end
4584 // implies that it should be used, i.e. code is unoptimized).
4585 Dwarf_Addr handler_dwfl_addr = dwfl_addr;
4586 if (q.prologue_end != 0 && q.has_return)
4587 {
4588 handler_dwfl_addr = q.prologue_end;
4589 if (q.sess.verbose > 2)
4590 clog << _F("expanding .return vars at prologue_end (0x%s) "
4591 "rather than entrypc (0x%s)\n",
4592 lex_cast_hex(handler_dwfl_addr).c_str(),
4593 lex_cast_hex(dwfl_addr).c_str());
4594 }
4595 dwarf_var_expanding_visitor v (q, scope_die, handler_dwfl_addr);
8b095b45 4596 v.replace (this->body);
3689db05
SC
4597
4598 // Propagate perf.counters so we can emit later
4599 this->perf_counter_refs = v.perf_counter_refs;
4600 // Emit local var used to save the perf counter read value
698de6cc 4601 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4602 for (pcii = v.perf_counter_refs.begin();
4603 pcii != v.perf_counter_refs.end(); pcii++)
4604 {
4605 map<string, pair<string,derived_probe*> >::iterator it;
4606 // Find the associated perf counter probe
4607 for (it=q.sess.perf_counters.begin() ;
4608 it != q.sess.perf_counters.end();
4609 it++)
4610 if ((*it).second.second == (*pcii))
4611 break;
4612 vardecl* vd = new vardecl;
4613 vd->name = "__perf_read_" + (*it).first;
4614 vd->tok = this->tok;
4615 vd->set_arity(0, this->tok);
4616 vd->type = pe_long;
4617 vd->synthetic = true;
4618 this->locals.push_back (vd);
4619 }
4620
4621
6b66b9f7
JS
4622 if (!q.has_process)
4623 access_vars = v.visited;
37ebca01
FCE
4624
4625 // If during target-variable-expanding the probe, we added a new block
4626 // of code, add it to the start of the probe.
4627 if (v.add_block)
ba6f838d 4628 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4629
4630 // If when target-variable-expanding the probe, we need to synthesize a
4631 // sibling function-entry probe. We don't go through the whole probe derivation
4632 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4633 // dwarf-induced duplication.
4634 if (v.add_call_probe)
37ebca01 4635 {
2260f4e3
FCE
4636 assert (q.has_return && !q.has_call);
4637
4638 // We temporarily replace q.base_probe.
4639 statement* old_body = q.base_probe->body;
4640 q.base_probe->body = v.add_call_probe;
4641 q.has_return = false;
4642 q.has_call = true;
af234c40 4643
da23eceb 4644 if (q.has_process)
5a617dc6
JL
4645 {
4646 // Place handler probe at the same addr as where the vars were
4647 // expanded (which may not be the same addr as the one for the
4648 // main retprobe, PR14436).
4649 Dwarf_Addr handler_addr = addr;
4650 if (handler_dwfl_addr != dwfl_addr)
4651 // adjust section offset by prologue_end-entrypc
4652 handler_addr += handler_dwfl_addr - dwfl_addr;
4653 entry_handler = new uprobe_derived_probe (funcname, filename,
4654 line, module, section,
4655 handler_dwfl_addr,
4656 handler_addr, q,
4657 scope_die);
4658 }
da23eceb 4659 else
af234c40
JS
4660 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4661 module, section, dwfl_addr,
4662 addr, q, scope_die);
4663
4664 saved_longs = entry_handler->saved_longs = v.saved_longs;
4665 saved_strings = entry_handler->saved_strings = v.saved_strings;
4666
4667 q.results.push_back (entry_handler);
2260f4e3
FCE
4668
4669 q.has_return = true;
4670 q.has_call = false;
4671 q.base_probe->body = old_body;
37ebca01 4672 }
a7696882
JL
4673 // Save the local variables for listing mode. If the scope_die is null,
4674 // local vars aren't accessible, so no need to invoke saveargs (PR10820).
bba368c5
JL
4675 if (!null_die(scope_die) &&
4676 q.sess.dump_mode == systemtap_session::dump_matched_probes_vars)
4677 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4678 }
0a98fd42 4679
5d23847d 4680 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4681 // "reverse-engineered" form of the incoming (q.base_loc) probe
4682 // point. This allows a user to see what function / file / line
4683 // number any particular match of the wildcards.
919debfc
JL
4684
4685 vector<probe_point::component*> comps;
4686 if (q.has_kernel)
4687 comps.push_back (new probe_point::component(TOK_KERNEL));
4688 else if(q.has_module)
4689 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4690 else if(q.has_process)
4691 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4692 else
4693 assert (0);
4694
4695 string fn_or_stmt;
4696 if (q.has_function_str || q.has_function_num)
e772a6e7 4697 fn_or_stmt = TOK_FUNCTION;
919debfc 4698 else
e772a6e7 4699 fn_or_stmt = TOK_STATEMENT;
919debfc
JL
4700
4701 if (q.has_function_str || q.has_statement_str)
4702 {
e772a6e7 4703 string retro_name = q.final_function_name(funcname, filename, line);
919debfc
JL
4704 comps.push_back
4705 (new probe_point::component
4706 (fn_or_stmt, new literal_string (retro_name)));
4707 }
4708 else if (q.has_function_num || q.has_statement_num)
4709 {
4710 Dwarf_Addr retro_addr;
4711 if (q.has_function_num)
4712 retro_addr = q.function_num_val;
4713 else
4714 retro_addr = q.statement_num_val;
4715 comps.push_back (new probe_point::component
4716 (fn_or_stmt,
4717 new literal_number(retro_addr, true)));
4718
4719 if (q.has_absolute)
4720 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
4721 }
4722
4723 if (q.has_call)
4724 comps.push_back (new probe_point::component(TOK_CALL));
4725 if (q.has_exported)
4726 comps.push_back (new probe_point::component(TOK_EXPORTED));
4727 if (q.has_inline)
4728 comps.push_back (new probe_point::component(TOK_INLINE));
4729 if (has_return)
4730 comps.push_back (new probe_point::component(TOK_RETURN));
4731 if (has_maxactive)
4732 comps.push_back (new probe_point::component
4733 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
4734
4735 // Overwrite it.
4736 this->sole_location()->components = comps;
e2941743
JL
4737
4738 // if it's a .callee[s[(N)]] call, add checks to the probe body so that the
4739 // user body is only 'triggered' when called from q.callers[N-1], which
4740 // itself is called from q.callers[N-2], etc... I.E.
4741 // callees(N) --> N elements in q.callers --> N checks against [u]stack(0..N-1)
4742 if ((q.has_callee || q.has_callees_num) && q.callers && !q.callers->empty())
4743 {
4744 if (q.sess.verbose > 2)
7761da8b 4745 clog << _F("adding caller checks for callee %s\n", funcname.c_str());
e2941743
JL
4746
4747 // Copy the stack and empty it out
4748 stack<Dwarf_Addr> callers(*q.callers);
4749 for (unsigned level = 1; !callers.empty(); level++,
4750 callers.pop())
4751 {
4752 Dwarf_Addr caller = callers.top();
4753
4754 // We first need to make the caller addr relocatable
4755 string caller_section;
4756 Dwarf_Addr caller_reloc;
4757 if (module == TOK_KERNEL)
4758 { // allow for relocatable kernel (see also add_probe_point())
4759 caller_reloc = caller - q.sess.sym_stext;
4760 caller_section = "_stext";
4761 }
4762 else
4763 caller_reloc = q.dw.relocate_address(caller,
4764 caller_section);
4765
4766 if (q.sess.verbose > 2)
7761da8b
JL
4767 clog << _F("adding caller check [u]stack(%d) == reloc(0x%s)\n",
4768 level, lex_cast_hex(caller_reloc).c_str());
e2941743
JL
4769
4770 // We want to add a statement like this:
6211aed9 4771 // if (!_caller_match(user, mod, sec, addr)) next;
e2941743
JL
4772 // Something similar is done in semantic_pass_conditions()
4773
4774 functioncall* check = new functioncall();
4775 check->tok = this->tok;
6211aed9 4776 check->function = "_caller_match";
e2941743
JL
4777 check->args.push_back(new literal_number(q.has_process));
4778 check->args[0]->tok = this->tok;
4779 check->args.push_back(new literal_number(level));
4780 check->args[1]->tok = this->tok;
4781 check->args.push_back(new literal_string(module));
4782 check->args[2]->tok = this->tok;
4783 check->args.push_back(new literal_string(caller_section));
4784 check->args[3]->tok = this->tok;
4785 check->args.push_back(new literal_number(caller_reloc, true /* hex */));
4786 check->args[4]->tok = this->tok;
4787
4788 unary_expression* notexp = new unary_expression();
4789 notexp->tok = this->tok;
4790 notexp->op = "!";
4791 notexp->operand = check;
4792
4793 if_statement* ifs = new if_statement();
4794 ifs->tok = this->tok;
4795 ifs->thenblock = new next_statement();
4796 ifs->thenblock->tok = this->tok;
4797 ifs->elseblock = NULL;
4798 ifs->condition = notexp;
4799
4800 this->body = new block(ifs, this->body);
4801 }
4802 }
2930abc7
FCE
4803}
4804
bd2b1e68 4805
0a98fd42 4806void
8c67c337
JS
4807dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4808 Dwarf_Addr dwfl_addr)
0a98fd42 4809{
9aa8ffce 4810 if (null_die(scope_die))
0a98fd42 4811 return;
0a98fd42 4812
8c67c337 4813 bool verbose = q.sess.verbose > 2;
0a98fd42 4814
8c67c337 4815 if (verbose)
b530b5b3 4816 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4817
8c67c337
JS
4818 if (has_return)
4819 {
4820 /* Only save the return value if it has a type. */
4821 string type_name;
4822 Dwarf_Die type_die;
4823 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4824 dwarf_type_name(&type_die, type_name))
4825 args.push_back("$return:"+type_name);
4826
4827 else if (verbose)
b530b5b3
LB
4828 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4829 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4830 }
d87623a1 4831
0a98fd42 4832 Dwarf_Die arg;
4ef35696
JS
4833 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4834 for (unsigned i = 0; i < scopes.size(); ++i)
4835 {
4836 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4837 break; // we don't want file-level variables
4838 if (dwarf_child (&scopes[i], &arg) == 0)
4839 do
0a98fd42 4840 {
4ef35696
JS
4841 switch (dwarf_tag (&arg))
4842 {
4843 case DW_TAG_variable:
4844 case DW_TAG_formal_parameter:
4845 break;
0a98fd42 4846
4ef35696
JS
4847 default:
4848 continue;
4849 }
0a98fd42 4850
4ef35696
JS
4851 /* Ignore this local if it has no name. */
4852 const char *arg_name = dwarf_diename (&arg);
4853 if (!arg_name)
8c67c337
JS
4854 {
4855 if (verbose)
b530b5b3
LB
4856 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4857 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4858 continue;
4859 }
4ef35696
JS
4860
4861 if (verbose)
b530b5b3
LB
4862 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4863 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4864
4865 /* Ignore this local if it has no location (or not at this PC). */
4866 /* NB: It still may not be directly accessible, e.g. if it is an
4867 * aggregate type, implicit_pointer, etc., but the user can later
4868 * figure out how to access the interesting parts. */
45b02a36
FCE
4869
4870 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4871 * several synthetic
4872 * probe foo { $var }
4873 * probes, testing them for overall resolvability.
4874 */
4875
4ef35696
JS
4876 Dwarf_Attribute attr_mem;
4877 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4878 {
4879 Dwarf_Op *expr;
4880 size_t len;
4881 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4882 {
4883 if (verbose)
b530b5b3
LB
4884 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4885 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4886 continue;
4887 }
4888 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4889 &len, 1) == 1 && len > 0))
4890 {
45b02a36
FCE
4891 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4892 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4893 &len, 1) == 1 && len > 0))) {
4894 if (verbose)
4895 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4896 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4897 continue;
4898 }
4ef35696
JS
4899 }
4900 }
4901
4902 /* Ignore this local if it has no type. */
4903 string type_name;
4904 Dwarf_Die type_die;
4905 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4906 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4907 {
4908 if (verbose)
b530b5b3
LB
4909 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4910 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4911 continue;
4912 }
8c67c337 4913
4ef35696
JS
4914 /* This local looks good -- save it! */
4915 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4916 }
4ef35696
JS
4917 while (dwarf_siblingof (&arg, &arg) == 0);
4918 }
0a98fd42
JS
4919}
4920
4921
4922void
d0bfd2ac 4923dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4924{
d0bfd2ac 4925 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4926}
4927
4928
27dc09b1 4929void
42e38653 4930dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4931{
4932 if (has_process)
4933 {
4934 // These probes are allowed for unprivileged users, but only in the
4935 // context of processes which they own.
4936 emit_process_owner_assertion (o);
4937 return;
4938 }
4939
4940 // Other probes must contain the default assertion which aborts
4941 // if executed by an unprivileged user.
42e38653 4942 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4943}
4944
4945
4946void
4947dwarf_derived_probe::print_dupe_stamp(ostream& o)
4948{
4949 if (has_process)
4950 {
4951 // These probes are allowed for unprivileged users, but only in the
4952 // context of processes which they own.
4953 print_dupe_stamp_unprivileged_process_owner (o);
4954 return;
4955 }
4956
4957 // Other probes must contain the default dupe stamp
4958 derived_probe::print_dupe_stamp (o);
4959}
4960
64211010 4961
7a053d3b 4962void
20c6c071 4963dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4964 dwarf_builder * dw,
42e38653 4965 privilege_t privilege)
bd2b1e68 4966{
27dc09b1 4967 root
42e38653 4968 ->bind_privilege(privilege)
27dc09b1 4969 ->bind(dw);
54efe513
GH
4970}
4971
7a053d3b 4972void
fd6602a0 4973dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4974 dwarf_builder * dw,
42e38653 4975 privilege_t privilege)
2865d17a 4976{
27dc09b1 4977 root
42e38653 4978 ->bind_privilege(privilege)
27dc09b1 4979 ->bind(dw);
27dc09b1 4980 root->bind(TOK_CALL)
42e38653 4981 ->bind_privilege(privilege)
27dc09b1 4982 ->bind(dw);
4bda987e
SC
4983 root->bind(TOK_EXPORTED)
4984 ->bind_privilege(privilege)
4985 ->bind(dw);
27dc09b1 4986 root->bind(TOK_RETURN)
42e38653 4987 ->bind_privilege(privilege)
27dc09b1 4988 ->bind(dw);
1e035395 4989
f6be7c06
DB
4990 // For process probes / uprobes, .maxactive() is unused.
4991 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4992 {
4993 root->bind(TOK_RETURN)
1e035395
FCE
4994 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4995 }
bd2b1e68
GH
4996}
4997
7a053d3b 4998void
27dc09b1 4999dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 5000 systemtap_session& s,
27dc09b1
DB
5001 match_node * root,
5002 dwarf_builder * dw,
42e38653 5003 privilege_t privilege
27dc09b1 5004)
bd2b1e68
GH
5005{
5006 // Here we match 4 forms:
5007 //
5008 // .function("foo")
5009 // .function(0xdeadbeef)
5010 // .statement("foo")
5011 // .statement(0xdeadbeef)
5012
440d9b00 5013 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 5014 register_function_variants(fv_root, dw, privilege);
7f02ca94 5015 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 5016 fv_root->bind(TOK_INLINE)
42e38653 5017 ->bind_privilege(privilege)
440d9b00 5018 ->bind(dw);
7f02ca94
JS
5019 fv_root->bind_str(TOK_LABEL)
5020 ->bind_privilege(privilege)
440d9b00 5021 ->bind(dw);
c31add50
JL
5022 fv_root->bind_str(TOK_CALLEE)
5023 ->bind_privilege(privilege)
5024 ->bind(dw);
5025 fv_root->bind(TOK_CALLEES)
5026 ->bind_privilege(privilege)
5027 ->bind(dw);
5028 fv_root->bind_num(TOK_CALLEES)
5029 ->bind_privilege(privilege)
5030 ->bind(dw);
440d9b00
DB
5031
5032 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 5033 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
5034 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
5035 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
5036 {
5037 fv_root->bind(TOK_INLINE)
42e38653 5038 ->bind_privilege(privilege)
440d9b00
DB
5039 ->bind(dw);
5040 }
5041
42e38653
DB
5042 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
5043 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
5044}
5045
b1615c74
JS
5046void
5047dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
5048 match_node * root,
5049 dwarf_builder * dw)
5050{
5051 root->bind_str(TOK_MARK)
f66bb29a 5052 ->bind_privilege(pr_all)
b1615c74
JS
5053 ->bind(dw);
5054 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 5055 ->bind_privilege(pr_all)
b1615c74
JS
5056 ->bind(dw);
5057}
5058
5059void
5060dwarf_derived_probe::register_plt_variants(systemtap_session& s,
5061 match_node * root,
5062 dwarf_builder * dw)
5063{
5064 root->bind(TOK_PLT)
f66bb29a 5065 ->bind_privilege(pr_all)
b1615c74
JS
5066 ->bind(dw);
5067 root->bind_str(TOK_PLT)
f66bb29a 5068 ->bind_privilege(pr_all)
b1615c74
JS
5069 ->bind(dw);
5070 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5071 ->bind_privilege(pr_all)
b1615c74
JS
5072 ->bind(dw);
5073 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5074 ->bind_privilege(pr_all)
b1615c74 5075 ->bind(dw);
bd2b1e68
GH
5076}
5077
5078void
c4ce66a1 5079dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 5080{
c4ce66a1 5081 match_node* root = s.pattern_root;
bd2b1e68
GH
5082 dwarf_builder *dw = new dwarf_builder();
5083
c4ce66a1
JS
5084 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
5085 s.code_filters.push_back(filter);
5086
bd1fcbad
YZ
5087 filter = new dwarf_atvar_expanding_visitor(s, *dw);
5088 s.code_filters.push_back(filter);
5089
73f52eb4
DB
5090 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
5091 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
5092 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
5093 ->bind(dw);
2cab6244 5094
7f02ca94
JS
5095 match_node* uprobes[] = {
5096 root->bind(TOK_PROCESS),
5097 root->bind_str(TOK_PROCESS),
5098 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5099 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5100 };
5101 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
5102 {
f66bb29a 5103 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
5104 register_sdt_variants(s, uprobes[i], dw);
5105 register_plt_variants(s, uprobes[i], dw);
5106 }
bd2b1e68
GH
5107}
5108
9020300d 5109void
3689db05
SC
5110dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
5111{
698de6cc 5112 std::set<derived_probe*>::iterator pcii;
3689db05
SC
5113 for (pcii = perf_counter_refs.begin();
5114 pcii != perf_counter_refs.end();
5115 pcii++)
5116 {
5117 map<string, pair<string,derived_probe*> >::iterator it;
5118 // Find the associated perf.counter probe
5119 unsigned i = 0;
5120 for (it=s.perf_counters.begin() ;
5121 it != s.perf_counters.end();
5122 it++, i++)
5123 if ((*it).second.second == (*pcii))
5124 break;
5125 // place the perf counter read so it precedes stp_lock_probe
5126 o->newline() << "l->l___perf_read_" + (*it).first
5127 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
5128 + lex_cast(i) + "))));";
5129 }
b78a0fbb 5130
b95e2b79
MH
5131 if (access_vars)
5132 {
5133 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 5134 o->newline() << "#if defined __ia64__";
d9aed31e 5135 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 5136 o->newline() << "#endif";
b95e2b79 5137 }
9020300d 5138}
2930abc7 5139
b20febf3 5140// ------------------------------------------------------------------------
46b84a80
DS
5141
5142void
b20febf3 5143dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 5144{
b20febf3 5145 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
5146
5147 // XXX: probes put at the same address should all share a
5148 // single kprobe/kretprobe, and have their handlers executed
5149 // sequentially.
b55bc428
FCE
5150}
5151
7a053d3b 5152void
775d51e5 5153dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 5154{
b20febf3 5155 if (probes_by_module.empty()) return;
2930abc7 5156
775d51e5
DS
5157 s.op->newline() << "/* ---- dwarf probes ---- */";
5158
5159 // Warn of misconfigured kernels
f41595cc
FCE
5160 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
5161 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
5162 s.op->newline() << "#endif";
775d51e5 5163 s.op->newline();
f41595cc 5164
f07c3b68 5165 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 5166 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
5167 s.op->newline() << "#endif";
5168
14cf7e42 5169 // Forward decls
2ba1736a 5170 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 5171
b20febf3
FCE
5172 // Forward declare the master entry functions
5173 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5174 s.op->line() << " struct pt_regs *regs);";
5175 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5176 s.op->line() << " struct pt_regs *regs);";
5177
42cb22bd
MH
5178 // Emit an array of kprobe/kretprobe pointers
5179 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5180 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
5181 s.op->newline() << "#endif";
5182
b20febf3 5183 // Emit the actual probe list.
606fd9c8
FCE
5184
5185 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
5186 // struct stap_dwarf_probe, but it being initialized data makes it add
5187 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 5188 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
5189 // NB: bss!
5190
4c2732a1 5191 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
5192 s.op->newline(1) << "const unsigned return_p:1;";
5193 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 5194 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 5195 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 5196 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 5197
af234c40
JS
5198 // data saved in the kretprobe_instance packet
5199 s.op->newline() << "const unsigned short saved_longs;";
5200 s.op->newline() << "const unsigned short saved_strings;";
5201
faea5e16 5202 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5203 // are small and uniform enough to justify putting char[MAX]'s into
5204 // the array instead of relocated char*'s.
faea5e16
JS
5205 size_t module_name_max = 0, section_name_max = 0;
5206 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5207 size_t all_name_cnt = probes_by_module.size(); // for average
5208 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5209 {
5210 dwarf_derived_probe* p = it->second;
5211#define DOIT(var,expr) do { \
5212 size_t var##_size = (expr) + 1; \
5213 var##_max = max (var##_max, var##_size); \
5214 var##_tot += var##_size; } while (0)
5215 DOIT(module_name, p->module.size());
5216 DOIT(section_name, p->section.size());
606fd9c8
FCE
5217#undef DOIT
5218 }
5219
5220 // Decide whether it's worthwhile to use char[] or char* by comparing
5221 // the amount of average waste (max - avg) to the relocation data size
5222 // (3 native long words).
5223#define CALCIT(var) \
5224 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5225 { \
5226 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5227 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5228 << "[" << var##_name_max << "]" << endl; \
5229 } \
5230 else \
5231 { \
b0986e7a 5232 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5233 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5234 }
5235
5236 CALCIT(module);
5237 CALCIT(section);
e6fe60e7 5238#undef CALCIT
606fd9c8 5239
b0986e7a 5240 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5241 s.op->newline() << "const struct stap_probe * const probe;";
5242 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5243 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5244 s.op->indent(1);
5245
5246 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5247 {
b20febf3
FCE
5248 dwarf_derived_probe* p = it->second;
5249 s.op->newline() << "{";
5250 if (p->has_return)
5251 s.op->line() << " .return_p=1,";
c9bad430 5252 if (p->has_maxactive)
606fd9c8
FCE
5253 {
5254 s.op->line() << " .maxactive_p=1,";
5255 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5256 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5257 }
af234c40
JS
5258 if (p->saved_longs || p->saved_strings)
5259 {
5260 if (p->saved_longs)
5261 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5262 if (p->saved_strings)
5263 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5264 if (p->entry_handler)
c87ae2c1 5265 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5266 }
b350f56b
JS
5267 if (p->locations[0]->optional)
5268 s.op->line() << " .optional_p=1,";
dc38c256 5269 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5270 s.op->line() << " .module=\"" << p->module << "\",";
5271 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5272 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5273 s.op->line() << " },";
2930abc7 5274 }
2930abc7 5275
b20febf3
FCE
5276 s.op->newline(-1) << "};";
5277
5278 // Emit the kprobes callback function
5279 s.op->newline();
5280 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5281 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5282 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5283 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5284 // Check that the index is plausible
5285 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5286 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5287 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5288 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5289 s.op->line() << "];";
71db462b 5290 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5291 "stp_probe_type_kprobe");
d9aed31e 5292 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5293
5294 // Make it look like the IP is set as it wouldn't have been replaced
5295 // by a breakpoint instruction when calling real probe handler. Reset
5296 // IP regs on return, so we don't confuse kprobes. PR10458
5297 s.op->newline() << "{";
5298 s.op->indent(1);
d9aed31e 5299 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5300 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5301 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5302 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5303 s.op->newline(-1) << "}";
5304
f887a8c9 5305 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5306 s.op->newline() << "return 0;";
5307 s.op->newline(-1) << "}";
5308
5309 // Same for kretprobes
5310 s.op->newline();
af234c40
JS
5311 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5312 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5313 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5314
5315 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5316 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5317 // Check that the index is plausible
5318 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5319 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5320 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5321 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5322 s.op->line() << "];";
5323
7c3e97f4 5324 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5325 s.op->newline() << "if (sp) {";
5326 s.op->indent(1);
71db462b 5327 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5328 "stp_probe_type_kretprobe");
d9aed31e 5329 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5330
5331 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5332 s.op->newline() << "c->ips.krp.pi = inst;";
5333 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5334
5335 // Make it look like the IP is set as it wouldn't have been replaced
5336 // by a breakpoint instruction when calling real probe handler. Reset
5337 // IP regs on return, so we don't confuse kprobes. PR10458
5338 s.op->newline() << "{";
d9aed31e 5339 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5340 s.op->newline() << "if (entry)";
5341 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5342 s.op->newline(-1) << "else";
5343 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5344 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5345 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5346 s.op->newline(-1) << "}";
5347
f887a8c9 5348 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5349 s.op->newline(-1) << "}";
b20febf3
FCE
5350 s.op->newline() << "return 0;";
5351 s.op->newline(-1) << "}";
af234c40
JS
5352
5353 s.op->newline();
5354 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5355 s.op->line() << " struct pt_regs *regs) {";
5356 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5357 s.op->newline(-1) << "}";
5358
5359 s.op->newline();
5360 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5361 s.op->line() << " struct pt_regs *regs) {";
5362 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5363 s.op->newline(-1) << "}";
b642c901 5364
14cf7e42 5365 s.op->newline();
20c6c071 5366}
ec4373ff 5367
20c6c071 5368
dc38c0ae 5369void
b20febf3
FCE
5370dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5371{
5372 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5373 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5374 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5375 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5376 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5377 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5378 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5379 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5380 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5381 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5382 s.op->newline(-1) << "} else {";
f07c3b68 5383 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5384 s.op->newline(-1) << "}";
606fd9c8 5385 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5386 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5387 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5388 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5389 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5390 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5391 s.op->newline(-1) << "}";
5392 s.op->newline() << "#endif";
e4cb375f
MH
5393 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5394 s.op->newline() << "#ifdef __ia64__";
5395 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5396 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5397 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5398 s.op->newline() << "if (rc == 0) {";
5399 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5400 s.op->newline() << "if (rc != 0)";
5401 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5402 s.op->newline(-2) << "}";
5403 s.op->newline() << "#else";
606fd9c8 5404 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5405 s.op->newline() << "#endif";
b20febf3 5406 s.op->newline(-1) << "} else {";
e4cb375f 5407 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5408 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5409 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5410 s.op->newline() << "#ifdef __ia64__";
5411 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5412 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5413 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5414 s.op->newline() << "if (rc == 0) {";
5415 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5416 s.op->newline() << "if (rc != 0)";
5417 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5418 s.op->newline(-2) << "}";
5419 s.op->newline() << "#else";
606fd9c8 5420 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5421 s.op->newline() << "#endif";
b20febf3 5422 s.op->newline(-1) << "}";
9063462a
FCE
5423 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5424 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5425 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5426 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5427 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5428 // XXX: shall we increment numskipped?
5429 s.op->newline(-1) << "}";
5430
5431#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5432 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5433 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5434 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5435 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5436 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5437 s.op->newline() << "#ifdef __ia64__";
5438 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5439 s.op->newline() << "#endif";
c48cb0cc
FCE
5440 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5441 // not run for this early-abort case.
5442 s.op->newline(-1) << "}";
5443 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5444 s.op->newline(-1) << "}";
9063462a
FCE
5445#endif
5446
b20febf3
FCE
5447 s.op->newline() << "else sdp->registered_p = 1;";
5448 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5449}
5450
5451
b4be7cbc
FCE
5452void
5453dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5454{
5455 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5456 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5457 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5458 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5459 s.op->newline() << "int rc;";
5460
5461 // new module arrived?
5462 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5463 s.op->newline(1) << "if (sdp->return_p) {";
5464 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5465 s.op->newline() << "if (sdp->maxactive_p) {";
5466 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5467 s.op->newline(-1) << "} else {";
5468 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5469 s.op->newline(-1) << "}";
5470 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5471 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5472 s.op->newline() << "if (sdp->entry_probe) {";
5473 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5474 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5475 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5476 s.op->newline(-1) << "}";
5477 s.op->newline() << "#endif";
5478 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5479 s.op->newline() << "#ifdef __ia64__";
5480 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5481 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5482 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5483 s.op->newline() << "if (rc == 0) {";
5484 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5485 s.op->newline() << "if (rc != 0)";
5486 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5487 s.op->newline(-2) << "}";
5488 s.op->newline() << "#else";
5489 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5490 s.op->newline() << "#endif";
5491 s.op->newline(-1) << "} else {";
5492 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5493 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5494 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5495 s.op->newline() << "#ifdef __ia64__";
5496 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5497 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5498 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5499 s.op->newline() << "if (rc == 0) {";
5500 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5501 s.op->newline() << "if (rc != 0)";
5502 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5503 s.op->newline(-2) << "}";
5504 s.op->newline() << "#else";
5505 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5506 s.op->newline() << "#endif";
5507 s.op->newline(-1) << "}";
5508 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5509
5510 // old module disappeared?
5511 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5512 s.op->newline(1) << "if (sdp->return_p) {";
5513 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5514 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5515 s.op->newline() << "#ifdef STP_TIMING";
5516 s.op->newline() << "if (kp->u.krp.nmissed)";
5517 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5518 s.op->newline(-1) << "#endif";
065d5567 5519 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5520 s.op->newline() << "#ifdef STP_TIMING";
5521 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5522 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5523 s.op->newline(-1) << "#endif";
5524 s.op->newline(-1) << "} else {";
5525 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5526 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5527 s.op->newline() << "#ifdef STP_TIMING";
5528 s.op->newline() << "if (kp->u.kp.nmissed)";
5529 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5530 s.op->newline(-1) << "#endif";
5531 s.op->newline(-1) << "}";
5532 s.op->newline() << "#if defined(__ia64__)";
5533 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5534 s.op->newline() << "#endif";
5535 s.op->newline() << "sdp->registered_p = 0;";
5536 s.op->newline(-1) << "}";
5537
5538 s.op->newline(-1) << "}"; // for loop
5539}
5540
5541
5542
5543
46b84a80 5544void
b20febf3 5545dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5546{
42cb22bd
MH
5547 //Unregister kprobes by batch interfaces.
5548 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5549 s.op->newline() << "j = 0;";
5550 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5551 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5552 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5553 s.op->newline() << "if (! sdp->registered_p) continue;";
5554 s.op->newline() << "if (!sdp->return_p)";
5555 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5556 s.op->newline(-2) << "}";
5557 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5558 s.op->newline() << "j = 0;";
5559 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5560 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5561 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5562 s.op->newline() << "if (! sdp->registered_p) continue;";
5563 s.op->newline() << "if (sdp->return_p)";
5564 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5565 s.op->newline(-2) << "}";
5566 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5567 s.op->newline() << "#ifdef __ia64__";
5568 s.op->newline() << "j = 0;";
5569 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5570 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5571 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5572 s.op->newline() << "if (! sdp->registered_p) continue;";
5573 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5574 s.op->newline(-1) << "}";
5575 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5576 s.op->newline() << "#endif";
42cb22bd
MH
5577 s.op->newline() << "#endif";
5578
b20febf3
FCE
5579 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5580 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5581 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5582 s.op->newline() << "if (! sdp->registered_p) continue;";
5583 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5584 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5585 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5586 s.op->newline() << "#endif";
065d5567 5587 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5588 s.op->newline() << "#ifdef STP_TIMING";
5589 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5590 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5591 s.op->newline(-1) << "#endif";
065d5567 5592 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5593 s.op->newline() << "#ifdef STP_TIMING";
5594 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5595 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 5596 s.op->newline(-1) << "#endif";
557fb7a8 5597 s.op->newline(-1) << "} else {";
42cb22bd 5598 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5599 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5600 s.op->newline() << "#endif";
065d5567 5601 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5602 s.op->newline() << "#ifdef STP_TIMING";
5603 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5604 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5605 s.op->newline(-1) << "#endif";
b20febf3 5606 s.op->newline(-1) << "}";
e4cb375f
MH
5607 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5608 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5609 s.op->newline() << "#endif";
b20febf3
FCE
5610 s.op->newline() << "sdp->registered_p = 0;";
5611 s.op->newline(-1) << "}";
46b84a80
DS
5612}
5613
272c9036
WF
5614static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5615{
5616 string::size_type pos;
5617 string::size_type lastPos = str.find_first_not_of(" ", 0);
5618 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5619
5620 if (nextAt == string::npos)
5621 {
5622 // PR13934: Assembly probes are not forced to use the N@OP form.
5623 // In this case, N is inferred to be the native word size. Since we
5624 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5625 // then must not put any spaces in arguments, to avoid ambiguity.
5626 tokenize(str, tokens, " ");
5627 return;
5628 }
5629
272c9036
WF
5630 while (lastPos != string::npos)
5631 {
5632 pos = nextAt + 1;
5633 nextAt = str.find("@", pos);
5634 if (nextAt == string::npos)
5635 pos = string::npos;
5636 else
5637 pos = str.rfind(" ", nextAt);
5638
5639 tokens.push_back(str.substr(lastPos, pos - lastPos));
5640 lastPos = str.find_first_not_of(" ", pos);
5641 }
5642}
8aabf152 5643
8aabf152 5644
aff5d390 5645struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5646{
ae1418f0 5647 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5 5648 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
b8688ee6 5649 dwflpp& dw,
f83336a5
FCE
5650 int elf_machine,
5651 const string & process_name,
a794dbeb 5652 const string & provider_name,
aff5d390 5653 const string & probe_name,
71e5e13d 5654 stap_sdt_probe_type probe_type,
aff5d390 5655 const string & arg_string,
8aabf152 5656 int ac):
b8688ee6
JL
5657 session (s), dw (dw), elf_machine (elf_machine),
5658 process_name (process_name), provider_name (provider_name),
5659 probe_name (probe_name), probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5660 {
a57b7534
JL
5661 // sanity check that we're not somehow here for a kernel probe
5662 assert(is_user_module(process_name));
5663
2e6d617a 5664 build_dwarf_registers();
f83336a5 5665
ebbd2b45 5666 need_debug_info = false;
88e39987 5667 if (probe_type == uprobe3_type)
272c9036
WF
5668 {
5669 sdt_v3_tokenize(arg_string, arg_tokens);
5670 assert(arg_count <= 12);
5671 }
88e39987 5672 else
272c9036
WF
5673 {
5674 tokenize(arg_string, arg_tokens, " ");
5675 assert(arg_count <= 10);
5676 }
a8ec7719 5677 }
8aabf152 5678
f83336a5 5679 systemtap_session& session;
b8688ee6 5680 dwflpp& dw;
332ba7e7 5681 int elf_machine;
aff5d390 5682 const string & process_name;
a794dbeb 5683 const string & provider_name;
aff5d390 5684 const string & probe_name;
71e5e13d 5685 stap_sdt_probe_type probe_type;
8aabf152 5686 unsigned arg_count;
aff5d390 5687 vector<string> arg_tokens;
2e6d617a 5688
46a94997 5689 map<string, pair<unsigned,int> > dwarf_regs;
2e6d617a
JL
5690 string regnames;
5691 string percent_regnames;
5692
ebbd2b45 5693 bool need_debug_info;
aff5d390 5694
2e6d617a 5695 void build_dwarf_registers();
aff5d390 5696 void visit_target_symbol (target_symbol* e);
03c45fcb 5697 unsigned get_target_symbol_argno_and_validate (target_symbol* e);
ac074daf 5698 long parse_out_arg_precision(string& asmarg);
0fbf6fb8
JL
5699 expression* try_parse_arg_literal (target_symbol *e,
5700 const string& asmarg,
5701 long precision);
95b78bc9
JL
5702 expression* try_parse_arg_register (target_symbol *e,
5703 const string& asmarg,
5704 long precision);
8da56b62
JL
5705 expression* try_parse_arg_offset_register (target_symbol *e,
5706 const string& asmarg,
5707 long precision);
10fcca15
JL
5708 expression* try_parse_arg_effective_addr (target_symbol *e,
5709 const string& asmarg,
5710 long precision);
451c0c25
JL
5711 expression* try_parse_arg_varname (target_symbol *e,
5712 const string& asmarg,
5713 long precision);
6ef331c8
SC
5714 void visit_target_symbol_arg (target_symbol* e);
5715 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5716 void visit_atvar_op (atvar_op* e);
40a0c64e 5717 void visit_cast_op (cast_op* e);
aff5d390
SC
5718};
5719
2e6d617a
JL
5720void
5721sdt_uprobe_var_expanding_visitor::build_dwarf_registers ()
5722{
5723 /* Register name mapping table depends on the elf machine of this particular
5724 probe target process/file, not upon the host. So we can't just
5725 #ifdef _i686_ etc. */
5726
5727#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
5728 if (elf_machine == EM_X86_64) {
5729 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5730 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5731 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5732 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5733 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5734 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5735 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5736 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5737 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5738 DRI ("%sil", 4, QI);
5739 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5740 DRI ("%dil", 5, QI);
5741 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5742 DRI ("%bpl", 6, QI);
5743 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5744 DRI ("%spl", 7, QI);
5745 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5746 DRI ("%r8b", 8, QI);
5747 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5748 DRI ("%r9b", 9, QI);
5749 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5750 DRI ("%r10b", 10, QI);
5751 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5752 DRI ("%r11b", 11, QI);
5753 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5754 DRI ("%r12b", 12, QI);
5755 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5756 DRI ("%r13b", 13, QI);
5757 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5758 DRI ("%r14b", 14, QI);
5759 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5760 DRI ("%r15b", 15, QI);
5761 DRI ("%rip", 16, DI); DRI ("%eip", 16, SI); DRI ("%ip", 16, HI);
5762 } else if (elf_machine == EM_386) {
5763 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5764 DRI ("%ah", 0, QIh);
5765 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5766 DRI ("%ch", 1, QIh);
5767 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5768 DRI ("%dh", 2, QIh);
5769 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5770 DRI ("%bh", 3, QIh);
5771 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5772 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5773 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5774 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
5775 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
5776 DRI ("%r0", 0, DI);
5777 DRI ("%r1", 1, DI);
5778 DRI ("%r2", 2, DI);
5779 DRI ("%r3", 3, DI);
5780 DRI ("%r4", 4, DI);
5781 DRI ("%r5", 5, DI);
5782 DRI ("%r6", 6, DI);
5783 DRI ("%r7", 7, DI);
5784 DRI ("%r8", 8, DI);
5785 DRI ("%r9", 9, DI);
5786 DRI ("%r10", 10, DI);
5787 DRI ("%r11", 11, DI);
5788 DRI ("%r12", 12, DI);
5789 DRI ("%r13", 13, DI);
5790 DRI ("%r14", 14, DI);
5791 DRI ("%r15", 15, DI);
5792 DRI ("%r16", 16, DI);
5793 DRI ("%r17", 17, DI);
5794 DRI ("%r18", 18, DI);
5795 DRI ("%r19", 19, DI);
5796 DRI ("%r20", 20, DI);
5797 DRI ("%r21", 21, DI);
5798 DRI ("%r22", 22, DI);
5799 DRI ("%r23", 23, DI);
5800 DRI ("%r24", 24, DI);
5801 DRI ("%r25", 25, DI);
5802 DRI ("%r26", 26, DI);
5803 DRI ("%r27", 27, DI);
5804 DRI ("%r28", 28, DI);
5805 DRI ("%r29", 29, DI);
5806 DRI ("%r30", 30, DI);
5807 DRI ("%r31", 31, DI);
5808 // PR11821: unadorned register "names" without -mregnames
5809 DRI ("0", 0, DI);
5810 DRI ("1", 1, DI);
5811 DRI ("2", 2, DI);
5812 DRI ("3", 3, DI);
5813 DRI ("4", 4, DI);
5814 DRI ("5", 5, DI);
5815 DRI ("6", 6, DI);
5816 DRI ("7", 7, DI);
5817 DRI ("8", 8, DI);
5818 DRI ("9", 9, DI);
5819 DRI ("10", 10, DI);
5820 DRI ("11", 11, DI);
5821 DRI ("12", 12, DI);
5822 DRI ("13", 13, DI);
5823 DRI ("14", 14, DI);
5824 DRI ("15", 15, DI);
5825 DRI ("16", 16, DI);
5826 DRI ("17", 17, DI);
5827 DRI ("18", 18, DI);
5828 DRI ("19", 19, DI);
5829 DRI ("20", 20, DI);
5830 DRI ("21", 21, DI);
5831 DRI ("22", 22, DI);
5832 DRI ("23", 23, DI);
5833 DRI ("24", 24, DI);
5834 DRI ("25", 25, DI);
5835 DRI ("26", 26, DI);
5836 DRI ("27", 27, DI);
5837 DRI ("28", 28, DI);
5838 DRI ("29", 29, DI);
5839 DRI ("30", 30, DI);
5840 DRI ("31", 31, DI);
5841 } else if (elf_machine == EM_S390) {
5842 DRI ("%r0", 0, DI);
5843 DRI ("%r1", 1, DI);
5844 DRI ("%r2", 2, DI);
5845 DRI ("%r3", 3, DI);
5846 DRI ("%r4", 4, DI);
5847 DRI ("%r5", 5, DI);
5848 DRI ("%r6", 6, DI);
5849 DRI ("%r7", 7, DI);
5850 DRI ("%r8", 8, DI);
5851 DRI ("%r9", 9, DI);
5852 DRI ("%r10", 10, DI);
5853 DRI ("%r11", 11, DI);
5854 DRI ("%r12", 12, DI);
5855 DRI ("%r13", 13, DI);
5856 DRI ("%r14", 14, DI);
5857 DRI ("%r15", 15, DI);
5858 } else if (elf_machine == EM_ARM) {
5859 DRI ("r0", 0, SI);
5860 DRI ("r1", 1, SI);
5861 DRI ("r2", 2, SI);
5862 DRI ("r3", 3, SI);
5863 DRI ("r4", 4, SI);
5864 DRI ("r5", 5, SI);
5865 DRI ("r6", 6, SI);
5866 DRI ("r7", 7, SI);
5867 DRI ("r8", 8, SI);
5868 DRI ("r9", 9, SI);
5869 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
5870 DRI ("fp", 11, SI);
5871 DRI ("ip", 12, SI);
5872 DRI ("sp", 13, SI);
5873 DRI ("lr", 14, SI);
5874 DRI ("pc", 15, SI);
5875 } else if (elf_machine == EM_AARCH64) {
5876 DRI ("x0", 0, DI); DRI ("w0", 0, SI);
5877 DRI ("x1", 1, DI); DRI ("w1", 1, SI);
5878 DRI ("x2", 2, DI); DRI ("w2", 2, SI);
5879 DRI ("x3", 3, DI); DRI ("w3", 3, SI);
5880 DRI ("x4", 4, DI); DRI ("w4", 4, SI);
5881 DRI ("x5", 5, DI); DRI ("w5", 5, SI);
5882 DRI ("x6", 6, DI); DRI ("w6", 6, SI);
5883 DRI ("x7", 7, DI); DRI ("w7", 7, SI);
5884 DRI ("x8", 8, DI); DRI ("w8", 8, SI);
5885 DRI ("x9", 9, DI); DRI ("w9", 9, SI);
5886 DRI ("x10", 10, DI); DRI ("w10", 10, SI);
5887 DRI ("x11", 11, DI); DRI ("w11", 11, SI);
5888 DRI ("x12", 12, DI); DRI ("w12", 12, SI);
5889 DRI ("x13", 13, DI); DRI ("w13", 13, SI);
5890 DRI ("x14", 14, DI); DRI ("w14", 14, SI);
5891 DRI ("x15", 15, DI); DRI ("w15", 15, SI);
5892 DRI ("x16", 16, DI); DRI ("w16", 16, SI);
5893 DRI ("x17", 17, DI); DRI ("w17", 17, SI);
5894 DRI ("x18", 18, DI); DRI ("w18", 18, SI);
5895 DRI ("x19", 19, DI); DRI ("w19", 19, SI);
5896 DRI ("x20", 20, DI); DRI ("w20", 20, SI);
5897 DRI ("x21", 21, DI); DRI ("w21", 21, SI);
5898 DRI ("x22", 22, DI); DRI ("w22", 22, SI);
5899 DRI ("x23", 23, DI); DRI ("w23", 23, SI);
5900 DRI ("x24", 24, DI); DRI ("w24", 24, SI);
5901 DRI ("x25", 25, DI); DRI ("w25", 25, SI);
5902 DRI ("x26", 26, DI); DRI ("w26", 26, SI);
5903 DRI ("x27", 27, DI); DRI ("w27", 27, SI);
5904 DRI ("x28", 28, DI); DRI ("w28", 28, SI);
5905 DRI ("x29", 29, DI); DRI ("w29", 29, SI);
5906 DRI ("x30", 30, DI); DRI ("w30", 30, SI);
5907 DRI ("sp", 31, DI);
5908 } else if (arg_count) {
5909 /* permit this case; just fall back to dwarf */
5910 }
5911#undef DRI
5912
5913 // Build regex pieces out of the known dwarf_regs. We keep two separate
5914 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5915 // and ones with no prefix (and thus only usable in unambiguous contexts).
5916 map<string,pair<unsigned,int> >::const_iterator ri;
5917 for (ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
5918 {
5919 string regname = ri->first;
5920 assert (regname != "");
5921 regnames += string("|")+regname;
5922 if (regname[0]=='%')
5923 percent_regnames += string("|")+regname;
5924 }
5925
5926 // clip off leading |
5927 if (regnames != "")
5928 regnames = regnames.substr(1);
5929 if (percent_regnames != "")
5930 percent_regnames = percent_regnames.substr(1);
5931}
7a05f484
SC
5932
5933void
6ef331c8 5934sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5935{
6ef331c8 5936 if (e->addressof)
dc09353a 5937 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5938
5939 if (e->name == "$$name")
7a05f484 5940 {
6ef331c8
SC
5941 literal_string *myname = new literal_string (probe_name);
5942 myname->tok = e->tok;
5943 provide(myname);
5944 return;
5945 }
7a05f484 5946
6ef331c8
SC
5947 else if (e->name == "$$provider")
5948 {
5949 literal_string *myname = new literal_string (provider_name);
5950 myname->tok = e->tok;
5951 provide(myname);
5952 return;
5953 }
a794dbeb 5954
6ef331c8
SC
5955 else if (e->name == "$$vars" || e->name == "$$parms")
5956 {
5957 e->assert_no_components("sdt", true);
6ef331c8
SC
5958
5959 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
63ea4244 5960
1c922ad7 5961 print_format* pf = print_format::create(e->tok, "sprintf");
6ef331c8
SC
5962
5963 for (unsigned i = 1; i <= arg_count; ++i)
5964 {
5965 if (i > 1)
5966 pf->raw_components += " ";
5967 target_symbol *tsym = new target_symbol;
5968 tsym->tok = e->tok;
5969 tsym->name = "$arg" + lex_cast(i);
5970 pf->raw_components += tsym->name;
5971 tsym->components = e->components;
5972
8c2f50c0 5973 expression *texp = require<expression> (tsym);
6ef331c8
SC
5974 if (!e->components.empty() &&
5975 e->components[0].type == target_symbol::comp_pretty_print)
5976 pf->raw_components += "=%s";
5977 else
5978 pf->raw_components += "=%#x";
5979 pf->args.push_back(texp);
5980 }
5981
5982 pf->components = print_format::string_to_components(pf->raw_components);
5983 provide (pf);
5984 }
5985 else
5986 assert(0); // shouldn't get here
5987}
5988
03c45fcb
JL
5989unsigned
5990sdt_uprobe_var_expanding_visitor::get_target_symbol_argno_and_validate (target_symbol *e)
5991{
5992 // parsing
5993 unsigned argno = 0;
5994 if (startswith(e->name, "$arg"))
5995 {
5996 try
5997 {
5998 argno = lex_cast<unsigned>(e->name.substr(4));
5999 }
6000 catch (const runtime_error& f)
6001 {
6002 // non-integral $arg suffix: e.g. $argKKKSDF
6003 argno = 0;
6004 }
6005 }
6006
6007 // validation
6008 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
6009 argno < 1 || argno > arg_count) // a $argN with out-of-range N
6010 {
6011 // NB: Either
6012 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
6013 // 2) uprobe2_type $FOO (no probe args)
6014 // both of which get resolved later.
6015 // Throw it now, and it might be resolved by DWARF later.
6016 need_debug_info = true;
6017 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
6018 }
6019 assert (arg_tokens.size() >= argno);
6020 return argno;
6021}
6ef331c8 6022
ac074daf
JL
6023long
6024sdt_uprobe_var_expanding_visitor::parse_out_arg_precision(string& asmarg)
6025{
6026 long precision;
6027 if (asmarg.find('@') != string::npos)
6028 {
6029 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
6030 asmarg = asmarg.substr(asmarg.find('@')+1);
6031 }
6032 else
6033 {
6034 // V1/V2 do not have precision field so default to signed long
6035 // V3 asm does not have precision field so default to unsigned long
6036 if (probe_type == uprobe3_type)
6037 precision = sizeof(long); // this is an asm probe
6038 else
6039 precision = -sizeof(long);
6040 }
6041 return precision;
6042}
6043
0fbf6fb8
JL
6044expression*
6045sdt_uprobe_var_expanding_visitor::try_parse_arg_literal (target_symbol *e,
6046 const string& asmarg,
6047 long precision)
6048{
6049 expression *argexpr = NULL;
6050
6051 // Here, we test for a numeric literal.
6052 // Only accept (signed) decimals throughout. XXX
6053
6054 // PR11821. NB: on powerpc, literals are not prefixed with $,
6055 // so this regex does not match. But that's OK, since without
6056 // -mregnames, we can't tell them apart from register numbers
6057 // anyway. With -mregnames, we could, if gcc somehow
6058 // communicated to us the presence of that option, but alas it
6059 // doesn't. http://gcc.gnu.org/PR44995.
6060 vector<string> matches;
6061 if (!regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches))
6062 {
6063 string sn = matches[0].substr(1);
6064 int64_t n;
6065
6066 // We have to pay attention to the size & sign, as gcc sometimes
6067 // propagates constants that don't quite match, like a negative
6068 // value to fill an unsigned type.
6069 // NB: let it throw if something happens
6070 switch (precision)
6071 {
6072 case -1: n = lex_cast< int8_t>(sn); break;
6073 case 1: n = lex_cast< uint8_t>(sn); break;
6074 case -2: n = lex_cast< int16_t>(sn); break;
6075 case 2: n = lex_cast<uint16_t>(sn); break;
6076 case -4: n = lex_cast< int32_t>(sn); break;
6077 case 4: n = lex_cast<uint32_t>(sn); break;
6078 default:
6079 case -8: n = lex_cast< int64_t>(sn); break;
6080 case 8: n = lex_cast<uint64_t>(sn); break;
6081 }
6082
6083 literal_number* ln = new literal_number(n);
6084 ln->tok = e->tok;
6085 argexpr = ln;
6086 }
6087
6088 return argexpr;
6089}
6090
95b78bc9
JL
6091expression*
6092sdt_uprobe_var_expanding_visitor::try_parse_arg_register (target_symbol *e,
6093 const string& asmarg,
6094 long precision)
6095{
6096 expression *argexpr = NULL;
6097
6098 // test for REGISTER
6099 // NB: Because PR11821, we must use percent_regnames here.
6100 string regexp;
6101 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
6102 regexp = "^(" + regnames + ")$";
6103 else
6104 regexp = "^(" + percent_regnames + ")$";
6105
6106 vector<string> matches;
6107 if (!regexp_match(asmarg, regexp, matches))
6108 {
6109 string regname = matches[1];
6110 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
6111 if (ri != dwarf_regs.end()) // known register
6112 {
6113 embedded_expr *get_arg1 = new embedded_expr;
6114 string width_adjust;
6115 switch (ri->second.second)
6116 {
6117 case QI: width_adjust = ") & 0xff)"; break;
6118 case QIh: width_adjust = ">>8) & 0xff)"; break;
6119 case HI:
6120 // preserve 16 bit register signness
6121 width_adjust = ") & 0xffff)";
6122 if (precision < 0)
6123 width_adjust += " << 48 >> 48";
6124 break;
6125 case SI:
6126 // preserve 32 bit register signness
6127 width_adjust = ") & 0xffffffff)";
6128 if (precision < 0)
6129 width_adjust += " << 32 >> 32";
6130 break;
6131 default: width_adjust = "))";
6132 }
6133 string type = "";
6134 if (probe_type == uprobe3_type)
6135 type = (precision < 0
6136 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
6137 type = type + "((";
6138 get_arg1->tok = e->tok;
6139 get_arg1->code = string("/* unprivileged */ /* pure */")
6140 + string(" ((int64_t)") + type
a57b7534 6141 + string("u_fetch_register(")
95b78bc9
JL
6142 + lex_cast(dwarf_regs[regname].first) + string("))")
6143 + width_adjust;
6144 argexpr = get_arg1;
6145 }
6146 }
6147 return argexpr;
6148}
6149
b15f98b2
JL
6150static string
6151precision_to_function(long precision)
6152{
6153 switch (precision)
6154 {
6155 case 1: case -1:
6156 return "user_int8";
6157 case 2:
6158 return "user_uint16";
6159 case -2:
6160 return "user_int16";
6161 case 4:
6162 return "user_uint32";
6163 case -4:
6164 return "user_int32";
6165 case 8: case -8:
6166 return "user_int64";
6167 default:
6168 return "user_long";
6169 }
6170}
6171
8da56b62
JL
6172expression*
6173sdt_uprobe_var_expanding_visitor::try_parse_arg_offset_register (target_symbol *e,
6174 const string& asmarg,
6175 long precision)
6176{
6177 expression *argexpr = NULL;
6178
6179 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
6180 // NB: Despite PR11821, we can use regnames here, since the parentheses
6181 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6182 // On ARM test for [REGISTER, OFFSET]
6183
6184 string regexp;
6185 int reg, offset1;
6186 if (elf_machine == EM_ARM)
6187 {
6188 regexp = "^\\[(" + regnames + ")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$";
6189 reg = 1;
6190 offset1 = 3;
6191 }
6192 else
6193 {
6194 regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + ")[)]$";
6195 reg = 4;
6196 offset1 = 1;
6197 }
6198
6199 vector<string> matches;
6200 if (!regexp_match(asmarg, regexp, matches))
6201 {
6202 string regname;
6203 int64_t disp = 0;
6204 if (matches[reg].length())
6205 regname = matches[reg];
6206 if (dwarf_regs.find (regname) == dwarf_regs.end())
6207 throw SEMANTIC_ERROR(_F("unrecognized register '%s'", regname.c_str()));
6208
6209 for (int i=offset1; i <= (offset1 + 2); i++)
6210 if (matches[i].length())
6211 // should decode positive/negative hex/decimal
6212 // NB: let it throw if something happens
6213 disp += lex_cast<int64_t>(matches[i]);
6214
6215 // synthesize user_long(%{fetch_register(R)%} + D)
6216 embedded_expr *get_arg1 = new embedded_expr;
6217 get_arg1->tok = e->tok;
6218 get_arg1->code = string("/* unprivileged */ /* pure */")
a57b7534 6219 + string("u_fetch_register(")
8da56b62
JL
6220 + lex_cast(dwarf_regs[regname].first) + string(")");
6221 // XXX: may we ever need to cast that to a narrower type?
6222
6223 literal_number* inc = new literal_number(disp);
6224 inc->tok = e->tok;
6225
6226 binary_expression *be = new binary_expression;
6227 be->tok = e->tok;
6228 be->left = get_arg1;
6229 be->op = "+";
6230 be->right = inc;
6231
6232 functioncall *fc = new functioncall;
b15f98b2 6233 fc->function = precision_to_function(precision);
8da56b62
JL
6234 fc->tok = e->tok;
6235 fc->args.push_back(be);
6236
6237 argexpr = fc;
6238 }
6239
6240 return argexpr;
6241}
6242
10fcca15
JL
6243expression*
6244sdt_uprobe_var_expanding_visitor::try_parse_arg_effective_addr (target_symbol *e,
6245 const string& asmarg,
6246 long precision)
6247{
6248 expression *argexpr = NULL;
6249
6250 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
6251 // NB: Despite PR11821, we can use regnames here, since the parentheses
6252 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6253 string regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + "),(" +
6254 regnames + ")(,[1248])?[)]$";
6255 vector<string> matches;
6256 if (!regexp_match(asmarg, regexp, matches))
6257 {
6258 string baseregname;
6259 string indexregname;
6260 int64_t disp = 0;
6261 short scale = 1;
6262
6263 if (matches[6].length())
6264 // NB: let it throw if we can't cast
6265 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
6266
6267 if (matches[4].length())
6268 baseregname = matches[4];
6269 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6270 throw SEMANTIC_ERROR(_F("unrecognized base register '%s'", baseregname.c_str()));
6271
6272 if (matches[5].length())
6273 indexregname = matches[5];
6274 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6275 throw SEMANTIC_ERROR(_F("unrecognized index register '%s'", indexregname.c_str()));
6276
6277 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
6278 if (matches[i].length())
6279 // should decode positive/negative hex/decimal
6280 // NB: let it throw if something happens
6281 disp += lex_cast<int64_t>(matches[i]);
6282
6283 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6284
6285 embedded_expr *get_arg1 = new embedded_expr;
a57b7534 6286 string regfn = "u_fetch_register";
10fcca15
JL
6287
6288 get_arg1->tok = e->tok;
6289 get_arg1->code = string("/* unprivileged */ /* pure */")
6290 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6291 + string("+(")
6292 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6293 + string("*")
6294 + lex_cast(scale)
6295 + string(")");
6296
6297 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6298 literal_number* inc = new literal_number(disp);
6299 inc->tok = e->tok;
6300
6301 binary_expression *be = new binary_expression;
6302 be->tok = e->tok;
6303 be->left = get_arg1;
6304 be->op = "+";
6305 be->right = inc;
6306
6307 functioncall *fc = new functioncall;
b15f98b2 6308 fc->function = precision_to_function(precision);
10fcca15
JL
6309 fc->tok = e->tok;
6310 fc->args.push_back(be);
6311
6312 argexpr = fc;
6313 }
6314
6315 return argexpr;
6316}
6317
451c0c25
JL
6318expression*
6319sdt_uprobe_var_expanding_visitor::try_parse_arg_varname (target_symbol *e,
6320 const string& asmarg,
6321 long precision)
6ef331c8 6322{
b8688ee6 6323 static unsigned tick = 0;
451c0c25
JL
6324 expression *argexpr = NULL;
6325
6326 // test for [OFF+]VARNAME[+OFF][(REGISTER)], where VARNAME is a variable
6327 // name. NB: Despite PR11821, we can use regnames here, since the parentheses
6328 // make things unambiguous.
6329 string regex = "^(([0-9]+)[+])?([a-zA-Z_][a-zA-Z0-9_]*)([+][0-9]+)?([(]("
6330 + regnames + ")[)])?$";
6331 vector<string> matches;
6332 if (!regexp_match(asmarg, regex, matches))
6333 {
6334 assert(matches.size() >= 4);
6335 string varname = matches[3];
6336
6337 // OFF can be before VARNAME (put in matches[2]) or after (put in
6338 // matches[4]) (or both?). Seems like in most cases it comes after,
6339 // unless the code was compiled with -fPIC.
6340 int64_t offset = 0;
6341 if (!matches[2].empty())
6342 offset += lex_cast<int64_t>(matches[2]);
6343 if (matches.size() >= 5 && !matches[4].empty())
6344 offset += lex_cast<int64_t>(matches[4]);
6345
6346 string regname;
6347 if (matches.size() >= 7)
6348 regname = matches[6];
6349
6350 // If it's just VARNAME, then proceed. If it's VARNAME(REGISTER), then
6351 // only proceed if it's RIP-relative addressing on x86_64.
6352 if (regname.empty() || (regname == "%rip" && elf_machine == EM_X86_64))
6353 {
6354 dw.mod_info->get_symtab();
6355 if (dw.mod_info->symtab_status != info_present)
6356 throw SEMANTIC_ERROR(_("can't retrieve symbol table"));
6357
6358 assert(dw.mod_info->sym_table);
6359 map<string, Dwarf_Addr>& globals = dw.mod_info->sym_table->globals;
6360 map<string, Dwarf_Addr>& locals = dw.mod_info->sym_table->locals;
6361 Dwarf_Addr addr = 0;
6362
6363 // check symtab locals then globals
6364 if (locals.count(varname))
6365 addr = locals[varname];
6366 if (globals.count(varname))
6367 addr = globals[varname];
6368
6369 if (addr)
6370 {
6371 // add whatever offset is in the operand
6372 addr += offset;
6373
6374 // adjust for dw bias because relocate_address() expects a
6375 // libdw address and this addr is from the symtab
6376 dw.get_module_dwarf(false, false);
6377 addr -= dw.module_bias;
6378
6379 string reloc_section;
6380 Dwarf_Addr reloc_addr = dw.relocate_address(addr, reloc_section);
6381
6382 // OK, we have an address for the variable. Let's create a
6383 // function that will just relocate it at runtime, and then
6384 // call user_[u]int*() on the address it returns.
6385
6386 functioncall *user_int_call = new functioncall;
b15f98b2 6387 user_int_call->function = precision_to_function(precision);
451c0c25
JL
6388 user_int_call->tok = e->tok;
6389
6390 functiondecl *get_addr_decl = new functiondecl;
6391 get_addr_decl->tok = e->tok;
6392 get_addr_decl->synthetic = true;
6393 get_addr_decl->name = "_sdt_arg_get_addr_" + lex_cast(tick++);
6394 get_addr_decl->type = pe_long;
6395
6396 // build _stp_[ku]module_relocate(module, addr, current)
6397 stringstream ss;
6398 ss << " /* unprivileged */ /* pure */ /* pragma:vma */" << endl;
a57b7534
JL
6399 ss << "STAP_RETURN(_stp_umodule_relocate(";
6400 ss << "\"" << path_remove_sysroot(session, process_name) << "\", ";
6401 ss << "0x" << hex << reloc_addr << dec << ", ";
6402 ss << "current";
6403 ss << "));" << endl;
451c0c25
JL
6404
6405 embeddedcode *ec = new embeddedcode;
6406 ec->tok = e->tok;
6407 ec->code = ss.str();
6408 get_addr_decl->body = ec;
6409 get_addr_decl->join(session);
6410
6411 functioncall *get_addr_call = new functioncall;
6412 get_addr_call->tok = e->tok;
6413 get_addr_call->function = get_addr_decl->name;
6414 user_int_call->args.push_back(get_addr_call);
b8688ee6 6415
451c0c25
JL
6416 argexpr = user_int_call;
6417 }
6418 }
6419 }
6420
6421 return argexpr;
6422}
6423
6424void
6425sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
6426{
6ef331c8
SC
6427 try
6428 {
03c45fcb 6429 unsigned argno = get_target_symbol_argno_and_validate(e); // the N in $argN
8aabf152 6430 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 6431
8aabf152
FCE
6432 // Now we try to parse this thing, which is an assembler operand
6433 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 6434 // and hope for the best. Here is the syntax for a few architectures.
9859b766 6435 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157 6436 //
b6aaaf21
JL
6437 // literal reg reg reg+ base+index*size+ VAR VAR+off RIP-relative
6438 // indirect offset offset VAR+off
6439 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6440 // x86_64 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6441 // power iN R (R) N(R)
6442 // ia64 N rR [r16]
6443 // s390 N %rR 0(rR) N(r15)
6444 // arm #N rR [rR] [rR, #N]
b874bd52 6445
8aabf152
FCE
6446 expression* argexpr = 0; // filled in in case of successful parse
6447
ac074daf
JL
6448 // Parse (and remove from asmarg) the leading length
6449 long precision = parse_out_arg_precision(asmarg);
40fe32e0 6450
0fbf6fb8 6451 try
8aabf152 6452 {
0fbf6fb8
JL
6453 if ((argexpr = try_parse_arg_literal(e, asmarg, precision)) != NULL)
6454 goto matched;
2e6d617a
JL
6455
6456 // all other matches require registers
6457 if (regnames == "")
6458 throw SEMANTIC_ERROR("no registers to use for parsing");
95b78bc9
JL
6459
6460 if ((argexpr = try_parse_arg_register(e, asmarg, precision)) != NULL)
6461 goto matched;
8da56b62
JL
6462 if ((argexpr = try_parse_arg_offset_register(e, asmarg, precision)) != NULL)
6463 goto matched;
10fcca15
JL
6464 if ((argexpr = try_parse_arg_effective_addr(e, asmarg, precision)) != NULL)
6465 goto matched;
451c0c25
JL
6466 if ((argexpr = try_parse_arg_varname(e, asmarg, precision)) != NULL)
6467 goto matched;
0fbf6fb8
JL
6468 }
6469 catch (const semantic_error& err)
6470 {
6471 e->chain(err);
b8688ee6 6472 }
8aabf152 6473
8aabf152
FCE
6474 // The asmarg operand was not recognized. Back down to dwarf.
6475 if (! session.suppress_warnings)
84fef8ee
FCE
6476 {
6477 if (probe_type == UPROBE3_TYPE)
451c0c25
JL
6478 session.print_warning (_F("Can't parse SDT_V3 operand '%s' "
6479 "[man error::sdt]", asmarg.c_str()),
6480 e->tok);
84fef8ee 6481 else // must be *PROBE2; others don't get asm operands
451c0c25
JL
6482 session.print_warning (_F("Downgrading SDT_V2 probe argument to "
6483 "dwarf, can't parse '%s' [man error::sdt]",
6484 asmarg.c_str()),
6485 e->tok);
84fef8ee 6486 }
451c0c25 6487
8aabf152 6488 need_debug_info = true;
451c0c25
JL
6489 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo "
6490 "[man error::sdt]"), e->tok);
6491
6492 /* NOTREACHED */
366af4e7 6493
8aabf152
FCE
6494 matched:
6495 assert (argexpr != 0);
366af4e7
RM
6496
6497 if (session.verbose > 2)
1e41115c 6498 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6499 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6500
aff5d390 6501 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6502 {
6503 if (e->addressof)
dc09353a 6504 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152 6505 provide (argexpr);
8aabf152
FCE
6506 }
6507 else // $var->foo
6508 {
6509 cast_op *cast = new cast_op;
6510 cast->name = "@cast";
6511 cast->tok = e->tok;
6512 cast->operand = argexpr;
6513 cast->components = e->components;
6514 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6515 cast->module = process_name;
6516 cast->visit(this);
8aabf152 6517 }
aff5d390
SC
6518 }
6519 catch (const semantic_error &er)
6520 {
6521 e->chain (er);
6522 provide (e);
6523 }
6524}
6525
6526
6ef331c8
SC
6527void
6528sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6529{
6530 try
6531 {
49131a6d 6532 assert(e->name.size() > 0
bd1fcbad 6533 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6534
6535 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6536 visit_target_symbol_context (e);
6537 else
6538 visit_target_symbol_arg (e);
6539 }
6540 catch (const semantic_error &er)
6541 {
6542 e->chain (er);
6543 provide (e);
6544 }
6545}
6546
6547
bd1fcbad
YZ
6548void
6549sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6550{
6551 need_debug_info = true;
6552
6553 // Fill in our current module context if needed
6554 if (e->module.empty())
6555 e->module = process_name;
6556
6557 var_expanding_visitor::visit_atvar_op(e);
6558}
6559
6560
40a0c64e
JS
6561void
6562sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6563{
6564 // Fill in our current module context if needed
6565 if (e->module.empty())
6566 e->module = process_name;
6567
6568 var_expanding_visitor::visit_cast_op(e);
6569}
6570
6571
576eaefe
SC
6572void
6573plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6574{
6575 try
6576 {
6577 if (e->name == "$$name")
6578 {
6579 literal_string *myname = new literal_string (entry);
6580 myname->tok = e->tok;
6581 provide(myname);
6582 return;
6583 }
3d69c03f
JS
6584
6585 // variable not found -> throw a semantic error
6586 // (only to be caught right away, but this may be more complex later...)
6587 string alternatives = "$$name";
dc09353a 6588 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6589 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6590 }
6591 catch (const semantic_error &er)
6592 {
6593 e->chain (er);
6594 provide (e);
6595 }
6596}
6597
6598
edce5b67
JS
6599struct sdt_query : public base_query
6600{
6601 sdt_query(probe * base_probe, probe_point * base_loc,
6602 dwflpp & dw, literal_map_t const & params,
51d6bda3 6603 vector<derived_probe *> & results, const string user_lib);
edce5b67 6604
51d6bda3 6605 void query_library (const char *data);
576eaefe 6606 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6607 void handle_query_module();
6608
6609private:
15284963 6610 stap_sdt_probe_type probe_type;
d61ea602 6611 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6612 probe * base_probe;
6613 probe_point * base_loc;
6846cfc8 6614 literal_map_t const & params;
edce5b67 6615 vector<derived_probe *> & results;
a794dbeb
FCE
6616 string pp_mark;
6617 string pp_provider;
51d6bda3 6618 string user_lib;
edce5b67
JS
6619
6620 set<string> probes_handled;
6621
6622 Elf_Data *pdata;
6623 size_t probe_scn_offset;
6624 size_t probe_scn_addr;
aff5d390 6625 uint64_t arg_count;
40fe32e0 6626 GElf_Addr base;
c57ea854 6627 GElf_Addr pc;
aff5d390 6628 string arg_string;
edce5b67 6629 string probe_name;
a794dbeb 6630 string provider_name;
909ab234 6631 GElf_Addr semaphore_load_offset;
79a0ca08 6632 Dwarf_Addr semaphore;
edce5b67
JS
6633
6634 bool init_probe_scn();
6b51ee12 6635 bool get_next_probe();
c57ea854
SC
6636 void iterate_over_probe_entries();
6637 void handle_probe_entry();
edce5b67 6638
488d3c1b 6639 static void setup_note_probe_entry_callback (sdt_query *me,
dbd24034
JL
6640 const string& scn_name,
6641 const string& note_name,
488d3c1b
JL
6642 int type,
6643 const char *data,
6644 size_t len);
dbd24034
JL
6645 void setup_note_probe_entry (const string& scn_name,
6646 const string& note_name, int type,
6647 const char *data, size_t len);
40fe32e0 6648
edce5b67 6649 void convert_probe(probe *base);
4ddb6dd0 6650 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6651 probe* convert_location();
40fe32e0 6652 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6653 bool have_debuginfo_uprobe(bool need_debug_info)
6654 {return probe_type == uprobe1_type
40fe32e0 6655 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6656 && need_debug_info);}
40fe32e0 6657 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6658};
6659
6660
6661sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6662 dwflpp & dw, literal_map_t const & params,
51d6bda3 6663 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6664 base_query(dw, params), probe_type(unknown_probe_type),
6665 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6666 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6667 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6668 semaphore_load_offset(0), semaphore(0)
edce5b67 6669{
a794dbeb
FCE
6670 assert(get_string_param(params, TOK_MARK, pp_mark));
6671 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6672
ef428667
FCE
6673 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6674 // map it to double-underscores.
6675 size_t pos = 0;
6676 while (1) // there may be more than one
6677 {
a794dbeb 6678 size_t i = pp_mark.find("-", pos);
ef428667 6679 if (i == string::npos) break;
a794dbeb 6680 pp_mark.replace (i, 1, "__");
ef428667
FCE
6681 pos = i+1; // resume searching after the inserted __
6682 }
a794dbeb
FCE
6683
6684 // XXX: same for pp_provider?
edce5b67
JS
6685}
6686
6687
6688void
c57ea854 6689sdt_query::handle_probe_entry()
edce5b67 6690{
c57ea854
SC
6691 if (! have_uprobe()
6692 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6693 return;
6694
6695 if (sess.verbose > 3)
c57ea854 6696 {
b78a0fbb 6697 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
b530b5b3
LB
6698 //TRANSLATORS: is matched to.
6699 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6700 switch (probe_type)
6701 {
6702 case uprobe1_type:
6703 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6704 break;
6705 case uprobe2_type:
6706 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6707 break;
40fe32e0
SC
6708 case uprobe3_type:
6709 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6710 break;
d61ea602
JS
6711 default:
6712 clog << "unknown!" << endl;
6713 break;
c57ea854
SC
6714 }
6715 }
edce5b67 6716
c57ea854
SC
6717 // Extend the derivation chain
6718 probe *new_base = convert_location();
6719 probe_point *new_location = new_base->locations[0];
6720
c57ea854
SC
6721 bool need_debug_info = false;
6722
7d395255
JS
6723 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6724 // or dwfl_module_getelf(...). We only need it for the machine type, which
6725 // should be the same. The bias is used for relocating debuginfoless probes,
6726 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6727 Dwarf_Addr bias;
7d395255 6728 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6729
1cc41cd6
DS
6730 /* Figure out the architecture of this particular ELF file. The
6731 dwarfless register-name mappings depend on it. */
6732 GElf_Ehdr ehdr_mem;
6733 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 6734 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6735 assert(em);
1cc41cd6 6736 int elf_machine = em->e_machine;
b8688ee6
JL
6737 sdt_uprobe_var_expanding_visitor svv (sess, dw, elf_machine, module_val,
6738 provider_name, probe_name, probe_type,
6739 arg_string, arg_count);
1cc41cd6
DS
6740 svv.replace (new_base->body);
6741 need_debug_info = svv.need_debug_info;
c57ea854 6742
1cc41cd6
DS
6743 // XXX: why not derive_probes() in the uprobes case too?
6744 literal_map_t params;
6745 for (unsigned i = 0; i < new_location->components.size(); ++i)
6746 {
6747 probe_point::component *c = new_location->components[i];
6748 params[c->functor] = c->arg;
6749 }
c57ea854 6750
73d53dd2 6751 unsigned prior_results_size = results.size();
1cc41cd6
DS
6752 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6753 q.has_mark = true; // enables mid-statement probing
30263a73 6754
73d53dd2
JS
6755 // V1 probes always need dwarf info
6756 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6 6757 if (have_debuginfo_uprobe(need_debug_info))
06de3a04 6758 dw.iterate_over_modules<base_query>(&query_module, &q);
73d53dd2
JS
6759
6760 // For V2+ probes, if variable references weren't used or failed (PR14369),
6761 // then try with the more direct approach. Unresolved $vars might still
6762 // cause their own error, but this gives them a chance to be optimized out.
6763 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6764 {
6765 string section;
6766 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6767 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6768 {
6769 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6770 section = ".dynamic";
6771 }
6772 else
6773 section = ".absolute";
edce5b67 6774
1cc41cd6
DS
6775 uprobe_derived_probe* p =
6776 new uprobe_derived_probe ("", "", 0,
6777 path_remove_sysroot(sess,q.module_val),
6778 section,
6779 q.statement_num_val, reloc_addr, q, 0);
6780 p->saveargs (arg_count);
6781 results.push_back (p);
c57ea854 6782 }
487bf4e2 6783 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6784 record_semaphore(results, prior_results_size);
c57ea854 6785}
edce5b67 6786
4ddb6dd0 6787
c57ea854
SC
6788void
6789sdt_query::handle_query_module()
6790{
6791 if (!init_probe_scn())
6792 return;
edce5b67 6793
c57ea854
SC
6794 if (sess.verbose > 3)
6795 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6796
40fe32e0
SC
6797 if (probe_loc == note_section)
6798 {
6799 GElf_Shdr shdr_mem;
6800 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6801
909ab234
JS
6802 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6803 // effects. The 'semaphore_load_offset' accounts for the difference in
6804 // load addresses between text and data, so the semaphore can be
6805 // converted to a file offset if needed.
40fe32e0 6806 if (shdr)
909ab234
JS
6807 {
6808 base = shdr->sh_addr;
6809 GElf_Addr base_offset = shdr->sh_offset;
6810 shdr = dw.get_section (".probes", &shdr_mem);
6811 if (shdr)
6812 semaphore_load_offset =
6813 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6814 }
40fe32e0 6815 else
909ab234
JS
6816 base = semaphore_load_offset = 0;
6817
488d3c1b 6818 dw.iterate_over_notes (this, &sdt_query::setup_note_probe_entry_callback);
40fe32e0 6819 }
d61ea602 6820 else if (probe_loc == probe_section)
40fe32e0 6821 iterate_over_probe_entries ();
edce5b67
JS
6822}
6823
6824
6825bool
6826sdt_query::init_probe_scn()
6827{
448a86b7 6828 Elf* elf;
edce5b67 6829 GElf_Shdr shdr_mem;
40fe32e0
SC
6830
6831 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6832 if (shdr)
6833 {
6834 probe_loc = note_section;
6835 return true;
6836 }
edce5b67 6837
448a86b7 6838 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6839 if (shdr)
edce5b67 6840 {
fea74777
SC
6841 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6842 probe_scn_offset = 0;
6843 probe_scn_addr = shdr->sh_addr;
6844 assert (pdata != NULL);
6845 if (sess.verbose > 4)
ce0f6648
LB
6846 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6847 << pdata->d_size << endl;
40fe32e0 6848 probe_loc = probe_section;
fea74777 6849 return true;
edce5b67 6850 }
fea74777 6851 else
edce5b67 6852 return false;
edce5b67
JS
6853}
6854
40fe32e0 6855void
dbd24034
JL
6856sdt_query::setup_note_probe_entry_callback (sdt_query *me,
6857 const string& scn_name,
6858 const string& note_name, int type,
6859 const char *data, size_t len)
40fe32e0 6860{
dbd24034 6861 me->setup_note_probe_entry (scn_name, note_name, type, data, len);
40fe32e0
SC
6862}
6863
6864
6865void
dbd24034
JL
6866sdt_query::setup_note_probe_entry (const string& scn_name,
6867 const string& note_name, int type,
6868 const char *data, size_t len)
40fe32e0 6869{
dbd24034
JL
6870 if (scn_name.compare(".note.stapsdt"))
6871 return;
6872#define _SDT_NOTE_NAME "stapsdt"
6873 if (note_name.compare(_SDT_NOTE_NAME))
6874 return;
40fe32e0
SC
6875#define _SDT_NOTE_TYPE 3
6876 if (type != _SDT_NOTE_TYPE)
6877 return;
6878
dbd24034 6879 // we found a probe entry
40fe32e0
SC
6880 union
6881 {
6882 Elf64_Addr a64[3];
6883 Elf32_Addr a32[3];
6884 } buf;
6885 Dwarf_Addr bias;
6886 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6887 Elf_Data dst =
6888 {
6889 &buf, ELF_T_ADDR, EV_CURRENT,
6890 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6891 };
6892 assert (dst.d_size <= sizeof buf);
6893
6894 if (len < dst.d_size + 3)
6895 return;
6896
6897 Elf_Data src =
6898 {
6899 (void *) data, ELF_T_ADDR, EV_CURRENT,
6900 dst.d_size, 0, 0
6901 };
6902
6903 if (gelf_xlatetom (elf, &dst, &src,
6904 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6905 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6906
6907 probe_type = uprobe3_type;
6908 const char * provider = data + dst.d_size;
3f803f9e 6909
40fe32e0 6910 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6911 if(name++ == NULL)
6912 return;
6913
6914 const char *args = (const char*)memchr (name, '\0', data + len - name);
6915 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6916 return;
6917
6918 provider_name = provider;
6919 probe_name = name;
6920 arg_string = args;
40fe32e0 6921
e90006d7
JL
6922 dw.mod_info->marks.insert(make_pair(provider, name));
6923
40fe32e0
SC
6924 // Did we find a matching probe?
6925 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6926 && ((pp_provider == "")
6927 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6928 return;
6929
e9a90eee
JS
6930 // PR13934: Assembly probes are not forced to use the N@OP form.
6931 // If we have '@' then great, else count based on space-delimiters.
6932 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6933 if (!arg_count && !arg_string.empty())
6934 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6935
40fe32e0
SC
6936 GElf_Addr base_ref;
6937 if (gelf_getclass (elf) == ELFCLASS32)
6938 {
6939 pc = buf.a32[0];
6940 base_ref = buf.a32[1];
6941 semaphore = buf.a32[2];
6942 }
6943 else
6944 {
6945 pc = buf.a64[0];
6946 base_ref = buf.a64[1];
6947 semaphore = buf.a64[2];
6948 }
6949
6950 semaphore += base - base_ref;
6951 pc += base - base_ref;
6952
7d395255
JS
6953 // The semaphore also needs the ELF bias added now, so
6954 // record_semaphore can properly relocate it later.
6955 semaphore += bias;
6956
40fe32e0 6957 if (sess.verbose > 4)
b530b5b3 6958 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
6959
6960 handle_probe_entry();
6961}
6962
6963
c57ea854
SC
6964void
6965sdt_query::iterate_over_probe_entries()
edce5b67 6966{
c57ea854 6967 // probes are in the .probe section
edce5b67
JS
6968 while (probe_scn_offset < pdata->d_size)
6969 {
aff5d390
SC
6970 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6971 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6972 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6973 if (! have_uprobe())
edce5b67
JS
6974 {
6975 // Unless this is a mangled .probes section, this happens
6976 // because the name of the probe comes first, followed by
6977 // the sentinel.
6978 if (sess.verbose > 5)
b530b5b3 6979 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6980 probe_scn_offset += sizeof(__uint32_t);
6981 continue;
6982 }
aff5d390
SC
6983 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6984 {
6985 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6986 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6987 continue;
6988 }
6989
1cc41cd6 6990 if (probe_type == uprobe1_type)
aff5d390 6991 {
79a0ca08 6992 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6993 return;
79a0ca08 6994 semaphore = 0;
aff5d390 6995 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6996 provider_name = ""; // unknown
1cc41cd6
DS
6997 pc = pbe_v1->arg;
6998 arg_count = 0;
aff5d390
SC
6999 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
7000 }
08b5a50c 7001 else if (probe_type == uprobe2_type)
aff5d390 7002 {
79a0ca08 7003 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 7004 return;
79a0ca08 7005 semaphore = pbe_v2->semaphore;
aff5d390 7006 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 7007 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
7008 arg_count = pbe_v2->arg_count;
7009 pc = pbe_v2->pc;
7010 if (pbe_v2->arg_string)
7011 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
7012 // skip over pbe_v2, probe_name text and provider text
7013 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
7014 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 7015 }
edce5b67 7016 if (sess.verbose > 4)
b530b5b3 7017 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 7018 << "@0x" << hex << pc << dec << endl;
edce5b67 7019
e90006d7
JL
7020 dw.mod_info->marks.insert(make_pair(provider_name, probe_name));
7021
a794dbeb
FCE
7022 if (dw.function_name_matches_pattern (probe_name, pp_mark)
7023 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 7024 handle_probe_entry ();
edce5b67 7025 }
edce5b67
JS
7026}
7027
7028
6846cfc8 7029void
4ddb6dd0 7030sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 7031{
a794dbeb
FCE
7032 for (unsigned i=0; i<2; i++) {
7033 // prefer with-provider symbol; look without provider prefix for backward compatibility only
7034 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
7035 // XXX: multiple addresses?
7036 if (sess.verbose > 2)
b530b5b3 7037 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 7038
79a0ca08
SC
7039 Dwarf_Addr addr;
7040 if (this->semaphore)
7041 addr = this->semaphore;
7042 else
7043 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
7044 if (addr)
7045 {
7d395255 7046 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
7047 dwfl_module_relocate_address (dw.module, &addr);
7048 // XXX: relocation basis?
909ab234
JS
7049
7050 // Dyninst needs the *file*-based offset for semaphores,
7051 // so subtract the difference in load addresses between .text and .probes
7052 if (dw.sess.runtime_usermode_p())
7053 addr -= semaphore_load_offset;
7054
a794dbeb
FCE
7055 for (unsigned i = start; i < results.size(); ++i)
7056 results[i]->sdt_semaphore_addr = addr;
7057 if (sess.verbose > 2)
b530b5b3 7058 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
7059 return;
7060 }
7061 else
7062 if (sess.verbose > 2)
b530b5b3 7063 clog << _(", not found") << endl;
a794dbeb 7064 }
6846cfc8
SC
7065}
7066
7067
edce5b67
JS
7068void
7069sdt_query::convert_probe (probe *base)
7070{
7071 block *b = new block;
7072 b->tok = base->body->tok;
7073
edce5b67
JS
7074 // Generate: if (arg1 != mark("label")) next;
7075 functioncall *fc = new functioncall;
bbafcb1e 7076 fc->function = "ulong_arg";
edce5b67 7077 fc->tok = b->tok;
bbafcb1e 7078 literal_number* num = new literal_number(1);
edce5b67
JS
7079 num->tok = b->tok;
7080 fc->args.push_back(num);
7081
7082 functioncall *fcus = new functioncall;
7083 fcus->function = "user_string";
7084 fcus->type = pe_string;
7085 fcus->tok = b->tok;
7086 fcus->args.push_back(fc);
7087
7088 if_statement *is = new if_statement;
7089 is->thenblock = new next_statement;
7090 is->elseblock = NULL;
7091 is->tok = b->tok;
63ea4244 7092 is->thenblock->tok = b->tok;
edce5b67
JS
7093 comparison *be = new comparison;
7094 be->op = "!=";
7095 be->tok = b->tok;
7096 be->left = fcus;
7097 be->right = new literal_string(probe_name);
63ea4244 7098 be->right->tok = b->tok;
edce5b67
JS
7099 is->condition = be;
7100 b->statements.push_back(is);
7101
7102 // Now replace the body
7103 b->statements.push_back(base->body);
7104 base->body = b;
7105}
7106
7107
c72aa911
JS
7108probe*
7109sdt_query::convert_location ()
edce5b67 7110{
684b8718
JL
7111 string module = dw.module_name;
7112 if (has_process)
7113 module = path_remove_sysroot(sess, module);
7114
c72aa911 7115 probe_point* specific_loc = new probe_point(*base_loc);
684b8718
JL
7116 specific_loc->well_formed = true;
7117
662539d9 7118 vector<probe_point::component*> derived_comps;
edce5b67 7119
662539d9
JS
7120 vector<probe_point::component*>::iterator it;
7121 for (it = specific_loc->components.begin();
7122 it != specific_loc->components.end(); ++it)
7123 if ((*it)->functor == TOK_PROCESS)
7124 {
684b8718
JL
7125 // replace the possibly incomplete path to process
7126 *it = new probe_point::component(TOK_PROCESS,
7127 new literal_string(has_library ? path : module));
7128
1cc41cd6
DS
7129 // copy the process name
7130 derived_comps.push_back(*it);
662539d9
JS
7131 }
7132 else if ((*it)->functor == TOK_LIBRARY)
7133 {
1cc41cd6
DS
7134 // copy the library name for process probes
7135 derived_comps.push_back(*it);
662539d9
JS
7136 }
7137 else if ((*it)->functor == TOK_PROVIDER)
7138 {
7139 // replace the possibly wildcarded arg with the specific provider name
7140 *it = new probe_point::component(TOK_PROVIDER,
7141 new literal_string(provider_name));
7142 }
7143 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
7144 {
7145 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
7146 *it = new probe_point::component(TOK_MARK,
7147 new literal_string(probe_name));
a794dbeb 7148
aff5d390
SC
7149 if (sess.verbose > 3)
7150 switch (probe_type)
7151 {
7152 case uprobe1_type:
b530b5b3 7153 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
7154 << hex << pc << dec << endl;
7155 break;
7156 case uprobe2_type:
b530b5b3 7157 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
7158 << hex << pc << dec << endl;
7159 break;
40fe32e0 7160 case uprobe3_type:
b530b5b3 7161 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
7162 << hex << pc << dec << endl;
7163 break;
aff5d390 7164 default:
b530b5b3
LB
7165 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
7166 pp_mark.c_str()) << endl;
aff5d390
SC
7167 }
7168
c72aa911
JS
7169 switch (probe_type)
7170 {
aff5d390
SC
7171 case uprobe1_type:
7172 case uprobe2_type:
40fe32e0 7173 case uprobe3_type:
c72aa911 7174 // process("executable").statement(probe_arg)
662539d9
JS
7175 derived_comps.push_back
7176 (new probe_point::component(TOK_STATEMENT,
7177 new literal_number(pc, true)));
c72aa911
JS
7178 break;
7179
a794dbeb 7180 default: // deprecated
c72aa911 7181 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
7182 derived_comps.push_back
7183 (new probe_point::component(TOK_FUNCTION,
7184 new literal_string("*")));
7185 derived_comps.push_back
c72aa911 7186 (new probe_point::component(TOK_LABEL,
a794dbeb 7187 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
7188 break;
7189 }
7190 }
edce5b67 7191
662539d9
JS
7192 probe_point* derived_loc = new probe_point(*specific_loc);
7193 derived_loc->components = derived_comps;
8159bf55 7194 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
7195}
7196
7197
51d6bda3
SC
7198void
7199sdt_query::query_library (const char *library)
7200{
7201 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
7202}
7203
e90006d7
JL
7204string
7205suggest_marks(systemtap_session& sess,
7206 const set<string>& modules,
7207 const string& mark,
7208 const string& provider)
7209{
7210 if (mark.empty() || modules.empty() || sess.module_cache == NULL)
7211 return "";
7212
7213 set<string> marks;
7214 const map<string, module_info*> &cache = sess.module_cache->cache;
7215 bool dash_suggestions = (mark.find("-") != string::npos);
7216
7217 for (set<string>::iterator itmod = modules.begin();
7218 itmod != modules.end(); ++itmod)
7219 {
7220 map<string, module_info*>::const_iterator itcache;
7221 if ((itcache = cache.find(*itmod)) != cache.end())
7222 {
7223 set<pair<string,string> >::const_iterator itmarks;
7224 for (itmarks = itcache->second->marks.begin();
7225 itmarks != itcache->second->marks.end(); ++itmarks)
7226 {
7227 if (provider.empty()
7228 // simulating dw.function_name_matches_pattern()
7229 || (fnmatch(provider.c_str(), itmarks->first.c_str(), 0) == 0))
7230 {
7231 string marksug = itmarks->second;
7232 if (dash_suggestions)
7233 {
7234 size_t pos = 0;
7235 while (1) // there may be more than one
7236 {
7237 size_t i = marksug.find("__", pos);
7238 if (i == string::npos) break;
7239 marksug.replace (i, 2, "-");
7240 pos = i+1; // resume searching after the inserted -
7241 }
7242 }
7243 marks.insert(marksug);
7244 }
7245 }
7246 }
7247 }
7248
7249 if (sess.verbose > 2)
7250 {
7251 clog << "suggesting " << marks.size() << " marks "
7252 << "from modules:" << endl;
7253 for (set<string>::iterator itmod = modules.begin();
7254 itmod != modules.end(); ++itmod)
7255 clog << *itmod << endl;
7256 }
7257
7258 if (marks.empty())
7259 return "";
7260
7261 return levenshtein_suggest(mark, marks, 5); // print top 5 marks only
7262}
7263
40a70f52
JL
7264string
7265suggest_plt_functions(systemtap_session& sess,
7266 const set<string>& modules,
7267 const string& func)
7268{
7269 if (func.empty() || modules.empty() || sess.module_cache == NULL)
7270 return "";
7271
7272 set<string> funcs;
7273 const map<string, module_info*> &cache = sess.module_cache->cache;
7274
7275 for (set<string>::iterator itmod = modules.begin();
7276 itmod != modules.end(); ++itmod)
7277 {
7278 map<string, module_info*>::const_iterator itcache;
7279 if ((itcache = cache.find(*itmod)) != cache.end())
7280 funcs.insert(itcache->second->plt_funcs.begin(),
7281 itcache->second->plt_funcs.end());
7282 }
7283
7284 if (sess.verbose > 2)
d82dd71f
JL
7285 {
7286 clog << "suggesting " << funcs.size() << " plt functions "
7287 << "from modules:" << endl;
7288 for (set<string>::iterator itmod = modules.begin();
7289 itmod != modules.end(); ++itmod)
7290 clog << *itmod << endl;
7291 }
40a70f52
JL
7292
7293 if (funcs.empty())
7294 return "";
7295
7296 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
7297}
51d6bda3 7298
0508c45f
JL
7299string
7300suggest_dwarf_functions(systemtap_session& sess,
7301 const set<string>& modules,
7302 string func)
44ffe90c
JL
7303{
7304 // Trim any @ component
7305 size_t pos = func.find('@');
7306 if (pos != string::npos)
7307 func.erase(pos);
7308
0508c45f 7309 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
7310 return "";
7311
7312 // We must first aggregate all the functions from the cache
7313 set<string> funcs;
7314 const map<string, module_info*> &cache = sess.module_cache->cache;
7315
0508c45f
JL
7316 for (set<string>::iterator itmod = modules.begin();
7317 itmod != modules.end(); ++itmod)
44ffe90c 7318 {
6e6d9a3b
JL
7319 module_info *module;
7320
7321 // retrieve module_info from cache
44ffe90c
JL
7322 map<string, module_info*>::const_iterator itcache;
7323 if ((itcache = cache.find(*itmod)) != cache.end())
6e6d9a3b
JL
7324 module = itcache->second;
7325 else // module not found
7326 continue;
7327
7328 // add inlines
7329 funcs.insert(module->inlined_funcs.begin(),
7330 module->inlined_funcs.end());
7331
7332 // add all function symbols in cache
7333 if (module->symtab_status != info_present || module->sym_table == NULL)
7334 continue;
7335 map<string, func_info*>& modfuncs = module->sym_table->map_by_name;
7336 for (map<string, func_info*>::const_iterator itfuncs = modfuncs.begin();
7337 itfuncs != modfuncs.end(); ++itfuncs)
7338 funcs.insert(itfuncs->first);
44ffe90c
JL
7339 }
7340
7341 if (sess.verbose > 2)
d82dd71f
JL
7342 {
7343 clog << "suggesting " << funcs.size() << " dwarf functions "
7344 << "from modules:" << endl;
7345 for (set<string>::iterator itmod = modules.begin();
7346 itmod != modules.end(); ++itmod)
7347 clog << *itmod << endl;
7348 }
44ffe90c
JL
7349
7350 if (funcs.empty())
7351 return "";
7352
593f09eb 7353 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
7354}
7355
20c6c071 7356void
5227f1ea 7357dwarf_builder::build(systemtap_session & sess,
7a053d3b 7358 probe * base,
20c6c071 7359 probe_point * location,
86bf665e 7360 literal_map_t const & parameters,
20c6c071
GH
7361 vector<derived_probe *> & finished_results)
7362{
b20febf3
FCE
7363 // NB: the kernel/user dwlfpp objects are long-lived.
7364 // XXX: but they should be per-session, as this builder object
7365 // may be reused if we try to cross-instrument multiple targets.
84048984 7366
7a24d422 7367 dwflpp* dw = 0;
6d5d594e 7368 literal_map_t filled_parameters = parameters;
7a24d422 7369
7a24d422 7370 string module_name;
ae2552da
FCE
7371 if (has_null_param (parameters, TOK_KERNEL))
7372 {
7373 dw = get_kern_dw(sess, "kernel");
7374 }
7375 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 7376 {
c523a015
LB
7377 size_t dash_pos = 0;
7378 while((dash_pos=module_name.find('-'))!=string::npos)
7379 module_name.replace(int(dash_pos),1,"_");
7380 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
7381 // NB: glob patterns get expanded later, during the offline
7382 // elfutils module listing.
ae2552da 7383 dw = get_kern_dw(sess, module_name);
b8da0ad1 7384 }
6d5d594e 7385 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 7386 {
05fb3e0c 7387 module_name = sess.sysroot + module_name;
6d5d594e
LB
7388 if(has_null_param(filled_parameters, TOK_PROCESS))
7389 {
fc18e6c4
JL
7390 string file;
7391 try
7392 {
7393 file = sess.cmd_file();
7394 }
7395 catch (const semantic_error& e)
7396 {
7397 throw SEMANTIC_ERROR(_("invalid -c command for unspecified process"
7398 " probe [man stapprobes]"), NULL, NULL, &e);
7399 }
48cd804a 7400 if(file.empty())
fc18e6c4
JL
7401 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without"
7402 " a -c COMMAND [man stapprobes]"));
48cd804a 7403 module_name = sess.sysroot + file;
6d5d594e
LB
7404 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
7405 // in the case of TOK_MARK we need to modify locations as well
7406 if(location->components[0]->functor==TOK_PROCESS &&
7407 location->components[0]->arg == 0)
7408 location->components[0]->arg = new literal_string(module_name);
b78a0fbb 7409 }
5750ecc6 7410
37001baa
FCE
7411 // PR6456 process("/bin/*") glob handling
7412 if (contains_glob_chars (module_name))
7413 {
7414 // Expand glob via rewriting the probe-point process("....")
7415 // parameter, asserted to be the first one.
7416
7417 assert (location->components.size() > 0);
7418 assert (location->components[0]->functor == TOK_PROCESS);
7419 assert (location->components[0]->arg);
7420 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7421 assert (lit);
7422
7423 // Evaluate glob here, and call derive_probes recursively with each match.
7424 glob_t the_blob;
88f8e2c0 7425 set<string> dupes;
37001baa 7426 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 7427 if (rc)
dc09353a 7428 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 7429 unsigned results_pre = finished_results.size();
37001baa
FCE
7430 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
7431 {
e19ebcf7 7432 assert_no_interrupts();
37001baa
FCE
7433
7434 const char* globbed = the_blob.gl_pathv[i];
7435 struct stat st;
7436
7437 if (access (globbed, X_OK) == 0
7438 && stat (globbed, &st) == 0
7439 && S_ISREG (st.st_mode)) // see find_executable()
7440 {
7977a734
FCE
7441 // Need to call canonicalize here, in order to path-expand
7442 // patterns like process("stap*"). Otherwise it may go through
7443 // to the next round of expansion as ("stap"), leading to a $PATH
7444 // search that's not consistent with the glob search already done.
5bca76a8
JS
7445 string canononicalized = resolve_path (globbed);
7446 globbed = canononicalized.c_str();
7977a734 7447
88f8e2c0
JS
7448 // The canonical names can result in duplication, for example
7449 // having followed symlinks that are common with shared
7450 // libraries. Filter those out.
7451 if (!dupes.insert(canononicalized).second)
7452 continue;
7453
37001baa
FCE
7454 // synthesize a new probe_point, with the glob-expanded string
7455 probe_point *pp = new probe_point (*location);
ef0943df
JL
7456 pp->from_glob = true;
7457
5750ecc6
FCE
7458 // PR13338: quote results to prevent recursion
7459 string eglobbed = escape_glob_chars (globbed);
7460
7461 if (sess.verbose > 1)
7462 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7463 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 7464 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 7465
37001baa 7466 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7467 new literal_string (eglobbed_tgt));
37001baa
FCE
7468 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7469 pp->components[0] = ppc;
7470
d885563b 7471 probe* new_probe = new probe (base, pp);
7977a734
FCE
7472
7473 // We override "optional = true" here, as if the
7474 // wildcarded probe point was given a "?" suffix.
7475
7476 // This is because wildcard probes will be expected
7477 // by users to apply only to some subset of the
7478 // matching binaries, in the sense of "any", rather
7479 // than "all", sort of similarly how
7480 // module("*").function("...") patterns work.
7481
7482 derive_probes (sess, new_probe, finished_results,
7483 true /* NB: not location->optional */ );
37001baa
FCE
7484 }
7485 }
7486
7487 globfree (& the_blob);
44ffe90c
JL
7488
7489 unsigned results_post = finished_results.size();
7490
e90006d7 7491 // Did we fail to find a function/plt/mark by name? Let's suggest
44ffe90c
JL
7492 // something!
7493 string func;
7494 if (results_pre == results_post
7495 && get_param(filled_parameters, TOK_FUNCTION, func)
7496 && !func.empty())
7497 {
0508c45f 7498 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7499 modules_seen.clear();
7500 if (!sugs.empty())
dc09353a 7501 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7502 "no match (similar functions: %s)",
7503 sugs.find(',') == string::npos,
7504 sugs.c_str()));
7505 }
40a70f52
JL
7506 else if (results_pre == results_post
7507 && get_param(filled_parameters, TOK_PLT, func)
7508 && !func.empty())
7509 {
7510 string sugs = suggest_plt_functions(sess, modules_seen, func);
7511 modules_seen.clear();
7512 if (!sugs.empty())
7513 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7514 "no match (similar functions: %s)",
7515 sugs.find(',') == string::npos,
7516 sugs.c_str()));
7517 }
e90006d7
JL
7518 else if (results_pre == results_post
7519 && get_param(filled_parameters, TOK_MARK, func)
7520 && !func.empty())
7521 {
7522 string provider;
7523 get_param(filled_parameters, TOK_PROVIDER, provider);
7524
7525 string sugs = suggest_marks(sess, modules_seen, func, provider);
7526 modules_seen.clear();
7527 if (!sugs.empty())
7528 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7529 "no match (similar marks: %s)",
7530 sugs.find(',') == string::npos,
7531 sugs.c_str()));
7532 }
44ffe90c 7533
37001baa
FCE
7534 return; // avoid falling through
7535 }
7536
5750ecc6
FCE
7537 // PR13338: unquote glob results
7538 module_name = unescape_glob_chars (module_name);
05fb3e0c 7539 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
7540
7541 // if the executable starts with "#!", we look for the interpreter of the script
7542 {
7543 ifstream script_file (user_path.c_str () );
7544
7545 if (script_file.good ())
7546 {
7547 string line;
7548
7549 getline (script_file, line);
7550
7551 if (line.compare (0, 2, "#!") == 0)
7552 {
7553 string path_head = line.substr(2);
7554
7555 // remove white spaces at the beginning of the string
7556 size_t p2 = path_head.find_first_not_of(" \t");
7557
7558 if (p2 != string::npos)
7559 {
7560 string path = path_head.substr(p2);
7561
7562 // remove white spaces at the end of the string
7563 p2 = path.find_last_not_of(" \t\n");
7564 if (string::npos != p2)
7565 path.erase(p2+1);
7566
8e13c1a1
RH
7567 // handle "#!/usr/bin/env" redirect
7568 size_t offset = 0;
7569 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7570 {
7571 offset = sizeof("/bin/env")-1;
7572 }
7573 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7574 {
7575 offset = sizeof("/usr/bin/env")-1;
7576 }
7577
7578 if (offset != 0)
7579 {
7580 size_t p3 = path.find_first_not_of(" \t", offset);
7581
7582 if (p3 != string::npos)
7583 {
7584 string env_path = path.substr(p3);
05fb3e0c
WF
7585 user_path = find_executable (env_path, sess.sysroot,
7586 sess.sysenv);
8e13c1a1
RH
7587 }
7588 }
7589 else
7590 {
05fb3e0c 7591 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7592 }
d1bcbe71
RH
7593
7594 struct stat st;
7595
7596 if (access (user_path.c_str(), X_OK) == 0
7597 && stat (user_path.c_str(), &st) == 0
7598 && S_ISREG (st.st_mode)) // see find_executable()
7599 {
7600 if (sess.verbose > 1)
b530b5b3
LB
7601 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7602 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7603
7604 assert (location->components.size() > 0);
7605 assert (location->components[0]->functor == TOK_PROCESS);
7606 assert (location->components[0]->arg);
7607 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7608 assert (lit);
7609
7610 // synthesize a new probe_point, with the expanded string
7611 probe_point *pp = new probe_point (*location);
05fb3e0c 7612 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7613 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7614 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7615 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7616 pp->components[0] = ppc;
7617
d885563b 7618 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7619
7620 derive_probes (sess, new_probe, finished_results);
7621
7622 script_file.close();
7623 return;
7624 }
7625 }
7626 }
7627 }
7628 script_file.close();
7629 }
7630
47e226ed 7631 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7632 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7633 {
7634 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7635 "LD_LIBRARY_PATH");
7636 if (module_name.find('/') == string::npos)
7637 // We didn't find user_lib so use iterate_over_libraries
7638 module_name = user_path;
7639 }
63b4fd14 7640 else
b642c901 7641 module_name = user_path; // canonicalize it
d0a7f5a9 7642
3667d615 7643 // uretprobes aren't available everywhere
536f1261 7644 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7645 {
3667d615
JS
7646 if (kernel_supports_inode_uprobes(sess) &&
7647 !kernel_supports_inode_uretprobes(sess))
dc09353a 7648 throw SEMANTIC_ERROR
3ffeaf3c 7649 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7650 }
3667d615 7651
f4000852
MW
7652 // There is a similar check in pass 4 (buildrun), but it is
7653 // needed here too to make sure alternatives for optional
7654 // (? or !) process probes are disposed and/or alternatives
7655 // are selected.
3667d615
JS
7656 if (!sess.runtime_usermode_p())
7657 check_process_probe_kernel_support(sess);
e34d5d13 7658
7a24d422
FCE
7659 // user-space target; we use one dwflpp instance per module name
7660 // (= program or shared library)
707bf35e 7661 dw = get_user_dw(sess, module_name);
c8959a29 7662 }
20c6c071 7663
1acfc030
JS
7664 assert(dw);
7665
e90006d7
JL
7666 unsigned results_pre = finished_results.size();
7667
5896cd05 7668 if (sess.verbose > 3)
b530b5b3 7669 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7670
a794dbeb
FCE
7671 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7672 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7673 {
51d6bda3 7674 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
06de3a04 7675 dw->iterate_over_modules<base_query>(&query_module, &sdtq);
e90006d7
JL
7676
7677 // We need to update modules_seen with the modules we've visited
7678 modules_seen.insert(sdtq.visited_modules.begin(),
7679 sdtq.visited_modules.end());
7680
7681 // Did we fail to find a mark?
7682 if (results_pre == finished_results.size() && !location->from_glob)
7683 {
7684 string provider;
7685 get_param(filled_parameters, TOK_PROVIDER, provider);
7686
7687 string sugs = suggest_marks(sess, modules_seen, dummy_mark_name, provider);
7688 modules_seen.clear();
7689 if (!sugs.empty())
7690 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7691 "no match (similar marks: %s)",
7692 sugs.find(',') == string::npos,
7693 sugs.c_str()));
7694 }
7695
edce5b67 7696 return;
7a05f484 7697 }
20c6c071 7698
6d5d594e 7699 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7700
7701 // XXX: kernel.statement.absolute is a special case that requires no
7702 // dwfl processing. This code should be in a separate builder.
7a24d422 7703 if (q.has_kernel && q.has_absolute)
37ebca01 7704 {
4baf0e53 7705 // assert guru mode for absolute probes
37ebca01
FCE
7706 if (! q.base_probe->privileged)
7707 {
dc09353a 7708 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7709 q.base_probe->tok);
37ebca01
FCE
7710 }
7711
7712 // For kernel.statement(NUM).absolute probe points, we bypass
7713 // all the debuginfo stuff: We just wire up a
7714 // dwarf_derived_probe right here and now.
4baf0e53 7715 dwarf_derived_probe* p =
b8da0ad1
FCE
7716 new dwarf_derived_probe ("", "", 0, "kernel", "",
7717 q.statement_num_val, q.statement_num_val,
7718 q, 0);
37ebca01 7719 finished_results.push_back (p);
1a0dbc5a 7720 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7721 return;
7722 }
7723
06de3a04 7724 dw->iterate_over_modules<base_query>(&query_module, &q);
8f14e444 7725
44ffe90c
JL
7726 // We need to update modules_seen with the modules we've visited
7727 modules_seen.insert(q.visited_modules.begin(),
7728 q.visited_modules.end());
8f14e444
FCE
7729
7730 // PR11553 special processing: .return probes requested, but
7731 // some inlined function instances matched.
7732 unsigned i_n_r = q.inlined_non_returnable.size();
7733 unsigned results_post = finished_results.size();
7734 if (i_n_r > 0)
7735 {
7736 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7737 {
7738 string quicklist;
7739 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7740 it != q.inlined_non_returnable.end();
7741 it++)
7742 {
7743 quicklist += " " + (*it);
7744 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7745 {
7746 quicklist += " ...";
7747 break;
7748 }
7749 }
c57ea854 7750
52c2652f 7751 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7752 "cannot probe .return of %u inlined functions %s",
52c2652f 7753 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7754 // There will be also a "no matches" semantic error generated.
7755 }
7756 if (sess.verbose > 1)
52c2652f
NMA
7757 clog << _NF("skipped .return probe of %u inlined function",
7758 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7759 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7760 {
7761 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7762 it != q.inlined_non_returnable.end();
7763 it++)
7764 clog << (*it) << " ";
7765 clog << endl;
7766 }
7767 } // i_n_r > 0
44ffe90c 7768
e90006d7 7769 // If we just failed to resolve a function/plt by name, we can suggest
ef0943df
JL
7770 // something. We only suggest things for probe points that were not
7771 // synthesized from a glob, i.e. only for 'real' probes. This is also
7772 // required because modules_seen needs to accumulate across recursive
7773 // calls for process(glob)[.library(glob)] probes.
44ffe90c 7774 string func;
ef0943df 7775 if (results_pre == results_post && !location->from_glob
44ffe90c
JL
7776 && get_param(filled_parameters, TOK_FUNCTION, func)
7777 && !func.empty())
7778 {
0508c45f 7779 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7780 modules_seen.clear();
7781 if (!sugs.empty())
dc09353a 7782 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7783 "no match (similar functions: %s)",
7784 sugs.find(',') == string::npos,
7785 sugs.c_str()));
7786 }
ef0943df 7787 else if (results_pre == results_post && !location->from_glob
40a70f52
JL
7788 && get_param(filled_parameters, TOK_PLT, func)
7789 && !func.empty())
7790 {
7791 string sugs = suggest_plt_functions(sess, modules_seen, func);
7792 modules_seen.clear();
7793 if (!sugs.empty())
7794 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7795 "no match (similar functions: %s)",
7796 sugs.find(',') == string::npos,
7797 sugs.c_str()));
7798 }
44ffe90c
JL
7799 else if (results_pre != results_post)
7800 // Something was derived so we won't need to suggest something
7801 modules_seen.clear();
5f0a03a6
JK
7802}
7803
7804symbol_table::~symbol_table()
7805{
c9efa5c9 7806 delete_map(map_by_addr);
5f0a03a6
JK
7807}
7808
7809void
2867a2a1 7810symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7811 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7812{
ab91b232
JK
7813#ifdef __powerpc__
7814 // Map ".sys_foo" to "sys_foo".
7815 if (name[0] == '.')
7816 name++;
7817#endif
5f0a03a6
JK
7818 func_info *fi = new func_info();
7819 fi->addr = addr;
7820 fi->name = name;
ab91b232 7821 fi->weak = weak;
2867a2a1 7822 fi->descriptor = descriptor;
5f0a03a6
JK
7823 map_by_name[fi->name] = fi;
7824 // TODO: Use a multimap in case there are multiple static
7825 // functions with the same name?
1c6b77e5 7826 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7827}
7828
46f7b6be 7829void
f98c6346 7830symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7831{
7832#ifdef __powerpc__
7833 /*
7834 * The .opd section contains function descriptors that can look
7835 * just like function entry points. For example, there's a function
7836 * descriptor called "do_exit" that links to the entry point ".do_exit".
7837 * Reject all symbols in .opd.
7838 */
7839 opd_section = SHN_UNDEF;
7840 Dwarf_Addr bias;
7841 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7842 ?: dwfl_module_getelf (mod, &bias));
7843 Elf_Scn* scn = 0;
7844 size_t shstrndx;
7845
7846 if (!elf)
7847 return;
fcc30d6d 7848 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7849 return;
7850 while ((scn = elf_nextscn(elf, scn)) != NULL)
7851 {
7852 GElf_Shdr shdr_mem;
7853 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7854 if (!shdr)
7855 continue;
7856 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7857 if (!strcmp(name, ".opd"))
7858 {
7859 opd_section = elf_ndxscn(scn);
7860 return;
7861 }
7862 }
7863#endif
7864}
7865
7866bool
7867symbol_table::reject_section(GElf_Word section)
7868{
7869 if (section == SHN_UNDEF)
7870 return true;
7871#ifdef __powerpc__
7872 if (section == opd_section)
7873 return true;
7874#endif
7875 return false;
7876}
7877
5f0a03a6
JK
7878enum info_status
7879symbol_table::get_from_elf()
7880{
7881 Dwarf_Addr high_addr = 0;
7882 Dwfl_Module *mod = mod_info->mod;
7883 int syments = dwfl_module_getsymtab(mod);
7884 assert(syments);
46f7b6be 7885 prepare_section_rejection(mod);
5f0a03a6
JK
7886 for (int i = 1; i < syments; ++i)
7887 {
7888 GElf_Sym sym;
ab91b232 7889 GElf_Word section;
cba67d8f
MW
7890 const char *name;
7891 GElf_Addr addr;
7892 bool reject;
7893
7894/* Note that dwfl_module_getsym does adjust the sym.st_value but doesn't
7895 try to resolve it to a function address. dwfl_module_getsym_info leaves
7896 the st_value in tact (no adjustment applied) and returns the fully
7897 resolved address separately. In that case we can simply reject the
7898 symbol if it is SHN_UNDEF and don't need to call reject_section which
7899 does extra checks to see whether the address fall in an architecture
7900 specific descriptor table (which will never be the case when using the
7901 new dwfl_module_getsym_info). dwfl_module_getsym will only provide us
7902 with the (adjusted) st_value of the symbol, which might point into a
7903 function descriptor table. So in that case we still have to call
7904 reject_section. */
7905#if _ELFUTILS_PREREQ (0, 158)
7906 name = dwfl_module_getsym_info (mod, i, &sym, &addr, &section,
7907 NULL, NULL);
7908 reject = section == SHN_UNDEF;
7909#else
7910 name = dwfl_module_getsym (mod, i, &sym, &section);
b23098cd 7911 addr = sym.st_value;
cba67d8f
MW
7912 reject = reject_section(section);
7913#endif
7914
2867a2a1 7915 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7916 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
cba67d8f 7917 reject, addr, &high_addr);
2a4acb09
JL
7918 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
7919 && GELF_ST_BIND(sym.st_info) == STB_GLOBAL)
7920 globals[name] = addr;
7921 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
7922 && GELF_ST_BIND(sym.st_info) == STB_LOCAL)
7923 locals[name] = addr;
5f0a03a6
JK
7924 }
7925 return info_present;
7926}
7927
5f0a03a6
JK
7928func_info *
7929symbol_table::get_func_containing_address(Dwarf_Addr addr)
7930{
1c6b77e5
JS
7931 iterator_t iter = map_by_addr.upper_bound(addr);
7932 if (iter == map_by_addr.begin())
5f0a03a6 7933 return NULL;
2e67a43b 7934 else
1c6b77e5 7935 return (--iter)->second;
5f0a03a6
JK
7936}
7937
3d372d6b
SC
7938func_info *
7939symbol_table::get_first_func()
7940{
7941 iterator_t iter = map_by_addr.begin();
7942 return (iter)->second;
7943}
7944
5f0a03a6
JK
7945func_info *
7946symbol_table::lookup_symbol(const string& name)
7947{
7948 map<string, func_info*>::iterator i = map_by_name.find(name);
7949 if (i == map_by_name.end())
7950 return NULL;
7951 return i->second;
7952}
7953
7954Dwarf_Addr
7955symbol_table::lookup_symbol_address(const string& name)
7956{
7957 func_info *fi = lookup_symbol(name);
7958 if (fi)
7959 return fi->addr;
7960 return 0;
7961}
7962
ab91b232
JK
7963// This is the kernel symbol table. The kernel macro cond_syscall creates
7964// a weak symbol for each system call and maps it to sys_ni_syscall.
7965// For system calls not implemented elsewhere, this weak symbol shows up
7966// in the kernel symbol table. Following the precedent of dwarfful stap,
7967// we refuse to consider such symbols. Here we delete them from our
7968// symbol table.
7969// TODO: Consider generalizing this and/or making it part of blacklist
7970// processing.
7971void
7972symbol_table::purge_syscall_stubs()
7973{
7974 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7975 if (stub_addr == 0)
7976 return;
1c6b77e5 7977 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7978 for (iterator_t iter = purge_range.first;
7979 iter != purge_range.second;
1c6b77e5 7980 )
ab91b232 7981 {
1c6b77e5 7982 func_info *fi = iter->second;
2e67a43b 7983 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7984 {
2e67a43b 7985 map_by_name.erase(fi->name);
1c6b77e5 7986 map_by_addr.erase(iter++);
2e67a43b 7987 delete fi;
2e67a43b 7988 }
1c6b77e5
JS
7989 else
7990 iter++;
ab91b232
JK
7991 }
7992}
7993
5f0a03a6 7994void
5f52fafe 7995module_info::get_symtab()
5f0a03a6 7996{
1c6b77e5
JS
7997 if (symtab_status != info_unknown)
7998 return;
7999
5f0a03a6
JK
8000 sym_table = new symbol_table(this);
8001 if (!elf_path.empty())
8002 {
5f0a03a6
JK
8003 symtab_status = sym_table->get_from_elf();
8004 }
8005 else
8006 {
8007 assert(name == TOK_KERNEL);
ab3ed72d
DS
8008 symtab_status = info_absent;
8009 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
8010 }
8011 if (symtab_status == info_absent)
8012 {
8013 delete sym_table;
8014 sym_table = NULL;
8015 return;
8016 }
8017
ab91b232
JK
8018 if (name == TOK_KERNEL)
8019 sym_table->purge_syscall_stubs();
5f0a03a6
JK
8020}
8021
1c6b77e5
JS
8022// update_symtab reconciles data between the elf symbol table and the dwarf
8023// function enumeration. It updates the symbol table entries with the dwarf
8024// die that describes the function, which also signals to query_module_symtab
8025// that a statement probe isn't needed. In return, it also adds aliases to the
8026// function table for names that share the same addr/die.
8027void
8028module_info::update_symtab(cu_function_cache_t *funcs)
8029{
8030 if (!sym_table)
8031 return;
8032
8033 cu_function_cache_t new_funcs;
8034
8035 for (cu_function_cache_t::iterator func = funcs->begin();
8036 func != funcs->end(); func++)
8037 {
8038 // optimization: inlines will never be in the symbol table
8039 if (dwarf_func_inline(&func->second) != 0)
6e6d9a3b
JL
8040 {
8041 inlined_funcs.insert(func->first);
8042 continue;
8043 }
1c6b77e5 8044
1ffb8bd1
JS
8045 // XXX We may want to make additional efforts to match mangled elf names
8046 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
8047 // missing, so we may also need to try matching by address. See also the
8048 // notes about _Z in dwflpp::iterate_over_functions().
8049
1c6b77e5
JS
8050 func_info *fi = sym_table->lookup_symbol(func->first);
8051 if (!fi)
8052 continue;
8053
8054 // iterate over all functions at the same address
8055 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
8056 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
8057 {
8058 // update this function with the dwarf die
8059 it->second->die = func->second;
8060
8061 // if this function is a new alias, then
8062 // save it to merge into the function cache
8063 if (it->second != fi)
b7478964 8064 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
8065 }
8066 }
8067
8068 // add all discovered aliases back into the function cache
8069 // NB: this won't replace any names that dwarf may have already found
8070 funcs->insert(new_funcs.begin(), new_funcs.end());
8071}
8072
5f0a03a6
JK
8073module_info::~module_info()
8074{
8075 if (sym_table)
8076 delete sym_table;
b55bc428
FCE
8077}
8078
935447c8 8079// ------------------------------------------------------------------------
888af770 8080// user-space probes
935447c8
DS
8081// ------------------------------------------------------------------------
8082
935447c8 8083
888af770 8084struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 8085{
89ba3085
FCE
8086private:
8087 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 8088 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
8089 }
8090
cfcab6c7
JS
8091 void emit_module_maxuprobes (systemtap_session& s);
8092
2b69faaf
JS
8093 // Using our own utrace-based uprobes
8094 void emit_module_utrace_decls (systemtap_session& s);
8095 void emit_module_utrace_init (systemtap_session& s);
8096 void emit_module_utrace_exit (systemtap_session& s);
8097
8098 // Using the upstream inode-based uprobes
8099 void emit_module_inode_decls (systemtap_session& s);
8100 void emit_module_inode_init (systemtap_session& s);
8101 void emit_module_inode_exit (systemtap_session& s);
8102
3a894f7e
JS
8103 // Using the dyninst backend (via stapdyn)
8104 void emit_module_dyninst_decls (systemtap_session& s);
8105 void emit_module_dyninst_init (systemtap_session& s);
8106 void emit_module_dyninst_exit (systemtap_session& s);
8107
935447c8 8108public:
888af770 8109 void emit_module_decls (systemtap_session& s);
935447c8
DS
8110 void emit_module_init (systemtap_session& s);
8111 void emit_module_exit (systemtap_session& s);
8112};
8113
8114
888af770
FCE
8115void
8116uprobe_derived_probe::join_group (systemtap_session& s)
8117{
8118 if (! s.uprobe_derived_probes)
8119 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
8120 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
8121 if (s.runtime_usermode_p())
8122 enable_dynprobes(s);
8123 else
4441e344 8124 enable_task_finder(s);
a96d1db0 8125
8a03658e 8126 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
8127 // signal staprun to load that module. If we're using the builtin
8128 // inode-uprobes, we still need to know that it is required.
8a03658e 8129 s.need_uprobes = true;
a96d1db0
DN
8130}
8131
888af770 8132
c0f84e7b
SC
8133void
8134uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
8135{
8136 dwarf_derived_probe::getargs(arg_set);
8137 arg_set.insert(arg_set.end(), args.begin(), args.end());
8138}
8139
8140
8141void
8142uprobe_derived_probe::saveargs(int nargs)
8143{
8144 for (int i = 1; i <= nargs; i++)
8145 args.push_back("$arg" + lex_cast (i) + ":long");
8146}
8147
8148
2865d17a 8149void
42e38653 8150uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
8151{
8152 // These probes are allowed for unprivileged users, but only in the
8153 // context of processes which they own.
8154 emit_process_owner_assertion (o);
8155}
8156
8157
888af770 8158struct uprobe_builder: public derived_probe_builder
a96d1db0 8159{
888af770 8160 uprobe_builder() {}
2b69faaf 8161 virtual void build(systemtap_session & sess,
a96d1db0
DN
8162 probe * base,
8163 probe_point * location,
86bf665e 8164 literal_map_t const & parameters,
a96d1db0
DN
8165 vector<derived_probe *> & finished_results)
8166 {
888af770 8167 int64_t process, address;
a96d1db0 8168
2b69faaf 8169 if (kernel_supports_inode_uprobes(sess))
dc09353a 8170 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 8171
888af770 8172 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 8173 (void) b1;
888af770 8174 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 8175 (void) b2;
888af770
FCE
8176 bool rr = has_null_param (parameters, TOK_RETURN);
8177 assert (b1 && b2); // by pattern_root construction
a96d1db0 8178
0973d815 8179 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
8180 }
8181};
8182
8183
8184void
cfcab6c7 8185uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 8186{
43241c44
FCE
8187 // We'll probably need at least this many:
8188 unsigned minuprobes = probes.size();
8189 // .. but we don't want so many that .bss is inflated (PR10507):
8190 unsigned uprobesize = 64;
8191 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
8192 unsigned maxuprobes = maxuprobesmem / uprobesize;
8193
aaf7ffe8
FCE
8194 // Let's choose a value on the geometric middle. This should end up
8195 // between minuprobes and maxuprobes. It's OK if this number turns
8196 // out to be < minuprobes or > maxuprobes. At worst, we get a
8197 // run-time error of one kind (too few: missed uprobe registrations)
8198 // or another (too many: vmalloc errors at module load time).
8199 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 8200
6d0f3f0c 8201 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 8202 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 8203 s.op->newline() << "#endif";
cfcab6c7
JS
8204}
8205
8206
8207void
8208uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
8209{
8210 if (probes.empty()) return;
8211 s.op->newline() << "/* ---- utrace uprobes ---- */";
8212 // If uprobes isn't in the kernel, pull it in from the runtime.
8213
8214 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
8215 s.op->newline() << "#include <linux/uprobes.h>";
8216 s.op->newline() << "#else";
2ba1736a 8217 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
8218 s.op->newline() << "#endif";
8219 s.op->newline() << "#ifndef UPROBES_API_VERSION";
8220 s.op->newline() << "#define UPROBES_API_VERSION 1";
8221 s.op->newline() << "#endif";
8222
8223 emit_module_maxuprobes (s);
a96d1db0 8224
cc52276b 8225 // Forward decls
2ba1736a 8226 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 8227
5e112f92
FCE
8228 // In .bss, the shared pool of uprobe/uretprobe structs. These are
8229 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
8230 // XXX: consider a slab cache or somesuch for stap_uprobes
8231 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 8232 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 8233
89ba3085
FCE
8234 s.op->assert_0_indent();
8235
89ba3085
FCE
8236 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
8237 // This means we process probes[] in two passes.
8238 map <string,unsigned> module_index;
8239 unsigned module_index_ctr = 0;
8240
cc52276b
WC
8241 // not const since embedded task_finder_target struct changes
8242 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
8243 s.op->indent(1);
8244 for (unsigned i=0; i<probes.size(); i++)
8245 {
8246 uprobe_derived_probe *p = probes[i];
8247 string pbmkey = make_pbm_key (p);
8248 if (module_index.find (pbmkey) == module_index.end())
8249 {
8250 module_index[pbmkey] = module_index_ctr++;
8251
8252 s.op->newline() << "{";
8253 // NB: it's essential that make_pbm_key() use all of and
8254 // only the same fields as we're about to emit.
8255 s.op->line() << " .finder={";
1af100fc 8256 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 8257 if (p->pid != 0)
68910c97
JK
8258 s.op->line() << " .pid=" << p->pid << ",";
8259
8260 if (p->section == "") // .statement(addr).absolute
8261 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
8262 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8263 {
8264 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8265 s.op->line() << " .callback=&stap_uprobe_process_found,";
8266 }
68910c97 8267 else if (p->section != ".absolute") // ET_DYN
89ba3085 8268 {
4ad95bbc
SC
8269 if (p->has_library)
8270 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
8271 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
8272 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 8273 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 8274 }
89ba3085 8275 s.op->line() << " },";
68910c97
JK
8276 if (p->module != "")
8277 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
8278 s.op->line() << " },";
8279 }
c57ea854 8280 else
822a6a3d 8281 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
8282 }
8283 s.op->newline(-1) << "};";
8284
8285 s.op->assert_0_indent();
8286
3689db05
SC
8287 unsigned pci;
8288 for (pci=0; pci<probes.size(); pci++)
8289 {
8290 // List of perf counters used by each probe
8291 // This list is an index into struct stap_perf_probe,
8292 uprobe_derived_probe *p = probes[pci];
698de6cc 8293 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8294 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8295 for (pcii = p->perf_counter_refs.begin();
8296 pcii != p->perf_counter_refs.end(); pcii++)
8297 {
8298 map<string, pair<string,derived_probe*> >::iterator it;
8299 unsigned i = 0;
8300 // Find the associated perf.counter probe
8301 for (it=s.perf_counters.begin() ;
8302 it != s.perf_counters.end(); it++, i++)
8303 if ((*it).second.second == (*pcii))
8304 break;
8305 s.op->line() << lex_cast(i) << ", ";
8306 }
8307 s.op->newline() << "};";
8308 }
8309
cc52276b
WC
8310 // NB: read-only structure
8311 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 8312 s.op->indent(1);
888af770
FCE
8313 for (unsigned i =0; i<probes.size(); i++)
8314 {
8315 uprobe_derived_probe* p = probes[i];
8316 s.op->newline() << "{";
89ba3085
FCE
8317 string key = make_pbm_key (p);
8318 unsigned value = module_index[key];
759e1d76
FCE
8319 if (value != 0)
8320 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 8321 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 8322 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 8323
038c38c6 8324 if (p->sdt_semaphore_addr != 0)
63b4fd14 8325 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 8326 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 8327
0d049a1d 8328 // XXX: don't bother emit if array is empty
3689db05
SC
8329 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8330 // List of perf counters used by a probe from above
0d049a1d 8331 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 8332
4ddb6dd0
JS
8333 if (p->has_return)
8334 s.op->line() << " .return_p=1,";
888af770
FCE
8335 s.op->line() << " },";
8336 }
8337 s.op->newline(-1) << "};";
a96d1db0 8338
89ba3085
FCE
8339 s.op->assert_0_indent();
8340
48e685da 8341 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 8342 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 8343 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8344 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8345 "stp_probe_type_uprobe");
0e090c74 8346 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
8347 << "sup->spec_index >= " << probes.size() << ") {";
8348 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8349 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
8350 s.op->newline() << "goto probe_epilogue;";
8351 s.op->newline(-1) << "}";
d9aed31e 8352 s.op->newline() << "c->uregs = regs;";
e04b5d74 8353 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8354
8355 // Make it look like the IP is set as it would in the actual user
8356 // task when calling real probe handler. Reset IP regs on return, so
8357 // we don't confuse uprobes. PR10458
8358 s.op->newline() << "{";
8359 s.op->indent(1);
d9aed31e 8360 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 8361 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 8362 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8363 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8364 s.op->newline(-1) << "}";
8365
f887a8c9 8366 common_probe_entryfn_epilogue (s, true);
888af770 8367 s.op->newline(-1) << "}";
a96d1db0 8368
48e685da 8369 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 8370 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 8371 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8372 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8373 "stp_probe_type_uretprobe");
6dceb5c9 8374 s.op->newline() << "c->ips.ri = inst;";
0e090c74 8375 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
8376 << "sup->spec_index >= " << probes.size() << ") {";
8377 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8378 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
8379 s.op->newline() << "goto probe_epilogue;";
8380 s.op->newline(-1) << "}";
8381
d9aed31e 8382 s.op->newline() << "c->uregs = regs;";
e04b5d74 8383 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8384
8385 // Make it look like the IP is set as it would in the actual user
8386 // task when calling real probe handler. Reset IP regs on return, so
8387 // we don't confuse uprobes. PR10458
8388 s.op->newline() << "{";
8389 s.op->indent(1);
d9aed31e 8390 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 8391 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 8392 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8393 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8394 s.op->newline(-1) << "}";
8395
f887a8c9 8396 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
8397 s.op->newline(-1) << "}";
8398
89ba3085 8399 s.op->newline();
2ba1736a 8400 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 8401 s.op->newline();
888af770 8402}
935447c8
DS
8403
8404
888af770 8405void
2b69faaf 8406uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 8407{
888af770 8408 if (probes.empty()) return;
935447c8 8409
2b69faaf 8410 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 8411
01b05e2e 8412 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
8413 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
8414 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
8415 // NB: we assume the rest of the struct (specificaly, sup->up) is
8416 // initialized to zero. This is so that we can use
8417 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
8418 s.op->newline(-1) << "}";
8419 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 8420
89ba3085
FCE
8421 // Set up the task_finders
8422 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
8423 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 8424 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 8425 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 8426
5e112f92
FCE
8427 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
8428 // finders already registered, since mere registration does not
8429 // cause any utrace or memory allocation actions. That happens only
8430 // later, once the task finder engine starts running. So, for a
8431 // partial initialization requiring unwind, we need do nothing.
8432 s.op->newline() << "if (rc) break;";
a7a68293 8433
888af770
FCE
8434 s.op->newline(-1) << "}";
8435}
d0ea46ce 8436
d0a7f5a9 8437
888af770 8438void
2b69faaf 8439uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
8440{
8441 if (probes.empty()) return;
2b69faaf 8442 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 8443
6d0f3f0c
FCE
8444 // NB: there is no stap_unregister_task_finder_target call;
8445 // important stuff like utrace cleanups are done by
d41d451c
FCE
8446 // __stp_task_finder_cleanup() via stap_stop_task_finder().
8447 //
8448 // This function blocks until all callbacks are completed, so there
8449 // is supposed to be no possibility of any registration-related code starting
8450 // to run in parallel with our shutdown here. So we don't need to protect the
8451 // stap_uprobes[] array with the mutex.
d0a7f5a9 8452
01b05e2e 8453 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 8454 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 8455 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 8456 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 8457
8faa1fc5 8458 // PR10655: decrement that ENABLED semaphore
c116c31b 8459 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
8460 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
8461 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
8462 s.op->newline() << "struct task_struct *tsk;";
8463 s.op->newline() << "rcu_read_lock();";
6846cfc8 8464
86229a55
DS
8465 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
8466 // that the pid is always in the global namespace, not in any
8467 // private namespace.
8faa1fc5 8468 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
8469 // We'd like to call find_task_by_pid_ns() here, but it isn't
8470 // exported. So, we call what it calls...
8471 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
8472 s.op->newline() << "#else";
8473 s.op->newline() << " tsk = find_task_by_pid (pid);";
8474 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
8475
8476 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 8477 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 8478 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 8479 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 8480 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 8481 s.op->newline() << "#endif";
3c5b8e2b 8482 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 8483 s.op->newline(-1) << "}";
8faa1fc5
FCE
8484 // XXX: need to analyze possibility of race condition
8485 s.op->newline(-1) << "}";
8486 s.op->newline() << "rcu_read_unlock();";
8487 s.op->newline(-1) << "}";
6846cfc8 8488
3568f1dd
FCE
8489 s.op->newline() << "if (sups->return_p) {";
8490 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 8491 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 8492 s.op->newline() << "#endif";
80b4ad8b
FCE
8493 // NB: PR6829 does not change that we still need to unregister at
8494 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
8495 s.op->newline() << "unregister_uretprobe (& sup->urp);";
8496 s.op->newline(-1) << "} else {";
8497 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 8498 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
8499 s.op->newline() << "#endif";
8500 s.op->newline() << "unregister_uprobe (& sup->up);";
8501 s.op->newline(-1) << "}";
935447c8 8502
6d0f3f0c 8503 s.op->newline() << "sup->spec_index = -1;";
935447c8 8504
3568f1dd
FCE
8505 // XXX: uprobe missed counts?
8506
6d0f3f0c 8507 s.op->newline(-1) << "}";
935447c8 8508
5e112f92 8509 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8510}
8511
2b69faaf
JS
8512
8513void
8514uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8515{
8516 if (probes.empty()) return;
8517 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8518 emit_module_maxuprobes (s);
2ba1736a 8519 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8520
8521 // Write the probe handler.
79af55c3
JS
8522 s.op->newline() << "static int stapiu_probe_handler "
8523 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8524 s.op->newline(1);
2dbbd473
JS
8525
8526 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8527 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8528 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8529 probe_type);
8530
3bff6634 8531 s.op->newline() << "c->uregs = regs;";
e04b5d74 8532 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8533 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8534 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8535
f887a8c9 8536 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8537 s.op->newline() << "return 0;";
8538 s.op->newline(-1) << "}";
8539 s.op->assert_0_indent();
8540
8541 // Index of all the modules for which we need inodes.
8542 map<string, unsigned> module_index;
8543 unsigned module_index_ctr = 0;
8544
8545 // Discover and declare targets for each unique path.
cfcab6c7 8546 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8547 << "stap_inode_uprobe_targets[] = {";
8548 s.op->indent(1);
8549 for (unsigned i=0; i<probes.size(); i++)
8550 {
8551 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8552 const string key = make_pbm_key(p);
8553 if (module_index.find (key) == module_index.end())
2b69faaf 8554 {
cfcab6c7
JS
8555 module_index[key] = module_index_ctr++;
8556 s.op->newline() << "{";
8557 s.op->line() << " .finder={";
b78a0fbb 8558 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8559 if (p->pid != 0)
8560 s.op->line() << " .pid=" << p->pid << ",";
8561
8562 if (p->section == "") // .statement(addr).absolute XXX?
8563 s.op->line() << " .callback=&stapiu_process_found,";
8564 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8565 {
8566 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8567 s.op->line() << " .callback=&stapiu_process_found,";
8568 }
8569 else if (p->section != ".absolute") // ET_DYN
8570 {
8571 if (p->has_library)
8572 s.op->line() << " .procname=\"" << p->path << "\", ";
8573 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8574 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8575 s.op->line() << " .callback=&stapiu_process_munmap,";
8576 }
8577 s.op->line() << " },";
8578 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8579 s.op->line() << " },";
2b69faaf
JS
8580 }
8581 }
8582 s.op->newline(-1) << "};";
8583 s.op->assert_0_indent();
8584
8585 // Declare the actual probes.
3689db05
SC
8586 unsigned pci;
8587 for (pci=0; pci<probes.size(); pci++)
8588 {
8589 // List of perf counters used by each probe
8590 // This list is an index into struct stap_perf_probe,
8591 uprobe_derived_probe *p = probes[pci];
698de6cc 8592 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8593 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8594 for (pcii = p->perf_counter_refs.begin();
8595 pcii != p->perf_counter_refs.end(); pcii++)
8596 {
8597 map<string, pair<string,derived_probe*> >::iterator it;
8598 unsigned i = 0;
8599 // Find the associated perf.counter probe
4fa83377
SC
8600 for (it=s.perf_counters.begin() ;
8601 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8602 if ((*it).second.second == (*pcii))
8603 break;
8604 s.op->line() << lex_cast(i) << ", ";
8605 }
8606 s.op->newline() << "};";
8607 }
8608
cfcab6c7 8609 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8610 << "stap_inode_uprobe_consumers[] = {";
8611 s.op->indent(1);
8612 for (unsigned i=0; i<probes.size(); i++)
8613 {
8614 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8615 unsigned index = module_index[make_pbm_key(p)];
8616 s.op->newline() << "{";
79af55c3
JS
8617 if (p->has_return)
8618 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8619 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8620 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8621 if (p->sdt_semaphore_addr)
8622 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8623 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8624 // XXX: don't bother emit if array is empty
3689db05
SC
8625 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8626 // List of perf counters used by a probe from above
0d049a1d 8627 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8628 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8629 s.op->line() << " },";
2b69faaf
JS
8630 }
8631 s.op->newline(-1) << "};";
8632 s.op->assert_0_indent();
8633}
8634
8635
8636void
8637uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8638{
8639 if (probes.empty()) return;
8640 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8641 // Let stapiu_init() handle reporting errors by setting probe_point
8642 // to NULL.
8643 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8644 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8645 << "stap_inode_uprobe_targets, "
8646 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8647 << "stap_inode_uprobe_consumers, "
8648 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8649}
8650
8651
8652void
8653uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8654{
8655 if (probes.empty()) return;
8656 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8657 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8658 << "stap_inode_uprobe_targets, "
8659 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8660 << "stap_inode_uprobe_consumers, "
8661 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8662}
8663
8664
3a894f7e
JS
8665void
8666uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8667{
8668 if (probes.empty()) return;
8669 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8670 emit_module_maxuprobes (s);
e00f3fb7 8671 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8672
f31a77f5
DS
8673 // Let the dynprobe_derived_probe_group handle outputting targets
8674 // and probes. This allows us to merge different types of probes.
8675 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8676 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8677 {
8678 uprobe_derived_probe *p = probes[i];
e00f3fb7 8679
f31a77f5
DS
8680 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8681 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8682 common_probe_init(p));
3a894f7e 8683 }
874d38bf
JS
8684 // loc2c-generated code assumes pt_regs are available, so use this to make
8685 // sure we always have *something* for it to dereference...
f31a77f5 8686 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8687
3a894f7e
JS
8688 // Write the probe handler.
8689 // NB: not static, so dyninst can find it
8690 s.op->newline() << "int enter_dyninst_uprobe "
8691 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8692 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8693
8694 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8695 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8696 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8697 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8698 probe_type);
8699
874d38bf 8700 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8701 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8702 // XXX: once we have regs, check how dyninst sets the IP
8703 // XXX: the way that dyninst rewrites stuff is probably going to be
8704 // ... very confusing to our backtracer (at least if we stay in process)
8705 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8706 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8707 s.op->newline() << "return 0;";
8708 s.op->newline(-1) << "}";
3debb935 8709 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8710 s.op->assert_0_indent();
8711}
8712
8713
8714void
8715uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8716{
8717 if (probes.empty()) return;
8718
8719 /* stapdyn handles the dirty work via dyninst */
8720 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8721 s.op->newline() << "/* this section left intentionally blank */";
8722}
8723
8724
8725void
8726uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8727{
8728 if (probes.empty()) return;
8729
8730 /* stapdyn handles the dirty work via dyninst */
8731 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8732 s.op->newline() << "/* this section left intentionally blank */";
8733}
8734
8735
2b69faaf
JS
8736void
8737uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8738{
ac3af990 8739 if (s.runtime_usermode_p())
4441e344
JS
8740 emit_module_dyninst_decls (s);
8741 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8742 emit_module_inode_decls (s);
8743 else
8744 emit_module_utrace_decls (s);
8745}
8746
8747
8748void
8749uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8750{
ac3af990 8751 if (s.runtime_usermode_p())
4441e344
JS
8752 emit_module_dyninst_init (s);
8753 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8754 emit_module_inode_init (s);
8755 else
8756 emit_module_utrace_init (s);
8757}
8758
8759
8760void
8761uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8762{
ac3af990 8763 if (s.runtime_usermode_p())
4441e344
JS
8764 emit_module_dyninst_exit (s);
8765 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8766 emit_module_inode_exit (s);
8767 else
8768 emit_module_utrace_exit (s);
8769}
8770
8771
e6fe60e7
AM
8772// ------------------------------------------------------------------------
8773// Kprobe derived probes
8774// ------------------------------------------------------------------------
8775
4627ed58 8776static const string TOK_KPROBE("kprobe");
935447c8 8777
bae55db9 8778struct kprobe_derived_probe: public derived_probe
d0ea46ce 8779{
23dc94f6
DS
8780 kprobe_derived_probe (systemtap_session& sess,
8781 vector<derived_probe *> & results,
8782 probe *base,
bae55db9
JS
8783 probe_point *location,
8784 const string& name,
8785 int64_t stmt_addr,
8786 bool has_return,
8787 bool has_statement,
8788 bool has_maxactive,
b642c901
SC
8789 bool has_path,
8790 bool has_library,
8791 long maxactive_val,
8792 const string& path,
8793 const string& library
bae55db9
JS
8794 );
8795 string symbol_name;
8796 Dwarf_Addr addr;
8797 bool has_return;
8798 bool has_statement;
8799 bool has_maxactive;
b642c901
SC
8800 bool has_path;
8801 bool has_library;
bae55db9 8802 long maxactive_val;
b642c901
SC
8803 string path;
8804 string library;
bae55db9
JS
8805 bool access_var;
8806 void printsig (std::ostream &o) const;
8807 void join_group (systemtap_session& s);
8808};
d0ea46ce 8809
bae55db9
JS
8810struct kprobe_derived_probe_group: public derived_probe_group
8811{
8812private:
8813 multimap<string,kprobe_derived_probe*> probes_by_module;
8814 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8815
bae55db9
JS
8816public:
8817 void enroll (kprobe_derived_probe* probe);
8818 void emit_module_decls (systemtap_session& s);
8819 void emit_module_init (systemtap_session& s);
8820 void emit_module_exit (systemtap_session& s);
8821};
d0ea46ce 8822
23dc94f6
DS
8823struct kprobe_var_expanding_visitor: public var_expanding_visitor
8824{
8825 systemtap_session& sess;
8826 block *add_block;
8827 block *add_call_probe; // synthesized from .return probes with saved $vars
8828 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8829 bool has_return;
23dc94f6 8830
bd5b25e1 8831 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8832 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8833 add_block_tid(false), add_call_probe_tid(false),
8834 has_return(has_return) {}
23dc94f6
DS
8835
8836 void visit_entry_op (entry_op* e);
8837};
8838
8839
8840kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8841 vector<derived_probe *> & results,
8842 probe *base,
e6fe60e7 8843 probe_point *location,
b6371390 8844 const string& name,
e6fe60e7 8845 int64_t stmt_addr,
b6371390
JS
8846 bool has_return,
8847 bool has_statement,
8848 bool has_maxactive,
b642c901
SC
8849 bool has_path,
8850 bool has_library,
8851 long maxactive_val,
8852 const string& path,
8853 const string& library
b6371390 8854 ):
4c5d1300 8855 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 8856 symbol_name (name), addr (stmt_addr),
b6371390 8857 has_return (has_return), has_statement (has_statement),
b642c901
SC
8858 has_maxactive (has_maxactive), has_path (has_path),
8859 has_library (has_library),
8860 maxactive_val (maxactive_val),
8861 path (path), library (library)
e6fe60e7
AM
8862{
8863 this->tok = base->tok;
8864 this->access_var = false;
d0ea46ce 8865
e6fe60e7
AM
8866#ifndef USHRT_MAX
8867#define USHRT_MAX 32767
8868#endif
d0ea46ce 8869
46856d8d
JS
8870 // Expansion of $target variables in the probe body produces an error during
8871 // translate phase, since we're not using debuginfo
d0ea46ce 8872
e6fe60e7 8873 vector<probe_point::component*> comps;
46856d8d 8874 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8875
46856d8d
JS
8876 if (has_statement)
8877 {
9ea68eb9
JS
8878 comps.push_back (new probe_point::component(TOK_STATEMENT,
8879 new literal_number(addr, true)));
46856d8d
JS
8880 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8881 }
8882 else
8883 {
8884 size_t pos = name.find(':');
8885 if (pos != string::npos)
d0ea46ce 8886 {
46856d8d
JS
8887 string module = name.substr(0, pos);
8888 string function = name.substr(pos + 1);
8889 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8890 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8891 }
8892 else
8893 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8894 }
d0ea46ce 8895
b6371390
JS
8896 if (has_return)
8897 comps.push_back (new probe_point::component(TOK_RETURN));
8898 if (has_maxactive)
8899 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8900
bd5b25e1 8901 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8902 v.replace (this->body);
8903
8904 // If during target-variable-expanding the probe, we added a new block
8905 // of code, add it to the start of the probe.
8906 if (v.add_block)
8907 this->body = new block(v.add_block, this->body);
8908
8909 // If when target-variable-expanding the probe, we need to
8910 // synthesize a sibling function-entry probe. We don't go through
8911 // the whole probe derivation business (PR10642) that could lead to
8912 // wildcard/alias resolution, or for that dwarf-induced duplication.
8913 if (v.add_call_probe)
8914 {
8915 assert (has_return);
8916
8917 // We temporarily replace base.
8918 statement* old_body = base->body;
8919 base->body = v.add_call_probe;
8920
8921 derived_probe *entry_handler
8922 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8923 false, has_statement, has_maxactive,
8924 has_path, has_library, maxactive_val,
8925 path, library);
8926 results.push_back (entry_handler);
8927
8928 base->body = old_body;
8929 }
8930
e6fe60e7
AM
8931 this->sole_location()->components = comps;
8932}
d0ea46ce 8933
e6fe60e7
AM
8934void kprobe_derived_probe::printsig (ostream& o) const
8935{
8936 sole_location()->print (o);
8937 o << " /* " << " name = " << symbol_name << "*/";
8938 printsig_nested (o);
8939}
d0ea46ce 8940
e6fe60e7
AM
8941void kprobe_derived_probe::join_group (systemtap_session& s)
8942{
d0ea46ce 8943
e6fe60e7
AM
8944 if (! s.kprobe_derived_probes)
8945 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8946 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8947
e6fe60e7 8948}
d0ea46ce 8949
e6fe60e7
AM
8950void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8951{
8952 probes_by_module.insert (make_pair (p->symbol_name, p));
8953 // probes of same symbol should share single kprobe/kretprobe
8954}
d0ea46ce 8955
e6fe60e7
AM
8956void
8957kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8958{
8959 if (probes_by_module.empty()) return;
d0ea46ce 8960
e6fe60e7 8961 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8962
e6fe60e7
AM
8963 // Warn of misconfigured kernels
8964 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8965 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8966 s.op->newline() << "#endif";
8967 s.op->newline();
d0ea46ce 8968
f07c3b68 8969 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8970 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8971 s.op->newline() << "#endif";
8972
e6fe60e7 8973 // Forward declare the master entry functions
88747011 8974 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8975 s.op->line() << " struct pt_regs *regs);";
88747011 8976 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8977 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8978
e6fe60e7
AM
8979 // Emit an array of kprobe/kretprobe pointers
8980 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8981 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8982 s.op->newline() << "#endif";
d0ea46ce 8983
e6fe60e7 8984 // Emit the actual probe list.
d0ea46ce 8985
e6fe60e7
AM
8986 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8987 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8988 s.op->newline() << "#ifdef __ia64__";
8989 s.op->newline() << "struct kprobe dummy;";
8990 s.op->newline() << "#endif";
8991 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8992 // NB: bss!
d0ea46ce 8993
e6fe60e7
AM
8994 s.op->newline() << "static struct stap_dwarfless_probe {";
8995 s.op->newline(1) << "const unsigned return_p:1;";
8996 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8997 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8998 s.op->newline() << "unsigned registered_p:1;";
8999 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 9000
e6fe60e7
AM
9001 // Function Names are mostly small and uniform enough to justify putting
9002 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 9003
faea5e16
JS
9004 size_t symbol_string_name_max = 0;
9005 size_t symbol_string_name_tot = 0;
e6fe60e7 9006 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 9007 {
e6fe60e7
AM
9008 kprobe_derived_probe* p = it->second;
9009#define DOIT(var,expr) do { \
9010 size_t var##_size = (expr) + 1; \
9011 var##_max = max (var##_max, var##_size); \
9012 var##_tot += var##_size; } while (0)
e6fe60e7
AM
9013 DOIT(symbol_string_name, p->symbol_name.size());
9014#undef DOIT
6270adc1
MH
9015 }
9016
e6fe60e7
AM
9017#define CALCIT(var) \
9018 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 9019
e6fe60e7
AM
9020 CALCIT(symbol_string);
9021#undef CALCIT
6270adc1 9022
bd659351 9023 s.op->newline() << "unsigned long address;";
7c3e97f4 9024 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
9025 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
9026 s.op->indent(1);
6270adc1 9027
e6fe60e7
AM
9028 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
9029 {
9030 kprobe_derived_probe* p = it->second;
9031 s.op->newline() << "{";
9032 if (p->has_return)
9033 s.op->line() << " .return_p=1,";
6270adc1 9034
e6fe60e7
AM
9035 if (p->has_maxactive)
9036 {
9037 s.op->line() << " .maxactive_p=1,";
9038 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
9039 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
9040 }
6270adc1 9041
b350f56b
JS
9042 if (p->locations[0]->optional)
9043 s.op->line() << " .optional_p=1,";
9044
e6fe60e7 9045 if (p->has_statement)
c8d9d15e 9046 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 9047 else
c8d9d15e 9048 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 9049
faea5e16 9050 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 9051 s.op->line() << " },";
935447c8
DS
9052 }
9053
e6fe60e7 9054 s.op->newline(-1) << "};";
5d67b47c 9055
e6fe60e7
AM
9056 // Emit the kprobes callback function
9057 s.op->newline();
88747011 9058 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
9059 s.op->line() << " struct pt_regs *regs) {";
9060 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9061 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9062 // Check that the index is plausible
9063 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9064 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9065 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9066 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9067 s.op->line() << "];";
71db462b 9068 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9069 "stp_probe_type_kprobe");
d9aed31e 9070 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
9071
9072 // Make it look like the IP is set as it wouldn't have been replaced
9073 // by a breakpoint instruction when calling real probe handler. Reset
9074 // IP regs on return, so we don't confuse kprobes. PR10458
9075 s.op->newline() << "{";
9076 s.op->indent(1);
d9aed31e 9077 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9078 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 9079 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9080 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9081 s.op->newline(-1) << "}";
9082
f887a8c9 9083 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9084 s.op->newline() << "return 0;";
9085 s.op->newline(-1) << "}";
935447c8 9086
e6fe60e7
AM
9087 // Same for kretprobes
9088 s.op->newline();
88747011 9089 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
9090 s.op->line() << " struct pt_regs *regs) {";
9091 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 9092
e6fe60e7
AM
9093 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9094 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9095 // Check that the index is plausible
9096 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9097 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9098 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9099 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9100 s.op->line() << "];";
935447c8 9101
71db462b 9102 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9103 "stp_probe_type_kretprobe");
d9aed31e 9104 s.op->newline() << "c->kregs = regs;";
6dceb5c9 9105 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
9106
9107 // Make it look like the IP is set as it wouldn't have been replaced
9108 // by a breakpoint instruction when calling real probe handler. Reset
9109 // IP regs on return, so we don't confuse kprobes. PR10458
9110 s.op->newline() << "{";
9111 s.op->indent(1);
d9aed31e 9112 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9113 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 9114 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9115 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9116 s.op->newline(-1) << "}";
9117
f887a8c9 9118 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9119 s.op->newline() << "return 0;";
9120 s.op->newline(-1) << "}";
bd659351 9121
03a4ec63 9122 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9123 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
9124 s.op->newline() << " struct module *owner,";
9125 s.op->newline() << " unsigned long val) {";
9126 s.op->newline(1) << "int i;";
fc1d2aa2
MW
9127 s.op->newline() << "int *p = (int *) data;";
9128 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
9129 << " && *p > 0; i++) {";
bd659351 9130 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
9131 s.op->newline() << "if (! sdp->address) {";
9132 s.op->indent(1);
9133 s.op->newline() << "const char *colon;";
9134 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
9135 s.op->indent(1);
9136 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
9137 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
9138 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
9139 s.op->newline(1) << "sdp->address = val;";
9140 s.op->newline() << "(*p)--;";
9141 s.op->newline(-1) << "}";
9142 s.op->newline(-1) << "}";
9143 s.op->newline() << "else {";
fc1d2aa2 9144 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 9145 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
9146 s.op->newline() << "(*p)--;";
9147 s.op->newline(-1) << "}";
8c272819
YW
9148 s.op->newline(-1) << "}";
9149 s.op->newline(-1) << "}";
9150 s.op->newline(-1) << "}";
fc1d2aa2 9151 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 9152 s.op->newline(-1) << "}";
03a4ec63 9153 s.op->newline() << "#endif";
935447c8
DS
9154}
9155
e6fe60e7 9156
6270adc1 9157void
e6fe60e7 9158kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 9159{
03a4ec63 9160 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
9161 s.op->newline() << "{";
9162 s.op->newline(1) << "int p = 0;";
9163 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
9164 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9165 s.op->newline() << "if (! sdp->address)";
9166 s.op->newline(1) << "p++;";
9167 s.op->newline(-2) << "}";
9168 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
9169 s.op->newline(-1) << "}";
03a4ec63 9170 s.op->newline() << "#endif";
bd659351 9171
e6fe60e7 9172 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 9173 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 9174 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 9175 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
9176 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
9177
9178 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9179 s.op->newline() << "if (! addr) {";
9180 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
9181 s.op->newline() << "if (!sdp->optional_p)";
9182 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
9183 s.op->newline(-1) << "continue;";
bd659351 9184 s.op->newline(-1) << "}";
03a4ec63
MW
9185 s.op->newline() << "#endif";
9186
26e63673 9187 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 9188 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 9189 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 9190 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9191 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 9192 s.op->newline() << "#endif";
e6fe60e7
AM
9193 s.op->newline() << "if (sdp->maxactive_p) {";
9194 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
9195 s.op->newline(-1) << "} else {";
f07c3b68 9196 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 9197 s.op->newline(-1) << "}";
88747011 9198 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
9199 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
9200 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9201 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 9202 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9203 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 9204 s.op->newline() << "#endif";
c8d9d15e 9205 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
9206 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9207 s.op->newline() << "if (rc == 0) {";
9208 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
9209 s.op->newline() << "if (rc != 0)";
9210 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9211 s.op->newline(-2) << "}";
9212 s.op->newline() << "#else";
9213 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
9214 s.op->newline() << "#endif";
9215 s.op->newline(-1) << "} else {";
9216 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 9217 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 9218 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9219 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 9220 s.op->newline() << "#endif";
88747011 9221 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 9222 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9223 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 9224 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 9225 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9226 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 9227 s.op->newline() << "#endif";
e6fe60e7
AM
9228 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9229 s.op->newline() << "if (rc == 0) {";
9230 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
9231 s.op->newline() << "if (rc != 0)";
9232 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9233 s.op->newline(-2) << "}";
9234 s.op->newline() << "#else";
9235 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
9236 s.op->newline() << "#endif";
9237 s.op->newline(-1) << "}";
9238 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
9239 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 9240 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 9241 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 9242 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
9243 // XXX: shall we increment numskipped?
9244 s.op->newline(-1) << "}";
6270adc1 9245
e6fe60e7
AM
9246 s.op->newline() << "else sdp->registered_p = 1;";
9247 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
9248}
9249
b4be7cbc 9250
e6fe60e7
AM
9251void
9252kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 9253{
e6fe60e7
AM
9254 //Unregister kprobes by batch interfaces.
9255 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
9256 s.op->newline() << "j = 0;";
9257 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9258 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9259 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9260 s.op->newline() << "if (! sdp->registered_p) continue;";
9261 s.op->newline() << "if (!sdp->return_p)";
c9116e99 9262 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 9263 s.op->newline(-2) << "}";
c9116e99 9264 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9265 s.op->newline() << "j = 0;";
9266 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9267 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9268 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9269 s.op->newline() << "if (! sdp->registered_p) continue;";
9270 s.op->newline() << "if (sdp->return_p)";
c9116e99 9271 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 9272 s.op->newline(-2) << "}";
c9116e99 9273 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9274 s.op->newline() << "#ifdef __ia64__";
9275 s.op->newline() << "j = 0;";
9276 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9277 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9278 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9279 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 9280 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 9281 s.op->newline(-1) << "}";
c9116e99 9282 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9283 s.op->newline() << "#endif";
9284 s.op->newline() << "#endif";
3e3bd7b6 9285
e6fe60e7
AM
9286 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9287 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9288 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9289 s.op->newline() << "if (! sdp->registered_p) continue;";
9290 s.op->newline() << "if (sdp->return_p) {";
9291 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9292 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
9293 s.op->newline() << "#endif";
065d5567 9294 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
9295 s.op->newline() << "#ifdef STP_TIMING";
9296 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 9297 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 9298 s.op->newline(-1) << "#endif";
065d5567 9299 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
9300 s.op->newline() << "#ifdef STP_TIMING";
9301 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 9302 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
9303 s.op->newline(-1) << "#endif";
9304 s.op->newline(-1) << "} else {";
9305 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9306 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
9307 s.op->newline() << "#endif";
065d5567 9308 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
9309 s.op->newline() << "#ifdef STP_TIMING";
9310 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 9311 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
9312 s.op->newline(-1) << "#endif";
9313 s.op->newline(-1) << "}";
9314 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
9315 s.op->newline() << "unregister_kprobe (&kp->dummy);";
9316 s.op->newline() << "#endif";
9317 s.op->newline() << "sdp->registered_p = 0;";
9318 s.op->newline(-1) << "}";
f8a968bc
JS
9319}
9320
e6fe60e7 9321struct kprobe_builder: public derived_probe_builder
3c1b3d06 9322{
9fdf787d 9323public:
2a639817 9324 kprobe_builder() {}
9fdf787d 9325
2a639817 9326 void build_no_more (systemtap_session &s) {}
9fdf787d 9327
e6fe60e7
AM
9328 virtual void build(systemtap_session & sess,
9329 probe * base,
9330 probe_point * location,
9331 literal_map_t const & parameters,
9332 vector<derived_probe *> & finished_results);
9333};
3c1b3d06
FCE
9334
9335
79189b84 9336void
05fb3e0c 9337kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
9338 probe * base,
9339 probe_point * location,
9340 literal_map_t const & parameters,
9341 vector<derived_probe *> & finished_results)
79189b84 9342{
e6fe60e7 9343 string function_string_val, module_string_val;
05fb3e0c 9344 string path, library, path_tgt, library_tgt;
b6371390
JS
9345 int64_t statement_num_val = 0, maxactive_val = 0;
9346 bool has_function_str, has_module_str, has_statement_num;
9347 bool has_absolute, has_return, has_maxactive;
b642c901 9348 bool has_path, has_library;
79189b84 9349
b6371390
JS
9350 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
9351 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
9352 has_return = has_null_param (parameters, TOK_RETURN);
9353 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
9354 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
9355 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
9356 has_path = get_param (parameters, TOK_PROCESS, path);
9357 has_library = get_param (parameters, TOK_LIBRARY, library);
9358
9359 if (has_path)
05fb3e0c
WF
9360 {
9361 path = find_executable (path, sess.sysroot, sess.sysenv);
9362 path_tgt = path_remove_sysroot(sess, path);
9363 }
b642c901 9364 if (has_library)
05fb3e0c
WF
9365 {
9366 library = find_executable (library, sess.sysroot, sess.sysenv,
9367 "LD_LIBRARY_PATH");
9368 library_tgt = path_remove_sysroot(sess, library);
9369 }
c57ea854 9370
b6371390 9371 if (has_function_str)
6fb70fb7 9372 {
2a639817 9373 if (has_module_str)
9fdf787d
DS
9374 {
9375 function_string_val = module_string_val + ":" + function_string_val;
9376 derived_probe *dp
23dc94f6
DS
9377 = new kprobe_derived_probe (sess, finished_results, base,
9378 location, function_string_val,
9fdf787d
DS
9379 0, has_return, has_statement_num,
9380 has_maxactive, has_path, has_library,
9381 maxactive_val, path_tgt, library_tgt);
9382 finished_results.push_back (dp);
9383 }
9384 else
9385 {
2a639817
JS
9386 vector<string> matches;
9387
9388 // Simple names can be found directly
9389 if (function_string_val.find_first_of("*?[") == string::npos)
9390 {
9391 if (sess.kernel_functions.count(function_string_val))
9392 matches.push_back(function_string_val);
9393 }
9394 else // Search function name list for matching names
9395 {
9396 for (set<string>::const_iterator it = sess.kernel_functions.begin();
9397 it != sess.kernel_functions.end(); it++)
9398 // fnmatch returns zero for matching.
9399 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
9400 matches.push_back(*it);
9401 }
86758d5f 9402
2a639817
JS
9403 for (vector<string>::const_iterator it = matches.begin();
9404 it != matches.end(); it++)
9fdf787d 9405 {
2a639817
JS
9406 derived_probe *dp
9407 = new kprobe_derived_probe (sess, finished_results, base,
9408 location, *it, 0, has_return,
9409 has_statement_num,
9410 has_maxactive, has_path,
9411 has_library, maxactive_val,
9412 path_tgt, library_tgt);
9413 finished_results.push_back (dp);
9fdf787d
DS
9414 }
9415 }
6fb70fb7 9416 }
e6fe60e7 9417 else
b6371390
JS
9418 {
9419 // assert guru mode for absolute probes
9420 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 9421 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 9422
23dc94f6
DS
9423 finished_results.push_back (new kprobe_derived_probe (sess,
9424 finished_results,
9425 base,
b6371390
JS
9426 location, "",
9427 statement_num_val,
9428 has_return,
9429 has_statement_num,
9430 has_maxactive,
b642c901
SC
9431 has_path,
9432 has_library,
9433 maxactive_val,
05fb3e0c
WF
9434 path_tgt,
9435 library_tgt));
96b030fe 9436 }
79189b84
JS
9437}
9438
23dc94f6
DS
9439
9440void
9441kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
9442{
9443 expression *repl = e;
9444
bd5b25e1
JS
9445 if (has_return)
9446 {
9447 // expand the operand as if it weren't a return probe
9448 has_return = false;
9449 replace (e->operand);
9450 has_return = true;
23dc94f6 9451
bd5b25e1
JS
9452 // XXX it would be nice to use gen_kretprobe_saved_return when
9453 // available, but it requires knowing the types already, which is
9454 // problematic for arbitrary expressons.
9455 repl = gen_mapped_saved_return (sess, e->operand, "entry",
9456 add_block, add_block_tid,
9457 add_call_probe, add_call_probe_tid);
9458 }
23dc94f6
DS
9459 provide (repl);
9460}
9461
9462
dd225250
PS
9463// ------------------------------------------------------------------------
9464// Hardware breakpoint based probes.
9465// ------------------------------------------------------------------------
9466
9467static const string TOK_HWBKPT("data");
9468static const string TOK_HWBKPT_WRITE("write");
9469static const string TOK_HWBKPT_RW("rw");
9470static const string TOK_LENGTH("length");
9471
9472#define HWBKPT_READ 0
9473#define HWBKPT_WRITE 1
9474#define HWBKPT_RW 2
9475struct hwbkpt_derived_probe: public derived_probe
9476{
9477 hwbkpt_derived_probe (probe *base,
9478 probe_point *location,
9479 uint64_t addr,
9480 string symname,
9481 unsigned int len,
9482 bool has_only_read_access,
9483 bool has_only_write_access,
9484 bool has_rw_access
9485 );
9486 Dwarf_Addr hwbkpt_addr;
9487 string symbol_name;
9488 unsigned int hwbkpt_access,hwbkpt_len;
9489
9490 void printsig (std::ostream &o) const;
9491 void join_group (systemtap_session& s);
9492};
9493
9494struct hwbkpt_derived_probe_group: public derived_probe_group
9495{
dd225250 9496private:
dac77b80 9497 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
9498
9499public:
9500 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
9501 void emit_module_decls (systemtap_session& s);
9502 void emit_module_init (systemtap_session& s);
9503 void emit_module_exit (systemtap_session& s);
9504};
9505
9506hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
9507 probe_point *location,
9508 uint64_t addr,
9509 string symname,
9510 unsigned int len,
9511 bool has_only_read_access,
9512 bool has_only_write_access,
822a6a3d 9513 bool):
4c5d1300 9514 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9515 hwbkpt_addr (addr),
9516 symbol_name (symname),
9517 hwbkpt_len (len)
9518{
9519 this->tok = base->tok;
9520
9521 vector<probe_point::component*> comps;
9522 comps.push_back (new probe_point::component(TOK_KERNEL));
9523
9524 if (hwbkpt_addr)
9ea68eb9
JS
9525 comps.push_back (new probe_point::component (TOK_HWBKPT,
9526 new literal_number(hwbkpt_addr, true)));
9527 else if (symbol_name.size())
9528 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9529
9530 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9531
9532 if (has_only_read_access)
9ea68eb9 9533 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9534//TODO add code for comps.push_back for read, since this flag is not for x86
9535
9536 else
9ea68eb9
JS
9537 {
9538 if (has_only_write_access)
9539 {
9540 this->hwbkpt_access = HWBKPT_WRITE ;
9541 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9542 }
9543 else
9544 {
9545 this->hwbkpt_access = HWBKPT_RW ;
9546 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9547 }
9548 }
dd225250
PS
9549
9550 this->sole_location()->components = comps;
9551}
9552
9553void hwbkpt_derived_probe::printsig (ostream& o) const
9554{
9555 sole_location()->print (o);
9556 printsig_nested (o);
9557}
9558
9559void hwbkpt_derived_probe::join_group (systemtap_session& s)
9560{
dac77b80
FCE
9561 if (! s.hwbkpt_derived_probes)
9562 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9563 s.hwbkpt_derived_probes->enroll (this, s);
9564}
9565
9566void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9567{
dac77b80
FCE
9568 hwbkpt_probes.push_back (p);
9569
9570 unsigned max_hwbkpt_probes_by_arch = 0;
9571 if (s.architecture == "i386" || s.architecture == "x86_64")
9572 max_hwbkpt_probes_by_arch = 4;
9573 else if (s.architecture == "s390")
9574 max_hwbkpt_probes_by_arch = 1;
9575
c57ea854 9576 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9577 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9578 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9579}
9580
9581void
9582hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9583{
dac77b80 9584 if (hwbkpt_probes.empty()) return;
dd225250
PS
9585
9586 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9587
9588 s.op->newline() << "#include <linux/perf_event.h>";
9589 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9590 s.op->newline();
9591
9592 // Forward declare the master entry functions
23063de1 9593 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9594 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9595 s.op->line() << " int nmi,";
9596 s.op->line() << " struct perf_sample_data *data,";
9597 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9598 s.op->newline() << "#else";
9599 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9600 s.op->line() << " struct perf_sample_data *data,";
9601 s.op->line() << " struct pt_regs *regs);";
9602 s.op->newline() << "#endif";
79189b84 9603
dd225250
PS
9604 // Emit the actual probe list.
9605
9606 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9607 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9608
9609 s.op->newline() << "static struct perf_event **";
dac77b80 9610 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9611 s.op->newline() << "static struct stap_hwbkpt_probe {";
9612 s.op->newline() << "int registered_p:1;";
43650b10 9613// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9614// registered_p = 1 signifies a probe that got registered successfully
9615
faea5e16 9616 // Symbol Names are mostly small and uniform enough
dd225250 9617 // to justify putting const char*.
dac77b80 9618 s.op->newline() << "const char * const symbol;";
dd225250
PS
9619
9620 s.op->newline() << "const unsigned long address;";
9621 s.op->newline() << "uint8_t atype;";
bb0a4e12 9622 s.op->newline() << "unsigned int len;";
7c3e97f4 9623 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9624 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9625 s.op->indent(1);
9626
dac77b80 9627 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9628 {
dac77b80 9629 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9630 s.op->newline() << "{";
dd225250
PS
9631 if (p->symbol_name.size())
9632 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9633 else
9634 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9635 switch(p->hwbkpt_access){
9636 case HWBKPT_READ:
9637 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9638 break;
dd225250
PS
9639 case HWBKPT_WRITE:
9640 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9641 break;
dd225250
PS
9642 case HWBKPT_RW:
9643 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9644 break;
dd225250
PS
9645 };
9646 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9647 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9648 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9649 s.op->line() << " },";
9650 }
dac77b80 9651 s.op->newline(-1) << "};";
dd225250
PS
9652
9653 // Emit the hwbkpt callback function
9654 s.op->newline() ;
23063de1 9655 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9656 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9657 s.op->line() << " int nmi,";
9658 s.op->line() << " struct perf_sample_data *data,";
9659 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9660 s.op->newline() << "#else";
9661 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9662 s.op->line() << " struct perf_sample_data *data,";
9663 s.op->line() << " struct pt_regs *regs) {";
9664 s.op->newline() << "#endif";
dac77b80
FCE
9665 s.op->newline(1) << "unsigned int i;";
9666 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9667 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9668 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9669 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9670 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) {";
9671 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9672 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9673 "stp_probe_type_hwbkpt");
d9aed31e 9674 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9675 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9676 s.op->newline() << "c->uregs = regs;";
9677 s.op->newline(-1) << "} else {";
9678 s.op->newline(1) << "c->kregs = regs;";
9679 s.op->newline(-1) << "}";
26e63673 9680 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9681 common_probe_entryfn_epilogue (s, true);
dac77b80 9682 s.op->newline(-1) << "}";
dd225250
PS
9683 s.op->newline(-1) << "}";
9684 s.op->newline() << "return 0;";
dac77b80 9685 s.op->newline(-1) << "}";
dd225250
PS
9686}
9687
9688void
9689hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9690{
dac77b80 9691 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9692 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9693 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9694 s.op->newline() << "void *addr = (void *) sdp->address;";
9695 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9696 s.op->newline() << "hw_breakpoint_init(hp);";
9697 s.op->newline() << "if (addr)";
9698 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9699 s.op->newline(-1) << "else { ";
9700 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9701 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9702 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9703 s.op->newline() << "continue;";
9704 s.op->newline(-1) << "}";
9705 s.op->newline(-1) << "}";
9706 s.op->newline() << "hp->bp_type = sdp->atype;";
9707
9708 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9709 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9710 {
9711 s.op->newline() << "switch(sdp->len) {";
9712 s.op->newline() << "case 1:";
9713 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9714 s.op->newline() << "break;";
9715 s.op->newline(-1) << "case 2:";
9716 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9717 s.op->newline() << "break;";
9718 s.op->newline(-1) << "case 3:";
9719 s.op->newline() << "case 4:";
9720 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9721 s.op->newline() << "break;";
9722 s.op->newline(-1) << "case 5:";
9723 s.op->newline() << "case 6:";
9724 s.op->newline() << "case 7:";
9725 s.op->newline() << "case 8:";
9726 s.op->newline() << "default:"; // XXX: could instead reject
9727 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9728 s.op->newline() << "break;";
9729 s.op->newline(-1) << "}";
9730 }
9731 else // other architectures presumed straightforward
9732 s.op->newline() << "hp->bp_len = sdp->len;";
9733
26e63673 9734 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9735 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9736 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9737 s.op->newline() << "#else";
dac77b80 9738 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9739 s.op->newline() << "#endif";
43650b10 9740 s.op->newline() << "rc = 0;";
dac77b80 9741 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9742 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9743 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9744 s.op->newline(-1) << "}";
217ef1f4
WC
9745 s.op->newline() << "if (rc) {";
9746 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9747 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9748 s.op->newline(-1) << "}";
dd225250 9749 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9750 s.op->newline(-1) << "}"; // for loop
9751}
9752
9753void
9754hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9755{
9756 //Unregister hwbkpt probes.
dac77b80 9757 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9758 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9759 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9760 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9761 s.op->newline() << "sdp->registered_p = 0;";
9762 s.op->newline(-1) << "}";
9763}
9764
9765struct hwbkpt_builder: public derived_probe_builder
9766{
9767 hwbkpt_builder() {}
9768 virtual void build(systemtap_session & sess,
9769 probe * base,
9770 probe_point * location,
9771 literal_map_t const & parameters,
9772 vector<derived_probe *> & finished_results);
9773};
9774
9775void
9776hwbkpt_builder::build(systemtap_session & sess,
9777 probe * base,
9778 probe_point * location,
9779 literal_map_t const & parameters,
9780 vector<derived_probe *> & finished_results)
9781{
9782 string symbol_str_val;
9783 int64_t hwbkpt_address, len;
9784 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9785
b47f3a55 9786 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9787 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9788 location->components[0]->tok);
9789 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9790 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9791 location->components[0]->tok);
9792
dd225250
PS
9793 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9794 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9795 has_len = get_param (parameters, TOK_LENGTH, len);
9796 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9797 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9798
b31695eb
JL
9799 // Make an intermediate pp that is well-formed. It's pretty much the same as
9800 // the user-provided one, except that the addr literal is well-typed.
9801 probe_point* well_formed_loc = new probe_point(*location);
9802 well_formed_loc->well_formed = true;
9803
9804 vector<probe_point::component*> well_formed_comps;
9805 vector<probe_point::component*>::iterator it;
9806 for (it = location->components.begin();
9807 it != location->components.end(); ++it)
9808 if ((*it)->functor == TOK_HWBKPT && has_addr)
9809 well_formed_comps.push_back(new probe_point::component(TOK_HWBKPT,
9810 new literal_number(hwbkpt_address, true /* hex */ )));
9811 else
9812 well_formed_comps.push_back(*it);
9813 well_formed_loc->components = well_formed_comps;
9814 probe *new_base = new probe (base, well_formed_loc);
9815
dd225250
PS
9816 if (!has_len)
9817 len = 1;
9818
9819 if (has_addr)
b31695eb 9820 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9821 location,
9822 hwbkpt_address,
9823 "",len,0,
9824 has_write,
9825 has_rw));
5d8a0aea 9826 else if (has_symbol_str)
b31695eb 9827 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9828 location,
9829 0,
9830 symbol_str_val,len,0,
9831 has_write,
9832 has_rw));
5d8a0aea
FCE
9833 else
9834 assert (0);
dd225250 9835}
342d3f96 9836
0a6f5a3f
JS
9837// ------------------------------------------------------------------------
9838// statically inserted kernel-tracepoint derived probes
9839// ------------------------------------------------------------------------
9840
6fb70fb7 9841struct tracepoint_arg
79189b84 9842{
ad370dcc 9843 string name, c_type, typecast;
dcaa1a65 9844 bool usable, used, isptr;
f8a968bc 9845 Dwarf_Die type_die;
dcaa1a65 9846 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9847};
79189b84 9848
0a6f5a3f
JS
9849struct tracepoint_derived_probe: public derived_probe
9850{
79189b84
JS
9851 tracepoint_derived_probe (systemtap_session& s,
9852 dwflpp& dw, Dwarf_Die& func_die,
9853 const string& tracepoint_name,
9854 probe* base_probe, probe_point* location);
bc9a523d 9855
79189b84 9856 systemtap_session& sess;
6fb70fb7
JS
9857 string tracepoint_name, header;
9858 vector <struct tracepoint_arg> args;
bc9a523d 9859
6fb70fb7 9860 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9861 void getargs (std::list<std::string> &arg_set) const;
79189b84 9862 void join_group (systemtap_session& s);
3e3bd7b6 9863 void print_dupe_stamp(ostream& o);
0a6f5a3f 9864};
79189b84
JS
9865
9866
0a6f5a3f 9867struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9868{
79189b84
JS
9869 void emit_module_decls (systemtap_session& s);
9870 void emit_module_init (systemtap_session& s);
9871 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9872};
79189b84 9873
bc9a523d 9874
f8a968bc
JS
9875struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9876{
9877 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9878 vector <struct tracepoint_arg>& args):
9879 dw (dw), probe_name (probe_name), args (args) {}
9880 dwflpp& dw;
9881 const string& probe_name;
9882 vector <struct tracepoint_arg>& args;
bc9a523d 9883
f8a968bc
JS
9884 void visit_target_symbol (target_symbol* e);
9885 void visit_target_symbol_arg (target_symbol* e);
9886 void visit_target_symbol_context (target_symbol* e);
9887};
79189b84
JS
9888
9889
f8a968bc
JS
9890void
9891tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9892{
cc9001af 9893 string argname = e->sym_name();
75ead1f7 9894
f8a968bc
JS
9895 // search for a tracepoint parameter matching this name
9896 tracepoint_arg *arg = NULL;
9897 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9898 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9899 {
9900 arg = &args[i];
9901 arg->used = true;
9902 break;
9903 }
75ead1f7 9904
f8a968bc
JS
9905 if (arg == NULL)
9906 {
1d0499c2 9907 set<string> vars;
f8a968bc 9908 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
9909 vars.insert("$" + args[i].name);
9910 vars.insert("$$name");
9911 vars.insert("$$parms");
9912 vars.insert("$$vars");
9913 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 9914
f8a968bc
JS
9915 // We hope that this value ends up not being referenced after all, so it
9916 // can be optimized out quietly.
1d0499c2
JL
9917 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
9918 e->name.c_str(), sugs.empty() ? "" :
9919 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
9920 // NB: we use 'alternatives' because we list all
f8a968bc
JS
9921 // NB: we can have multiple errors, since a target variable
9922 // may be expanded in several different contexts:
9923 // trace ("*") { $foo->bar }
f8a968bc 9924 }
75ead1f7 9925
f8a968bc 9926 // make sure we're not dereferencing base types
dc5a09fc 9927 if (!arg->isptr)
d19a9a82 9928 e->assert_no_components("tracepoint", true);
75ead1f7 9929
f8a968bc
JS
9930 // we can only write to dereferenced fields, and only if guru mode is on
9931 bool lvalue = is_active_lvalue(e);
9932 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 9933 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 9934
ad370dcc
JS
9935 // XXX: if a struct/union arg is passed by value, then writing to its fields
9936 // is also meaningless until you dereference past a pointer member. It's
9937 // harder to detect and prevent that though...
75ead1f7 9938
f8a968bc
JS
9939 if (e->components.empty())
9940 {
03c75a4a 9941 if (e->addressof)
dc09353a 9942 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 9943
3e3bd7b6 9944 // Just grab the value from the probe locals
a45664f4
JS
9945 symbol* sym = new symbol;
9946 sym->tok = e->tok;
9947 sym->name = "__tracepoint_arg_" + arg->name;
9948 provide (sym);
f8a968bc
JS
9949 }
9950 else
9951 {
5f36109e
JS
9952 // make a copy of the original as a bare target symbol for the tracepoint
9953 // value, which will be passed into the dwarf dereferencing code
9954 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9955 e2->components.clear();
9956
9957 if (e->components.back().type == target_symbol::comp_pretty_print)
9958 {
9959 if (lvalue)
dc09353a 9960 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9961
d19a9a82 9962 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9963 dpp.expand()->visit (this);
9964 return;
9965 }
9966
1c0be8c7 9967 bool userspace_p = false;
f8a968bc 9968 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9969 + "_" + e->sym_name()
aca66a36 9970 + "_" + lex_cast(tick++));
75ead1f7 9971
1c0be8c7
JS
9972 exp_type type = pe_long;
9973 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 9974
1c0be8c7
JS
9975 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
9976 userspace_p, lvalue, e, e2);
75ead1f7 9977
f8a968bc
JS
9978 if (lvalue)
9979 {
9980 // Provide the functioncall to our parent, so that it can be
9981 // used to substitute for the assignment node immediately above
9982 // us.
9983 assert(!target_symbol_setter_functioncalls.empty());
9984 *(target_symbol_setter_functioncalls.top()) = n;
9985 }
75ead1f7 9986
1c0be8c7
JS
9987 // Revisit the functioncall so arguments can be expanded.
9988 n->visit (this);
f8a968bc 9989 }
75ead1f7
JS
9990}
9991
9992
f8a968bc
JS
9993void
9994tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9995{
03c75a4a 9996 if (e->addressof)
dc09353a 9997 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 9998
f8a968bc 9999 if (is_active_lvalue (e))
dc09353a 10000 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 10001
277c21bc 10002 if (e->name == "$$name")
f8a968bc 10003 {
5f36109e
JS
10004 e->assert_no_components("tracepoint");
10005
bfdaad1e
DS
10006 // Synthesize an embedded expression.
10007 embedded_expr *expr = new embedded_expr;
10008 expr->tok = e->tok;
10009 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 10010 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 10011 provide (expr);
f8a968bc 10012 }
277c21bc 10013 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 10014 {
5f36109e
JS
10015 e->assert_no_components("tracepoint", true);
10016
1c922ad7 10017 print_format* pf = print_format::create(e->tok, "sprintf");
0a6f5a3f 10018
f8a968bc 10019 for (unsigned i = 0; i < args.size(); ++i)
b278033a 10020 {
dcaa1a65
JS
10021 if (!args[i].usable)
10022 continue;
f8a968bc
JS
10023 if (i > 0)
10024 pf->raw_components += " ";
10025 pf->raw_components += args[i].name;
3e3bd7b6 10026 target_symbol *tsym = new target_symbol;
f8a968bc 10027 tsym->tok = e->tok;
277c21bc 10028 tsym->name = "$" + args[i].name;
5f36109e 10029 tsym->components = e->components;
b278033a 10030
f8a968bc
JS
10031 // every variable should always be accessible!
10032 tsym->saved_conversion_error = 0;
8c2f50c0 10033 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
10034 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
10035 {
10036 if (dw.sess.verbose>2)
e26c2f83 10037 for (const semantic_error *c = tsym->saved_conversion_error;
c081af73 10038 c != 0; c = c->get_chain())
4c5d9906 10039 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
10040 pf->raw_components += "=?";
10041 continue;
10042 }
b278033a 10043
5f36109e
JS
10044 if (!e->components.empty() &&
10045 e->components[0].type == target_symbol::comp_pretty_print)
10046 pf->raw_components += "=%s";
10047 else
10048 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
10049 pf->args.push_back(texp);
10050 }
0a6f5a3f 10051
f8a968bc
JS
10052 pf->components = print_format::string_to_components(pf->raw_components);
10053 provide (pf);
b278033a 10054 }
f8a968bc
JS
10055 else
10056 assert(0); // shouldn't get here
0a6f5a3f
JS
10057}
10058
0a6f5a3f 10059void
f8a968bc 10060tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 10061{
aff5d390 10062 try
c69a87e0 10063 {
bd1fcbad 10064 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 10065
277c21bc 10066 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 10067 visit_target_symbol_context (e);
bd1fcbad 10068
c69a87e0
FCE
10069 else
10070 visit_target_symbol_arg (e);
10071 }
10072 catch (const semantic_error &er)
10073 {
1af1e62d 10074 e->chain (er);
c69a87e0
FCE
10075 provide (e);
10076 }
0a6f5a3f
JS
10077}
10078
10079
79189b84
JS
10080tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
10081 dwflpp& dw, Dwarf_Die& func_die,
10082 const string& tracepoint_name,
10083 probe* base, probe_point* loc):
4c5d1300 10084 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 10085 sess (s), tracepoint_name (tracepoint_name)
56894e91 10086{
79189b84
JS
10087 // create synthetic probe point name; preserve condition
10088 vector<probe_point::component*> comps;
10089 comps.push_back (new probe_point::component (TOK_KERNEL));
10090 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
10091 this->sole_location()->components = comps;
10092
6fb70fb7
JS
10093 // fill out the available arguments in this tracepoint
10094 build_args(dw, func_die);
56894e91 10095
6fb70fb7
JS
10096 // determine which header defined this tracepoint
10097 string decl_file = dwarf_decl_file(&func_die);
b78a0fbb 10098 header = decl_file;
d4393459
FCE
10099
10100#if 0 /* This convention is not enforced. */
6fb70fb7
JS
10101 size_t header_pos = decl_file.rfind("trace/");
10102 if (header_pos == string::npos)
dc09353a 10103 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
10104 + tracepoint_name + "' in '"
10105 + decl_file + "'");
10106 header = decl_file.substr(header_pos);
d4393459 10107#endif
56894e91 10108
6fb70fb7
JS
10109 // tracepoints from FOO_event_types.h should really be included from FOO.h
10110 // XXX can dwarf tell us the include hierarchy? it would be better to
10111 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 10112 // XXX: see also PR9993.
d4393459 10113 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
10114 if (header_pos != string::npos)
10115 header.erase(header_pos, 12);
56894e91 10116
f8a968bc
JS
10117 // Now expand the local variables in the probe body
10118 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 10119 v.replace (this->body);
a45664f4
JS
10120 for (unsigned i = 0; i < args.size(); i++)
10121 if (args[i].used)
10122 {
10123 vardecl* v = new vardecl;
10124 v->name = "__tracepoint_arg_" + args[i].name;
10125 v->tok = this->tok;
58701b78 10126 v->set_arity(0, this->tok);
a45664f4 10127 v->type = pe_long;
69aa668e 10128 v->synthetic = true;
a45664f4
JS
10129 this->locals.push_back (v);
10130 }
56894e91 10131
79189b84 10132 if (sess.verbose > 2)
ce0f6648 10133 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 10134}
dc38c0ae 10135
56894e91 10136
f8a968bc 10137static bool
dcaa1a65 10138resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 10139{
d19a9a82 10140 Dwarf_Die type;
dcaa1a65 10141 switch (dwarf_tag(&arg.type_die))
b20febf3 10142 {
f8a968bc
JS
10143 case DW_TAG_typedef:
10144 case DW_TAG_const_type:
10145 case DW_TAG_volatile_type:
10146 // iterate on the referent type
3d1ad340 10147 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 10148 && resolve_tracepoint_arg_type(arg));
f8a968bc 10149 case DW_TAG_base_type:
a52d2ac0 10150 case DW_TAG_enumeration_type:
f8a968bc 10151 // base types will simply be treated as script longs
dcaa1a65 10152 arg.isptr = false;
f8a968bc
JS
10153 return true;
10154 case DW_TAG_pointer_type:
dcaa1a65
JS
10155 // pointers can be treated as script longs,
10156 // and if we know their type, they can also be dereferenced
d19a9a82
JS
10157 type = arg.type_die;
10158 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
10159 {
10160 // It still might be a non-type, e.g. const void,
10161 // so we need to strip away all qualifiers.
10162 int tag = dwarf_tag(&arg.type_die);
10163 if (tag != DW_TAG_typedef &&
10164 tag != DW_TAG_const_type &&
10165 tag != DW_TAG_volatile_type)
10166 {
10167 arg.isptr = true;
10168 break;
10169 }
10170 }
10171 if (!arg.isptr)
10172 arg.type_die = type;
ad370dcc
JS
10173 arg.typecast = "(intptr_t)";
10174 return true;
10175 case DW_TAG_structure_type:
10176 case DW_TAG_union_type:
10177 // for structs/unions which are passed by value, we turn it into
10178 // a pointer that can be dereferenced.
10179 arg.isptr = true;
10180 arg.typecast = "(intptr_t)&";
dcaa1a65 10181 return true;
f8a968bc
JS
10182 default:
10183 // should we consider other types too?
10184 return false;
b20febf3 10185 }
56894e91
JS
10186}
10187
10188
10189void
822a6a3d 10190tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 10191{
6fb70fb7
JS
10192 Dwarf_Die arg;
10193 if (dwarf_child(&func_die, &arg) == 0)
10194 do
10195 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
10196 {
10197 // build a tracepoint_arg for this parameter
10198 tracepoint_arg tparg;
c60517ca 10199 tparg.name = dwarf_diename(&arg) ?: "";
56894e91 10200
6fb70fb7 10201 // read the type of this parameter
3d1ad340 10202 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 10203 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 10204 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 10205 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 10206
dcaa1a65 10207 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
10208 args.push_back(tparg);
10209 if (sess.verbose > 4)
a52d2ac0
JS
10210 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
10211 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
10212 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
10213 }
10214 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
10215}
10216
dc38c0ae 10217void
d0bfd2ac 10218tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 10219{
dcaa1a65
JS
10220 for (unsigned i = 0; i < args.size(); ++i)
10221 if (args[i].usable)
d0bfd2ac 10222 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
10223}
10224
79189b84
JS
10225void
10226tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 10227{
79189b84
JS
10228 if (! s.tracepoint_derived_probes)
10229 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
10230 s.tracepoint_derived_probes->enroll (this);
10231}
e38d6504 10232
56894e91 10233
197a4d62 10234void
3e3bd7b6 10235tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 10236{
3e3bd7b6
JS
10237 for (unsigned i = 0; i < args.size(); i++)
10238 if (args[i].used)
10239 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 10240}
56894e91 10241
3e3bd7b6 10242
c9ccb642 10243static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 10244{
3c1b3d06
FCE
10245 vector<string> they_live;
10246 // PR 9993
10247 // XXX: may need this to be configurable
d4393459 10248 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
10249
10250 // PR11649: conditional extra header
10251 // for kvm tracepoints in 2.6.33ish
10252 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
10253 they_live.push_back ("#include <linux/kvm_host.h>");
10254 }
10255
50b72692 10256 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 10257 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
10258 if (s.kernel_source_tree != "")
10259 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
10260 they_live.push_back ("struct xfs_mount;");
10261 they_live.push_back ("struct xfs_inode;");
10262 they_live.push_back ("struct xfs_buf;");
10263 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 10264 they_live.push_back ("struct xfs_trans;");
9e0cd21a 10265 }
d4393459 10266
50b72692 10267 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
10268 they_live.push_back ("struct rpc_task;");
10269 }
b64d65e2
FCE
10270 // RHEL6.3
10271 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
10272 they_live.push_back ("struct rpc_clnt;");
10273 they_live.push_back ("struct rpc_wait_queue;");
10274 }
d4393459
FCE
10275
10276 they_live.push_back ("#include <asm/cputime.h>");
10277
c2cf1b87
FCE
10278 // linux 3.0
10279 they_live.push_back ("struct cpu_workqueue_struct;");
10280
50b72692 10281 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
10282 if (s.kernel_source_tree != "")
10283 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
10284
d97d428e 10285 if (header.find("ext3") != string::npos)
50b72692
HP
10286 they_live.push_back ("struct ext3_reserve_window_node;");
10287
d97d428e
FCE
10288 if (header.find("workqueue") != string::npos)
10289 {
10290 they_live.push_back ("struct pool_workqueue;");
10291 they_live.push_back ("struct work_struct;");
10292 }
10293
10294 if (header.find("asoc") != string::npos)
10295 they_live.push_back ("struct snd_soc_dapm_path;");
10296
10297 if (header.find("9p") != string::npos)
10298 {
10299 they_live.push_back ("struct p9_client;");
10300 they_live.push_back ("struct p9_fcall;");
10301 }
10302
10303 if (header.find("bcache") != string::npos)
10304 {
10305 they_live.push_back ("struct bkey;");
10306 they_live.push_back ("struct btree;");
10307 they_live.push_back ("struct cache_set;");
10308 they_live.push_back ("struct cache;");
10309 }
10310
10311 if (header.find("f2fs") != string::npos)
10312 {
10313 // cannot get fs/f2fs/f2fs.h #included
10314 they_live.push_back ("typedef u32 block_t;");
10315 they_live.push_back ("typedef u32 nid_t;");
10316 }
10317
10318 if (header.find("radeon") != string::npos)
10319 they_live.push_back ("struct radeon_bo;");
10320
10321 // argh, 3.11, i915_trace.h -> i915_drv.h -> i915_reg.h without -I
10322 // also brcms_trace_events.h -> ... -> "types.h"
10323 // XXX: need a way to add a temporary -I flag
10324
10325 if (header.find("/ath/") != string::npos)
10326 they_live.push_back ("struct ath5k_hw;");
10327
10328
3c1b3d06
FCE
10329 return they_live;
10330}
47dd066d
WC
10331
10332
10333void
79189b84 10334tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 10335{
79189b84
JS
10336 if (probes.empty())
10337 return;
47dd066d 10338
96b030fe 10339 s.op->newline() << "/* ---- tracepoint probes ---- */";
3ef9830a 10340 s.op->newline() << "#include <linux/stp_tracepoint.h>" << endl;
96b030fe 10341 s.op->newline();
79189b84 10342
47dd066d 10343
a4b9c3b3
FCE
10344 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
10345 // to be separately compiled. That's because kernel tracepoint headers sometimes
10346 // conflict. PR13155.
10347
10348 map<string,translator_output*> per_header_aux;
10349 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 10350
6fb70fb7
JS
10351 for (unsigned i = 0; i < probes.size(); ++i)
10352 {
10353 tracepoint_derived_probe *p = probes[i];
75ae2ec9 10354 string header = p->header;
5f73a260 10355
a4b9c3b3
FCE
10356 // We cache the auxiliary output files on a per-header basis. We don't
10357 // need one aux file per tracepoint, only one per tracepoint-header.
10358 translator_output *tpop = per_header_aux[header];
10359 if (tpop == 0)
10360 {
10361 tpop = s.op_create_auxiliary();
10362 per_header_aux[header] = tpop;
10363
10364 // PR9993: Add extra headers to work around undeclared types in individual
10365 // include/trace/foo.h files
10366 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
10367 for (unsigned z=0; z<extra_decls.size(); z++)
10368 tpop->newline() << extra_decls[z] << "\n";
720c435f 10369
a4b9c3b3
FCE
10370 // strip include/ substring, the same way as done in get_tracequery_module()
10371 size_t root_pos = header.rfind("include/");
10372 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443 10373
3ef9830a 10374 tpop->newline() << "#include <linux/stp_tracepoint.h>" << endl;
a4b9c3b3 10375 tpop->newline() << "#include <" << header << ">";
a4b9c3b3
FCE
10376 }
10377
720c435f
JS
10378 // collect the args that are actually in use
10379 vector<const tracepoint_arg*> used_args;
6fb70fb7 10380 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
10381 if (p->args[j].used)
10382 used_args.push_back(&p->args[j]);
10383
3ef9830a
JS
10384 // forward-declare the generated-side tracepoint callback, and define the
10385 // generated-side tracepoint callback in the main translator-output
10386 string enter_real_fn = "enter_real_tracepoint_probe_" + lex_cast(i);
720c435f 10387 if (used_args.empty())
6fb70fb7 10388 {
3ef9830a
JS
10389 tpop->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
10390 s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ")";
6fb70fb7 10391 }
3ef9830a 10392 else
a4b9c3b3 10393 {
3ef9830a
JS
10394 tpop->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10395 s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10396 s.op->indent(2);
10397 for (unsigned j = 0; j < used_args.size(); ++j)
10398 {
10399 tpop->line() << ", int64_t";
10400 s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
10401 }
10402 tpop->line() << ");";
10403 s.op->newline() << ")";
10404 s.op->indent(-2);
6fb70fb7 10405 }
3ef9830a 10406 s.op->newline() << "{";
7c3e97f4 10407 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 10408 << common_probe_init (p) << ";";
71db462b 10409 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 10410 "stp_probe_type_tracepoint");
6dceb5c9 10411 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
10412 << lex_cast_qstring (p->tracepoint_name)
10413 << ";";
720c435f
JS
10414 for (unsigned j = 0; j < used_args.size(); ++j)
10415 {
10416 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 10417 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
10418 << " = __tracepoint_arg_" << used_args[j]->name << ";";
10419 }
26e63673 10420 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 10421 common_probe_entryfn_epilogue (s, true);
6fb70fb7 10422 s.op->newline(-1) << "}";
47dd066d 10423
a4b9c3b3 10424 // define the real tracepoint callback function
3ef9830a
JS
10425 string enter_fn = "enter_tracepoint_probe_" + lex_cast(i);
10426 if (p->args.empty())
10427 tpop->newline() << "static STP_TRACE_ENTER_NOARGS(" << enter_fn << ")";
10428 else
a4b9c3b3 10429 {
3ef9830a
JS
10430 tpop->newline() << "static STP_TRACE_ENTER(" << enter_fn;
10431 s.op->indent(2);
10432 for (unsigned j = 0; j < p->args.size(); ++j)
10433 {
10434 tpop->newline() << ", " << p->args[j].c_type
10435 << " __tracepoint_arg_" << p->args[j].name;
10436 }
10437 tpop->newline() << ")";
10438 s.op->indent(-2);
a4b9c3b3 10439 }
3ef9830a
JS
10440 tpop->newline() << "{";
10441 tpop->newline(1) << enter_real_fn << "(";
720c435f
JS
10442 tpop->indent(2);
10443 for (unsigned j = 0; j < used_args.size(); ++j)
10444 {
10445 if (j > 0)
10446 tpop->line() << ", ";
10447 tpop->newline() << "(int64_t)" << used_args[j]->typecast
10448 << "__tracepoint_arg_" << used_args[j]->name;
10449 }
10450 tpop->newline() << ");";
10451 tpop->newline(-3) << "}";
a4b9c3b3
FCE
10452
10453
96b030fe 10454 // emit normalized registration functions
720c435f 10455 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10456 tpop->newline(1) << "return STP_TRACE_REGISTER(" << p->tracepoint_name
10457 << ", " << enter_fn << ");";
a4b9c3b3 10458 tpop->newline(-1) << "}";
47dd066d 10459
86758d5f
JS
10460 // NB: we're not prepared to deal with unreg failures. However, failures
10461 // can only occur if the tracepoint doesn't exist (yet?), or if we
10462 // weren't even registered. The former should be OKed by the initial
10463 // registration call, and the latter is safe to ignore.
720c435f 10464 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10465 tpop->newline(1) << "(void) STP_TRACE_UNREGISTER(" << p->tracepoint_name
10466 << ", " << enter_fn << ");";
a4b9c3b3
FCE
10467 tpop->newline(-1) << "}";
10468 tpop->newline();
5f73a260 10469
720c435f
JS
10470 // declare normalized registration functions
10471 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
10472 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 10473
a4b9c3b3 10474 tpop->assert_0_indent();
af304783
DS
10475 }
10476
96b030fe
JS
10477 // emit an array of registration functions for easy init/shutdown
10478 s.op->newline() << "static struct stap_tracepoint_probe {";
10479 s.op->newline(1) << "int (*reg)(void);";
86758d5f 10480 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
10481 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
10482 s.op->indent(1);
10483 for (unsigned i = 0; i < probes.size(); ++i)
10484 {
10485 s.op->newline () << "{";
10486 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
10487 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
10488 s.op->line() << " },";
10489 }
10490 s.op->newline(-1) << "};";
10491 s.op->newline();
47dd066d
WC
10492}
10493
10494
79189b84
JS
10495void
10496tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 10497{
79189b84
JS
10498 if (probes.size () == 0)
10499 return;
47dd066d 10500
79189b84 10501 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
10502 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
10503 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
10504 s.op->newline() << "if (rc) {";
10505 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
10506 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
10507 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
10508 s.op->newline(-1) << "}";
10509 s.op->newline(-1) << "}";
47dd066d 10510
bc9a523d
FCE
10511 // This would be technically proper (on those autoconf-detectable
10512 // kernels that include this function in tracepoint.h), however we
10513 // already make several calls to synchronze_sched() during our
10514 // shutdown processes.
47dd066d 10515
bc9a523d
FCE
10516 // s.op->newline() << "if (rc)";
10517 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
10518 // s.op->indent(-1);
79189b84 10519}
47dd066d
WC
10520
10521
79189b84
JS
10522void
10523tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 10524{
79189b84
JS
10525 if (probes.empty())
10526 return;
47dd066d 10527
96b030fe
JS
10528 s.op->newline() << "/* deregister tracepoint probes */";
10529 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
10530 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
10531 s.op->indent(-1);
47dd066d 10532
bc9a523d 10533 // Not necessary: see above.
47dd066d 10534
bc9a523d 10535 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 10536}
b20febf3 10537
47dd066d 10538
75ead1f7 10539struct tracepoint_query : public base_query
47dd066d 10540{
75ead1f7
JS
10541 tracepoint_query(dwflpp & dw, const string & tracepoint,
10542 probe * base_probe, probe_point * base_loc,
10543 vector<derived_probe *> & results):
10544 base_query(dw, "*"), tracepoint(tracepoint),
10545 base_probe(base_probe), base_loc(base_loc),
10546 results(results) {}
47dd066d 10547
75ead1f7 10548 const string& tracepoint;
47dd066d 10549
75ead1f7
JS
10550 probe * base_probe;
10551 probe_point * base_loc;
10552 vector<derived_probe *> & results;
f982c59b 10553 set<string> probed_names;
47dd066d 10554
75ead1f7
JS
10555 void handle_query_module();
10556 int handle_query_cu(Dwarf_Die * cudie);
10557 int handle_query_func(Dwarf_Die * func);
822a6a3d 10558 void query_library (const char *) {}
576eaefe 10559 void query_plt (const char *entry, size_t addr) {}
b20febf3 10560
5c378838 10561 static int tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q);
7d007451 10562 static int tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q);
75ead1f7 10563};
47dd066d
WC
10564
10565
10566void
75ead1f7 10567tracepoint_query::handle_query_module()
47dd066d 10568{
75ead1f7 10569 // look for the tracepoints in each CU
337b7c44 10570 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10571}
10572
10573
75ead1f7
JS
10574int
10575tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10576{
75ead1f7 10577 dw.focus_on_cu (cudie);
5f52fafe 10578 dw.mod_info->get_symtab();
47dd066d 10579
75ead1f7
JS
10580 // look at each function to see if it's a tracepoint
10581 string function = "stapprobe_" + tracepoint;
10582 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10583}
10584
10585
75ead1f7
JS
10586int
10587tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10588{
75ead1f7 10589 dw.focus_on_function (func);
47dd066d 10590
60d98537 10591 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10592 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10593
10594 // check for duplicates -- sometimes tracepoint headers may be indirectly
10595 // included in more than one of our tracequery modules.
10596 if (!probed_names.insert(tracepoint_instance).second)
10597 return DWARF_CB_OK;
10598
79189b84
JS
10599 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10600 tracepoint_instance,
10601 base_probe, base_loc);
10602 results.push_back (dp);
75ead1f7 10603 return DWARF_CB_OK;
47dd066d
WC
10604}
10605
10606
75ead1f7 10607int
5c378838 10608tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q)
47dd066d 10609{
85007c04 10610 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10611 return q->handle_query_cu(cudie);
47dd066d
WC
10612}
10613
10614
75ead1f7 10615int
7d007451 10616tracepoint_query::tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q)
47dd066d 10617{
85007c04 10618 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10619 return q->handle_query_func(func);
47dd066d
WC
10620}
10621
10622
0a6f5a3f 10623struct tracepoint_builder: public derived_probe_builder
47dd066d 10624{
0a6f5a3f
JS
10625private:
10626 dwflpp *dw;
10627 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10628 void get_tracequery_modules(systemtap_session& s,
10629 const vector<string>& headers,
10630 vector<string>& modules);
47dd066d 10631
0a6f5a3f 10632public:
47dd066d 10633
0a6f5a3f
JS
10634 tracepoint_builder(): dw(0) {}
10635 ~tracepoint_builder() { delete dw; }
47dd066d 10636
0a6f5a3f
JS
10637 void build_no_more (systemtap_session& s)
10638 {
10639 if (dw && s.verbose > 3)
b530b5b3 10640 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10641 delete dw;
10642 dw = NULL;
435f53a7
FCE
10643
10644 delete_session_module_cache (s);
0a6f5a3f 10645 }
47dd066d 10646
0a6f5a3f
JS
10647 void build(systemtap_session& s,
10648 probe *base, probe_point *location,
10649 literal_map_t const& parameters,
10650 vector<derived_probe*>& finished_results);
10651};
47dd066d 10652
47dd066d 10653
c9ccb642 10654
2a0e62a8 10655// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10656// tracepoint-related header files given. Return the generated or cached
10657// modules[].
10658
10659void
10660tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10661 const vector<string>& headers,
10662 vector<string>& modules)
0a6f5a3f 10663{
c95eddf7 10664 if (s.verbose > 2)
55e50c24 10665 {
ce0f6648 10666 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10667 for (size_t i = 0; i < headers.size(); ++i)
10668 clog << " " << headers[i] << endl;
10669 }
c95eddf7 10670
2a0e62a8
JS
10671 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10672 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10673 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10674 // so we prefer not to repeat this.
10675 vector<string> uncached_headers;
10676 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10677 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10678
10679 // They may be in the cache already.
10680 if (s.use_cache && !s.poison_cache)
10681 for (size_t i=0; i<headers.size(); i++)
10682 {
10683 // see if the cached module exists
2a0e62a8 10684 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10685 if (!tracequery_path.empty() && file_exists(tracequery_path))
10686 {
10687 if (s.verbose > 2)
10688 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10689
c252fca2
JS
10690 // an empty file is a cached failure
10691 if (get_file_size(tracequery_path) > 0)
10692 modules.push_back (tracequery_path);
c9ccb642
FCE
10693 }
10694 else
10695 uncached_headers.push_back(headers[i]);
10696 }
10697 else
10698 uncached_headers = headers;
f982c59b 10699
c9ccb642
FCE
10700 // If we have nothing left to search for, quit
10701 if (uncached_headers.empty()) return;
55e50c24 10702
c9ccb642 10703 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10704
c9ccb642
FCE
10705 // We could query several subsets of headers[] to make this go
10706 // faster, but let's KISS and do one at a time.
10707 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10708 {
c9ccb642
FCE
10709 const string& header = uncached_headers[i];
10710
10711 // create a tracequery source file
10712 ostringstream osrc;
10713
10714 // PR9993: Add extra headers to work around undeclared types in individual
10715 // include/trace/foo.h files
10716 vector<string> short_decls = tracepoint_extra_decls(s, header);
10717
10718 // add each requested tracepoint header
75ae2ec9 10719 size_t root_pos = header.rfind("include/");
832f100d 10720 short_decls.push_back(string("#include <") +
75ae2ec9 10721 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10722 string(">"));
f982c59b 10723
c9ccb642
FCE
10724 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10725 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10726
10727 // the kernel has changed this naming a few times, previously TPPROTO,
10728 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10729 osrc << "#ifndef PARAMS" << endl;
10730 osrc << "#define PARAMS(args...) args" << endl;
10731 osrc << "#endif" << endl;
10732
c9ccb642
FCE
10733 // override DECLARE_TRACE to synthesize probe functions for us
10734 osrc << "#undef DECLARE_TRACE" << endl;
10735 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10736 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10737
c9ccb642
FCE
10738 // 2.6.35 added the NOARGS variant, but it's the same for us
10739 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10740 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10741 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10742
10743 // 2.6.38 added the CONDITION variant, which can also just redirect
10744 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10745 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10746 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10747
c9ccb642
FCE
10748 // older tracepoints used DEFINE_TRACE, so redirect that too
10749 osrc << "#undef DEFINE_TRACE" << endl;
10750 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10751 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10752
c9ccb642
FCE
10753 // add the specified decls/#includes
10754 for (unsigned z=0; z<short_decls.size(); z++)
10755 osrc << "#undef TRACE_INCLUDE_FILE\n"
10756 << "#undef TRACE_INCLUDE_PATH\n"
10757 << short_decls[z] << "\n";
10758
10759 // finish up the module source
10760 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10761
c9ccb642
FCE
10762 // save the source file away
10763 headers_tracequery_src[header] = osrc.str();
55e50c24 10764 }
f982c59b 10765
c9ccb642 10766 // now build them all together
2a0e62a8 10767 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10768
c9ccb642 10769 // now plop them into the cache
b278033a 10770 if (s.use_cache)
c9ccb642
FCE
10771 for (size_t i=0; i<uncached_headers.size(); i++)
10772 {
10773 const string& header = uncached_headers[i];
2a0e62a8
JS
10774 const string& tracequery_obj = tracequery_objs[header];
10775 const string& tracequery_path = headers_cache_obj[header];
10776 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10777 {
2a0e62a8 10778 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10779 modules.push_back (tracequery_path);
10780 }
c252fca2
JS
10781 else
10782 // cache an empty file for failures
10783 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10784 }
f982c59b
JS
10785}
10786
10787
d4393459 10788
f982c59b
JS
10789bool
10790tracepoint_builder::init_dw(systemtap_session& s)
10791{
10792 if (dw != NULL)
10793 return true;
10794
10795 vector<string> tracequery_modules;
55e50c24 10796 vector<string> system_headers;
f982c59b
JS
10797
10798 glob_t trace_glob;
d4393459
FCE
10799
10800 // find kernel_source_tree
10801 if (s.kernel_source_tree == "")
f982c59b 10802 {
d4393459 10803 unsigned found;
ccf2c922 10804 Dwfl *dwfl = setup_dwfl_kernel ("kernel", &found, s);
d4393459
FCE
10805 if (found)
10806 {
10807 Dwarf_Die *cudie = 0;
10808 Dwarf_Addr bias;
10809 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10810 {
e19ebcf7 10811 assert_no_interrupts();
d4393459
FCE
10812 Dwarf_Attribute attr;
10813 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10814 if (name)
d4393459 10815 {
36d65b45
JS
10816 // check that the path actually exists locally before we try to use it
10817 if (file_exists(name))
10818 {
10819 if (s.verbose > 2)
10820 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10821 s.kernel_source_tree = name;
10822 }
10823 else
10824 {
10825 if (s.verbose > 2)
10826 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10827 }
61f1a63b 10828
d4393459
FCE
10829 break; // skip others; modern Kbuild uses same comp_dir for them all
10830 }
10831 }
10832 }
44392d73 10833 dwfl_end (dwfl);
d4393459
FCE
10834 }
10835
10836 // prefixes
10837 vector<string> glob_prefixes;
10838 glob_prefixes.push_back (s.kernel_build_tree);
10839 if (s.kernel_source_tree != "")
10840 glob_prefixes.push_back (s.kernel_source_tree);
10841
10842 // suffixes
10843 vector<string> glob_suffixes;
10844 glob_suffixes.push_back("include/trace/events/*.h");
10845 glob_suffixes.push_back("include/trace/*.h");
d97d428e 10846 glob_suffixes.push_back("include/ras/*_event.h");
d4393459 10847 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
d97d428e
FCE
10848 glob_suffixes.push_back("arch/x86/kernel/*trace.h");
10849 glob_suffixes.push_back("arch/*/include/asm/trace*.h");
10850 glob_suffixes.push_back("arch/*/include/asm/trace/*.h");
f89ff3e2 10851 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d97d428e
FCE
10852 glob_suffixes.push_back("fs/*/*trace*.h");
10853 glob_suffixes.push_back("net/*/*trace*.h");
10854 glob_suffixes.push_back("sound/pci/hda/*_trace.h");
10855 glob_suffixes.push_back("drivers/gpu/drm/*_trace.h");
10856 glob_suffixes.push_back("drivers/gpu/drm/*/*_trace.h");
10857 glob_suffixes.push_back("drivers/net/wireless/*/*/*trace*.h");
10858 glob_suffixes.push_back("drivers/usb/host/*trace*.h");
10859
10860 // see also tracepoint_extra_decls above
d4393459
FCE
10861
10862 // compute cartesian product
10863 vector<string> globs;
10864 for (unsigned i=0; i<glob_prefixes.size(); i++)
10865 for (unsigned j=0; j<glob_suffixes.size(); j++)
10866 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10867
8aa43b8d 10868 set<string> duped_headers;
d4393459
FCE
10869 for (unsigned z = 0; z < globs.size(); z++)
10870 {
10871 string glob_str = globs[z];
10872 if (s.verbose > 3)
b530b5b3 10873 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10874
067cc66f
CM
10875 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10876 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10877 throw runtime_error("Error globbing tracepoint");
10878
f982c59b
JS
10879 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10880 {
10881 string header(trace_glob.gl_pathv[i]);
10882
10883 // filter out a few known "internal-only" headers
60d98537
JS
10884 if (endswith(header, "/define_trace.h") ||
10885 endswith(header, "/ftrace.h") ||
10886 endswith(header, "/trace_events.h") ||
10887 endswith(header, "_event_types.h"))
f982c59b
JS
10888 continue;
10889
b1966849
FCE
10890 // With headers now plopped under arch/FOO/include/asm/*,
10891 // the following logic miss some tracepoints.
10892#if 0
8aa43b8d
JS
10893 // skip identical headers from the build and source trees.
10894 size_t root_pos = header.rfind("include/");
10895 if (root_pos != string::npos &&
10896 !duped_headers.insert(header.substr(root_pos + 8)).second)
10897 continue;
b1966849 10898#endif
8aa43b8d 10899
55e50c24 10900 system_headers.push_back(header);
f982c59b
JS
10901 }
10902 globfree(&trace_glob);
10903 }
10904
c9ccb642
FCE
10905 // Build tracequery modules
10906 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 10907
f982c59b
JS
10908 // TODO: consider other sources of tracepoint headers too, like from
10909 // a command-line parameter or some environment or .systemtaprc
47dd066d 10910
59c11f91 10911 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
10912 return true;
10913}
47dd066d 10914
0a6f5a3f
JS
10915void
10916tracepoint_builder::build(systemtap_session& s,
10917 probe *base, probe_point *location,
10918 literal_map_t const& parameters,
10919 vector<derived_probe*>& finished_results)
10920{
10921 if (!init_dw(s))
10922 return;
47dd066d 10923
75ead1f7
JS
10924 string tracepoint;
10925 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 10926
75ead1f7 10927 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
d906ab9d 10928 unsigned results_pre = finished_results.size();
06de3a04 10929 dw->iterate_over_modules<base_query>(&query_module, &q);
d906ab9d
JL
10930 unsigned results_post = finished_results.size();
10931
10932 // Did we fail to find a match? Let's suggest something!
10933 if (results_pre == results_post)
10934 {
10935 size_t pos;
10936 string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
10937 while ((pos = sugs.find("stapprobe_")) != string::npos)
10938 sugs.erase(pos, string("stapprobe_").size());
10939 if (!sugs.empty())
ece93f53
JL
10940 throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
10941 "no match (similar tracepoints: %s)",
d906ab9d
JL
10942 sugs.find(',') == string::npos,
10943 sugs.c_str()));
10944 }
47dd066d 10945}
47dd066d 10946
e6fe60e7 10947
b55bc428 10948// ------------------------------------------------------------------------
bd2b1e68 10949// Standard tapset registry.
b55bc428
FCE
10950// ------------------------------------------------------------------------
10951
7a053d3b 10952void
f8220a7b 10953register_standard_tapsets(systemtap_session & s)
b55bc428 10954{
47e0478e 10955 register_tapset_been(s);
93646f4d 10956 register_tapset_itrace(s);
dd0e4fa7 10957 register_tapset_mark(s);
7a212aa8 10958 register_tapset_procfs(s);
912e8c59 10959 register_tapset_timers(s);
8d9609f5 10960 register_tapset_netfilter(s);
b84779a5 10961 register_tapset_utrace(s);
b98a8d73 10962
7a24d422 10963 // dwarf-based kprobe/uprobe parts
c4ce66a1 10964 dwarf_derived_probe::register_patterns(s);
30a279be 10965
888af770
FCE
10966 // XXX: user-space starter set
10967 s.pattern_root->bind_num(TOK_PROCESS)
10968 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10969 ->bind_privilege(pr_all)
888af770
FCE
10970 ->bind(new uprobe_builder ());
10971 s.pattern_root->bind_num(TOK_PROCESS)
10972 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10973 ->bind_privilege(pr_all)
888af770
FCE
10974 ->bind(new uprobe_builder ());
10975
0a6f5a3f
JS
10976 // kernel tracepoint probes
10977 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10978 ->bind(new tracepoint_builder());
10979
e6fe60e7
AM
10980 // Kprobe based probe
10981 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10982 ->bind(new kprobe_builder());
3c57fe1f
JS
10983 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
10984 ->bind(new kprobe_builder());
e6fe60e7
AM
10985 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10986 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
10987 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10988 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
10989 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10990 ->bind(new kprobe_builder());
b6371390
JS
10991 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10992 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10993 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10994 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10995 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10996 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10997 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10998 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10999 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
11000
11001 //Hwbkpt based probe
b47f3a55
FCE
11002 // NB: we formerly registered the probe point types only if the kernel configuration
11003 // allowed it. However, we get better error messages if we allow probes to resolve.
11004 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11005 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11006 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11007 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11008 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11009 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11010 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11011 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11012 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11013 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11014 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11015 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11016 // length supported with address only, not symbol names
83ea76b1
WC
11017
11018 //perf event based probe
4763f713 11019 register_tapset_perf(s);
a29858ef 11020 register_tapset_java(s);
b55bc428 11021}
dc38c0ae
DS
11022
11023
b20febf3
FCE
11024vector<derived_probe_group*>
11025all_session_groups(systemtap_session& s)
dc38c0ae 11026{
b20febf3 11027 vector<derived_probe_group*> g;
912e8c59
JS
11028
11029#define DOONE(x) \
11030 if (s. x##_derived_probes) \
11031 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
11032
11033 // Note that order *is* important here. We want to make sure we
11034 // register (actually run) begin probes before any other probe type
11035 // is run. Similarly, when unregistering probes, we want to
11036 // unregister (actually run) end probes after every other probe type
11037 // has be unregistered. To do the latter,
11038 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
11039 DOONE(be);
11040 DOONE(dwarf);
888af770 11041 DOONE(uprobe);
b20febf3
FCE
11042 DOONE(timer);
11043 DOONE(profile);
11044 DOONE(mark);
0a6f5a3f 11045 DOONE(tracepoint);
e6fe60e7 11046 DOONE(kprobe);
dd225250 11047 DOONE(hwbkpt);
83ea76b1 11048 DOONE(perf);
b20febf3 11049 DOONE(hrtimer);
ce82316f 11050 DOONE(procfs);
8d9609f5 11051 DOONE(netfilter);
935447c8
DS
11052
11053 // Another "order is important" item. We want to make sure we
11054 // "register" the dummy task_finder probe group after all probe
11055 // groups that use the task_finder.
11056 DOONE(utrace);
a96d1db0 11057 DOONE(itrace);
f31a77f5 11058 DOONE(dynprobe);
e7d4410d 11059 DOONE(java);
935447c8 11060 DOONE(task_finder);
b20febf3
FCE
11061#undef DOONE
11062 return g;
46b84a80 11063}
73267b89
JS
11064
11065/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 3.36609 seconds and 5 git commands to generate.