]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
query_callee(): add well-formed probe point
[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
613c8675
JL
740 void mount_well_formed_probe_point();
741 void unmount_well_formed_probe_point();
742 stack<pair<probe_point*, probe*> > previous_bases;
743
71dfce11
JL
744 void replace_probe_point_component_arg(const string& functor,
745 const string& new_functor,
746 int64_t new_arg,
747 bool hex = false);
748 void replace_probe_point_component_arg(const string& functor,
749 int64_t new_arg,
750 bool hex = false);
751 void replace_probe_point_component_arg(const string& functor,
752 const string& new_functor,
753 const string& new_arg);
754 void replace_probe_point_component_arg(const string& functor,
755 const string& new_arg);
756 void remove_probe_point_component(const string& functor);
757
857bdfd1
JS
758 // Track addresses we've already seen in a given module
759 set<Dwarf_Addr> alias_dupes;
760
7fdd3e2c
JS
761 // Track inlines we've already seen as well
762 // NB: this can't be compared just by entrypc, as inlines can overlap
763 set<inline_instance_info> inline_dupes;
764
e2941743
JL
765 // Used in .callee[s] probes, when calling iterate_over_callees() (which
766 // provides the actual stack). Retains the addrs of the callers unwind addr
767 // where the callee is found. Specifies multiple callers. E.g. when a callee
768 // at depth 2 is found, callers[1] has the addr of the caller, and callers[0]
769 // has the addr of the caller's caller.
770 stack<Dwarf_Addr> *callers;
771
20c6c071
GH
772 bool has_function_str;
773 bool has_statement_str;
774 bool has_function_num;
775 bool has_statement_num;
7a053d3b
RM
776 string statement_str_val;
777 string function_str_val;
c239d28c
GH
778 Dwarf_Addr statement_num_val;
779 Dwarf_Addr function_num_val;
20c6c071 780
b8da0ad1 781 bool has_call;
4bda987e 782 bool has_exported;
b8da0ad1 783 bool has_inline;
20c6c071
GH
784 bool has_return;
785
c9bad430
DS
786 bool has_maxactive;
787 long maxactive_val;
788
20c6c071
GH
789 bool has_label;
790 string label_val;
791
c31add50
JL
792 bool has_callee;
793 string callee_val;
794
795 bool has_callees_num;
796 long callees_num_val;
797
20c6c071
GH
798 bool has_relative;
799 long relative_val;
800
37ebca01
FCE
801 bool has_absolute;
802
467bea43
SC
803 bool has_mark;
804
5f0a03a6
JK
805 enum dbinfo_reqt dbinfo_reqt;
806 enum dbinfo_reqt assess_dbinfo_reqt();
807
7d6d0afc 808 void parse_function_spec(const string & spec);
20c6c071 809 function_spec_type spec_type;
7d6d0afc 810 vector<string> scopes;
20c6c071
GH
811 string function;
812 string file;
4a81c0d9
JL
813 lineno_t lineno_type;
814 int linenos[2];
5f0a03a6 815 bool query_done; // Found exact match
20c6c071 816
5a617dc6
JL
817 // Holds the prologue end of the current function
818 Dwarf_Addr prologue_end;
819
bd25380d 820 set<string> filtered_srcfiles;
7e1279ea
FCE
821
822 // Map official entrypc -> func_info object
86bf665e
TM
823 inline_instance_map_t filtered_inlines;
824 func_info_map_t filtered_functions;
4df79aaf 825
959ccfed
JL
826 // Helper when we want to iterate over both
827 base_func_info_map_t filtered_all();
828
4df79aaf 829 void query_module_functions ();
e772a6e7
JL
830
831 string final_function_name(const string& final_func,
832 const string& final_file,
833 int final_line);
b55bc428
FCE
834};
835
98afd80e 836
435f53a7
FCE
837static void delete_session_module_cache (systemtap_session& s); // forward decl
838
839
98afd80e 840struct dwarf_builder: public derived_probe_builder
b55bc428 841{
665e1256 842 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 843 map <string,dwflpp*> user_dw;
b642c901
SC
844 string user_path;
845 string user_lib;
44ffe90c
JL
846
847 // Holds modules to suggest functions from. NB: aggregates over
848 // recursive calls to build() when deriving globby probes.
849 set <string> modules_seen;
850
ae2552da 851 dwarf_builder() {}
aa30ccd3 852
ae2552da 853 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 854 {
ea14cf67
FCE
855 if (kern_dw[module] == 0)
856 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 857 return kern_dw[module];
707bf35e
JS
858 }
859
860 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
861 {
ea14cf67
FCE
862 if (user_dw[module] == 0)
863 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
864 return user_dw[module];
865 }
7a24d422
FCE
866
867 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 868 void dwarf_build_no_more (bool)
aa30ccd3 869 {
435f53a7
FCE
870 delete_map(kern_dw);
871 delete_map(user_dw);
7a24d422
FCE
872 }
873
874 void build_no_more (systemtap_session &s)
875 {
876 dwarf_build_no_more (s.verbose > 3);
435f53a7 877 delete_session_module_cache (s);
aa30ccd3
FCE
878 }
879
e38d6504
RM
880 ~dwarf_builder()
881 {
7a24d422 882 dwarf_build_no_more (false);
c8959a29 883 }
aa30ccd3 884
5227f1ea 885 virtual void build(systemtap_session & sess,
7a053d3b 886 probe * base,
20c6c071 887 probe_point * location,
86bf665e 888 literal_map_t const & parameters,
20c6c071 889 vector<derived_probe *> & finished_results);
b55bc428
FCE
890};
891
5111fc3e 892
e1278bd4 893dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
894 probe_point * base_loc,
895 dwflpp & dw,
86bf665e 896 literal_map_t const & params,
b642c901
SC
897 vector<derived_probe *> & results,
898 const string user_path,
899 const string user_lib)
e2941743
JL
900 : base_query(dw, params), results(results), base_probe(base_probe),
901 base_loc(base_loc), user_path(user_path), user_lib(user_lib),
5a617dc6 902 callers(NULL), has_relative(false), relative_val(0), prologue_end(0)
bd2b1e68
GH
903{
904 // Reduce the query to more reasonable semantic values (booleans,
905 // extracted strings, numbers, etc).
bd2b1e68
GH
906 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
907 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
908
909 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
910 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
911
0f336e95 912 has_label = get_string_param(params, TOK_LABEL, label_val);
c31add50
JL
913 has_callee = get_string_param(params, TOK_CALLEE, callee_val);
914 if (has_null_param(params, TOK_CALLEES))
915 { // .callees ==> .callees(1) (also equivalent to .callee("*"))
916 has_callees_num = true;
917 callees_num_val = 1;
918 }
919 else
920 {
921 has_callees_num = get_number_param(params, TOK_CALLEES, callees_num_val);
922 if (has_callees_num && callees_num_val < 1)
923 throw SEMANTIC_ERROR(_(".callees(N) only acceptable for N >= 1"),
924 base_probe->tok);
925 }
0f336e95 926
b8da0ad1 927 has_call = has_null_param(params, TOK_CALL);
4bda987e 928 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 929 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 930 has_return = has_null_param(params, TOK_RETURN);
c9bad430 931 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 932 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 933 has_mark = false;
37ebca01 934
bd2b1e68 935 if (has_function_str)
7d6d0afc 936 parse_function_spec(function_str_val);
bd2b1e68 937 else if (has_statement_str)
7d6d0afc 938 parse_function_spec(statement_str_val);
0daad364 939
5f0a03a6
JK
940 dbinfo_reqt = assess_dbinfo_reqt();
941 query_done = false;
0daad364
JS
942}
943
944
2c384610 945void
5f0a03a6 946dwarf_query::query_module_dwarf()
2c384610
DS
947{
948 if (has_function_num || has_statement_num)
949 {
950 // If we have module("foo").function(0xbeef) or
951 // module("foo").statement(0xbeef), the address is relative
952 // to the start of the module, so we seek the function
953 // number plus the module's bias.
6b517475
JS
954 Dwarf_Addr addr = has_function_num ?
955 function_num_val : statement_num_val;
08d1d520
MW
956
957 // These are raw addresses, we need to know what the elf_bias
958 // is to feed it to libdwfl based functions.
959 Dwarf_Addr elf_bias;
960 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
961 assert(elf);
962 addr += elf_bias;
6b517475 963 query_addr(addr, this);
2c384610
DS
964 }
965 else
966 {
967 // Otherwise if we have a function("foo") or statement("foo")
968 // specifier, we have to scan over all the CUs looking for
969 // the function(s) in question
970 assert(has_function_str || has_statement_str);
4df79aaf
JS
971
972 // For simple cases, no wildcard and no source:line, we can do a very
973 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
974 if (spec_type == function_alone &&
975 !dw.name_has_wildcard(function) &&
976 !startswith(function, "_Z"))
4df79aaf
JS
977 query_module_functions();
978 else
337b7c44 979 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
980 }
981}
982
5f0a03a6
JK
983static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
984 dwarf_query * q);
985
91bb9081
LB
986static void
987query_symtab_func_info (func_info & fi, dwarf_query * q)
988{
989 assert(null_die(&fi.die));
990
991 Dwarf_Addr addr = fi.addr;
992
993 // Now compensate for the dw bias because the addresses come
994 // from dwfl_module_symtab, so fi->addr is NOT a normal dw address.
995 q->dw.get_module_dwarf(false, false);
996 addr -= q->dw.module_bias;
997
998 // If there are already probes in this module, lets not duplicate.
999 // This can come from other weak symbols/aliases or existing
a41f2ad7
JS
1000 // matches from Dwarf DIE functions. Try to add this addr to the
1001 // collection, and only continue if it was new.
1002 if (q->alias_dupes.insert(addr).second)
1003 query_func_info(addr, fi, q);
91bb9081
LB
1004}
1005
5f0a03a6
JK
1006void
1007dwarf_query::query_module_symtab()
1008{
1009 // Get the symbol table if it's necessary, sufficient, and not already got.
1010 if (dbinfo_reqt == dbr_need_dwarf)
1011 return;
1012
1013 module_info *mi = dw.mod_info;
1014 if (dbinfo_reqt == dbr_need_symtab)
1015 {
1016 if (mi->symtab_status == info_unknown)
5f52fafe 1017 mi->get_symtab();
5f0a03a6
JK
1018 if (mi->symtab_status == info_absent)
1019 return;
1020 }
1021
1022 func_info *fi = NULL;
1023 symbol_table *sym_table = mi->sym_table;
1024
1025 if (has_function_str)
1026 {
1027 // Per dwarf_query::assess_dbinfo_reqt()...
1028 assert(spec_type == function_alone);
1029 if (dw.name_has_wildcard(function_str_val))
1030 {
2e67a43b 1031 symbol_table::iterator_t iter;
1c6b77e5
JS
1032 for (iter = sym_table->map_by_addr.begin();
1033 iter != sym_table->map_by_addr.end();
2e67a43b 1034 ++iter)
5f0a03a6 1035 {
1c6b77e5 1036 fi = iter->second;
5f0a03a6
JK
1037 if (!null_die(&fi->die))
1038 continue; // already handled in query_module_dwarf()
1039 if (dw.function_name_matches_pattern(fi->name, function_str_val))
91bb9081 1040 query_symtab_func_info(*fi, this);
5f0a03a6
JK
1041 }
1042 }
1043 else
1044 {
1045 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1046 if (fi && !fi->descriptor && null_die(&fi->die))
91bb9081 1047 query_symtab_func_info(*fi, this);
5f0a03a6 1048 }
5f0a03a6
JK
1049 }
1050}
1051
1052void
1053dwarf_query::handle_query_module()
1054{
f4faaf86
JS
1055 if (has_plt && has_statement_num)
1056 {
1057 query_plt_statement (this);
1058 return;
1059 }
1060
0035051e 1061 bool report = dbinfo_reqt == dbr_need_dwarf;
1c6b77e5
JS
1062 dw.get_module_dwarf(false, report);
1063
1064 // prebuild the symbol table to resolve aliases
5f52fafe 1065 dw.mod_info->get_symtab();
1c6b77e5 1066
857bdfd1
JS
1067 // reset the dupe-checking for each new module
1068 alias_dupes.clear();
7fdd3e2c 1069 inline_dupes.clear();
857bdfd1 1070
5f0a03a6
JK
1071 if (dw.mod_info->dwarf_status == info_present)
1072 query_module_dwarf();
1c6b77e5 1073
91bb9081
LB
1074 // Consult the symbol table, asm and weak functions can show up
1075 // in the symbol table but not in dwarf and minidebuginfo is
1076 // located in the gnu_debugdata section, alias_dupes checking
1077 // is done before adding any probe points
1078 if (!query_done && !pending_interrupts)
5f0a03a6
JK
1079 query_module_symtab();
1080}
1081
2c384610 1082
7d6d0afc
JS
1083void
1084dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1085{
4a81c0d9
JL
1086 lineno_type = ABSOLUTE;
1087 linenos[0] = linenos[1] = 0;
1d12a9b2 1088
91699a70 1089 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1090
7d6d0afc 1091 // look for named scopes
91699a70
JS
1092 scope_pos = spec.rfind("::");
1093 if (scope_pos != string::npos)
bd2b1e68 1094 {
91699a70
JS
1095 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1096 scope_pos += 2;
bd2b1e68 1097 }
91699a70
JS
1098 else
1099 scope_pos = 0;
bd2b1e68 1100
7d6d0afc
JS
1101 // look for a source separator
1102 src_pos = spec.find('@', scope_pos);
1103 if (src_pos == string::npos)
bd2b1e68 1104 {
7d6d0afc
JS
1105 function = spec.substr(scope_pos);
1106 spec_type = function_alone;
bd2b1e68 1107 }
7d6d0afc 1108 else
879eb9e9 1109 {
7d6d0afc 1110 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1111
7d6d0afc
JS
1112 // look for a line-number separator
1113 line_pos = spec.find_first_of(":+", src_pos);
1114 if (line_pos == string::npos)
1115 {
1116 file = spec.substr(src_pos + 1);
1117 spec_type = function_and_file;
1118 }
1119 else
1120 {
1121 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1122
1123 // classify the line spec
1124 spec_type = function_file_and_line;
1125 if (spec[line_pos] == '+')
4a81c0d9 1126 lineno_type = RELATIVE;
7d6d0afc
JS
1127 else if (spec[line_pos + 1] == '*' &&
1128 spec.length() == line_pos + 2)
4a81c0d9 1129 lineno_type = WILDCARD;
7d6d0afc 1130 else
4a81c0d9 1131 lineno_type = ABSOLUTE;
7d6d0afc 1132
4a81c0d9 1133 if (lineno_type != WILDCARD)
7d6d0afc
JS
1134 try
1135 {
1136 // try to parse either N or N-M
1137 dash_pos = spec.find('-', line_pos + 1);
1138 if (dash_pos == string::npos)
4a81c0d9 1139 linenos[0] = linenos[1] = lex_cast<int>(spec.substr(line_pos + 1));
7d6d0afc
JS
1140 else
1141 {
4a81c0d9
JL
1142 lineno_type = RANGE;
1143 linenos[0] = lex_cast<int>(spec.substr(line_pos + 1,
7d6d0afc 1144 dash_pos - line_pos - 1));
4a81c0d9
JL
1145 linenos[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1146 if (linenos[0] > linenos[1])
1147 throw runtime_error("bad range");
7d6d0afc
JS
1148 }
1149 }
1150 catch (runtime_error & exn)
1151 {
1152 goto bad;
1153 }
1154 }
bd2b1e68
GH
1155 }
1156
7d6d0afc
JS
1157 if (function.empty() ||
1158 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1159 goto bad;
1160
7d6d0afc 1161 if (sess.verbose > 2)
bd2b1e68 1162 {
b530b5b3
LB
1163 //clog << "parsed '" << spec << "'";
1164 clog << _F("parse '%s'", spec.c_str());
41c262f3 1165
7d6d0afc
JS
1166 if (!scopes.empty())
1167 clog << ", scope '" << scopes[0] << "'";
1168 for (unsigned i = 1; i < scopes.size(); ++i)
1169 clog << "::'" << scopes[i] << "'";
41c262f3 1170
7d6d0afc
JS
1171 clog << ", func '" << function << "'";
1172
1173 if (spec_type != function_alone)
1174 clog << ", file '" << file << "'";
1175
1176 if (spec_type == function_file_and_line)
1177 {
1178 clog << ", line ";
4a81c0d9 1179 switch (lineno_type)
7d6d0afc
JS
1180 {
1181 case ABSOLUTE:
4a81c0d9 1182 clog << linenos[0];
7d6d0afc
JS
1183 break;
1184
1185 case RELATIVE:
4a81c0d9 1186 clog << "+" << linenos[0];
7d6d0afc
JS
1187 break;
1188
1189 case RANGE:
4a81c0d9 1190 clog << linenos[0] << " - " << linenos[1];
7d6d0afc
JS
1191 break;
1192
1193 case WILDCARD:
1194 clog << "*";
1195 break;
1196 }
1197 }
1198
1199 clog << endl;
bd2b1e68
GH
1200 }
1201
7d6d0afc
JS
1202 return;
1203
1204bad:
dc09353a 1205 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1206 base_probe->tok);
bd2b1e68
GH
1207}
1208
05fb3e0c
WF
1209string path_remove_sysroot(const systemtap_session& sess, const string& path)
1210{
1211 size_t pos;
1212 string retval = path;
1213 if (!sess.sysroot.empty() &&
1214 (pos = retval.find(sess.sysroot)) != string::npos)
1215 retval.replace(pos, sess.sysroot.length(), "/");
1216 return retval;
1217}
bd2b1e68 1218
36f9dd1d 1219void
1ffb8bd1 1220dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1221 const char* filename,
36f9dd1d 1222 int line,
b20febf3 1223 Dwarf_Die* scope_die,
36f9dd1d
FCE
1224 Dwarf_Addr addr)
1225{
b20febf3 1226 string reloc_section; // base section for relocation purposes
27646582 1227 Dwarf_Addr reloc_addr; // relocated
b20febf3 1228 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1229 string funcname = dw_funcname;
36f9dd1d 1230
37ebca01
FCE
1231 assert (! has_absolute); // already handled in dwarf_builder::build()
1232
f4faaf86 1233 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1234
1ffb8bd1 1235 // If we originally used the linkage name, then let's call it that way
1ffb8bd1 1236 const char* linkage_name;
91bb9081 1237 if (!null_die(scope_die) && startswith (this->function, "_Z")
f450a7e3 1238 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1239 funcname = linkage_name;
1240
7f9f3386
FCE
1241 if (sess.verbose > 1)
1242 {
b530b5b3 1243 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1244 if (string(module) == TOK_KERNEL)
b530b5b3 1245 clog << _(" kernel");
91af0778 1246 else if (has_module)
b530b5b3 1247 clog << _(" module=") << module;
91af0778 1248 else if (has_process)
b530b5b3 1249 clog << _(" process=") << module;
b20febf3 1250 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1251 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1252 }
4baf0e53 1253
2f18e69b
JL
1254 dwflpp::blacklisted_type blacklisted = dw.blacklisted_p (funcname, filename,
1255 line, module, addr,
1256 has_return);
b20febf3
FCE
1257 if (sess.verbose > 1)
1258 clog << endl;
7f9f3386 1259
84048984
FCE
1260 if (module == TOK_KERNEL)
1261 {
1262 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1263 reloc_addr = addr - sess.sym_stext;
37ebca01 1264 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1265 }
1266
2f18e69b 1267 if (!blacklisted)
b20febf3 1268 {
1a0dbc5a 1269 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1270
1271 if (has_process)
1272 {
05fb3e0c 1273 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1274 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1275 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1276 *this, scope_die));
1277 }
1278 else
1279 {
1280 assert (has_kernel || has_module);
1281 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1282 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1283 *this, scope_die));
1284 }
b20febf3 1285 }
2f18e69b
JL
1286 else
1287 {
1288 switch (blacklisted)
1289 {
1290 case dwflpp::blacklisted_section:
1291 sess.print_warning(_F("function %s is in blacklisted section",
1292 funcname.c_str()), base_probe->tok);
1293 break;
1294 case dwflpp::blacklisted_kprobes:
1295 sess.print_warning(_F("kprobes function %s is blacklisted",
1296 funcname.c_str()), base_probe->tok);
1297 break;
1298 case dwflpp::blacklisted_function_return:
1299 sess.print_warning(_F("function %s return probe is blacklisted",
1300 funcname.c_str()), base_probe->tok);
1301 break;
1302 case dwflpp::blacklisted_file:
1303 sess.print_warning(_F("function %s is in blacklisted file",
1304 funcname.c_str()), base_probe->tok);
1305 break;
1306 case dwflpp::blacklisted_function:
1307 default:
1308 sess.print_warning(_F("function %s is blacklisted",
1309 funcname.c_str()), base_probe->tok);
1310 break;
1311 }
1312 }
2930abc7
FCE
1313}
1314
613c8675
JL
1315void
1316dwarf_query::mount_well_formed_probe_point()
1317{
1318 string module = dw.module_name;
1319 if (has_process)
1320 module = path_remove_sysroot(sess, module);
1321
1322 vector<probe_point::component*> comps;
1323 vector<probe_point::component*>::iterator it;
1324 for (it = base_loc->components.begin();
1325 it != base_loc->components.end(); ++it)
1326 {
1327 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1328 comps.push_back(new probe_point::component((*it)->functor,
1329 new literal_string(has_library ? path : module)));
1330 else
1331 comps.push_back(*it);
1332 }
1333
1334 probe_point *pp = new probe_point(*base_loc);
1335 pp->well_formed = true;
1336 pp->components = comps;
1337
1338 previous_bases.push(make_pair(base_loc, base_probe));
1339
1340 base_loc = pp;
1341 base_probe = new probe(base_probe, pp);
1342}
1343
1344void
1345dwarf_query::unmount_well_formed_probe_point()
1346{
1347 assert(!previous_bases.empty());
1348
1349 base_loc = previous_bases.top().first;
1350 base_probe = previous_bases.top().second;
1351
1352 previous_bases.pop();
1353}
1354
71dfce11
JL
1355void
1356dwarf_query::replace_probe_point_component_arg(const string& functor,
1357 const string& new_functor,
1358 int64_t new_arg,
1359 bool hex)
1360{
1361 // only allow these operations if we're editing the well-formed loc
1362 assert(!previous_bases.empty());
1363
1364 vector<probe_point::component*>::iterator it;
1365 for (it = base_loc->components.begin();
1366 it != base_loc->components.end(); ++it)
1367 if ((*it)->functor == functor)
1368 *it = new probe_point::component(new_functor,
1369 new literal_number(new_arg, hex));
1370}
1371
1372void
1373dwarf_query::replace_probe_point_component_arg(const string& functor,
1374 int64_t new_arg,
1375 bool hex)
1376{
1377 replace_probe_point_component_arg(functor, functor, new_arg, hex);
1378}
1379
1380void
1381dwarf_query::replace_probe_point_component_arg(const string& functor,
1382 const string& new_functor,
1383 const string& new_arg)
1384{
1385 // only allow these operations if we're editing the well-formed loc
1386 assert(!previous_bases.empty());
1387
1388 vector<probe_point::component*>::iterator it;
1389 for (it = base_loc->components.begin();
1390 it != base_loc->components.end(); ++it)
1391 if ((*it)->functor == functor)
1392 *it = new probe_point::component(new_functor,
1393 new literal_string(new_arg));
1394}
1395
1396void
1397dwarf_query::replace_probe_point_component_arg(const string& functor,
1398 const string& new_arg)
1399{
1400 replace_probe_point_component_arg(functor, functor, new_arg);
1401}
1402
1403void
1404dwarf_query::remove_probe_point_component(const string& functor)
1405{
1406 // only allow these operations if we're editing the well-formed loc
1407 assert(!previous_bases.empty());
1408
1409 vector<probe_point::component*> new_comps;
1410 vector<probe_point::component*>::iterator it;
1411 for (it = base_loc->components.begin();
1412 it != base_loc->components.end(); ++it)
1413 if ((*it)->functor != functor)
1414 new_comps.push_back(*it);
1415
1416 base_loc->components = new_comps;
1417}
1418
5f0a03a6
JK
1419enum dbinfo_reqt
1420dwarf_query::assess_dbinfo_reqt()
1421{
1422 if (has_absolute)
1423 {
1424 // kernel.statement(NUM).absolute
1425 return dbr_none;
1426 }
c31add50 1427 if (has_inline || has_label || has_callee || has_callees_num)
5f0a03a6
JK
1428 {
1429 // kernel.function("f").inline or module("m").function("f").inline
1430 return dbr_need_dwarf;
1431 }
1432 if (has_function_str && spec_type == function_alone)
1433 {
1434 // kernel.function("f") or module("m").function("f")
1435 return dbr_need_symtab;
1436 }
1437 if (has_statement_num)
1438 {
1439 // kernel.statement(NUM) or module("m").statement(NUM)
1440 // Technically, all we need is the module offset (or _stext, for
1441 // the kernel). But for that we need either the ELF file or (for
1442 // _stext) the symbol table. In either case, the symbol table
1443 // is available, and that allows us to map the NUM (address)
1444 // to a function, which is goodness.
1445 return dbr_need_symtab;
1446 }
1447 if (has_function_num)
1448 {
1449 // kernel.function(NUM) or module("m").function(NUM)
1450 // Need the symbol table so we can back up from NUM to the
1451 // start of the function.
1452 return dbr_need_symtab;
1453 }
1454 // Symbol table tells us nothing about source files or line numbers.
1455 return dbr_need_dwarf;
1456}
2930abc7 1457
e772a6e7
JL
1458string
1459dwarf_query::final_function_name(const string& final_func,
1460 const string& final_file,
1461 int final_line)
1462{
1463 string final_name = final_func;
1464 if (final_file != "")
1465 {
1466 final_name += ("@" + final_file);
1467 if (final_line > 0)
1468 final_name += (":" + lex_cast(final_line));
1469 }
1470 return final_name;
1471}
2930abc7 1472
959ccfed
JL
1473base_func_info_map_t
1474dwarf_query::filtered_all(void)
1475{
1476 vector<base_func_info> r;
1477 func_info_map_t::const_iterator f;
1478 for (f = filtered_functions.begin();
1479 f != filtered_functions.end(); ++f)
1480 r.push_back(*f);
1481 inline_instance_map_t::const_iterator i;
1482 for (i = filtered_inlines.begin();
1483 i != filtered_inlines.end(); ++i)
1484 r.push_back(*i);
1485 return r;
1486}
1487
b8da0ad1
FCE
1488// The critical determining factor when interpreting a pattern
1489// string is, perhaps surprisingly: "presence of a lineno". The
1490// presence of a lineno changes the search strategy completely.
1491//
1492// Compare the two cases:
1493//
1494// 1. {statement,function}(foo@file.c:lineno)
1495// - find the files matching file.c
1496// - in each file, find the functions matching foo
1497// - query the file for line records matching lineno
1498// - iterate over the line records,
1499// - and iterate over the functions,
1500// - if(haspc(function.DIE, line.addr))
1501// - if looking for statements: probe(lineno.addr)
1502// - if looking for functions: probe(function.{entrypc,return,etc.})
1503//
1504// 2. {statement,function}(foo@file.c)
1505// - find the files matching file.c
1506// - in each file, find the functions matching foo
1507// - probe(function.{entrypc,return,etc.})
1508//
1509// Thus the first decision we make is based on the presence of a
1510// lineno, and we enter entirely different sets of callbacks
1511// depending on that decision.
1512//
1513// Note that the first case is a generalization fo the second, in that
1514// we could theoretically search through line records for matching
1515// file names (a "table scan" in rdbms lingo). Luckily, file names
1516// are already cached elsewhere, so we can do an "index scan" as an
1517// optimization.
7e1279ea 1518
bd2b1e68 1519static void
4cd232e4 1520query_statement (string const & func,
20e4a32c 1521 char const * file,
4cd232e4 1522 int line,
bcc12710 1523 Dwarf_Die *scope_die,
20e4a32c 1524 Dwarf_Addr stmt_addr,
4cd232e4 1525 dwarf_query * q)
bd2b1e68 1526{
39bcd429
FCE
1527 try
1528 {
cee35f73 1529 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1530 line, scope_die, stmt_addr);
39bcd429
FCE
1531 }
1532 catch (const semantic_error& e)
1533 {
1534 q->sess.print_error (e);
1535 }
bd2b1e68
GH
1536}
1537
6b517475
JS
1538static void
1539query_addr(Dwarf_Addr addr, dwarf_query *q)
1540{
1541 dwflpp &dw = q->dw;
1542
08d1d520
MW
1543 if (q->sess.verbose > 2)
1544 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1545
1546 // First pick which CU contains this address
1547 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1548 if (!cudie) // address could be wildly out of range
1549 return;
1550 dw.focus_on_cu(cudie);
1551
1552 // Now compensate for the dw bias
1553 addr -= dw.module_bias;
1554
1555 // Per PR5787, we look up the scope die even for
1556 // statement_num's, for blacklist sensitivity and $var
1557 // resolution purposes.
1558
1559 // Find the scopes containing this address
1560 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1561 if (scopes.empty())
1562 return;
1563
1564 // Look for the innermost containing function
1565 Dwarf_Die *fnscope = NULL;
1566 for (size_t i = 0; i < scopes.size(); ++i)
1567 {
1568 int tag = dwarf_tag(&scopes[i]);
1569 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1570 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1571 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1572 {
1573 fnscope = &scopes[i];
1574 break;
1575 }
1576 }
1577 if (!fnscope)
1578 return;
1579 dw.focus_on_function(fnscope);
1580
1581 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1582
1583 const char *file = dwarf_decl_file(fnscope);
1584 int line;
1585 dwarf_decl_line(fnscope, &line);
1586
1587 // Function probes should reset the addr to the function entry
1588 // and possibly perform prologue searching
1589 if (q->has_function_num)
1590 {
1bbf3f90
JS
1591 if (!dw.die_entrypc(fnscope, &addr))
1592 return;
6b517475 1593 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
b5b9879f
JL
1594 (q->sess.prologue_searching ||
1595 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
6b517475
JS
1596 {
1597 func_info func;
1598 func.die = *fnscope;
1599 func.name = dw.function_name;
1600 func.decl_file = file;
1601 func.decl_line = line;
1602 func.entrypc = addr;
1603
1604 func_info_map_t funcs(1, func);
1605 dw.resolve_prologue_endings (funcs);
5a617dc6
JL
1606 q->prologue_end = funcs[0].prologue_end;
1607
1608 // PR13200: if it's a .return probe, we need to emit a *retprobe based
1609 // on the entrypc so here we only use prologue_end for non .return
1610 // probes (note however that .return probes still take advantage of
1611 // prologue_end: PR14436)
1612 if (!q->has_return)
1613 addr = funcs[0].prologue_end;
6b517475
JS
1614 }
1615 }
1616 else
1617 {
de797211
JL
1618 Dwarf_Line *address_line = dwarf_getsrc_die(cudie, addr);
1619 Dwarf_Addr address_line_addr = addr;
6b517475
JS
1620 if (address_line)
1621 {
bf5974d6
JL
1622 file = DWARF_LINESRC(address_line);
1623 line = DWARF_LINENO(address_line);
1624 address_line_addr = DWARF_LINEADDR(address_line);
6b517475
JS
1625 }
1626
1627 // Verify that a raw address matches the beginning of a
1628 // statement. This is a somewhat lame check that the address
1629 // is at the start of an assembly instruction. Mark probes are in the
1630 // middle of a macro and thus not strictly at a statement beginning.
1631 // Guru mode may override this check.
de797211 1632 if (!q->has_mark && (!address_line || address_line_addr != addr))
6b517475
JS
1633 {
1634 stringstream msg;
2a97f50b 1635 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1636 addr);
6b517475 1637 if (address_line)
de797211 1638 msg << _F(" (try %#" PRIx64 ")", address_line_addr);
6b517475 1639 else
b530b5b3
LB
1640 msg << _F(" (no line info found for '%s', in module '%s')",
1641 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475 1642 if (! q->sess.guru_mode)
dc09353a 1643 throw SEMANTIC_ERROR(msg.str());
2713ea24 1644 else
6b517475
JS
1645 q->sess.print_warning(msg.str());
1646 }
1647 }
1648
1649 // Build a probe at this point
1650 query_statement(dw.function_name, file, line, scope, addr, q);
1651}
1652
f4faaf86
JS
1653static void
1654query_plt_statement(dwarf_query *q)
1655{
1656 assert (q->has_plt && q->has_statement_num);
1657
1658 Dwarf_Addr addr = q->statement_num_val;
1659 if (q->sess.verbose > 2)
1660 clog << "query_plt_statement 0x" << hex << addr << dec << endl;
1661
1662 // First adjust the raw address to dwfl's elf bias.
1663 Dwarf_Addr elf_bias;
1664 Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
1665 assert(elf);
1666 addr += elf_bias;
1667
1668 // Now compensate for the dw bias
1669 q->dw.get_module_dwarf(false, false);
1670 addr -= q->dw.module_bias;
1671
1672 // Build a probe at this point
1673 query_statement(q->plt_val, NULL, -1, NULL, addr, q);
1674}
1675
8096dd7d
JS
1676static void
1677query_label (string const & func,
1678 char const * label,
1679 char const * file,
1680 int line,
1681 Dwarf_Die *scope_die,
1682 Dwarf_Addr stmt_addr,
1683 dwarf_query * q)
1684{
6b517475
JS
1685 assert (q->has_statement_str || q->has_function_str);
1686
8096dd7d
JS
1687 // weed out functions whose decl_file isn't one of
1688 // the source files that we actually care about
6b517475 1689 if (q->spec_type != function_alone &&
8096dd7d
JS
1690 q->filtered_srcfiles.count(file) == 0)
1691 return;
1692
9891c543
JL
1693 // To help users, we create an intermediate probe point containing the final
1694 // function name, as well as the matched label. See query_callee() for
1695 // something similar, but with more comments.
1696 string canon_func = q->final_function_name(func, file, line);
1697
1698 string module = q->dw.module_name;
1699 if (q->has_process)
1700 module = path_remove_sysroot(q->sess, module);
8096dd7d 1701
9891c543
JL
1702 probe_point *pp = new probe_point(*q->base_loc);
1703 vector<probe_point::component*> pp_comps;
1704 vector<probe_point::component*>::iterator it;
1705 for (it = pp->components.begin(); it != pp->components.end(); ++it)
c72aa911 1706 {
9891c543
JL
1707 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1708 pp_comps.push_back(new probe_point::component((*it)->functor,
1709 new literal_string(module)));
1710 else if ((*it)->functor == TOK_FUNCTION)
1711 pp_comps.push_back(new probe_point::component(TOK_FUNCTION,
1712 new literal_string(canon_func)));
1713 else if ((*it)->functor == TOK_LABEL)
1714 pp_comps.push_back(new probe_point::component(TOK_LABEL,
1715 new literal_string(label)));
1716 else
1717 pp_comps.push_back(*it);
c72aa911 1718 }
9891c543
JL
1719
1720 pp->components = pp_comps;
1721 dwarf_query q_label(*q);
1722 q_label.base_loc = pp;
1723 q_label.base_probe = new probe(q->base_probe, pp);
1724
1725 query_statement(func, file, line, scope_die, stmt_addr, &q_label);
8096dd7d
JS
1726}
1727
67959c62 1728static void
e772a6e7
JL
1729query_callee (base_func_info& callee,
1730 base_func_info& caller,
67959c62
JL
1731 stack<Dwarf_Addr> *callers,
1732 dwarf_query * q)
1733{
1734 assert (q->has_function_str);
e772a6e7
JL
1735 assert (q->has_callee || q->has_callees_num);
1736
1737 // OK, we found a callee for a targeted caller. To help users see the
04a89a2a 1738 // derivation, we add the well-formed form .function(caller).callee(callee).
e772a6e7 1739
e772a6e7
JL
1740 string canon_caller = q->final_function_name(caller.name, caller.decl_file,
1741 caller.decl_line);
1742 string canon_callee = q->final_function_name(callee.name, callee.decl_file,
1743 callee.decl_line);
1744
04a89a2a
JL
1745 q->mount_well_formed_probe_point();
1746 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_caller);
1747 q->replace_probe_point_component_arg(TOK_CALLEES, TOK_CALLEE, canon_callee);
1748 q->replace_probe_point_component_arg(TOK_CALLEE, canon_callee);
e772a6e7
JL
1749
1750 // Pass on the callers we'll need to add checks for
04a89a2a 1751 q->callers = callers;
e772a6e7
JL
1752
1753 query_statement(callee.name, callee.decl_file, callee.decl_line,
04a89a2a
JL
1754 &callee.die, callee.entrypc, q);
1755
1756 q->unmount_well_formed_probe_point();
67959c62
JL
1757}
1758
7e1279ea 1759static void
3e961ba6 1760query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1761 dwarf_query * q)
1762{
b6581717 1763 try
7e1279ea 1764 {
8f14e444
FCE
1765 assert (! q->has_return); // checked by caller already
1766 if (q->sess.verbose>2)
b530b5b3
LB
1767 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1768 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1769 query_statement (ii.name, ii.decl_file, ii.decl_line,
1770 &ii.die, ii.entrypc, q);
7e1279ea 1771 }
b6581717 1772 catch (semantic_error &e)
7e1279ea 1773 {
b6581717 1774 q->sess.print_error (e);
7e1279ea
FCE
1775 }
1776}
1777
1778static void
1779query_func_info (Dwarf_Addr entrypc,
bcc12710 1780 func_info & fi,
7e1279ea
FCE
1781 dwarf_query * q)
1782{
b6581717 1783 try
7e1279ea 1784 {
5a617dc6
JL
1785 // If it's a .return probe, we need to emit a *retprobe based on the
1786 // entrypc (PR13200). Note however that if prologue_end is valid,
1787 // dwarf_derived_probe will still take advantage of it by creating a new
1788 // probe there if necessary to pick up target vars (PR14436).
1789 if (fi.prologue_end == 0 || q->has_return)
1790 {
170ccf10 1791 q->prologue_end = fi.prologue_end;
5a617dc6
JL
1792 query_statement (fi.name, fi.decl_file, fi.decl_line,
1793 &fi.die, entrypc, q);
1794 }
b6581717 1795 else
5a617dc6 1796 {
5a617dc6
JL
1797 query_statement (fi.name, fi.decl_file, fi.decl_line,
1798 &fi.die, fi.prologue_end, q);
1799 }
7e1279ea 1800 }
b6581717 1801 catch (semantic_error &e)
7e1279ea 1802 {
b6581717 1803 q->sess.print_error (e);
7e1279ea
FCE
1804 }
1805}
1806
1807
bd4b874d 1808static void
de797211 1809query_srcfile_label (Dwarf_Addr addr, int lineno, dwarf_query * q)
bd4b874d 1810{
959ccfed
JL
1811 base_func_info_map_t bfis = q->filtered_all();
1812 base_func_info_map_t::iterator i;
1813 for (i = bfis.begin(); i != bfis.end(); ++i)
f09d0d1e
JS
1814 if (q->dw.die_has_pc (i->die, addr))
1815 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1816 q, query_label);
bd4b874d
SC
1817}
1818
7e1279ea 1819static void
de797211 1820query_srcfile_line (Dwarf_Addr addr, int lineno, dwarf_query * q)
7e1279ea 1821{
8fb810d7
JL
1822 assert (q->has_statement_str || q->has_function_str);
1823 assert (q->spec_type == function_file_and_line);
1824
959ccfed
JL
1825 base_func_info_map_t bfis = q->filtered_all();
1826 base_func_info_map_t::iterator i;
1827 for (i = bfis.begin(); i != bfis.end(); ++i)
897820ca 1828 {
3e961ba6 1829 if (q->dw.die_has_pc (i->die, addr))
959ccfed
JL
1830 {
1831 if (q->sess.verbose>3)
1832 clog << _("filtered DIE lands on srcfile\n");
1833 Dwarf_Die scope;
1834 q->dw.inner_die_containing_pc(i->die, addr, scope);
1835 query_statement (i->name, i->decl_file,
1836 lineno, // NB: not q->line !
1837 &scope, addr, q);
1838 }
20e4a32c 1839 }
7e1279ea
FCE
1840}
1841
7fdd3e2c
JS
1842bool
1843inline_instance_info::operator<(const inline_instance_info& other) const
1844{
1845 if (entrypc != other.entrypc)
1846 return entrypc < other.entrypc;
1847
1848 if (decl_line != other.decl_line)
1849 return decl_line < other.decl_line;
1850
1851 int cmp = name.compare(other.name);
c60517ca
FCE
1852
1853 if (!cmp)
1854 {
1855 assert (decl_file);
1856 assert (other.decl_file);
1857 cmp = strcmp(decl_file, other.decl_file);
1858 }
1859
7fdd3e2c
JS
1860 return cmp < 0;
1861}
1862
1863
4fa7b22b 1864static int
3956fccb 1865query_dwarf_inline_instance (Dwarf_Die * die, dwarf_query * q)
4fa7b22b 1866{
6b517475 1867 assert (q->has_statement_str || q->has_function_str);
4bda987e 1868 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1869
39bcd429 1870 try
7a053d3b 1871 {
b0ee93c4 1872 if (q->sess.verbose>2)
b530b5b3 1873 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1874
6b517475
JS
1875 Dwarf_Addr entrypc;
1876 if (q->dw.die_entrypc (die, &entrypc))
1877 {
1878 inline_instance_info inl;
1879 inl.die = *die;
1880 inl.name = q->dw.function_name;
1881 inl.entrypc = entrypc;
1882 q->dw.function_file (&inl.decl_file);
1883 q->dw.function_line (&inl.decl_line);
1884
1885 // make sure that this inline hasn't already
1886 // been matched from a different CU
1887 if (q->inline_dupes.insert(inl).second)
1888 q->filtered_inlines.push_back(inl);
1889 }
7e1279ea
FCE
1890 return DWARF_CB_OK;
1891 }
1892 catch (const semantic_error& e)
1893 {
1894 q->sess.print_error (e);
1895 return DWARF_CB_ABORT;
1896 }
1897}
bb788f9f 1898
7e1279ea 1899static int
7d007451 1900query_dwarf_func (Dwarf_Die * func, dwarf_query * q)
7e1279ea 1901{
6b517475 1902 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1903
bd25380d
JS
1904 // weed out functions whose decl_file isn't one of
1905 // the source files that we actually care about
6b517475 1906 if (q->spec_type != function_alone &&
bd25380d 1907 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1908 return DWARF_CB_OK;
bd25380d 1909
7e1279ea
FCE
1910 try
1911 {
7e1279ea
FCE
1912 q->dw.focus_on_function (func);
1913
7d6d0afc
JS
1914 if (!q->dw.function_scope_matches(q->scopes))
1915 return DWARF_CB_OK;
1916
857bdfd1
JS
1917 // make sure that this function address hasn't
1918 // already been matched under an aliased name
1919 Dwarf_Addr addr;
1920 if (!q->dw.func_is_inline() &&
1921 dwarf_entrypc(func, &addr) == 0 &&
1922 !q->alias_dupes.insert(addr).second)
1923 return DWARF_CB_OK;
1924
4bda987e 1925 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1926 {
4bda987e 1927 if (q->sess.verbose>3)
b530b5b3 1928 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1929 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1930 }
8f14e444
FCE
1931 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1932 {
1933 q->inlined_non_returnable.insert (q->dw.function_name);
1934 }
396afcee 1935 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1936 {
4bda987e
SC
1937 if (q->has_exported && !q->dw.func_is_exported ())
1938 return DWARF_CB_OK;
6b517475 1939 if (q->sess.verbose>2)
b530b5b3 1940 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1941
1942 func_info func;
1943 q->dw.function_die (&func.die);
1944 func.name = q->dw.function_name;
1945 q->dw.function_file (&func.decl_file);
1946 q->dw.function_line (&func.decl_line);
1947
1948 Dwarf_Addr entrypc;
1949 if (q->dw.function_entrypc (&entrypc))
1950 {
1951 func.entrypc = entrypc;
1952 q->filtered_functions.push_back (func);
1953 }
1954 /* else this function is fully inlined, just ignore it */
7e1279ea 1955 }
39bcd429 1956 return DWARF_CB_OK;
bd2b1e68 1957 }
39bcd429 1958 catch (const semantic_error& e)
bd2b1e68 1959 {
39bcd429
FCE
1960 q->sess.print_error (e);
1961 return DWARF_CB_ABORT;
bd2b1e68 1962 }
bd2b1e68
GH
1963}
1964
1965static int
5c378838 1966query_cu (Dwarf_Die * cudie, dwarf_query * q)
bd2b1e68 1967{
6b517475
JS
1968 assert (q->has_statement_str || q->has_function_str);
1969
85007c04 1970 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1971
39bcd429 1972 try
bd2b1e68 1973 {
7e1279ea 1974 q->dw.focus_on_cu (cudie);
b5d77020 1975
b0ee93c4 1976 if (false && q->sess.verbose>2)
b530b5b3
LB
1977 clog << _F("focused on CU '%s', in module '%s'\n",
1978 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1979
6b517475
JS
1980 q->filtered_srcfiles.clear();
1981 q->filtered_functions.clear();
1982 q->filtered_inlines.clear();
1983
1984 // In this path, we find "abstract functions", record
1985 // information about them, and then (depending on lineno
1986 // matching) possibly emit one or more of the function's
1987 // associated addresses. Unfortunately the control of this
1988 // cannot easily be turned inside out.
1989
1990 if (q->spec_type != function_alone)
39bcd429 1991 {
6b517475
JS
1992 // If we have a pattern string with a filename, we need
1993 // to elaborate the srcfile mask in question first.
1994 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1995
1996 // If we have a file pattern and *no* srcfile matches, there's
1997 // no need to look further into this CU, so skip.
1998 if (q->filtered_srcfiles.empty())
1999 return DWARF_CB_OK;
2000 }
e4c58386 2001
6b517475
JS
2002 // Pick up [entrypc, name, DIE] tuples for all the functions
2003 // matching the query, and fill in the prologue endings of them
2004 // all in a single pass.
5898b6e1 2005 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
2006 if (rc != DWARF_CB_OK)
2007 q->query_done = true;
2008
277a2b96
JL
2009 if (!q->filtered_functions.empty() &&
2010 !q->has_statement_str && // PR 2608
2011 (q->sess.prologue_searching ||
2012 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
2013 q->dw.resolve_prologue_endings (q->filtered_functions);
6b517475
JS
2014
2015 if (q->spec_type == function_file_and_line)
2016 {
58b070fb 2017 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 2018 if (q->has_function_str)
b530b5b3 2019 q->sess.print_warning (_("For probing a particular line, use a "
b78a0fbb 2020 ".statement() probe, not .function()"),
af2e341f 2021 q->base_probe->tok);
58b070fb 2022
de797211 2023 void (* callback) (Dwarf_Addr, int, dwarf_query*) =
6b517475 2024 q->has_label ? query_srcfile_label : query_srcfile_line;
516e1e2c
JL
2025
2026 base_func_info_map_t bfis = q->filtered_all();
2027
2028 set<string>::const_iterator srcfile;
2029 for (srcfile = q->filtered_srcfiles.begin();
2030 srcfile != q->filtered_srcfiles.end(); ++srcfile)
2031 q->dw.iterate_over_srcfile_lines(srcfile->c_str(), q->linenos,
2032 q->lineno_type, bfis, callback, q);
6b517475
JS
2033 }
2034 else if (q->has_label)
2035 {
959ccfed
JL
2036 base_func_info_map_t bfis = q->filtered_all();
2037 base_func_info_map_t::iterator i;
2038 for (i = bfis.begin(); i != bfis.end(); ++i)
6b517475
JS
2039 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
2040 q, query_label);
39bcd429 2041 }
67959c62
JL
2042 else if (q->has_callee || q->has_callees_num)
2043 {
2044 // .callee(str) --> str, .callees[(N)] --> "*"
2045 string callee_val = q->has_callee ? q->callee_val : "*";
2046 long callees_num_val = q->has_callees_num ? q->callees_num_val : 1;
2047
2048 // NB: We filter functions that do not match the file here rather than
2049 // in query_callee because we only want the filtering to apply to the
2050 // first level, not to callees that are recursed into if
2051 // callees_num_val > 1.
959ccfed
JL
2052 base_func_info_map_t bfis = q->filtered_all();
2053 base_func_info_map_t::iterator i;
2054 for (i = bfis.begin(); i != bfis.end(); ++i)
67959c62
JL
2055 {
2056 if (q->spec_type != function_alone &&
2057 q->filtered_srcfiles.count(i->decl_file) == 0)
2058 continue;
2059 q->dw.iterate_over_callees (&i->die, callee_val,
2060 callees_num_val,
e772a6e7 2061 q, query_callee, *i);
67959c62
JL
2062 }
2063 }
6b517475
JS
2064 else
2065 {
2066 // Otherwise, simply probe all resolved functions.
2067 for (func_info_map_t::iterator i = q->filtered_functions.begin();
2068 i != q->filtered_functions.end(); ++i)
2069 query_func_info (i->entrypc, *i, q);
2070
2071 // And all inline instances (if we're not excluding inlines with ".call")
2072 if (! q->has_call)
2073 for (inline_instance_map_t::iterator i
2074 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
2075 query_inline_instance_info (*i, q);
e772a6e7 2076 }
39bcd429 2077 return DWARF_CB_OK;
bd2b1e68 2078 }
39bcd429 2079 catch (const semantic_error& e)
bd2b1e68 2080 {
39bcd429
FCE
2081 q->sess.print_error (e);
2082 return DWARF_CB_ABORT;
bd2b1e68 2083 }
bd2b1e68
GH
2084}
2085
0ce64fb8 2086
4df79aaf
JS
2087void
2088dwarf_query::query_module_functions ()
2089{
2090 try
2091 {
2092 filtered_srcfiles.clear();
2093 filtered_functions.clear();
2094 filtered_inlines.clear();
2095
2096 // Collect all module functions so we know which CUs are interesting
2097 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
2098 if (rc != DWARF_CB_OK)
2099 {
2100 query_done = true;
2101 return;
2102 }
2103
2104 set<void*> used_cus; // by cu->addr
2105 vector<Dwarf_Die> cus;
2106 Dwarf_Die cu_mem;
2107
959ccfed
JL
2108 base_func_info_map_t bfis = filtered_all();
2109 base_func_info_map_t::iterator i;
2110 for (i = bfis.begin(); i != bfis.end(); ++i)
4df79aaf
JS
2111 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
2112 used_cus.insert(cu_mem.addr).second)
2113 cus.push_back(cu_mem);
2114
2115 // Reset the dupes since we didn't actually collect them the first time
2116 alias_dupes.clear();
2117 inline_dupes.clear();
2118
2119 // Run the query again on the individual CUs
91bb9081
LB
2120 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i){
2121 rc = query_cu(&*i, this);
2122 if (rc != DWARF_CB_OK)
2123 {
2124 query_done = true;
2125 return;
2126 }
2127 }
4df79aaf
JS
2128 }
2129 catch (const semantic_error& e)
2130 {
2131 sess.print_error (e);
2132 }
2133}
2134
2135
5f0a03a6
JK
2136static void
2137validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
2138{
2139 // Validate the machine code in this elf file against the
2140 // session machine. This is important, in case the wrong kind
2141 // of debuginfo is being automagically processed by elfutils.
2142 // While we can tell i686 apart from x86-64, unfortunately
2143 // we can't help confusing i586 vs i686 (both EM_386).
2144
2145 Dwarf_Addr bias;
2146 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
2147 // because dwfl_module_getelf can force costly section relocations
2148 // we don't really need, while either will do for this purpose.
2149 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
2150 ?: dwfl_module_getelf (mod, &bias));
2151
2152 GElf_Ehdr ehdr_mem;
2153 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 2154 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 2155 assert(em);
5f0a03a6
JK
2156 int elf_machine = em->e_machine;
2157 const char* debug_filename = "";
2158 const char* main_filename = "";
2159 (void) dwfl_module_info (mod, NULL, NULL,
2160 NULL, NULL, NULL,
2161 & main_filename,
2162 & debug_filename);
2163 const string& sess_machine = q->sess.architecture;
756c9462
FCE
2164
2165 string expect_machine; // to match sess.machine (i.e., kernel machine)
2166 string expect_machine2;
5f0a03a6 2167
d27e6fd5 2168 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
2169 switch (elf_machine)
2170 {
756c9462
FCE
2171 // x86 and ppc are bi-architecture; a 64-bit kernel
2172 // can normally run either 32-bit or 64-bit *userspace*.
2173 case EM_386:
2174 expect_machine = "i?86";
2175 if (! q->has_process) break; // 32-bit kernel/module
2176 /* FALLSTHROUGH */
2177 case EM_X86_64:
2178 expect_machine2 = "x86_64";
2179 break;
2180 case EM_PPC:
756c9462 2181 case EM_PPC64:
5a1c472e 2182 expect_machine = "powerpc";
756c9462 2183 break;
3fe7d888 2184 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2185 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2186 case EM_ARM: expect_machine = "arm*"; break;
86aae990 2187 case EM_AARCH64: expect_machine = "arm64"; break;
5f0a03a6
JK
2188 // XXX: fill in some more of these
2189 default: expect_machine = "?"; break;
2190 }
2191
2192 if (! debug_filename) debug_filename = main_filename;
2193 if (! debug_filename) debug_filename = name;
2194
756c9462
FCE
2195 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2196 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2197 {
2198 stringstream msg;
b530b5b3
LB
2199 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2200 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2201 sess_machine.c_str(), debug_filename);
dc09353a 2202 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2203 }
2204
b57082de 2205 if (q->sess.verbose>1)
b78a0fbb 2206 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2207 " file %s ELF machine %s|%s (code %d)\n",
2208 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2209 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2210 expect_machine2.c_str(), elf_machine);
5f0a03a6 2211}
1d3a40b6 2212
91af0778
FCE
2213
2214
2215static Dwarf_Addr
2216lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2217{
2218 int syments = dwfl_module_getsymtab(m);
2219 assert(syments);
2220 for (int i = 1; i < syments; ++i)
2221 {
2222 GElf_Sym sym;
2223 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2224 if (name != NULL && strcmp(name, wanted) == 0)
2225 return sym.st_value;
2226 }
2227
2228 return 0;
2229}
2230
2231
2232
bd2b1e68 2233static int
b8da0ad1 2234query_module (Dwfl_Module *mod,
91af0778 2235 void **,
b8da0ad1 2236 const char *name,
6f4c1275 2237 Dwarf_Addr addr,
06de3a04 2238 base_query *q)
bd2b1e68 2239{
39bcd429 2240 try
e38d6504 2241 {
91af0778
FCE
2242 module_info* mi = q->sess.module_cache->cache[name];
2243 if (mi == 0)
2244 {
2245 mi = q->sess.module_cache->cache[name] = new module_info(name);
2246
6f4c1275
FCE
2247 mi->mod = mod;
2248 mi->addr = addr;
91af0778 2249
6f4c1275
FCE
2250 const char* debug_filename = "";
2251 const char* main_filename = "";
2252 (void) dwfl_module_info (mod, NULL, NULL,
2253 NULL, NULL, NULL,
2254 & main_filename,
2255 & debug_filename);
2256
ab3ed72d 2257 if (debug_filename || main_filename)
91af0778 2258 {
6f4c1275
FCE
2259 mi->elf_path = debug_filename ?: main_filename;
2260 }
2261 else if (name == TOK_KERNEL)
2262 {
2263 mi->dwarf_status = info_absent;
91af0778 2264 }
91af0778
FCE
2265 }
2266 // OK, enough of that module_info caching business.
2267
5f0a03a6 2268 q->dw.focus_on_module(mod, mi);
d9b516ca 2269
39bcd429
FCE
2270 // If we have enough information in the pattern to skip a module and
2271 // the module does not match that information, return early.
b8da0ad1 2272 if (!q->dw.module_name_matches(q->module_val))
85007c04 2273 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2274
2275 // Don't allow module("*kernel*") type expressions to match the
2276 // elfutils module "kernel", which we refer to in the probe
2277 // point syntax exclusively as "kernel.*".
2278 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2279 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2280
5f0a03a6
JK
2281 if (mod)
2282 validate_module_elf(mod, name, q);
2283 else
91af0778
FCE
2284 assert(q->has_kernel); // and no vmlinux to examine
2285
2286 if (q->sess.verbose>2)
b530b5b3 2287 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2288
2289
2290 // Collect a few kernel addresses. XXX: these belong better
2291 // to the sess.module_info["kernel"] struct.
2292 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2293 {
91af0778
FCE
2294 if (! q->sess.sym_kprobes_text_start)
2295 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2296 if (! q->sess.sym_kprobes_text_end)
2297 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2298 if (! q->sess.sym_stext)
2299 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2300 }
2301
47e226ed
SC
2302 // We either have a wildcard or an unresolved library
2303 if (q->has_library && (contains_glob_chars (q->path)
2304 || q->path.find('/') == string::npos))
84c84ac4
SC
2305 // handle .library(GLOB)
2306 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2307 // .plt is translated to .plt.statement(N). We only want to iterate for the
2308 // .plt case
2309 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2310 {
2311 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2312 q->visited_modules.insert(name);
2313 }
84c84ac4 2314 else
070764c0
JL
2315 {
2316 // search the module for matches of the probe point.
2317 q->handle_query_module();
2318 q->visited_modules.insert(name);
2319 }
bb788f9f 2320
b8da0ad1 2321 // If we know that there will be no more matches, abort early.
85007c04 2322 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2323 return DWARF_CB_ABORT;
2324 else
2325 return DWARF_CB_OK;
7a053d3b 2326 }
39bcd429 2327 catch (const semantic_error& e)
bd2b1e68 2328 {
39bcd429
FCE
2329 q->sess.print_error (e);
2330 return DWARF_CB_ABORT;
bd2b1e68 2331 }
bd2b1e68
GH
2332}
2333
35d4ab18 2334
84c84ac4 2335void
bbbc7241 2336base_query::query_library_callback (base_query *me, const char *data)
84c84ac4 2337{
5d5bd369 2338 me->query_library (data);
84c84ac4
SC
2339}
2340
2341
2cbcfa9c 2342string
51d6bda3
SC
2343query_one_library (const char *library, dwflpp & dw,
2344 const string user_lib, probe * base_probe, probe_point *base_loc,
2345 vector<derived_probe *> & results)
84c84ac4 2346{
47e226ed 2347 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2348 {
05fb3e0c
WF
2349 string library_path = find_executable (library, "", dw.sess.sysenv,
2350 "LD_LIBRARY_PATH");
84c84ac4
SC
2351 probe_point* specific_loc = new probe_point(*base_loc);
2352 specific_loc->optional = true;
ef0943df 2353 specific_loc->from_glob = true;
84c84ac4
SC
2354 vector<probe_point::component*> derived_comps;
2355
5d25dfb6
JL
2356 // Create new probe point for the matching library. This is what will be
2357 // shown in listing mode. Also replace the process(str) with the real
2358 // absolute path rather than keeping what the user typed in.
84c84ac4
SC
2359 vector<probe_point::component*>::iterator it;
2360 for (it = specific_loc->components.begin();
2361 it != specific_loc->components.end(); ++it)
5d25dfb6
JL
2362 if ((*it)->functor == TOK_PROCESS)
2363 derived_comps.push_back(new probe_point::component(TOK_PROCESS,
2364 new literal_string(path_remove_sysroot(dw.sess, dw.module_name))));
2365 else if ((*it)->functor == TOK_LIBRARY)
84c84ac4
SC
2366 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2367 new literal_string(library_path)));
2368 else
2369 derived_comps.push_back(*it);
2370 probe_point* derived_loc = new probe_point(*specific_loc);
2371 derived_loc->components = derived_comps;
8159bf55 2372 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2373 derive_probes(dw.sess, new_base, results);
2374 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2375 clog << _("module=") << library_path << endl;
2376 return library_path;
84c84ac4 2377 }
2cbcfa9c 2378 return "";
84c84ac4
SC
2379}
2380
2381
51d6bda3
SC
2382void
2383dwarf_query::query_library (const char *library)
2384{
2cbcfa9c
JL
2385 string library_path =
2386 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2387 if (!library_path.empty())
2388 visited_modules.insert(library_path);
51d6bda3
SC
2389}
2390
576eaefe
SC
2391struct plt_expanding_visitor: public var_expanding_visitor
2392{
2393 plt_expanding_visitor(const string & entry):
2394 entry (entry)
2395 {
2396 }
2397 const string & entry;
2398
2399 void visit_target_symbol (target_symbol* e);
2400};
2401
2402
2403void
45cdb40e 2404base_query::query_plt_callback (base_query *me, const char *entry, size_t address)
576eaefe 2405{
576eaefe
SC
2406 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2407 me->query_plt (entry, address);
7f4964f1 2408 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2409}
2410
2411
2412void
2413query_one_plt (const char *entry, long addr, dwflpp & dw,
2414 probe * base_probe, probe_point *base_loc,
2415 vector<derived_probe *> & results)
2416{
2417 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2418 vector<probe_point::component*> derived_comps;
2419
2420 if (dw.sess.verbose > 2)
2421 clog << _F("plt entry=%s\n", entry);
2422
576eaefe
SC
2423 vector<probe_point::component*>::iterator it;
2424 for (it = specific_loc->components.begin();
2425 it != specific_loc->components.end(); ++it)
2426 if ((*it)->functor == TOK_PLT)
3d372d6b 2427 {
8159bf55
FCE
2428 *it = new probe_point::component(TOK_PLT,
2429 new literal_string(entry));
3d372d6b
SC
2430 derived_comps.push_back(*it);
2431 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2432 new literal_number(addr, true)));
3d372d6b 2433 }
576eaefe
SC
2434 else
2435 derived_comps.push_back(*it);
2436 probe_point* derived_loc = new probe_point(*specific_loc);
2437 derived_loc->components = derived_comps;
02c34e38
FCE
2438 probe *new_base = new probe (new probe (base_probe, specific_loc),
2439 derived_loc);
576eaefe
SC
2440 string e = string(entry);
2441 plt_expanding_visitor pltv (e);
2442 pltv.replace (new_base->body);
2443 derive_probes(dw.sess, new_base, results);
2444}
2445
2446
2447void
2448dwarf_query::query_plt (const char *entry, size_t address)
2449{
2450 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2451}
51d6bda3 2452
435f53a7
FCE
2453// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2454// but the needed declaration for module_cache is not available there.
2455// Nor for that matter in session.cxx. Only in this CU is that field ever
2456// set (in query_module() above), so we clean it up here too.
2457static void
2458delete_session_module_cache (systemtap_session& s)
2459{
2460 if (s.module_cache) {
2461 if (s.verbose > 3)
b530b5b3 2462 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2463 delete s.module_cache;
2464 s.module_cache = 0;
2465 }
2466}
2467
2468
de688825 2469struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2470{
77de5e9e 2471 dwarf_query & q;
bcc12710 2472 Dwarf_Die *scope_die;
77de5e9e 2473 Dwarf_Addr addr;
8c819921 2474 block *add_block;
2260f4e3 2475 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2476 // NB: tids are not always collected in add_block & add_call_probe, because
2477 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2478 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2479 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2480 unsigned saved_longs, saved_strings; // data saved within kretprobes
2481 map<std::string, expression *> return_ts_map;
729455a7 2482 vector<Dwarf_Die> scopes;
3689db05 2483 // probe counter name -> pointer of associated probe
698de6cc 2484 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2485 bool visited;
77de5e9e 2486
de688825 2487 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2488 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2489 add_block_tid(false), add_call_probe_tid(false),
af234c40 2490 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2491 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2492 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2493 void visit_target_symbol_saved_return (target_symbol* e);
2494 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2495 void visit_target_symbol (target_symbol* e);
bd1fcbad 2496 void visit_atvar_op (atvar_op* e);
c24447be 2497 void visit_cast_op (cast_op* e);
8cc799a5 2498 void visit_entry_op (entry_op* e);
3689db05 2499 void visit_perf_op (perf_op* e);
729455a7
JS
2500private:
2501 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2502};
2503
2504
de688825 2505unsigned var_expanding_visitor::tick = 0;
77de5e9e 2506
a50de939 2507
74fe61bc 2508var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2509{
2510 // FIXME: for the time being, by default we only support plain '$foo
2511 // = bar', not '+=' or any other op= variant. This is fixable, but a
2512 // bit ugly.
2513 //
2514 // If derived classes desire to add additional operator support, add
2515 // new operators to this list in the derived class constructor.
2516 valid_ops.insert ("=");
2517}
2518
2519
87214add
JS
2520bool
2521var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2522 expression*& lvalue, expression*& rvalue)
77de5e9e 2523{
e57b735a
GH
2524 // Our job would normally be to require() the left and right sides
2525 // into a new assignment. What we're doing is slightly trickier:
2526 // we're pushing a functioncall** onto a stack, and if our left
2527 // child sets the functioncall* for that value, we're going to
2528 // assume our left child was a target symbol -- transformed into a
2529 // set_target_foo(value) call, and it wants to take our right child
2530 // as the argument "value".
2531 //
2532 // This is why some people claim that languages with
2533 // constructor-decomposing case expressions have a leg up on
2534 // visitors.
2535
2536 functioncall *fcall = NULL;
d9b516ca 2537
a50de939 2538 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2539 const string* old_op = op;
2540 op = &eop;
a50de939 2541
e57b735a 2542 target_symbol_setter_functioncalls.push (&fcall);
87214add 2543 replace (lvalue);
e57b735a 2544 target_symbol_setter_functioncalls.pop ();
87214add
JS
2545 replace (rvalue);
2546
2547 op = old_op;
e57b735a
GH
2548
2549 if (fcall != NULL)
77de5e9e 2550 {
e57b735a
GH
2551 // Our left child is informing us that it was a target variable
2552 // and it has been replaced with a set_target_foo() function
2553 // call; we are going to provide that function call -- with the
2554 // right child spliced in as sole argument -- in place of
de688825 2555 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2556
87214add 2557 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2558 {
2559 // Build up a list of supported operators.
2560 string ops;
2561 std::set<string>::iterator i;
b530b5b3 2562 int valid_ops_size = 0;
a50de939 2563 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2564 {
a50de939 2565 ops += " " + *i + ",";
b530b5b3
LB
2566 valid_ops_size++;
2567 }
a50de939
DS
2568 ops.resize(ops.size() - 1); // chop off the last ','
2569
2570 // Throw the error.
dc09353a 2571 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2572 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2573 valid_ops_size, ops.c_str()), tok);
b530b5b3 2574
a50de939 2575 }
e57b735a 2576
87214add
JS
2577 assert (lvalue == fcall);
2578 if (rvalue)
2579 fcall->args.push_back (rvalue);
4ed05b15 2580 provide (fcall);
87214add 2581 return true;
77de5e9e 2582 }
e57b735a 2583 else
87214add
JS
2584 return false;
2585}
2586
2587
2588void
2589var_expanding_visitor::visit_assignment (assignment* e)
2590{
2591 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2592 provide (e);
2593}
2594
2595
2596void
2597var_expanding_visitor::visit_pre_crement (pre_crement* e)
2598{
2599 expression *dummy = NULL;
2600 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2601 provide (e);
2602}
2603
2604
2605void
2606var_expanding_visitor::visit_post_crement (post_crement* e)
2607{
2608 expression *dummy = NULL;
2609 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2610 provide (e);
2611}
2612
2613
2614void
2615var_expanding_visitor::visit_delete_statement (delete_statement* s)
2616{
2617 string fakeop = "delete";
2618 expression *dummy = NULL;
2619 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2620 provide (s);
e57b735a 2621}
d9b516ca 2622
d7f3e0c5 2623
30263a73
FCE
2624void
2625var_expanding_visitor::visit_defined_op (defined_op* e)
2626{
2627 bool resolved = true;
2628
2629 defined_ops.push (e);
2630 try {
2631 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2632 // defined with a target_symbol* operand, a subsidiary call may attempt to
2633 // rewrite it to a general expression* instead, and require<> happily
2634 // casts to/from void*, causing possible memory corruption. We use
2635 // expression* here, being the general case of rewritten $variable.
2636 expression *foo1 = e->operand;
2637 foo1 = require (foo1);
2638
c69a87e0 2639 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2640 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2641 // erroneous resolutions. Some would signal a visit_target_symbol failure
2642 // with an exception, with a set flag within the target_symbol, or nothing
2643 // at all.
30263a73 2644 //
c69a87e0
FCE
2645 // Now, failures always have to be signalled with a
2646 // saved_conversion_error being chained to the target_symbol.
2647 // Successes have to result in an attempted rewrite of the
850bfddd 2648 // target_symbol (via provide()).
780f11ff 2649 //
c69a87e0
FCE
2650 // Edna Mode: "no capes". fche: "no exceptions".
2651
30263a73
FCE
2652 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2653 //
2654 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2655 //
2656 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2657 // dwarf probe to take care of it.
2658 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2659 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2660 //
30263a73
FCE
2661 // utrace: success: rewrites to function; failure: semantic_error
2662 //
850bfddd 2663 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2664
2665 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2666 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2667 resolved = false;
a45664f4 2668 else if (foo2) // unresolved but not marked failing
b7aedf26 2669 {
780f11ff
JS
2670 // There are some visitors that won't touch certain target_symbols,
2671 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2672 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2673 e->operand = foo2;
2674 provide (e);
2675 return;
2676 }
30263a73
FCE
2677 else // resolved, rewritten to some other expression type
2678 resolved = true;
780f11ff 2679 } catch (const semantic_error& e) {
c69a87e0 2680 assert (0); // should not happen
30263a73
FCE
2681 }
2682 defined_ops.pop ();
2683
2684 literal_number* ln = new literal_number (resolved ? 1 : 0);
2685 ln->tok = e->tok;
2686 provide (ln);
2687}
2688
2689
5f36109e
JS
2690struct dwarf_pretty_print
2691{
2692 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2693 const string& local, bool userspace_p,
2694 const target_symbol& e):
d19a9a82
JS
2695 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2696 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2697 {
2698 init_ts (e);
2699 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2700 }
2701
2702 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2703 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2704 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2705 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2706 {
2707 init_ts (e);
2708 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2709 }
2710
2711 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2712 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2713 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2714 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2715 {
2716 init_ts (e);
2717 dw.type_die_for_pointer (type_die, ts, &base_type);
2718 }
2719
2720 functioncall* expand ();
ce83ff57 2721 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2722
2723private:
2724 dwflpp& dw;
2725 target_symbol* ts;
7d11d8c9 2726 bool print_full;
5f36109e
JS
2727 Dwarf_Die base_type;
2728
2729 string local;
2730 vector<Dwarf_Die> scopes;
2731 Dwarf_Addr pc;
2732
2733 expression* pointer;
2734 Dwarf_Die pointer_type;
2735
d19a9a82 2736 const bool userspace_p, deref_p;
5f36109e
JS
2737
2738 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2739 print_format* pf, bool top=false);
600551ca
JS
2740 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2741 print_format* pf);
5f36109e 2742 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2743 print_format* pf);
5f36109e 2744 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2745 print_format* pf, bool top);
5f36109e 2746 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2747 print_format* pf, bool top);
5f36109e 2748 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2749 print_format* pf, bool top);
5f36109e 2750 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2751 print_format* pf, int& count);
bbee5bb8 2752 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2753
2754 void init_ts (const target_symbol& e);
2755 expression* deref (target_symbol* e);
c55ea10d 2756 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2757};
2758
2759
2760void
2761dwarf_pretty_print::init_ts (const target_symbol& e)
2762{
2763 // Work with a new target_symbol so we can modify arguments
2764 ts = new target_symbol (e);
2765
2766 if (ts->addressof)
dc09353a 2767 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2768
2769 if (ts->components.empty() ||
2770 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2771 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2772 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2773 ts->components.pop_back();
2774}
2775
2776
2777functioncall*
2778dwarf_pretty_print::expand ()
2779{
2780 static unsigned tick = 0;
2781
2782 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2783 // try {
2784 // return sprintf("{.foo=...}", (ts)->foo, ...)
2785 // } catch {
2786 // return "ERROR"
2787 // }
5f36109e
JS
2788 // }
2789
2790 // Create the function decl and call.
2791
2792 functiondecl *fdecl = new functiondecl;
2793 fdecl->tok = ts->tok;
2794 fdecl->synthetic = true;
2795 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2796 fdecl->type = pe_string;
2797
2798 functioncall* fcall = new functioncall;
2799 fcall->tok = ts->tok;
2800 fcall->function = fdecl->name;
140be17a 2801 fcall->type = pe_string;
5f36109e
JS
2802
2803 // If there's a <pointer>, replace it with a new var and make that
2804 // the first function argument.
2805 if (pointer)
2806 {
2807 vardecl *v = new vardecl;
2808 v->type = pe_long;
2809 v->name = "pointer";
2810 v->tok = ts->tok;
2811 fdecl->formal_args.push_back (v);
2812 fcall->args.push_back (pointer);
2813
2814 symbol* sym = new symbol;
2815 sym->tok = ts->tok;
2816 sym->name = v->name;
5f36109e
JS
2817 pointer = sym;
2818 }
2819
2820 // For each expression argument, replace it with a function argument.
2821 for (unsigned i = 0; i < ts->components.size(); ++i)
2822 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2823 {
2824 vardecl *v = new vardecl;
2825 v->type = pe_long;
2826 v->name = "index" + lex_cast(i);
2827 v->tok = ts->tok;
2828 fdecl->formal_args.push_back (v);
2829 fcall->args.push_back (ts->components[i].expr_index);
2830
2831 symbol* sym = new symbol;
2832 sym->tok = ts->tok;
2833 sym->name = v->name;
5f36109e
JS
2834 ts->components[i].expr_index = sym;
2835 }
2836
2837 // Create the return sprintf.
1c922ad7 2838 print_format* pf = print_format::create(ts->tok, "sprintf");
5f36109e
JS
2839 return_statement* rs = new return_statement;
2840 rs->tok = ts->tok;
2841 rs->value = pf;
5f36109e
JS
2842
2843 // Recurse into the actual values.
7d11d8c9 2844 recurse (&base_type, ts, pf, true);
5f36109e
JS
2845 pf->components = print_format::string_to_components(pf->raw_components);
2846
7d11d8c9
JS
2847 // Create the try-catch net
2848 try_block* tb = new try_block;
2849 tb->tok = ts->tok;
2850 tb->try_block = rs;
2851 tb->catch_error_var = 0;
2852 return_statement* rs2 = new return_statement;
2853 rs2->tok = ts->tok;
2854 rs2->value = new literal_string ("ERROR");
2855 rs2->value->tok = ts->tok;
2856 tb->catch_block = rs2;
2857 fdecl->body = tb;
2858
f8809d54 2859 fdecl->join (dw.sess);
5f36109e
JS
2860 return fcall;
2861}
2862
2863
2864void
2865dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2866 print_format* pf, bool top)
5f36109e
JS
2867{
2868 Dwarf_Die type;
2869 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2870
2871 switch (dwarf_tag(&type))
2872 {
2873 default:
2874 // XXX need a warning?
2875 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2876 // + ") for " + dwarf_type_name(&type), e->tok);
2877 pf->raw_components.append("?");
2878 break;
2879
2880 case DW_TAG_enumeration_type:
2881 case DW_TAG_base_type:
7d11d8c9 2882 recurse_base (&type, e, pf);
5f36109e
JS
2883 break;
2884
2885 case DW_TAG_array_type:
7d11d8c9 2886 recurse_array (&type, e, pf, top);
5f36109e
JS
2887 break;
2888
2889 case DW_TAG_pointer_type:
2890 case DW_TAG_reference_type:
2891 case DW_TAG_rvalue_reference_type:
7d11d8c9 2892 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2893 break;
2894
2895 case DW_TAG_subroutine_type:
c55ea10d 2896 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2897 break;
2898
2899 case DW_TAG_union_type:
5f36109e
JS
2900 case DW_TAG_structure_type:
2901 case DW_TAG_class_type:
7d11d8c9 2902 recurse_struct (&type, e, pf, top);
5f36109e
JS
2903 break;
2904 }
2905}
2906
2907
600551ca
JS
2908// Bit fields are handled as a special-case combination of recurse() and
2909// recurse_base(), only called from recurse_struct_members(). The main
2910// difference is that the value is always printed numerically, even if the
2911// underlying type is a char.
2912void
2913dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2914 print_format* pf)
2915{
2916 Dwarf_Die type;
2917 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2918
2919 int tag = dwarf_tag(&type);
2920 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2921 {
2922 // XXX need a warning?
2923 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2924 // + ") for " + dwarf_type_name(&type), e->tok);
2925 pf->raw_components.append("?");
2926 return;
2927 }
2928
2929 Dwarf_Attribute attr;
2930 Dwarf_Word encoding = (Dwarf_Word) -1;
2931 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2932 &encoding);
2933 switch (encoding)
2934 {
2935 case DW_ATE_float:
2936 case DW_ATE_complex_float:
2937 // XXX need a warning?
2938 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2939 // + ") for " + dwarf_type_name(&type), e->tok);
2940 pf->raw_components.append("?");
2941 break;
2942
2943 case DW_ATE_unsigned:
2944 case DW_ATE_unsigned_char:
2945 push_deref (pf, "%u", e);
2946 break;
2947
2948 case DW_ATE_signed:
2949 case DW_ATE_signed_char:
2950 default:
2951 push_deref (pf, "%i", e);
2952 break;
2953 }
2954}
2955
2956
5f36109e
JS
2957void
2958dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2959 print_format* pf)
5f36109e
JS
2960{
2961 Dwarf_Attribute attr;
2962 Dwarf_Word encoding = (Dwarf_Word) -1;
2963 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2964 &encoding);
5f36109e
JS
2965 switch (encoding)
2966 {
2967 case DW_ATE_float:
2968 case DW_ATE_complex_float:
2969 // XXX need a warning?
2970 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2971 // + ") for " + dwarf_type_name(type), e->tok);
2972 pf->raw_components.append("?");
5f36109e
JS
2973 break;
2974
6561d8d1 2975 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2976 case DW_ATE_signed_char:
2977 case DW_ATE_unsigned_char:
941101c1
JS
2978 // Use escapes to make sure that non-printable characters
2979 // don't interrupt our stream (especially '\0' values).
2980 push_deref (pf, "'%#c'", e);
5f36109e
JS
2981 break;
2982
2983 case DW_ATE_unsigned:
c55ea10d 2984 push_deref (pf, "%u", e);
5f36109e
JS
2985 break;
2986
600551ca 2987 case DW_ATE_signed:
5f36109e 2988 default:
c55ea10d 2989 push_deref (pf, "%i", e);
5f36109e
JS
2990 break;
2991 }
5f36109e
JS
2992}
2993
2994
2995void
2996dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2997 print_format* pf, bool top)
5f36109e 2998{
7d11d8c9
JS
2999 if (!top && !print_full)
3000 {
3001 pf->raw_components.append("[...]");
3002 return;
3003 }
3004
5f36109e
JS
3005 Dwarf_Die childtype;
3006 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
3007
3008 if (print_chars (&childtype, e, pf))
3009 return;
3010
5f36109e
JS
3011 pf->raw_components.append("[");
3012
3013 // We print the array up to the first 5 elements.
3014 // XXX how can we determine the array size?
3015 // ... for now, just print the first element
64cddf39 3016 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 3017 unsigned i, size = 1;
64cddf39 3018 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
3019 {
3020 if (i > 0)
3021 pf->raw_components.append(", ");
3022 target_symbol* e2 = new target_symbol(*e);
3023 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 3024 recurse (&childtype, e2, pf);
5f36109e
JS
3025 }
3026 if (i < size || 1/*XXX until real size is known */)
3027 pf->raw_components.append(", ...");
3028 pf->raw_components.append("]");
3029}
3030
3031
3032void
3033dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3034 print_format* pf, bool top)
5f36109e 3035{
7d11d8c9 3036 // We chase to top-level pointers, but leave the rest alone
d19a9a82 3037 bool void_p = true;
7d11d8c9 3038 Dwarf_Die pointee;
bbee5bb8 3039 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
3040 {
3041 try
3042 {
3043 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
3044 void_p = false;
3045 }
3046 catch (const semantic_error&) {}
3047 }
3048
3049 if (!void_p)
5f36109e 3050 {
bbee5bb8
JS
3051 if (print_chars (&pointee, e, pf))
3052 return;
3053
3054 if (top)
3055 {
3056 recurse (&pointee, e, pf, top);
3057 return;
3058 }
5f36109e 3059 }
bbee5bb8 3060
c55ea10d 3061 push_deref (pf, "%p", e);
5f36109e
JS
3062}
3063
3064
3065void
3066dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3067 print_format* pf, bool top)
5f36109e 3068{
bdec0e18
JS
3069 if (dwarf_hasattr(type, DW_AT_declaration))
3070 {
a44a7cb5 3071 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
3072 if (!resolved)
3073 {
3074 // could be an error, but for now just stub it
3075 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
3076 pf->raw_components.append("{...}");
3077 return;
3078 }
3079 type = resolved;
3080 }
3081
5f36109e
JS
3082 int count = 0;
3083 pf->raw_components.append("{");
7d11d8c9
JS
3084 if (top || print_full)
3085 recurse_struct_members (type, e, pf, count);
3086 else
3087 pf->raw_components.append("...");
5f36109e
JS
3088 pf->raw_components.append("}");
3089}
3090
3091
3092void
3093dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3094 print_format* pf, int& count)
5f36109e 3095{
a80f28d8
JS
3096 /* With inheritance, a subclass may mask member names of parent classes, so
3097 * our search among the inheritance tree must be breadth-first rather than
3098 * depth-first (recursive). The type die is still our starting point. When
3099 * we encounter a masked name, just skip it. */
3100 set<string> dupes;
3101 deque<Dwarf_Die> inheritees(1, *type);
3102 for (; !inheritees.empty(); inheritees.pop_front())
3103 {
dee830d9 3104 Dwarf_Die child, childtype, import;
a80f28d8
JS
3105 if (dwarf_child (&inheritees.front(), &child) == 0)
3106 do
3107 {
3108 target_symbol* e2 = e;
5f36109e 3109
a80f28d8
JS
3110 // skip static members
3111 if (dwarf_hasattr(&child, DW_AT_declaration))
3112 continue;
5f36109e 3113
a80f28d8 3114 int tag = dwarf_tag (&child);
5f36109e 3115
dee830d9
MW
3116 /* Pretend imported units contain members by recursing into
3117 struct_member printing with the same count. */
3118 if (tag == DW_TAG_imported_unit
3119 && dwarf_attr_die (&child, DW_AT_import, &import))
3120 recurse_struct_members (&import, e2, pf, count);
3121
a80f28d8
JS
3122 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
3123 continue;
5f36109e 3124
a80f28d8 3125 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 3126
a80f28d8
JS
3127 if (tag == DW_TAG_inheritance)
3128 {
3129 inheritees.push_back(childtype);
3130 continue;
3131 }
5f36109e 3132
a80f28d8
JS
3133 int childtag = dwarf_tag (&childtype);
3134 const char *member = dwarf_diename (&child);
3a147004 3135
a80f28d8
JS
3136 // "_vptr.foo" members are C++ virtual function tables,
3137 // which (generally?) aren't interesting for users.
3138 if (member && startswith(member, "_vptr."))
3139 continue;
3a147004 3140
a80f28d8
JS
3141 // skip inheritance-masked duplicates
3142 if (member && !dupes.insert(member).second)
3143 continue;
64cddf39 3144
a80f28d8
JS
3145 if (++count > 1)
3146 pf->raw_components.append(", ");
64cddf39 3147
a80f28d8
JS
3148 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
3149 if (pf->args.size() >= 32)
3150 {
3151 pf->raw_components.append("...");
3152 break;
3153 }
3154
3155 if (member)
3156 {
3157 pf->raw_components.append(".");
3158 pf->raw_components.append(member);
5f36109e 3159
a80f28d8
JS
3160 e2 = new target_symbol(*e);
3161 e2->components.push_back (target_symbol::component(e->tok, member));
3162 }
3163 else if (childtag == DW_TAG_union_type)
3164 pf->raw_components.append("<union>");
3165 else if (childtag == DW_TAG_structure_type)
3166 pf->raw_components.append("<class>");
3167 else if (childtag == DW_TAG_class_type)
3168 pf->raw_components.append("<struct>");
3169 pf->raw_components.append("=");
600551ca
JS
3170
3171 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
3172 recurse_bitfield (&childtype, e2, pf);
3173 else
3174 recurse (&childtype, e2, pf);
5f36109e 3175 }
a80f28d8
JS
3176 while (dwarf_siblingof (&child, &child) == 0);
3177 }
5f36109e
JS
3178}
3179
3180
bbee5bb8
JS
3181bool
3182dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
3183 print_format* pf)
3184{
3185 Dwarf_Die type;
3186 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
3187
3188 Dwarf_Attribute attr;
3189 Dwarf_Word encoding = (Dwarf_Word) -1;
3190 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3191 &encoding);
3192 switch (encoding)
bbee5bb8 3193 {
6561d8d1
JS
3194 case DW_ATE_UTF:
3195 case DW_ATE_signed_char:
3196 case DW_ATE_unsigned_char:
3197 break;
3198 default:
3199 return false;
3200 }
3201
3202 string function = userspace_p ? "user_string2" : "kernel_string2";
3203 Dwarf_Word size = (Dwarf_Word) -1;
3204 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3205 switch (size)
3206 {
3207 case 1:
3208 break;
3209 case 2:
3210 function += "_utf16";
3211 break;
3212 case 4:
3213 function += "_utf32";
3214 break;
3215 default:
3216 return false;
3217 }
3218
3219 if (push_deref (pf, "\"%s\"", e))
3220 {
3221 // steal the last arg for a string access
3222 assert (!pf->args.empty());
3223 functioncall* fcall = new functioncall;
3224 fcall->tok = e->tok;
3225 fcall->function = function;
3226 fcall->args.push_back (pf->args.back());
3227 expression *err_msg = new literal_string ("<unknown>");
3228 err_msg->tok = e->tok;
3229 fcall->args.push_back (err_msg);
3230 pf->args.back() = fcall;
bbee5bb8 3231 }
6561d8d1 3232 return true;
bbee5bb8
JS
3233}
3234
a5ce5211
MW
3235// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3236static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3237 + "#define fetch_register k_fetch_register\n"
3238 + "#define store_register k_store_register\n"
3239 + "#define deref kderef\n"
3240 + "#define store_deref store_kderef\n";
a5ce5211
MW
3241
3242static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3243 + "#define fetch_register u_fetch_register\n"
3244 + "#define store_register u_store_register\n"
3245 + "#define deref uderef\n"
3246 + "#define store_deref store_uderef\n";
a5ce5211
MW
3247
3248#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3249 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3250
3251static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3252 + "#undef fetch_register\n"
3253 + "#undef store_register\n"
3254 + "#undef deref\n"
3255 + "#undef store_deref\n";
bbee5bb8 3256
1c0be8c7
JS
3257static functioncall*
3258synthetic_embedded_deref_call(systemtap_session& session,
3259 const string& function_name,
3260 const string& function_code,
3261 exp_type function_type,
3262 bool userspace_p,
3263 bool lvalue_p,
3264 target_symbol* e,
3265 expression* pointer=NULL)
3266{
3267 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3268 functiondecl *fdecl = new functiondecl;
3269 fdecl->synthetic = true;
3270 fdecl->tok = e->tok;
1c0be8c7
JS
3271 fdecl->name = function_name;
3272 fdecl->type = function_type;
3273
5f36109e
JS
3274 embeddedcode *ec = new embeddedcode;
3275 ec->tok = e->tok;
1c0be8c7
JS
3276 ec->code += "/* unprivileged */";
3277 if (! lvalue_p)
3278 ec->code += "/* pure */";
3279 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3280 ec->code += function_code;
3281 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3282 fdecl->body = ec;
3283
3284 // Synthesize a functioncall.
3285 functioncall* fcall = new functioncall;
3286 fcall->tok = e->tok;
3287 fcall->function = fdecl->name;
1c0be8c7 3288 fcall->type = fdecl->type;
5f36109e 3289
1c0be8c7
JS
3290 // If this code snippet uses a precomputed pointer,
3291 // pass that as the first argument.
5f36109e
JS
3292 if (pointer)
3293 {
5f36109e
JS
3294 vardecl *v = new vardecl;
3295 v->type = pe_long;
3296 v->name = "pointer";
3297 v->tok = e->tok;
3298 fdecl->formal_args.push_back(v);
3299 fcall->args.push_back(pointer);
3300 }
5f36109e 3301
1c0be8c7 3302 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3303 for (unsigned i = 0; i < e->components.size(); ++i)
3304 if (e->components[i].type == target_symbol::comp_expression_array_index)
3305 {
3306 vardecl *v = new vardecl;
3307 v->type = pe_long;
3308 v->name = "index" + lex_cast(i);
3309 v->tok = e->tok;
3310 fdecl->formal_args.push_back(v);
3311 fcall->args.push_back(e->components[i].expr_index);
3312 }
3313
1c0be8c7
JS
3314 // If this code snippet is assigning to an lvalue,
3315 // add a final argument for the rvalue.
3316 if (lvalue_p)
3317 {
3318 // Modify the fdecl so it carries a single pe_long formal
3319 // argument called "value".
5f36109e 3320
1c0be8c7
JS
3321 // FIXME: For the time being we only support setting target
3322 // variables which have base types; these are 'pe_long' in
3323 // stap's type vocabulary. Strings and pointers might be
3324 // reasonable, some day, but not today.
5f36109e 3325
1c0be8c7
JS
3326 vardecl *v = new vardecl;
3327 v->type = pe_long;
3328 v->name = "value";
3329 v->tok = e->tok;
3330 fdecl->formal_args.push_back(v);
3331 // NB: We don't know the value for fcall argument yet.
3332 // (see target_symbol_setter_functioncalls)
3333 }
3334
3335 // Add the synthesized decl to the session, and return the call.
3336 fdecl->join (session);
5f36109e
JS
3337 return fcall;
3338}
3339
1c0be8c7
JS
3340expression*
3341dwarf_pretty_print::deref (target_symbol* e)
3342{
3343 static unsigned tick = 0;
3344
3345 if (!deref_p)
3346 {
3347 assert (pointer && e->components.empty());
3348 return pointer;
3349 }
3350
3351 bool lvalue_p = false;
3352 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3353
3354 string code;
3355 exp_type type = pe_long;
3356 if (pointer)
3357 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3358 else if (!local.empty())
3359 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3360 else
3361 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3362
3363 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3364 userspace_p, lvalue_p, e, pointer);
3365}
3366
5f36109e 3367
c55ea10d
JS
3368bool
3369dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3370 target_symbol* e)
3371{
3372 expression* e2 = NULL;
3373 try
3374 {
3375 e2 = deref (e);
3376 }
3377 catch (const semantic_error&)
3378 {
3379 pf->raw_components.append ("?");
3380 return false;
3381 }
3382 pf->raw_components.append (fmt);
3383 pf->args.push_back (e2);
3384 return true;
3385}
3386
3387
e57b735a 3388void
a7999c82 3389dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3390{
a7999c82
JS
3391 // Get the full name of the target symbol.
3392 stringstream ts_name_stream;
3393 e->print(ts_name_stream);
3394 string ts_name = ts_name_stream.str();
3395
3396 // Check and make sure we haven't already seen this target
3397 // variable in this return probe. If we have, just return our
3398 // last replacement.
af234c40 3399 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3400 if (i != return_ts_map.end())
85ecf79a 3401 {
a7999c82
JS
3402 provide (i->second);
3403 return;
3404 }
85ecf79a 3405
70208613
JS
3406 // Attempt the expansion directly first, so if there's a problem with the
3407 // variable we won't have a bogus entry probe lying around. Like in
3408 // saveargs(), we pretend for a moment that we're not in a .return.
3409 bool saved_has_return = q.has_return;
3410 q.has_return = false;
3411 expression *repl = e;
3412 replace (repl);
3413 q.has_return = saved_has_return;
3414 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3415 if (n && n->saved_conversion_error)
3416 {
3417 provide (repl);
3418 return;
3419 }
3420
af234c40
JS
3421 expression *exp;
3422 if (!q.has_process &&
3423 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3424 exp = gen_kretprobe_saved_return(repl);
af234c40 3425 else
cc9001af 3426 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3427
3428 // Provide the variable to our parent so it can be used as a
3429 // substitute for the target symbol.
3430 provide (exp);
3431
3432 // Remember this replacement since we might be able to reuse
3433 // it later if the same return probe references this target
3434 // symbol again.
3435 return_ts_map[ts_name] = exp;
3436}
3437
4a2970a3 3438static expression*
23dc94f6
DS
3439gen_mapped_saved_return(systemtap_session &sess, expression* e,
3440 const string& name,
3441 block *& add_block, bool& add_block_tid,
3442 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3443{
23dc94f6
DS
3444 static unsigned tick = 0;
3445
a7999c82
JS
3446 // We've got to do several things here to handle target
3447 // variables in return probes.
85ecf79a 3448
a7999c82
JS
3449 // (1) Synthesize two global arrays. One is the cache of the
3450 // target variable and the other contains a thread specific
3451 // nesting level counter. The arrays will look like
3452 // this:
3453 //
23dc94f6
DS
3454 // _entry_tvar_{name}_{num}
3455 // _entry_tvar_{name}_{num}_ctr
a7999c82 3456
23dc94f6 3457 string aname = (string("_entry_tvar_")
cc9001af 3458 + name
aca66a36 3459 + "_" + lex_cast(tick++));
a7999c82
JS
3460 vardecl* vd = new vardecl;
3461 vd->name = aname;
3462 vd->tok = e->tok;
23dc94f6 3463 sess.globals.push_back (vd);
a7999c82
JS
3464
3465 string ctrname = aname + "_ctr";
3466 vd = new vardecl;
3467 vd->name = ctrname;
3468 vd->tok = e->tok;
23dc94f6 3469 sess.globals.push_back (vd);
a7999c82
JS
3470
3471 // (2) Create a new code block we're going to insert at the
3472 // beginning of this probe to get the cached value into a
3473 // temporary variable. We'll replace the target variable
3474 // reference with the temporary variable reference. The code
3475 // will look like this:
3476 //
23dc94f6
DS
3477 // _entry_tvar_tid = tid()
3478 // _entry_tvar_{name}_{num}_tmp
3479 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3480 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3481 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3482 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3483 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3484 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3485
3486 // (2a) Synthesize the tid temporary expression, which will look
3487 // like this:
3488 //
23dc94f6 3489 // _entry_tvar_tid = tid()
a7999c82 3490 symbol* tidsym = new symbol;
23dc94f6 3491 tidsym->name = string("_entry_tvar_tid");
a7999c82 3492 tidsym->tok = e->tok;
85ecf79a 3493
a7999c82
JS
3494 if (add_block == NULL)
3495 {
3496 add_block = new block;
3497 add_block->tok = e->tok;
8cc799a5 3498 }
8c819921 3499
8cc799a5
JS
3500 if (!add_block_tid)
3501 {
a7999c82
JS
3502 // Synthesize a functioncall to grab the thread id.
3503 functioncall* fc = new functioncall;
3504 fc->tok = e->tok;
3505 fc->function = string("tid");
8c819921 3506
23dc94f6 3507 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3508 assignment* a = new assignment;
3509 a->tok = e->tok;
3510 a->op = "=";
a7999c82
JS
3511 a->left = tidsym;
3512 a->right = fc;
8c819921
DS
3513
3514 expr_statement* es = new expr_statement;
3515 es->tok = e->tok;
3516 es->value = a;
8c819921 3517 add_block->statements.push_back (es);
8cc799a5 3518 add_block_tid = true;
a7999c82 3519 }
8c819921 3520
a7999c82
JS
3521 // (2b) Synthesize an array reference and assign it to a
3522 // temporary variable (that we'll use as replacement for the
3523 // target variable reference). It will look like this:
3524 //
23dc94f6
DS
3525 // _entry_tvar_{name}_{num}_tmp
3526 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3527 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3528
3529 arrayindex* ai_tvar_base = new arrayindex;
3530 ai_tvar_base->tok = e->tok;
3531
3532 symbol* sym = new symbol;
3533 sym->name = aname;
3534 sym->tok = e->tok;
3535 ai_tvar_base->base = sym;
3536
3537 ai_tvar_base->indexes.push_back(tidsym);
3538
3539 // We need to create a copy of the array index in its current
3540 // state so we can have 2 variants of it (the original and one
3541 // that post-decrements the second index).
3542 arrayindex* ai_tvar = new arrayindex;
3543 arrayindex* ai_tvar_postdec = new arrayindex;
3544 *ai_tvar = *ai_tvar_base;
3545 *ai_tvar_postdec = *ai_tvar_base;
3546
3547 // Synthesize the
23dc94f6 3548 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3549 // second index into the array.
3550 arrayindex* ai_ctr = new arrayindex;
3551 ai_ctr->tok = e->tok;
3552
3553 sym = new symbol;
3554 sym->name = ctrname;
3555 sym->tok = e->tok;
3556 ai_ctr->base = sym;
3557 ai_ctr->indexes.push_back(tidsym);
3558 ai_tvar->indexes.push_back(ai_ctr);
3559
3560 symbol* tmpsym = new symbol;
3561 tmpsym->name = aname + "_tmp";
3562 tmpsym->tok = e->tok;
3563
3564 assignment* a = new assignment;
3565 a->tok = e->tok;
3566 a->op = "=";
3567 a->left = tmpsym;
3568 a->right = ai_tvar;
3569
3570 expr_statement* es = new expr_statement;
3571 es->tok = e->tok;
3572 es->value = a;
3573
3574 add_block->statements.push_back (es);
3575
3576 // (2c) Add a post-decrement to the second array index and
3577 // delete the array value. It will look like this:
3578 //
23dc94f6
DS
3579 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3580 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3581
3582 post_crement* pc = new post_crement;
3583 pc->tok = e->tok;
3584 pc->op = "--";
3585 pc->operand = ai_ctr;
3586 ai_tvar_postdec->indexes.push_back(pc);
3587
3588 delete_statement* ds = new delete_statement;
3589 ds->tok = e->tok;
3590 ds->value = ai_tvar_postdec;
3591
3592 add_block->statements.push_back (ds);
3593
3594 // (2d) Delete the counter value if it is 0. It will look like
3595 // this:
23dc94f6
DS
3596 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3597 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3598
3599 ds = new delete_statement;
3600 ds->tok = e->tok;
3601 ds->value = ai_ctr;
3602
3603 unary_expression *ue = new unary_expression;
3604 ue->tok = e->tok;
3605 ue->op = "!";
3606 ue->operand = ai_ctr;
3607
3608 if_statement *ifs = new if_statement;
3609 ifs->tok = e->tok;
3610 ifs->condition = ue;
3611 ifs->thenblock = ds;
3612 ifs->elseblock = NULL;
3613
3614 add_block->statements.push_back (ifs);
3615
3616 // (3) We need an entry probe that saves the value for us in the
3617 // global array we created. Create the entry probe, which will
3618 // look like this:
3619 //
2260f4e3 3620 // probe kernel.function("{function}").call {
23dc94f6
DS
3621 // _entry_tvar_tid = tid()
3622 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3623 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3624 // = ${param}
3625 // }
3626
2260f4e3 3627 if (add_call_probe == NULL)
a7999c82 3628 {
2260f4e3
FCE
3629 add_call_probe = new block;
3630 add_call_probe->tok = e->tok;
8cc799a5 3631 }
4baf0e53 3632
8cc799a5
JS
3633 if (!add_call_probe_tid)
3634 {
a7999c82
JS
3635 // Synthesize a functioncall to grab the thread id.
3636 functioncall* fc = new functioncall;
3637 fc->tok = e->tok;
3638 fc->function = string("tid");
4baf0e53 3639
23dc94f6 3640 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3641 assignment* a = new assignment;
8fc05e57
DS
3642 a->tok = e->tok;
3643 a->op = "=";
a7999c82
JS
3644 a->left = tidsym;
3645 a->right = fc;
8fc05e57 3646
a7999c82 3647 expr_statement* es = new expr_statement;
8fc05e57
DS
3648 es->tok = e->tok;
3649 es->value = a;
2260f4e3 3650 add_call_probe = new block(add_call_probe, es);
8cc799a5 3651 add_call_probe_tid = true;
85ecf79a 3652 }
cf2a1f85 3653
a7999c82 3654 // Save the value, like this:
23dc94f6
DS
3655 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3656 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3657 // = ${param}
3658 arrayindex* ai_tvar_preinc = new arrayindex;
3659 *ai_tvar_preinc = *ai_tvar_base;
3660
3661 pre_crement* preinc = new pre_crement;
3662 preinc->tok = e->tok;
3663 preinc->op = "++";
3664 preinc->operand = ai_ctr;
3665 ai_tvar_preinc->indexes.push_back(preinc);
3666
3667 a = new assignment;
3668 a->tok = e->tok;
3669 a->op = "=";
3670 a->left = ai_tvar_preinc;
3671 a->right = e;
3672
3673 es = new expr_statement;
3674 es->tok = e->tok;
3675 es->value = a;
3676
2260f4e3 3677 add_call_probe = new block(add_call_probe, es);
a7999c82 3678
23dc94f6 3679 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3680 // our parent so it can be used as a substitute for the target
3681 // symbol.
3f803f9e 3682 delete ai_tvar_base;
af234c40
JS
3683 return tmpsym;
3684}
a7999c82 3685
af234c40 3686
23dc94f6
DS
3687expression*
3688dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3689 const string& name)
3690{
3691 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3692 add_block_tid, add_call_probe,
3693 add_call_probe_tid);
3694}
3695
3696
af234c40 3697expression*
140be17a 3698dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3699{
3700 // The code for this is simple.
3701 //
3702 // .call:
3703 // _set_kretprobe_long(index, $value)
3704 //
3705 // .return:
3706 // _get_kretprobe_long(index)
3707 //
3708 // (or s/long/string/ for things like $$parms)
3709
3710 unsigned index;
3711 string setfn, getfn;
3712
140be17a
JS
3713 // We need the caller to predetermine the type of the expression!
3714 switch (e->type)
af234c40 3715 {
140be17a 3716 case pe_string:
af234c40
JS
3717 index = saved_strings++;
3718 setfn = "_set_kretprobe_string";
3719 getfn = "_get_kretprobe_string";
140be17a
JS
3720 break;
3721 case pe_long:
af234c40
JS
3722 index = saved_longs++;
3723 setfn = "_set_kretprobe_long";
3724 getfn = "_get_kretprobe_long";
140be17a
JS
3725 break;
3726 default:
dc09353a 3727 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3728 }
3729
3730 // Create the entry code
3731 // _set_kretprobe_{long|string}(index, $value)
3732
3733 if (add_call_probe == NULL)
3734 {
3735 add_call_probe = new block;
3736 add_call_probe->tok = e->tok;
3737 }
3738
3739 functioncall* set_fc = new functioncall;
3740 set_fc->tok = e->tok;
3741 set_fc->function = setfn;
3742 set_fc->args.push_back(new literal_number(index));
3743 set_fc->args.back()->tok = e->tok;
3744 set_fc->args.push_back(e);
3745
3746 expr_statement* set_es = new expr_statement;
3747 set_es->tok = e->tok;
3748 set_es->value = set_fc;
3749
3750 add_call_probe->statements.push_back(set_es);
3751
3752 // Create the return code
3753 // _get_kretprobe_{long|string}(index)
3754
3755 functioncall* get_fc = new functioncall;
3756 get_fc->tok = e->tok;
3757 get_fc->function = getfn;
3758 get_fc->args.push_back(new literal_number(index));
3759 get_fc->args.back()->tok = e->tok;
3760
3761 return get_fc;
a7999c82 3762}
a43ba433 3763
2cb3fe26 3764
a7999c82
JS
3765void
3766dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3767{
b78a0fbb 3768 if (null_die(scope_die)) {
04c8e51b
JL
3769 literal_string *empty = new literal_string("");
3770 empty->tok = e->tok;
3771 provide(empty);
a7999c82 3772 return;
b78a0fbb 3773 }
2cb3fe26 3774
5f36109e
JS
3775 target_symbol *tsym = new target_symbol(*e);
3776
fde50242
JS
3777 bool pretty = (!e->components.empty() &&
3778 e->components[0].type == target_symbol::comp_pretty_print);
3779 string format = pretty ? "=%s" : "=%#x";
a43ba433 3780
a7999c82
JS
3781 // Convert $$parms to sprintf of a list of parms and active local vars
3782 // which we recursively evaluate
a43ba433 3783
1c922ad7 3784 print_format* pf = print_format::create(e->tok, "sprintf");
a7999c82 3785
277c21bc 3786 if (q.has_return && (e->name == "$$return"))
a7999c82 3787 {
277c21bc 3788 tsym->name = "$return";
a7999c82
JS
3789
3790 // Ignore any variable that isn't accessible.
3791 tsym->saved_conversion_error = 0;
3792 expression *texp = tsym;
8b095b45 3793 replace (texp); // NB: throws nothing ...
a7999c82 3794 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3795 {
2cb3fe26 3796
a43ba433
FCE
3797 }
3798 else
3799 {
a7999c82 3800 pf->raw_components += "return";
5f36109e 3801 pf->raw_components += format;
a7999c82
JS
3802 pf->args.push_back(texp);
3803 }
3804 }
3805 else
3806 {
3807 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3808 bool first = true;
a7999c82 3809 Dwarf_Die result;
d48bc7eb
JS
3810 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3811 for (unsigned i = 0; i < scopes.size(); ++i)
3812 {
3813 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3814 break; // we don't want file-level variables
3815 if (dwarf_child (&scopes[i], &result) == 0)
3816 do
00cf3709 3817 {
d48bc7eb
JS
3818 switch (dwarf_tag (&result))
3819 {
3820 case DW_TAG_variable:
3821 if (e->name == "$$parms")
3822 continue;
3823 break;
3824 case DW_TAG_formal_parameter:
3825 if (e->name == "$$locals")
3826 continue;
3827 break;
3828
3829 default:
3830 continue;
3831 }
41c262f3 3832
d48bc7eb
JS
3833 const char *diename = dwarf_diename (&result);
3834 if (! diename) continue;
f76427a2 3835
d48bc7eb
JS
3836 if (! first)
3837 pf->raw_components += " ";
3838 pf->raw_components += diename;
fde50242
JS
3839 first = false;
3840
3841 // Write a placeholder for ugly aggregates
3842 Dwarf_Die type;
3843 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3844 {
3845 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3846 switch (dwarf_tag(&type))
3847 {
3848 case DW_TAG_union_type:
3849 case DW_TAG_structure_type:
3850 case DW_TAG_class_type:
3851 pf->raw_components += "={...}";
3852 continue;
3853
3854 case DW_TAG_array_type:
3855 pf->raw_components += "=[...]";
3856 continue;
3857 }
3858 }
345bbb3d 3859
d48bc7eb
JS
3860 tsym->name = "$";
3861 tsym->name += diename;
41c262f3 3862
d48bc7eb
JS
3863 // Ignore any variable that isn't accessible.
3864 tsym->saved_conversion_error = 0;
3865 expression *texp = tsym;
3866 replace (texp); // NB: throws nothing ...
3867 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3868 {
d48bc7eb
JS
3869 if (q.sess.verbose>2)
3870 {
e26c2f83 3871 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb 3872 c != 0;
c081af73 3873 c = c->get_chain()) {
4c5d9906 3874 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3875 }
3876 }
3877
3878 pf->raw_components += "=?";
a43ba433 3879 }
d48bc7eb
JS
3880 else
3881 {
3882 pf->raw_components += format;
3883 pf->args.push_back(texp);
3884 }
a7999c82 3885 }
d48bc7eb
JS
3886 while (dwarf_siblingof (&result, &result) == 0);
3887 }
a7999c82 3888 }
2cb3fe26 3889
a7999c82 3890 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3891 pf->type = pe_string;
a7999c82
JS
3892 provide (pf);
3893}
3894
2cb3fe26 3895
bd1fcbad
YZ
3896void
3897dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3898{
3899 // Fill in our current module context if needed
3900 if (e->module.empty())
3901 e->module = q.dw.module_name;
3902
3903 if (e->module == q.dw.module_name && e->cu_name.empty())
3904 {
3905 // process like any other local
3906 // e->sym_name() will do the right thing
3907 visit_target_symbol(e);
3908 return;
3909 }
3910
3911 var_expanding_visitor::visit_atvar_op(e);
3912}
3913
3914
a7999c82
JS
3915void
3916dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3917{
bd1fcbad 3918 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3919 visited = true;
30263a73
FCE
3920 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3921 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3922
70208613 3923 try
a7999c82 3924 {
c69a87e0
FCE
3925 bool lvalue = is_active_lvalue(e);
3926 if (lvalue && !q.sess.guru_mode)
dc09353a 3927 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3928
100a540e 3929 // XXX: process $context vars should be writable
70208613 3930
c69a87e0
FCE
3931 // See if we need to generate a new probe to save/access function
3932 // parameters from a return probe. PR 1382.
3933 if (q.has_return
3934 && !defined_being_checked
277c21bc
JS
3935 && e->name != "$return" // not the special return-value variable handled below
3936 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3937 {
3938 if (lvalue)
dc09353a 3939 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3940 visit_target_symbol_saved_return(e);
3941 return;
3942 }
e57b735a 3943
277c21bc
JS
3944 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3945 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3946 {
3947 if (lvalue)
dc09353a 3948 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3949
c69a87e0 3950 if (e->addressof)
dc09353a 3951 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3952
5f36109e
JS
3953 e->assert_no_components("dwarf", true);
3954
c69a87e0
FCE
3955 visit_target_symbol_context(e);
3956 return;
3957 }
70208613 3958
04c8e51b
JL
3959 // Everything else (pretty-printed vars, and context vars) require a
3960 // scope_die in which to search for them. If we don't have that, just
3961 // leave it unresolved; we'll produce an error later on.
3962 if (null_die(scope_die))
3963 {
3964 provide(e);
3965 return;
3966 }
3967
5f36109e
JS
3968 if (!e->components.empty() &&
3969 e->components.back().type == target_symbol::comp_pretty_print)
3970 {
3971 if (lvalue)
dc09353a 3972 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3973
277c21bc 3974 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3975 {
3976 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3977 q.has_process, *e);
3978 dpp.expand()->visit(this);
3979 }
3980 else
3981 {
3982 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3983 e->sym_name(),
5f36109e
JS
3984 q.has_process, *e);
3985 dpp.expand()->visit(this);
3986 }
3987 return;
3988 }
3989
1c0be8c7 3990 bool userspace_p = q.has_process;
c69a87e0 3991 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3992 + "_" + e->sym_name()
c69a87e0 3993 + "_" + lex_cast(tick++));
70208613 3994
70208613 3995
1c0be8c7
JS
3996 exp_type type = pe_long;
3997 string code;
277c21bc 3998 if (q.has_return && (e->name == "$return"))
1c0be8c7 3999 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 4000 else
1c0be8c7
JS
4001 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
4002 e, lvalue, type);
70208613 4003
1c0be8c7
JS
4004 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
4005 userspace_p, lvalue, e);
70208613 4006
c69a87e0
FCE
4007 if (lvalue)
4008 {
4009 // Provide the functioncall to our parent, so that it can be
4010 // used to substitute for the assignment node immediately above
4011 // us.
4012 assert(!target_symbol_setter_functioncalls.empty());
4013 *(target_symbol_setter_functioncalls.top()) = n;
4014 }
70208613 4015
1c0be8c7
JS
4016 // Revisit the functioncall so arguments can be expanded.
4017 n->visit (this);
66d284f4
FCE
4018 }
4019 catch (const semantic_error& er)
4020 {
9fab2262
JS
4021 // We suppress this error message, and pass the unresolved
4022 // target_symbol to the next pass. We hope that this value ends
4023 // up not being referenced after all, so it can be optimized out
4024 // quietly.
1af1e62d 4025 e->chain (er);
9fab2262 4026 provide (e);
66d284f4 4027 }
77de5e9e
GH
4028}
4029
4030
c24447be
JS
4031void
4032dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
4033{
4034 // Fill in our current module context if needed
4035 if (e->module.empty())
4036 e->module = q.dw.module_name;
4037
4038 var_expanding_visitor::visit_cast_op(e);
4039}
4040
4041
8cc799a5
JS
4042void
4043dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
4044{
4045 expression *repl = e;
4046 if (q.has_return)
4047 {
4048 // expand the operand as if it weren't a return probe
4049 q.has_return = false;
4050 replace (e->operand);
4051 q.has_return = true;
4052
4053 // XXX it would be nice to use gen_kretprobe_saved_return when available,
4054 // but it requires knowing the types already, which is problematic for
4055 // arbitrary expressons.
cc9001af 4056 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
4057 }
4058 provide (repl);
4059}
4060
3689db05
SC
4061void
4062dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
4063{
ace7c23f 4064 string e_lit_val = e->operand->value;
b78a0fbb 4065
3689db05 4066 add_block = new block;
9eaaceaa 4067 add_block->tok = e->tok;
3689db05
SC
4068
4069 systemtap_session &s = this->q.sess;
4070 map<string, pair<string,derived_probe*> >::iterator it;
4071 // Find the associated perf.counter probe
4072 for (it=s.perf_counters.begin();
4073 it != s.perf_counters.end();
4074 it++)
4075 if ((*it).first == e_lit_val)
4076 {
4077 // if perf .function("name") omitted, then set it to this process name
4078 if ((*it).second.first.length() == 0)
4079 ((*it).second).first = this->q.user_path;
4080 if (((*it).second).first == this->q.user_path)
4081 break;
4082 }
4083
4084 if (it != s.perf_counters.end())
4085 {
698de6cc 4086 perf_counter_refs.insert((*it).second.second);
3689db05
SC
4087 // __perf_read_N is assigned in the probe prologue
4088 symbol* sym = new symbol;
4653caf1 4089 sym->tok = e->tok;
3689db05
SC
4090 sym->name = "__perf_read_" + (*it).first;
4091 provide (sym);
4092 }
4093 else
dc09353a 4094 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
4095}
4096
8cc799a5 4097
729455a7
JS
4098vector<Dwarf_Die>&
4099dwarf_var_expanding_visitor::getscopes(target_symbol *e)
4100{
4101 if (scopes.empty())
4102 {
04c8e51b 4103 if(!null_die(scope_die))
f25a9197 4104 scopes = q.dw.getscopes(scope_die);
729455a7 4105 if (scopes.empty())
b530b5b3
LB
4106 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
4107 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 4108 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7 4109 + lex_cast_hex(addr)
04c8e51b 4110 + (null_die(scope_die) ? ""
729455a7
JS
4111 : (string (" in ")
4112 + (dwarf_diename(scope_die) ?: "<unknown>")
4113 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
4114 + ")"))
4115 + " while searching for local '"
cc9001af 4116 + e->sym_name() + "'",
729455a7
JS
4117 e->tok);
4118 }
4119 return scopes;
4120}
4121
4122
5f36109e
JS
4123struct dwarf_cast_expanding_visitor: public var_expanding_visitor
4124{
4125 systemtap_session& s;
4126 dwarf_builder& db;
4127
4128 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4129 s(s), db(db) {}
4130 void visit_cast_op (cast_op* e);
4131 void filter_special_modules(string& module);
4132};
4133
4134
c4ce66a1
JS
4135struct dwarf_cast_query : public base_query
4136{
946e1a48 4137 cast_op& e;
c4ce66a1 4138 const bool lvalue;
5f36109e
JS
4139 const bool userspace_p;
4140 functioncall*& result;
c4ce66a1 4141
5f36109e
JS
4142 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
4143 const bool userspace_p, functioncall*& result):
abb41d92 4144 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 4145 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
4146
4147 void handle_query_module();
822a6a3d 4148 void query_library (const char *) {}
576eaefe 4149 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
4150};
4151
4152
c4ce66a1
JS
4153void
4154dwarf_cast_query::handle_query_module()
4155{
5f36109e
JS
4156 static unsigned tick = 0;
4157
4158 if (result)
c4ce66a1
JS
4159 return;
4160
ea1e477a 4161 // look for the type in any CU
a44a7cb5
JS
4162 Dwarf_Die* type_die = NULL;
4163 if (startswith(e.type_name, "class "))
4164 {
4165 // normalize to match dwflpp::global_alias_caching_callback
4166 string struct_name = "struct " + e.type_name.substr(6);
4167 type_die = dw.declaration_resolve_other_cus(struct_name);
4168 }
4169 else
4170 type_die = dw.declaration_resolve_other_cus(e.type_name);
4171
4172 // NB: We now index the types as "struct name"/"union name"/etc. instead of
4173 // just "name". But since we didn't require users to be explicit before, and
4174 // actually sort of discouraged it, we must be flexible now. So if a lookup
4175 // fails with a bare name, try augmenting it.
4176 if (!type_die &&
4177 !startswith(e.type_name, "class ") &&
4178 !startswith(e.type_name, "struct ") &&
4179 !startswith(e.type_name, "union ") &&
4180 !startswith(e.type_name, "enum "))
4181 {
4182 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
4183 if (!type_die)
4184 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
4185 if (!type_die)
4186 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
4187 }
4188
ea1e477a
JS
4189 if (!type_die)
4190 return;
c4ce66a1 4191
5f36109e
JS
4192 string code;
4193 exp_type type = pe_long;
4194
ea1e477a 4195 try
c4ce66a1 4196 {
ea1e477a
JS
4197 Dwarf_Die cu_mem;
4198 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4199
4200 if (!e.components.empty() &&
4201 e.components.back().type == target_symbol::comp_pretty_print)
4202 {
4203 if (lvalue)
dc09353a 4204 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4205
d19a9a82 4206 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4207 result = dpp.expand();
4208 return;
4209 }
4210
4211 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4212 }
4213 catch (const semantic_error& er)
4214 {
4215 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4216 // may be attempted using several different modules:
4217 // @cast(ptr, "type", "module1:module2:...")
4218 e.chain (er);
c4ce66a1 4219 }
c4ce66a1 4220
5f36109e
JS
4221 if (code.empty())
4222 return;
c4ce66a1 4223
5f36109e 4224 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4225 + "_" + e.sym_name()
5f36109e 4226 + "_" + lex_cast(tick++));
c4ce66a1 4227
1c0be8c7
JS
4228 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4229 userspace_p, lvalue, &e, e.operand);
5f36109e 4230}
c4ce66a1
JS
4231
4232
fb0274bc
JS
4233void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4234{
d90053e7 4235 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4236 // for those cases, build a module including that header
d90053e7 4237 if (module[module.size() - 1] == '>' &&
60d98537 4238 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4239 {
4240 string cached_module;
4241 if (s.use_cache)
4242 {
4243 // see if the cached module exists
a2639cb7 4244 cached_module = find_typequery_hash(s, module);
d105f664 4245 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4246 {
4247 int fd = open(cached_module.c_str(), O_RDONLY);
4248 if (fd != -1)
4249 {
4250 if (s.verbose > 2)
b530b5b3
LB
4251 //TRANSLATORS: Here we're using a cached module.
4252 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4253 module = cached_module;
4254 close(fd);
4255 return;
4256 }
4257 }
4258 }
4259
4260 // no cached module, time to make it
d90053e7 4261 if (make_typequery(s, module) == 0)
fb0274bc 4262 {
e16dc041 4263 // try to save typequery in the cache
fb0274bc 4264 if (s.use_cache)
e16dc041 4265 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4266 }
4267 }
4268}
4269
4270
c4ce66a1
JS
4271void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4272{
4273 bool lvalue = is_active_lvalue(e);
4274 if (lvalue && !s.guru_mode)
dc09353a 4275 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4276
4277 if (e->module.empty())
4278 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4279
5f36109e 4280 functioncall* result = NULL;
8b31197b
JS
4281
4282 // split the module string by ':' for alternatives
4283 vector<string> modules;
4284 tokenize(e->module, modules, ":");
b5a0dd41 4285 bool userspace_p=false; // PR10601
5f36109e 4286 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4287 {
8b31197b 4288 string& module = modules[i];
fb0274bc 4289 filter_special_modules(module);
abb41d92 4290
c4ce66a1
JS
4291 // NB: This uses '/' to distinguish between kernel modules and userspace,
4292 // which means that userspace modules won't get any PATH searching.
4293 dwflpp* dw;
707bf35e
JS
4294 try
4295 {
b5a0dd41
FCE
4296 userspace_p=is_user_module (module);
4297 if (! userspace_p)
707bf35e
JS
4298 {
4299 // kernel or kernel module target
ae2552da 4300 dw = db.get_kern_dw(s, module);
707bf35e
JS
4301 }
4302 else
4303 {
05fb3e0c 4304 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4305 dw = db.get_user_dw(s, module);
4306 }
4307 }
4308 catch (const semantic_error& er)
4309 {
4310 /* ignore and go to the next module */
4311 continue;
4312 }
c4ce66a1 4313
5f36109e 4314 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
06de3a04 4315 dw->iterate_over_modules<base_query>(&query_module, &q);
c4ce66a1 4316 }
abb41d92 4317
5f36109e 4318 if (!result)
c4ce66a1 4319 {
946e1a48
JS
4320 // We pass the unresolved cast_op to the next pass, and hope
4321 // that this value ends up not being referenced after all, so
4322 // it can be optimized out quietly.
c4ce66a1
JS
4323 provide (e);
4324 return;
4325 }
4326
c4ce66a1
JS
4327 if (lvalue)
4328 {
4329 // Provide the functioncall to our parent, so that it can be
4330 // used to substitute for the assignment node immediately above
4331 // us.
4332 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4333 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4334 }
4335
5f36109e 4336 result->visit (this);
77de5e9e
GH
4337}
4338
4339
bd1fcbad
YZ
4340struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4341{
4342 systemtap_session& s;
4343 dwarf_builder& db;
4344
4345 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4346 s(s), db(db) {}
4347 void visit_atvar_op (atvar_op* e);
4348};
4349
4350
4351struct dwarf_atvar_query: public base_query
4352{
4353 atvar_op& e;
4354 const bool userspace_p, lvalue;
4355 functioncall*& result;
4356 unsigned& tick;
4357 const string cu_name_pattern;
4358
4359 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4360 const bool userspace_p, const bool lvalue,
4361 functioncall*& result,
4362 unsigned& tick):
4363 base_query(dw, module), e(e),
4364 userspace_p(userspace_p), lvalue(lvalue), result(result),
4365 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4366
4367 void handle_query_module ();
4368 void query_library (const char *) {}
4369 void query_plt (const char *entry, size_t addr) {}
5c378838 4370 static int atvar_query_cu (Dwarf_Die *cudie, dwarf_atvar_query *q);
bd1fcbad
YZ
4371};
4372
4373
4374int
5c378838 4375dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, dwarf_atvar_query *q)
bd1fcbad 4376{
bd1fcbad
YZ
4377 if (! q->e.cu_name.empty())
4378 {
c60517ca 4379 const char *die_name = dwarf_diename(cudie) ?: "";
bd1fcbad
YZ
4380 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4381 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4382 {
4383 return DWARF_CB_OK;
4384 }
4385 }
4386
4387 try
4388 {
4389 vector<Dwarf_Die> scopes(1, *cudie);
4390
4391 q->dw.focus_on_cu (cudie);
4392
4393 if (! q->e.components.empty() &&
4394 q->e.components.back().type == target_symbol::comp_pretty_print)
4395 {
4396 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4397 q->userspace_p, q->e);
4398 q->result = dpp.expand();
4399 return DWARF_CB_ABORT;
4400 }
4401
4402 exp_type type = pe_long;
4403 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4404 &q->e, q->lvalue, type);
4405
4406 if (code.empty())
4407 return DWARF_CB_OK;
4408
4409 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4410 : "_dwarf_tvar_get")
4411 + "_" + q->e.sym_name()
4412 + "_" + lex_cast(q->tick++));
4413
4414 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4415 q->userspace_p, q->lvalue,
4416 &q->e);
4417 }
4418 catch (const semantic_error& er)
4419 {
4420 // Here we suppress the error because we often just have too many
4421 // when scanning all the CUs.
4422 return DWARF_CB_OK;
4423 }
4424
4425 if (q->result) {
4426 return DWARF_CB_ABORT;
4427 }
4428
4429 return DWARF_CB_OK;
4430}
4431
4432
4433void
4434dwarf_atvar_query::handle_query_module ()
4435{
4436
4437 dw.iterate_over_cus(atvar_query_cu, this, false);
4438}
4439
4440
4441void
4442dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4443{
4444 const bool lvalue = is_active_lvalue(e);
4445 if (lvalue && !s.guru_mode)
dc09353a 4446 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4447 "need stap -g"), e->tok);
4448
4449 if (e->module.empty())
4450 e->module = "kernel";
4451
4452 functioncall* result = NULL;
4453
4454 // split the module string by ':' for alternatives
4455 vector<string> modules;
4456 tokenize(e->module, modules, ":");
4457 bool userspace_p = false;
4458 for (unsigned i = 0; !result && i < modules.size(); ++i)
4459 {
4460 string& module = modules[i];
4461
4462 dwflpp* dw;
4463 try
4464 {
4465 userspace_p = is_user_module(module);
4466 if (!userspace_p)
4467 {
4468 // kernel or kernel module target
4469 dw = db.get_kern_dw(s, module);
4470 }
4471 else
4472 {
4473 module = find_executable(module, "", s.sysenv);
4474 dw = db.get_user_dw(s, module);
4475 }
4476 }
4477 catch (const semantic_error& er)
4478 {
4479 /* ignore and go to the next module */
4480 continue;
4481 }
4482
4483 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
06de3a04 4484 dw->iterate_over_modules<base_query>(&query_module, &q);
bd1fcbad
YZ
4485
4486 if (result)
4487 {
4488 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4489
4490 if (lvalue)
4491 {
4492 // Provide the functioncall to our parent, so that it can be
4493 // used to substitute for the assignment node immediately above
4494 // us.
4495 assert(!target_symbol_setter_functioncalls.empty());
4496 *(target_symbol_setter_functioncalls.top()) = result;
4497 }
4498
4499 result->visit(this);
4500 return;
4501 }
4502
4503 /* Unable to find the variable in the current module, so we chain
4504 * an error in atvar_op */
dc09353a 4505 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4506 e->sym_name().c_str(), module.c_str(),
4507 e->cu_name.empty() ? "" : _(", in "),
4508 e->cu_name.c_str()));
4509 e->chain (er);
4510 }
4511
4512 provide(e);
4513}
4514
4515
b8da0ad1
FCE
4516void
4517dwarf_derived_probe::printsig (ostream& o) const
4518{
4519 // Instead of just printing the plain locations, we add a PC value
4520 // as a comment as a way of telling e.g. apart multiple inlined
4521 // function instances. This is distinct from the verbose/clog
4522 // output, since this part goes into the cache hash calculations.
4523 sole_location()->print (o);
6d0f3f0c 4524 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4525 printsig_nested (o);
4526}
4527
4528
4529
dc38c0ae 4530void
b20febf3
FCE
4531dwarf_derived_probe::join_group (systemtap_session& s)
4532{
af234c40
JS
4533 // skip probes which are paired entry-handlers
4534 if (!has_return && (saved_longs || saved_strings))
4535 return;
4536
b20febf3
FCE
4537 if (! s.dwarf_derived_probes)
4538 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4539 s.dwarf_derived_probes->enroll (this);
4540}
4541
4542
2b69faaf
JS
4543static bool
4544kernel_supports_inode_uprobes(systemtap_session& s)
4545{
4546 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4547 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4548 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4549 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4550 && s.kernel_config["CONFIG_UPROBES"] == "y");
4551}
4552
4553
3667d615
JS
4554static bool
4555kernel_supports_inode_uretprobes(systemtap_session& s)
4556{
766013af
JS
4557 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4558 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4559 return kernel_supports_inode_uprobes(s) &&
af9e147f 4560 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4561}
4562
4563
5261f7ab
DS
4564void
4565check_process_probe_kernel_support(systemtap_session& s)
4566{
4567 // If we've got utrace, we're good to go.
4568 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4569 return;
4570
8c021542
DS
4571 // We don't have utrace. For process probes that aren't
4572 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4573 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4574 // specific autoconf test for its needs.
8c021542
DS
4575 //
4576 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4577 // approximation.
4578 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4579 return;
4580
d3e959b0
DS
4581 // For uprobes-based process probes, we need the task_finder plus
4582 // the builtin inode-uprobes.
8c021542
DS
4583 if (s.need_uprobes
4584 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4585 && kernel_supports_inode_uprobes(s))
8c021542
DS
4586 return;
4587
dc09353a 4588 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4589}
4590
4591
b20febf3
FCE
4592dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4593 const string& filename,
4594 int line,
91af0778 4595 // module & section specify a relocation
b20febf3
FCE
4596 // base for <addr>, unless section==""
4597 // (equivalently module=="kernel")
4598 const string& module,
4599 const string& section,
4600 // NB: dwfl_addr is the virtualized
4601 // address for this symbol.
4602 Dwarf_Addr dwfl_addr,
4603 // addr is the section-offset for
4604 // actual relocation.
4605 Dwarf_Addr addr,
4606 dwarf_query& q,
37ebca01 4607 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4608 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4609 module (module), section (section), addr (addr),
63b4fd14 4610 path (q.path),
27dc09b1 4611 has_process (q.has_process),
c9bad430
DS
4612 has_return (q.has_return),
4613 has_maxactive (q.has_maxactive),
c57ea854 4614 has_library (q.has_library),
6b66b9f7 4615 maxactive_val (q.maxactive_val),
b642c901
SC
4616 user_path (q.user_path),
4617 user_lib (q.user_lib),
af234c40 4618 access_vars(false),
c57ea854 4619 saved_longs(0), saved_strings(0),
af234c40 4620 entry_handler(0)
bd2b1e68 4621{
b642c901
SC
4622 if (user_lib.size() != 0)
4623 has_library = true;
4624
6b66b9f7
JS
4625 if (q.has_process)
4626 {
4627 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4628 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4629 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4630 // by the incoming section value (".absolute" vs. ".dynamic").
4631 // XXX Assert invariants here too?
2b69faaf
JS
4632
4633 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4634 // ditto for userspace runtimes (dyninst)
ac3af990 4635 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4636 section == ".absolute" && addr == dwfl_addr &&
4637 addr >= q.dw.module_start && addr < q.dw.module_end)
4638 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4639 }
4640 else
4641 {
4642 // Assert kernel relocation invariants
4643 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4644 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4645 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4646 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4647 }
2930abc7 4648
21beacc9
FCE
4649 // XXX: hack for strange g++/gcc's
4650#ifndef USHRT_MAX
4651#define USHRT_MAX 32767
4652#endif
4653
606fd9c8 4654 // Range limit maxactive() value
6b66b9f7 4655 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4656 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4657 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4658
a7696882
JL
4659 // Expand target variables in the probe body. Even if the scope_die is
4660 // invalid, we still want to expand things such as $$vars/$$parms/etc...
4661 // (PR15999, PR16473). Access to specific context vars e.g. $argc will not be
4662 // expanded and will produce an error during the typeresolution_info pass.
8fc05e57 4663 {
6b66b9f7 4664 // XXX: user-space deref's for q.has_process!
5a617dc6
JL
4665
4666 // PR14436: if we're expanding target variables in the probe body of a
4667 // .return probe, we need to make the expansion at the postprologue addr
4668 // instead (if any), which is then also the spot where the entry handler
4669 // probe is placed. (Note that at this point, a nonzero prologue_end
4670 // implies that it should be used, i.e. code is unoptimized).
4671 Dwarf_Addr handler_dwfl_addr = dwfl_addr;
4672 if (q.prologue_end != 0 && q.has_return)
4673 {
4674 handler_dwfl_addr = q.prologue_end;
4675 if (q.sess.verbose > 2)
4676 clog << _F("expanding .return vars at prologue_end (0x%s) "
4677 "rather than entrypc (0x%s)\n",
4678 lex_cast_hex(handler_dwfl_addr).c_str(),
4679 lex_cast_hex(dwfl_addr).c_str());
4680 }
4681 dwarf_var_expanding_visitor v (q, scope_die, handler_dwfl_addr);
8b095b45 4682 v.replace (this->body);
3689db05
SC
4683
4684 // Propagate perf.counters so we can emit later
4685 this->perf_counter_refs = v.perf_counter_refs;
4686 // Emit local var used to save the perf counter read value
698de6cc 4687 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4688 for (pcii = v.perf_counter_refs.begin();
4689 pcii != v.perf_counter_refs.end(); pcii++)
4690 {
4691 map<string, pair<string,derived_probe*> >::iterator it;
4692 // Find the associated perf counter probe
4693 for (it=q.sess.perf_counters.begin() ;
4694 it != q.sess.perf_counters.end();
4695 it++)
4696 if ((*it).second.second == (*pcii))
4697 break;
4698 vardecl* vd = new vardecl;
4699 vd->name = "__perf_read_" + (*it).first;
4700 vd->tok = this->tok;
4701 vd->set_arity(0, this->tok);
4702 vd->type = pe_long;
4703 vd->synthetic = true;
4704 this->locals.push_back (vd);
4705 }
4706
4707
6b66b9f7
JS
4708 if (!q.has_process)
4709 access_vars = v.visited;
37ebca01
FCE
4710
4711 // If during target-variable-expanding the probe, we added a new block
4712 // of code, add it to the start of the probe.
4713 if (v.add_block)
ba6f838d 4714 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4715
4716 // If when target-variable-expanding the probe, we need to synthesize a
4717 // sibling function-entry probe. We don't go through the whole probe derivation
4718 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4719 // dwarf-induced duplication.
4720 if (v.add_call_probe)
37ebca01 4721 {
2260f4e3
FCE
4722 assert (q.has_return && !q.has_call);
4723
4724 // We temporarily replace q.base_probe.
4725 statement* old_body = q.base_probe->body;
4726 q.base_probe->body = v.add_call_probe;
4727 q.has_return = false;
4728 q.has_call = true;
af234c40 4729
da23eceb 4730 if (q.has_process)
5a617dc6
JL
4731 {
4732 // Place handler probe at the same addr as where the vars were
4733 // expanded (which may not be the same addr as the one for the
4734 // main retprobe, PR14436).
4735 Dwarf_Addr handler_addr = addr;
4736 if (handler_dwfl_addr != dwfl_addr)
4737 // adjust section offset by prologue_end-entrypc
4738 handler_addr += handler_dwfl_addr - dwfl_addr;
4739 entry_handler = new uprobe_derived_probe (funcname, filename,
4740 line, module, section,
4741 handler_dwfl_addr,
4742 handler_addr, q,
4743 scope_die);
4744 }
da23eceb 4745 else
af234c40
JS
4746 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4747 module, section, dwfl_addr,
4748 addr, q, scope_die);
4749
4750 saved_longs = entry_handler->saved_longs = v.saved_longs;
4751 saved_strings = entry_handler->saved_strings = v.saved_strings;
4752
4753 q.results.push_back (entry_handler);
2260f4e3
FCE
4754
4755 q.has_return = true;
4756 q.has_call = false;
4757 q.base_probe->body = old_body;
37ebca01 4758 }
a7696882
JL
4759 // Save the local variables for listing mode. If the scope_die is null,
4760 // local vars aren't accessible, so no need to invoke saveargs (PR10820).
bba368c5
JL
4761 if (!null_die(scope_die) &&
4762 q.sess.dump_mode == systemtap_session::dump_matched_probes_vars)
4763 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4764 }
0a98fd42 4765
5d23847d 4766 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4767 // "reverse-engineered" form of the incoming (q.base_loc) probe
4768 // point. This allows a user to see what function / file / line
4769 // number any particular match of the wildcards.
919debfc
JL
4770
4771 vector<probe_point::component*> comps;
4772 if (q.has_kernel)
4773 comps.push_back (new probe_point::component(TOK_KERNEL));
4774 else if(q.has_module)
4775 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4776 else if(q.has_process)
4777 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4778 else
4779 assert (0);
4780
4781 string fn_or_stmt;
4782 if (q.has_function_str || q.has_function_num)
e772a6e7 4783 fn_or_stmt = TOK_FUNCTION;
919debfc 4784 else
e772a6e7 4785 fn_or_stmt = TOK_STATEMENT;
919debfc
JL
4786
4787 if (q.has_function_str || q.has_statement_str)
4788 {
e772a6e7 4789 string retro_name = q.final_function_name(funcname, filename, line);
919debfc
JL
4790 comps.push_back
4791 (new probe_point::component
4792 (fn_or_stmt, new literal_string (retro_name)));
4793 }
4794 else if (q.has_function_num || q.has_statement_num)
4795 {
4796 Dwarf_Addr retro_addr;
4797 if (q.has_function_num)
4798 retro_addr = q.function_num_val;
4799 else
4800 retro_addr = q.statement_num_val;
4801 comps.push_back (new probe_point::component
4802 (fn_or_stmt,
4803 new literal_number(retro_addr, true)));
4804
4805 if (q.has_absolute)
4806 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
4807 }
4808
4809 if (q.has_call)
4810 comps.push_back (new probe_point::component(TOK_CALL));
4811 if (q.has_exported)
4812 comps.push_back (new probe_point::component(TOK_EXPORTED));
4813 if (q.has_inline)
4814 comps.push_back (new probe_point::component(TOK_INLINE));
4815 if (has_return)
4816 comps.push_back (new probe_point::component(TOK_RETURN));
4817 if (has_maxactive)
4818 comps.push_back (new probe_point::component
4819 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
4820
4821 // Overwrite it.
4822 this->sole_location()->components = comps;
e2941743
JL
4823
4824 // if it's a .callee[s[(N)]] call, add checks to the probe body so that the
4825 // user body is only 'triggered' when called from q.callers[N-1], which
4826 // itself is called from q.callers[N-2], etc... I.E.
4827 // callees(N) --> N elements in q.callers --> N checks against [u]stack(0..N-1)
4828 if ((q.has_callee || q.has_callees_num) && q.callers && !q.callers->empty())
4829 {
4830 if (q.sess.verbose > 2)
7761da8b 4831 clog << _F("adding caller checks for callee %s\n", funcname.c_str());
e2941743
JL
4832
4833 // Copy the stack and empty it out
4834 stack<Dwarf_Addr> callers(*q.callers);
4835 for (unsigned level = 1; !callers.empty(); level++,
4836 callers.pop())
4837 {
4838 Dwarf_Addr caller = callers.top();
4839
4840 // We first need to make the caller addr relocatable
4841 string caller_section;
4842 Dwarf_Addr caller_reloc;
4843 if (module == TOK_KERNEL)
4844 { // allow for relocatable kernel (see also add_probe_point())
4845 caller_reloc = caller - q.sess.sym_stext;
4846 caller_section = "_stext";
4847 }
4848 else
4849 caller_reloc = q.dw.relocate_address(caller,
4850 caller_section);
4851
4852 if (q.sess.verbose > 2)
7761da8b
JL
4853 clog << _F("adding caller check [u]stack(%d) == reloc(0x%s)\n",
4854 level, lex_cast_hex(caller_reloc).c_str());
e2941743
JL
4855
4856 // We want to add a statement like this:
6211aed9 4857 // if (!_caller_match(user, mod, sec, addr)) next;
e2941743
JL
4858 // Something similar is done in semantic_pass_conditions()
4859
4860 functioncall* check = new functioncall();
4861 check->tok = this->tok;
6211aed9 4862 check->function = "_caller_match";
e2941743
JL
4863 check->args.push_back(new literal_number(q.has_process));
4864 check->args[0]->tok = this->tok;
4865 check->args.push_back(new literal_number(level));
4866 check->args[1]->tok = this->tok;
4867 check->args.push_back(new literal_string(module));
4868 check->args[2]->tok = this->tok;
4869 check->args.push_back(new literal_string(caller_section));
4870 check->args[3]->tok = this->tok;
4871 check->args.push_back(new literal_number(caller_reloc, true /* hex */));
4872 check->args[4]->tok = this->tok;
4873
4874 unary_expression* notexp = new unary_expression();
4875 notexp->tok = this->tok;
4876 notexp->op = "!";
4877 notexp->operand = check;
4878
4879 if_statement* ifs = new if_statement();
4880 ifs->tok = this->tok;
4881 ifs->thenblock = new next_statement();
4882 ifs->thenblock->tok = this->tok;
4883 ifs->elseblock = NULL;
4884 ifs->condition = notexp;
4885
4886 this->body = new block(ifs, this->body);
4887 }
4888 }
2930abc7
FCE
4889}
4890
bd2b1e68 4891
0a98fd42 4892void
8c67c337
JS
4893dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4894 Dwarf_Addr dwfl_addr)
0a98fd42 4895{
9aa8ffce 4896 if (null_die(scope_die))
0a98fd42 4897 return;
0a98fd42 4898
8c67c337 4899 bool verbose = q.sess.verbose > 2;
0a98fd42 4900
8c67c337 4901 if (verbose)
b530b5b3 4902 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4903
8c67c337
JS
4904 if (has_return)
4905 {
4906 /* Only save the return value if it has a type. */
4907 string type_name;
4908 Dwarf_Die type_die;
4909 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4910 dwarf_type_name(&type_die, type_name))
4911 args.push_back("$return:"+type_name);
4912
4913 else if (verbose)
b530b5b3
LB
4914 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4915 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4916 }
d87623a1 4917
0a98fd42 4918 Dwarf_Die arg;
4ef35696
JS
4919 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4920 for (unsigned i = 0; i < scopes.size(); ++i)
4921 {
4922 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4923 break; // we don't want file-level variables
4924 if (dwarf_child (&scopes[i], &arg) == 0)
4925 do
0a98fd42 4926 {
4ef35696
JS
4927 switch (dwarf_tag (&arg))
4928 {
4929 case DW_TAG_variable:
4930 case DW_TAG_formal_parameter:
4931 break;
0a98fd42 4932
4ef35696
JS
4933 default:
4934 continue;
4935 }
0a98fd42 4936
4ef35696
JS
4937 /* Ignore this local if it has no name. */
4938 const char *arg_name = dwarf_diename (&arg);
4939 if (!arg_name)
8c67c337
JS
4940 {
4941 if (verbose)
b530b5b3
LB
4942 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4943 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4944 continue;
4945 }
4ef35696
JS
4946
4947 if (verbose)
b530b5b3
LB
4948 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4949 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4950
4951 /* Ignore this local if it has no location (or not at this PC). */
4952 /* NB: It still may not be directly accessible, e.g. if it is an
4953 * aggregate type, implicit_pointer, etc., but the user can later
4954 * figure out how to access the interesting parts. */
45b02a36
FCE
4955
4956 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4957 * several synthetic
4958 * probe foo { $var }
4959 * probes, testing them for overall resolvability.
4960 */
4961
4ef35696
JS
4962 Dwarf_Attribute attr_mem;
4963 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4964 {
4965 Dwarf_Op *expr;
4966 size_t len;
4967 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4968 {
4969 if (verbose)
b530b5b3
LB
4970 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4971 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4972 continue;
4973 }
4974 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4975 &len, 1) == 1 && len > 0))
4976 {
45b02a36
FCE
4977 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4978 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4979 &len, 1) == 1 && len > 0))) {
4980 if (verbose)
4981 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4982 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4983 continue;
4984 }
4ef35696
JS
4985 }
4986 }
4987
4988 /* Ignore this local if it has no type. */
4989 string type_name;
4990 Dwarf_Die type_die;
4991 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4992 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4993 {
4994 if (verbose)
b530b5b3
LB
4995 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4996 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4997 continue;
4998 }
8c67c337 4999
4ef35696
JS
5000 /* This local looks good -- save it! */
5001 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 5002 }
4ef35696
JS
5003 while (dwarf_siblingof (&arg, &arg) == 0);
5004 }
0a98fd42
JS
5005}
5006
5007
5008void
d0bfd2ac 5009dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 5010{
d0bfd2ac 5011 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
5012}
5013
5014
27dc09b1 5015void
42e38653 5016dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
5017{
5018 if (has_process)
5019 {
5020 // These probes are allowed for unprivileged users, but only in the
5021 // context of processes which they own.
5022 emit_process_owner_assertion (o);
5023 return;
5024 }
5025
5026 // Other probes must contain the default assertion which aborts
5027 // if executed by an unprivileged user.
42e38653 5028 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
5029}
5030
5031
5032void
5033dwarf_derived_probe::print_dupe_stamp(ostream& o)
5034{
5035 if (has_process)
5036 {
5037 // These probes are allowed for unprivileged users, but only in the
5038 // context of processes which they own.
5039 print_dupe_stamp_unprivileged_process_owner (o);
5040 return;
5041 }
5042
5043 // Other probes must contain the default dupe stamp
5044 derived_probe::print_dupe_stamp (o);
5045}
5046
64211010 5047
7a053d3b 5048void
20c6c071 5049dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 5050 dwarf_builder * dw,
42e38653 5051 privilege_t privilege)
bd2b1e68 5052{
27dc09b1 5053 root
42e38653 5054 ->bind_privilege(privilege)
27dc09b1 5055 ->bind(dw);
54efe513
GH
5056}
5057
7a053d3b 5058void
fd6602a0 5059dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 5060 dwarf_builder * dw,
42e38653 5061 privilege_t privilege)
2865d17a 5062{
27dc09b1 5063 root
42e38653 5064 ->bind_privilege(privilege)
27dc09b1 5065 ->bind(dw);
27dc09b1 5066 root->bind(TOK_CALL)
42e38653 5067 ->bind_privilege(privilege)
27dc09b1 5068 ->bind(dw);
4bda987e
SC
5069 root->bind(TOK_EXPORTED)
5070 ->bind_privilege(privilege)
5071 ->bind(dw);
27dc09b1 5072 root->bind(TOK_RETURN)
42e38653 5073 ->bind_privilege(privilege)
27dc09b1 5074 ->bind(dw);
1e035395 5075
f6be7c06
DB
5076 // For process probes / uprobes, .maxactive() is unused.
5077 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
5078 {
5079 root->bind(TOK_RETURN)
1e035395
FCE
5080 ->bind_num(TOK_MAXACTIVE)->bind(dw);
5081 }
bd2b1e68
GH
5082}
5083
7a053d3b 5084void
27dc09b1 5085dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 5086 systemtap_session& s,
27dc09b1
DB
5087 match_node * root,
5088 dwarf_builder * dw,
42e38653 5089 privilege_t privilege
27dc09b1 5090)
bd2b1e68
GH
5091{
5092 // Here we match 4 forms:
5093 //
5094 // .function("foo")
5095 // .function(0xdeadbeef)
5096 // .statement("foo")
5097 // .statement(0xdeadbeef)
5098
440d9b00 5099 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 5100 register_function_variants(fv_root, dw, privilege);
7f02ca94 5101 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 5102 fv_root->bind(TOK_INLINE)
42e38653 5103 ->bind_privilege(privilege)
440d9b00 5104 ->bind(dw);
7f02ca94
JS
5105 fv_root->bind_str(TOK_LABEL)
5106 ->bind_privilege(privilege)
440d9b00 5107 ->bind(dw);
c31add50
JL
5108 fv_root->bind_str(TOK_CALLEE)
5109 ->bind_privilege(privilege)
5110 ->bind(dw);
5111 fv_root->bind(TOK_CALLEES)
5112 ->bind_privilege(privilege)
5113 ->bind(dw);
5114 fv_root->bind_num(TOK_CALLEES)
5115 ->bind_privilege(privilege)
5116 ->bind(dw);
440d9b00
DB
5117
5118 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 5119 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
5120 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
5121 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
5122 {
5123 fv_root->bind(TOK_INLINE)
42e38653 5124 ->bind_privilege(privilege)
440d9b00
DB
5125 ->bind(dw);
5126 }
5127
42e38653
DB
5128 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
5129 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
5130}
5131
b1615c74
JS
5132void
5133dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
5134 match_node * root,
5135 dwarf_builder * dw)
5136{
5137 root->bind_str(TOK_MARK)
f66bb29a 5138 ->bind_privilege(pr_all)
b1615c74
JS
5139 ->bind(dw);
5140 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 5141 ->bind_privilege(pr_all)
b1615c74
JS
5142 ->bind(dw);
5143}
5144
5145void
5146dwarf_derived_probe::register_plt_variants(systemtap_session& s,
5147 match_node * root,
5148 dwarf_builder * dw)
5149{
5150 root->bind(TOK_PLT)
f66bb29a 5151 ->bind_privilege(pr_all)
b1615c74
JS
5152 ->bind(dw);
5153 root->bind_str(TOK_PLT)
f66bb29a 5154 ->bind_privilege(pr_all)
b1615c74
JS
5155 ->bind(dw);
5156 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5157 ->bind_privilege(pr_all)
b1615c74
JS
5158 ->bind(dw);
5159 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5160 ->bind_privilege(pr_all)
b1615c74 5161 ->bind(dw);
bd2b1e68
GH
5162}
5163
5164void
c4ce66a1 5165dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 5166{
c4ce66a1 5167 match_node* root = s.pattern_root;
bd2b1e68
GH
5168 dwarf_builder *dw = new dwarf_builder();
5169
c4ce66a1
JS
5170 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
5171 s.code_filters.push_back(filter);
5172
bd1fcbad
YZ
5173 filter = new dwarf_atvar_expanding_visitor(s, *dw);
5174 s.code_filters.push_back(filter);
5175
73f52eb4
DB
5176 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
5177 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
5178 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
5179 ->bind(dw);
2cab6244 5180
7f02ca94
JS
5181 match_node* uprobes[] = {
5182 root->bind(TOK_PROCESS),
5183 root->bind_str(TOK_PROCESS),
5184 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5185 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5186 };
5187 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
5188 {
f66bb29a 5189 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
5190 register_sdt_variants(s, uprobes[i], dw);
5191 register_plt_variants(s, uprobes[i], dw);
5192 }
bd2b1e68
GH
5193}
5194
9020300d 5195void
3689db05
SC
5196dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
5197{
698de6cc 5198 std::set<derived_probe*>::iterator pcii;
3689db05
SC
5199 for (pcii = perf_counter_refs.begin();
5200 pcii != perf_counter_refs.end();
5201 pcii++)
5202 {
5203 map<string, pair<string,derived_probe*> >::iterator it;
5204 // Find the associated perf.counter probe
5205 unsigned i = 0;
5206 for (it=s.perf_counters.begin() ;
5207 it != s.perf_counters.end();
5208 it++, i++)
5209 if ((*it).second.second == (*pcii))
5210 break;
5211 // place the perf counter read so it precedes stp_lock_probe
5212 o->newline() << "l->l___perf_read_" + (*it).first
5213 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
5214 + lex_cast(i) + "))));";
5215 }
b78a0fbb 5216
b95e2b79
MH
5217 if (access_vars)
5218 {
5219 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 5220 o->newline() << "#if defined __ia64__";
d9aed31e 5221 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 5222 o->newline() << "#endif";
b95e2b79 5223 }
9020300d 5224}
2930abc7 5225
b20febf3 5226// ------------------------------------------------------------------------
46b84a80
DS
5227
5228void
b20febf3 5229dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 5230{
b20febf3 5231 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
5232
5233 // XXX: probes put at the same address should all share a
5234 // single kprobe/kretprobe, and have their handlers executed
5235 // sequentially.
b55bc428
FCE
5236}
5237
7a053d3b 5238void
775d51e5 5239dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 5240{
b20febf3 5241 if (probes_by_module.empty()) return;
2930abc7 5242
775d51e5
DS
5243 s.op->newline() << "/* ---- dwarf probes ---- */";
5244
5245 // Warn of misconfigured kernels
f41595cc
FCE
5246 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
5247 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
5248 s.op->newline() << "#endif";
775d51e5 5249 s.op->newline();
f41595cc 5250
f07c3b68 5251 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 5252 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
5253 s.op->newline() << "#endif";
5254
14cf7e42 5255 // Forward decls
2ba1736a 5256 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 5257
b20febf3
FCE
5258 // Forward declare the master entry functions
5259 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5260 s.op->line() << " struct pt_regs *regs);";
5261 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5262 s.op->line() << " struct pt_regs *regs);";
5263
42cb22bd
MH
5264 // Emit an array of kprobe/kretprobe pointers
5265 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5266 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
5267 s.op->newline() << "#endif";
5268
b20febf3 5269 // Emit the actual probe list.
606fd9c8
FCE
5270
5271 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
5272 // struct stap_dwarf_probe, but it being initialized data makes it add
5273 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 5274 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
5275 // NB: bss!
5276
4c2732a1 5277 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
5278 s.op->newline(1) << "const unsigned return_p:1;";
5279 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 5280 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 5281 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 5282 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 5283
af234c40
JS
5284 // data saved in the kretprobe_instance packet
5285 s.op->newline() << "const unsigned short saved_longs;";
5286 s.op->newline() << "const unsigned short saved_strings;";
5287
faea5e16 5288 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5289 // are small and uniform enough to justify putting char[MAX]'s into
5290 // the array instead of relocated char*'s.
faea5e16
JS
5291 size_t module_name_max = 0, section_name_max = 0;
5292 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5293 size_t all_name_cnt = probes_by_module.size(); // for average
5294 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5295 {
5296 dwarf_derived_probe* p = it->second;
5297#define DOIT(var,expr) do { \
5298 size_t var##_size = (expr) + 1; \
5299 var##_max = max (var##_max, var##_size); \
5300 var##_tot += var##_size; } while (0)
5301 DOIT(module_name, p->module.size());
5302 DOIT(section_name, p->section.size());
606fd9c8
FCE
5303#undef DOIT
5304 }
5305
5306 // Decide whether it's worthwhile to use char[] or char* by comparing
5307 // the amount of average waste (max - avg) to the relocation data size
5308 // (3 native long words).
5309#define CALCIT(var) \
5310 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5311 { \
5312 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5313 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5314 << "[" << var##_name_max << "]" << endl; \
5315 } \
5316 else \
5317 { \
b0986e7a 5318 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5319 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5320 }
5321
5322 CALCIT(module);
5323 CALCIT(section);
e6fe60e7 5324#undef CALCIT
606fd9c8 5325
b0986e7a 5326 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5327 s.op->newline() << "const struct stap_probe * const probe;";
5328 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5329 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5330 s.op->indent(1);
5331
5332 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5333 {
b20febf3
FCE
5334 dwarf_derived_probe* p = it->second;
5335 s.op->newline() << "{";
5336 if (p->has_return)
5337 s.op->line() << " .return_p=1,";
c9bad430 5338 if (p->has_maxactive)
606fd9c8
FCE
5339 {
5340 s.op->line() << " .maxactive_p=1,";
5341 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5342 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5343 }
af234c40
JS
5344 if (p->saved_longs || p->saved_strings)
5345 {
5346 if (p->saved_longs)
5347 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5348 if (p->saved_strings)
5349 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5350 if (p->entry_handler)
c87ae2c1 5351 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5352 }
b350f56b
JS
5353 if (p->locations[0]->optional)
5354 s.op->line() << " .optional_p=1,";
dc38c256 5355 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5356 s.op->line() << " .module=\"" << p->module << "\",";
5357 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5358 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5359 s.op->line() << " },";
2930abc7 5360 }
2930abc7 5361
b20febf3
FCE
5362 s.op->newline(-1) << "};";
5363
5364 // Emit the kprobes callback function
5365 s.op->newline();
5366 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5367 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5368 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5369 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5370 // Check that the index is plausible
5371 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5372 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5373 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5374 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5375 s.op->line() << "];";
71db462b 5376 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5377 "stp_probe_type_kprobe");
d9aed31e 5378 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5379
5380 // Make it look like the IP is set as it wouldn't have been replaced
5381 // by a breakpoint instruction when calling real probe handler. Reset
5382 // IP regs on return, so we don't confuse kprobes. PR10458
5383 s.op->newline() << "{";
5384 s.op->indent(1);
d9aed31e 5385 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5386 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5387 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5388 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5389 s.op->newline(-1) << "}";
5390
f887a8c9 5391 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5392 s.op->newline() << "return 0;";
5393 s.op->newline(-1) << "}";
5394
5395 // Same for kretprobes
5396 s.op->newline();
af234c40
JS
5397 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5398 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5399 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5400
5401 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5402 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5403 // Check that the index is plausible
5404 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5405 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5406 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5407 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5408 s.op->line() << "];";
5409
7c3e97f4 5410 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5411 s.op->newline() << "if (sp) {";
5412 s.op->indent(1);
71db462b 5413 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5414 "stp_probe_type_kretprobe");
d9aed31e 5415 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5416
5417 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5418 s.op->newline() << "c->ips.krp.pi = inst;";
5419 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5420
5421 // Make it look like the IP is set as it wouldn't have been replaced
5422 // by a breakpoint instruction when calling real probe handler. Reset
5423 // IP regs on return, so we don't confuse kprobes. PR10458
5424 s.op->newline() << "{";
d9aed31e 5425 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5426 s.op->newline() << "if (entry)";
5427 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5428 s.op->newline(-1) << "else";
5429 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5430 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5431 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5432 s.op->newline(-1) << "}";
5433
f887a8c9 5434 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5435 s.op->newline(-1) << "}";
b20febf3
FCE
5436 s.op->newline() << "return 0;";
5437 s.op->newline(-1) << "}";
af234c40
JS
5438
5439 s.op->newline();
5440 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5441 s.op->line() << " struct pt_regs *regs) {";
5442 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5443 s.op->newline(-1) << "}";
5444
5445 s.op->newline();
5446 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5447 s.op->line() << " struct pt_regs *regs) {";
5448 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5449 s.op->newline(-1) << "}";
b642c901 5450
14cf7e42 5451 s.op->newline();
20c6c071 5452}
ec4373ff 5453
20c6c071 5454
dc38c0ae 5455void
b20febf3
FCE
5456dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5457{
5458 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5459 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5460 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5461 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5462 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5463 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5464 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5465 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5466 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5467 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5468 s.op->newline(-1) << "} else {";
f07c3b68 5469 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5470 s.op->newline(-1) << "}";
606fd9c8 5471 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5472 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5473 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5474 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5475 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5476 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5477 s.op->newline(-1) << "}";
5478 s.op->newline() << "#endif";
e4cb375f
MH
5479 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5480 s.op->newline() << "#ifdef __ia64__";
5481 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5482 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5483 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5484 s.op->newline() << "if (rc == 0) {";
5485 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5486 s.op->newline() << "if (rc != 0)";
5487 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5488 s.op->newline(-2) << "}";
5489 s.op->newline() << "#else";
606fd9c8 5490 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5491 s.op->newline() << "#endif";
b20febf3 5492 s.op->newline(-1) << "} else {";
e4cb375f 5493 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5494 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5495 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5496 s.op->newline() << "#ifdef __ia64__";
5497 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5498 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5499 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5500 s.op->newline() << "if (rc == 0) {";
5501 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5502 s.op->newline() << "if (rc != 0)";
5503 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5504 s.op->newline(-2) << "}";
5505 s.op->newline() << "#else";
606fd9c8 5506 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5507 s.op->newline() << "#endif";
b20febf3 5508 s.op->newline(-1) << "}";
9063462a
FCE
5509 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5510 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5511 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5512 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5513 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5514 // XXX: shall we increment numskipped?
5515 s.op->newline(-1) << "}";
5516
5517#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5518 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5519 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5520 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5521 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5522 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5523 s.op->newline() << "#ifdef __ia64__";
5524 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5525 s.op->newline() << "#endif";
c48cb0cc
FCE
5526 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5527 // not run for this early-abort case.
5528 s.op->newline(-1) << "}";
5529 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5530 s.op->newline(-1) << "}";
9063462a
FCE
5531#endif
5532
b20febf3
FCE
5533 s.op->newline() << "else sdp->registered_p = 1;";
5534 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5535}
5536
5537
b4be7cbc
FCE
5538void
5539dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5540{
5541 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5542 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5543 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5544 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5545 s.op->newline() << "int rc;";
5546
5547 // new module arrived?
5548 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5549 s.op->newline(1) << "if (sdp->return_p) {";
5550 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5551 s.op->newline() << "if (sdp->maxactive_p) {";
5552 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5553 s.op->newline(-1) << "} else {";
5554 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5555 s.op->newline(-1) << "}";
5556 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5557 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5558 s.op->newline() << "if (sdp->entry_probe) {";
5559 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5560 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5561 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5562 s.op->newline(-1) << "}";
5563 s.op->newline() << "#endif";
5564 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5565 s.op->newline() << "#ifdef __ia64__";
5566 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5567 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5568 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5569 s.op->newline() << "if (rc == 0) {";
5570 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5571 s.op->newline() << "if (rc != 0)";
5572 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5573 s.op->newline(-2) << "}";
5574 s.op->newline() << "#else";
5575 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5576 s.op->newline() << "#endif";
5577 s.op->newline(-1) << "} else {";
5578 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5579 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5580 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5581 s.op->newline() << "#ifdef __ia64__";
5582 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5583 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5584 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5585 s.op->newline() << "if (rc == 0) {";
5586 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5587 s.op->newline() << "if (rc != 0)";
5588 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5589 s.op->newline(-2) << "}";
5590 s.op->newline() << "#else";
5591 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5592 s.op->newline() << "#endif";
5593 s.op->newline(-1) << "}";
5594 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5595
5596 // old module disappeared?
5597 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5598 s.op->newline(1) << "if (sdp->return_p) {";
5599 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5600 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5601 s.op->newline() << "#ifdef STP_TIMING";
5602 s.op->newline() << "if (kp->u.krp.nmissed)";
5603 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5604 s.op->newline(-1) << "#endif";
065d5567 5605 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5606 s.op->newline() << "#ifdef STP_TIMING";
5607 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5608 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5609 s.op->newline(-1) << "#endif";
5610 s.op->newline(-1) << "} else {";
5611 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5612 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5613 s.op->newline() << "#ifdef STP_TIMING";
5614 s.op->newline() << "if (kp->u.kp.nmissed)";
5615 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5616 s.op->newline(-1) << "#endif";
5617 s.op->newline(-1) << "}";
5618 s.op->newline() << "#if defined(__ia64__)";
5619 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5620 s.op->newline() << "#endif";
5621 s.op->newline() << "sdp->registered_p = 0;";
5622 s.op->newline(-1) << "}";
5623
5624 s.op->newline(-1) << "}"; // for loop
5625}
5626
5627
5628
5629
46b84a80 5630void
b20febf3 5631dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5632{
42cb22bd
MH
5633 //Unregister kprobes by batch interfaces.
5634 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5635 s.op->newline() << "j = 0;";
5636 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5637 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5638 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5639 s.op->newline() << "if (! sdp->registered_p) continue;";
5640 s.op->newline() << "if (!sdp->return_p)";
5641 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5642 s.op->newline(-2) << "}";
5643 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5644 s.op->newline() << "j = 0;";
5645 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5646 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5647 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5648 s.op->newline() << "if (! sdp->registered_p) continue;";
5649 s.op->newline() << "if (sdp->return_p)";
5650 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5651 s.op->newline(-2) << "}";
5652 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5653 s.op->newline() << "#ifdef __ia64__";
5654 s.op->newline() << "j = 0;";
5655 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5656 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5657 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5658 s.op->newline() << "if (! sdp->registered_p) continue;";
5659 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5660 s.op->newline(-1) << "}";
5661 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5662 s.op->newline() << "#endif";
42cb22bd
MH
5663 s.op->newline() << "#endif";
5664
b20febf3
FCE
5665 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5666 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5667 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5668 s.op->newline() << "if (! sdp->registered_p) continue;";
5669 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5670 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5671 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5672 s.op->newline() << "#endif";
065d5567 5673 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5674 s.op->newline() << "#ifdef STP_TIMING";
5675 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5676 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5677 s.op->newline(-1) << "#endif";
065d5567 5678 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5679 s.op->newline() << "#ifdef STP_TIMING";
5680 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5681 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 5682 s.op->newline(-1) << "#endif";
557fb7a8 5683 s.op->newline(-1) << "} else {";
42cb22bd 5684 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5685 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5686 s.op->newline() << "#endif";
065d5567 5687 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5688 s.op->newline() << "#ifdef STP_TIMING";
5689 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5690 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5691 s.op->newline(-1) << "#endif";
b20febf3 5692 s.op->newline(-1) << "}";
e4cb375f
MH
5693 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5694 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5695 s.op->newline() << "#endif";
b20febf3
FCE
5696 s.op->newline() << "sdp->registered_p = 0;";
5697 s.op->newline(-1) << "}";
46b84a80
DS
5698}
5699
272c9036
WF
5700static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5701{
5702 string::size_type pos;
5703 string::size_type lastPos = str.find_first_not_of(" ", 0);
5704 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5705
5706 if (nextAt == string::npos)
5707 {
5708 // PR13934: Assembly probes are not forced to use the N@OP form.
5709 // In this case, N is inferred to be the native word size. Since we
5710 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5711 // then must not put any spaces in arguments, to avoid ambiguity.
5712 tokenize(str, tokens, " ");
5713 return;
5714 }
5715
272c9036
WF
5716 while (lastPos != string::npos)
5717 {
5718 pos = nextAt + 1;
5719 nextAt = str.find("@", pos);
5720 if (nextAt == string::npos)
5721 pos = string::npos;
5722 else
5723 pos = str.rfind(" ", nextAt);
5724
5725 tokens.push_back(str.substr(lastPos, pos - lastPos));
5726 lastPos = str.find_first_not_of(" ", pos);
5727 }
5728}
8aabf152 5729
8aabf152 5730
aff5d390 5731struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5732{
ae1418f0 5733 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5 5734 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
b8688ee6 5735 dwflpp& dw,
f83336a5
FCE
5736 int elf_machine,
5737 const string & process_name,
a794dbeb 5738 const string & provider_name,
aff5d390 5739 const string & probe_name,
71e5e13d 5740 stap_sdt_probe_type probe_type,
aff5d390 5741 const string & arg_string,
8aabf152 5742 int ac):
b8688ee6
JL
5743 session (s), dw (dw), elf_machine (elf_machine),
5744 process_name (process_name), provider_name (provider_name),
5745 probe_name (probe_name), probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5746 {
a57b7534
JL
5747 // sanity check that we're not somehow here for a kernel probe
5748 assert(is_user_module(process_name));
5749
2e6d617a 5750 build_dwarf_registers();
f83336a5 5751
ebbd2b45 5752 need_debug_info = false;
88e39987 5753 if (probe_type == uprobe3_type)
272c9036
WF
5754 {
5755 sdt_v3_tokenize(arg_string, arg_tokens);
5756 assert(arg_count <= 12);
5757 }
88e39987 5758 else
272c9036
WF
5759 {
5760 tokenize(arg_string, arg_tokens, " ");
5761 assert(arg_count <= 10);
5762 }
a8ec7719 5763 }
8aabf152 5764
f83336a5 5765 systemtap_session& session;
b8688ee6 5766 dwflpp& dw;
332ba7e7 5767 int elf_machine;
aff5d390 5768 const string & process_name;
a794dbeb 5769 const string & provider_name;
aff5d390 5770 const string & probe_name;
71e5e13d 5771 stap_sdt_probe_type probe_type;
8aabf152 5772 unsigned arg_count;
aff5d390 5773 vector<string> arg_tokens;
2e6d617a 5774
46a94997 5775 map<string, pair<unsigned,int> > dwarf_regs;
2e6d617a
JL
5776 string regnames;
5777 string percent_regnames;
5778
ebbd2b45 5779 bool need_debug_info;
aff5d390 5780
2e6d617a 5781 void build_dwarf_registers();
aff5d390 5782 void visit_target_symbol (target_symbol* e);
03c45fcb 5783 unsigned get_target_symbol_argno_and_validate (target_symbol* e);
ac074daf 5784 long parse_out_arg_precision(string& asmarg);
0fbf6fb8
JL
5785 expression* try_parse_arg_literal (target_symbol *e,
5786 const string& asmarg,
5787 long precision);
95b78bc9
JL
5788 expression* try_parse_arg_register (target_symbol *e,
5789 const string& asmarg,
5790 long precision);
8da56b62
JL
5791 expression* try_parse_arg_offset_register (target_symbol *e,
5792 const string& asmarg,
5793 long precision);
10fcca15
JL
5794 expression* try_parse_arg_effective_addr (target_symbol *e,
5795 const string& asmarg,
5796 long precision);
451c0c25
JL
5797 expression* try_parse_arg_varname (target_symbol *e,
5798 const string& asmarg,
5799 long precision);
6ef331c8
SC
5800 void visit_target_symbol_arg (target_symbol* e);
5801 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5802 void visit_atvar_op (atvar_op* e);
40a0c64e 5803 void visit_cast_op (cast_op* e);
aff5d390
SC
5804};
5805
2e6d617a
JL
5806void
5807sdt_uprobe_var_expanding_visitor::build_dwarf_registers ()
5808{
5809 /* Register name mapping table depends on the elf machine of this particular
5810 probe target process/file, not upon the host. So we can't just
5811 #ifdef _i686_ etc. */
5812
5813#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
5814 if (elf_machine == EM_X86_64) {
5815 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5816 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5817 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5818 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5819 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5820 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5821 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5822 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5823 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5824 DRI ("%sil", 4, QI);
5825 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5826 DRI ("%dil", 5, QI);
5827 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5828 DRI ("%bpl", 6, QI);
5829 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5830 DRI ("%spl", 7, QI);
5831 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5832 DRI ("%r8b", 8, QI);
5833 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5834 DRI ("%r9b", 9, QI);
5835 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5836 DRI ("%r10b", 10, QI);
5837 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5838 DRI ("%r11b", 11, QI);
5839 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5840 DRI ("%r12b", 12, QI);
5841 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5842 DRI ("%r13b", 13, QI);
5843 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5844 DRI ("%r14b", 14, QI);
5845 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5846 DRI ("%r15b", 15, QI);
5847 DRI ("%rip", 16, DI); DRI ("%eip", 16, SI); DRI ("%ip", 16, HI);
5848 } else if (elf_machine == EM_386) {
5849 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5850 DRI ("%ah", 0, QIh);
5851 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5852 DRI ("%ch", 1, QIh);
5853 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5854 DRI ("%dh", 2, QIh);
5855 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5856 DRI ("%bh", 3, QIh);
5857 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5858 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5859 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5860 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
5861 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
5862 DRI ("%r0", 0, DI);
5863 DRI ("%r1", 1, DI);
5864 DRI ("%r2", 2, DI);
5865 DRI ("%r3", 3, DI);
5866 DRI ("%r4", 4, DI);
5867 DRI ("%r5", 5, DI);
5868 DRI ("%r6", 6, DI);
5869 DRI ("%r7", 7, DI);
5870 DRI ("%r8", 8, DI);
5871 DRI ("%r9", 9, DI);
5872 DRI ("%r10", 10, DI);
5873 DRI ("%r11", 11, DI);
5874 DRI ("%r12", 12, DI);
5875 DRI ("%r13", 13, DI);
5876 DRI ("%r14", 14, DI);
5877 DRI ("%r15", 15, DI);
5878 DRI ("%r16", 16, DI);
5879 DRI ("%r17", 17, DI);
5880 DRI ("%r18", 18, DI);
5881 DRI ("%r19", 19, DI);
5882 DRI ("%r20", 20, DI);
5883 DRI ("%r21", 21, DI);
5884 DRI ("%r22", 22, DI);
5885 DRI ("%r23", 23, DI);
5886 DRI ("%r24", 24, DI);
5887 DRI ("%r25", 25, DI);
5888 DRI ("%r26", 26, DI);
5889 DRI ("%r27", 27, DI);
5890 DRI ("%r28", 28, DI);
5891 DRI ("%r29", 29, DI);
5892 DRI ("%r30", 30, DI);
5893 DRI ("%r31", 31, DI);
5894 // PR11821: unadorned register "names" without -mregnames
5895 DRI ("0", 0, DI);
5896 DRI ("1", 1, DI);
5897 DRI ("2", 2, DI);
5898 DRI ("3", 3, DI);
5899 DRI ("4", 4, DI);
5900 DRI ("5", 5, DI);
5901 DRI ("6", 6, DI);
5902 DRI ("7", 7, DI);
5903 DRI ("8", 8, DI);
5904 DRI ("9", 9, DI);
5905 DRI ("10", 10, DI);
5906 DRI ("11", 11, DI);
5907 DRI ("12", 12, DI);
5908 DRI ("13", 13, DI);
5909 DRI ("14", 14, DI);
5910 DRI ("15", 15, DI);
5911 DRI ("16", 16, DI);
5912 DRI ("17", 17, DI);
5913 DRI ("18", 18, DI);
5914 DRI ("19", 19, DI);
5915 DRI ("20", 20, DI);
5916 DRI ("21", 21, DI);
5917 DRI ("22", 22, DI);
5918 DRI ("23", 23, DI);
5919 DRI ("24", 24, DI);
5920 DRI ("25", 25, DI);
5921 DRI ("26", 26, DI);
5922 DRI ("27", 27, DI);
5923 DRI ("28", 28, DI);
5924 DRI ("29", 29, DI);
5925 DRI ("30", 30, DI);
5926 DRI ("31", 31, DI);
5927 } else if (elf_machine == EM_S390) {
5928 DRI ("%r0", 0, DI);
5929 DRI ("%r1", 1, DI);
5930 DRI ("%r2", 2, DI);
5931 DRI ("%r3", 3, DI);
5932 DRI ("%r4", 4, DI);
5933 DRI ("%r5", 5, DI);
5934 DRI ("%r6", 6, DI);
5935 DRI ("%r7", 7, DI);
5936 DRI ("%r8", 8, DI);
5937 DRI ("%r9", 9, DI);
5938 DRI ("%r10", 10, DI);
5939 DRI ("%r11", 11, DI);
5940 DRI ("%r12", 12, DI);
5941 DRI ("%r13", 13, DI);
5942 DRI ("%r14", 14, DI);
5943 DRI ("%r15", 15, DI);
5944 } else if (elf_machine == EM_ARM) {
5945 DRI ("r0", 0, SI);
5946 DRI ("r1", 1, SI);
5947 DRI ("r2", 2, SI);
5948 DRI ("r3", 3, SI);
5949 DRI ("r4", 4, SI);
5950 DRI ("r5", 5, SI);
5951 DRI ("r6", 6, SI);
5952 DRI ("r7", 7, SI);
5953 DRI ("r8", 8, SI);
5954 DRI ("r9", 9, SI);
5955 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
5956 DRI ("fp", 11, SI);
5957 DRI ("ip", 12, SI);
5958 DRI ("sp", 13, SI);
5959 DRI ("lr", 14, SI);
5960 DRI ("pc", 15, SI);
5961 } else if (elf_machine == EM_AARCH64) {
5962 DRI ("x0", 0, DI); DRI ("w0", 0, SI);
5963 DRI ("x1", 1, DI); DRI ("w1", 1, SI);
5964 DRI ("x2", 2, DI); DRI ("w2", 2, SI);
5965 DRI ("x3", 3, DI); DRI ("w3", 3, SI);
5966 DRI ("x4", 4, DI); DRI ("w4", 4, SI);
5967 DRI ("x5", 5, DI); DRI ("w5", 5, SI);
5968 DRI ("x6", 6, DI); DRI ("w6", 6, SI);
5969 DRI ("x7", 7, DI); DRI ("w7", 7, SI);
5970 DRI ("x8", 8, DI); DRI ("w8", 8, SI);
5971 DRI ("x9", 9, DI); DRI ("w9", 9, SI);
5972 DRI ("x10", 10, DI); DRI ("w10", 10, SI);
5973 DRI ("x11", 11, DI); DRI ("w11", 11, SI);
5974 DRI ("x12", 12, DI); DRI ("w12", 12, SI);
5975 DRI ("x13", 13, DI); DRI ("w13", 13, SI);
5976 DRI ("x14", 14, DI); DRI ("w14", 14, SI);
5977 DRI ("x15", 15, DI); DRI ("w15", 15, SI);
5978 DRI ("x16", 16, DI); DRI ("w16", 16, SI);
5979 DRI ("x17", 17, DI); DRI ("w17", 17, SI);
5980 DRI ("x18", 18, DI); DRI ("w18", 18, SI);
5981 DRI ("x19", 19, DI); DRI ("w19", 19, SI);
5982 DRI ("x20", 20, DI); DRI ("w20", 20, SI);
5983 DRI ("x21", 21, DI); DRI ("w21", 21, SI);
5984 DRI ("x22", 22, DI); DRI ("w22", 22, SI);
5985 DRI ("x23", 23, DI); DRI ("w23", 23, SI);
5986 DRI ("x24", 24, DI); DRI ("w24", 24, SI);
5987 DRI ("x25", 25, DI); DRI ("w25", 25, SI);
5988 DRI ("x26", 26, DI); DRI ("w26", 26, SI);
5989 DRI ("x27", 27, DI); DRI ("w27", 27, SI);
5990 DRI ("x28", 28, DI); DRI ("w28", 28, SI);
5991 DRI ("x29", 29, DI); DRI ("w29", 29, SI);
5992 DRI ("x30", 30, DI); DRI ("w30", 30, SI);
5993 DRI ("sp", 31, DI);
5994 } else if (arg_count) {
5995 /* permit this case; just fall back to dwarf */
5996 }
5997#undef DRI
5998
5999 // Build regex pieces out of the known dwarf_regs. We keep two separate
6000 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
6001 // and ones with no prefix (and thus only usable in unambiguous contexts).
6002 map<string,pair<unsigned,int> >::const_iterator ri;
6003 for (ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
6004 {
6005 string regname = ri->first;
6006 assert (regname != "");
6007 regnames += string("|")+regname;
6008 if (regname[0]=='%')
6009 percent_regnames += string("|")+regname;
6010 }
6011
6012 // clip off leading |
6013 if (regnames != "")
6014 regnames = regnames.substr(1);
6015 if (percent_regnames != "")
6016 percent_regnames = percent_regnames.substr(1);
6017}
7a05f484
SC
6018
6019void
6ef331c8 6020sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 6021{
6ef331c8 6022 if (e->addressof)
dc09353a 6023 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
6024
6025 if (e->name == "$$name")
7a05f484 6026 {
6ef331c8
SC
6027 literal_string *myname = new literal_string (probe_name);
6028 myname->tok = e->tok;
6029 provide(myname);
6030 return;
6031 }
7a05f484 6032
6ef331c8
SC
6033 else if (e->name == "$$provider")
6034 {
6035 literal_string *myname = new literal_string (provider_name);
6036 myname->tok = e->tok;
6037 provide(myname);
6038 return;
6039 }
a794dbeb 6040
6ef331c8
SC
6041 else if (e->name == "$$vars" || e->name == "$$parms")
6042 {
6043 e->assert_no_components("sdt", true);
6ef331c8
SC
6044
6045 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
63ea4244 6046
1c922ad7 6047 print_format* pf = print_format::create(e->tok, "sprintf");
6ef331c8
SC
6048
6049 for (unsigned i = 1; i <= arg_count; ++i)
6050 {
6051 if (i > 1)
6052 pf->raw_components += " ";
6053 target_symbol *tsym = new target_symbol;
6054 tsym->tok = e->tok;
6055 tsym->name = "$arg" + lex_cast(i);
6056 pf->raw_components += tsym->name;
6057 tsym->components = e->components;
6058
8c2f50c0 6059 expression *texp = require<expression> (tsym);
6ef331c8
SC
6060 if (!e->components.empty() &&
6061 e->components[0].type == target_symbol::comp_pretty_print)
6062 pf->raw_components += "=%s";
6063 else
6064 pf->raw_components += "=%#x";
6065 pf->args.push_back(texp);
6066 }
6067
6068 pf->components = print_format::string_to_components(pf->raw_components);
6069 provide (pf);
6070 }
6071 else
6072 assert(0); // shouldn't get here
6073}
6074
03c45fcb
JL
6075unsigned
6076sdt_uprobe_var_expanding_visitor::get_target_symbol_argno_and_validate (target_symbol *e)
6077{
6078 // parsing
6079 unsigned argno = 0;
6080 if (startswith(e->name, "$arg"))
6081 {
6082 try
6083 {
6084 argno = lex_cast<unsigned>(e->name.substr(4));
6085 }
6086 catch (const runtime_error& f)
6087 {
6088 // non-integral $arg suffix: e.g. $argKKKSDF
6089 argno = 0;
6090 }
6091 }
6092
6093 // validation
6094 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
6095 argno < 1 || argno > arg_count) // a $argN with out-of-range N
6096 {
6097 // NB: Either
6098 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
6099 // 2) uprobe2_type $FOO (no probe args)
6100 // both of which get resolved later.
6101 // Throw it now, and it might be resolved by DWARF later.
6102 need_debug_info = true;
6103 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
6104 }
6105 assert (arg_tokens.size() >= argno);
6106 return argno;
6107}
6ef331c8 6108
ac074daf
JL
6109long
6110sdt_uprobe_var_expanding_visitor::parse_out_arg_precision(string& asmarg)
6111{
6112 long precision;
6113 if (asmarg.find('@') != string::npos)
6114 {
6115 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
6116 asmarg = asmarg.substr(asmarg.find('@')+1);
6117 }
6118 else
6119 {
6120 // V1/V2 do not have precision field so default to signed long
6121 // V3 asm does not have precision field so default to unsigned long
6122 if (probe_type == uprobe3_type)
6123 precision = sizeof(long); // this is an asm probe
6124 else
6125 precision = -sizeof(long);
6126 }
6127 return precision;
6128}
6129
0fbf6fb8
JL
6130expression*
6131sdt_uprobe_var_expanding_visitor::try_parse_arg_literal (target_symbol *e,
6132 const string& asmarg,
6133 long precision)
6134{
6135 expression *argexpr = NULL;
6136
6137 // Here, we test for a numeric literal.
6138 // Only accept (signed) decimals throughout. XXX
6139
6140 // PR11821. NB: on powerpc, literals are not prefixed with $,
6141 // so this regex does not match. But that's OK, since without
6142 // -mregnames, we can't tell them apart from register numbers
6143 // anyway. With -mregnames, we could, if gcc somehow
6144 // communicated to us the presence of that option, but alas it
6145 // doesn't. http://gcc.gnu.org/PR44995.
6146 vector<string> matches;
6147 if (!regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches))
6148 {
6149 string sn = matches[0].substr(1);
6150 int64_t n;
6151
6152 // We have to pay attention to the size & sign, as gcc sometimes
6153 // propagates constants that don't quite match, like a negative
6154 // value to fill an unsigned type.
6155 // NB: let it throw if something happens
6156 switch (precision)
6157 {
6158 case -1: n = lex_cast< int8_t>(sn); break;
6159 case 1: n = lex_cast< uint8_t>(sn); break;
6160 case -2: n = lex_cast< int16_t>(sn); break;
6161 case 2: n = lex_cast<uint16_t>(sn); break;
6162 case -4: n = lex_cast< int32_t>(sn); break;
6163 case 4: n = lex_cast<uint32_t>(sn); break;
6164 default:
6165 case -8: n = lex_cast< int64_t>(sn); break;
6166 case 8: n = lex_cast<uint64_t>(sn); break;
6167 }
6168
6169 literal_number* ln = new literal_number(n);
6170 ln->tok = e->tok;
6171 argexpr = ln;
6172 }
6173
6174 return argexpr;
6175}
6176
95b78bc9
JL
6177expression*
6178sdt_uprobe_var_expanding_visitor::try_parse_arg_register (target_symbol *e,
6179 const string& asmarg,
6180 long precision)
6181{
6182 expression *argexpr = NULL;
6183
6184 // test for REGISTER
6185 // NB: Because PR11821, we must use percent_regnames here.
6186 string regexp;
6187 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
6188 regexp = "^(" + regnames + ")$";
6189 else
6190 regexp = "^(" + percent_regnames + ")$";
6191
6192 vector<string> matches;
6193 if (!regexp_match(asmarg, regexp, matches))
6194 {
6195 string regname = matches[1];
6196 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
6197 if (ri != dwarf_regs.end()) // known register
6198 {
6199 embedded_expr *get_arg1 = new embedded_expr;
6200 string width_adjust;
6201 switch (ri->second.second)
6202 {
6203 case QI: width_adjust = ") & 0xff)"; break;
6204 case QIh: width_adjust = ">>8) & 0xff)"; break;
6205 case HI:
6206 // preserve 16 bit register signness
6207 width_adjust = ") & 0xffff)";
6208 if (precision < 0)
6209 width_adjust += " << 48 >> 48";
6210 break;
6211 case SI:
6212 // preserve 32 bit register signness
6213 width_adjust = ") & 0xffffffff)";
6214 if (precision < 0)
6215 width_adjust += " << 32 >> 32";
6216 break;
6217 default: width_adjust = "))";
6218 }
6219 string type = "";
6220 if (probe_type == uprobe3_type)
6221 type = (precision < 0
6222 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
6223 type = type + "((";
6224 get_arg1->tok = e->tok;
6225 get_arg1->code = string("/* unprivileged */ /* pure */")
6226 + string(" ((int64_t)") + type
a57b7534 6227 + string("u_fetch_register(")
95b78bc9
JL
6228 + lex_cast(dwarf_regs[regname].first) + string("))")
6229 + width_adjust;
6230 argexpr = get_arg1;
6231 }
6232 }
6233 return argexpr;
6234}
6235
b15f98b2
JL
6236static string
6237precision_to_function(long precision)
6238{
6239 switch (precision)
6240 {
6241 case 1: case -1:
6242 return "user_int8";
6243 case 2:
6244 return "user_uint16";
6245 case -2:
6246 return "user_int16";
6247 case 4:
6248 return "user_uint32";
6249 case -4:
6250 return "user_int32";
6251 case 8: case -8:
6252 return "user_int64";
6253 default:
6254 return "user_long";
6255 }
6256}
6257
8da56b62
JL
6258expression*
6259sdt_uprobe_var_expanding_visitor::try_parse_arg_offset_register (target_symbol *e,
6260 const string& asmarg,
6261 long precision)
6262{
6263 expression *argexpr = NULL;
6264
6265 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
6266 // NB: Despite PR11821, we can use regnames here, since the parentheses
6267 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6268 // On ARM test for [REGISTER, OFFSET]
6269
6270 string regexp;
6271 int reg, offset1;
6272 if (elf_machine == EM_ARM)
6273 {
6274 regexp = "^\\[(" + regnames + ")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$";
6275 reg = 1;
6276 offset1 = 3;
6277 }
6278 else
6279 {
6280 regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + ")[)]$";
6281 reg = 4;
6282 offset1 = 1;
6283 }
6284
6285 vector<string> matches;
6286 if (!regexp_match(asmarg, regexp, matches))
6287 {
6288 string regname;
6289 int64_t disp = 0;
6290 if (matches[reg].length())
6291 regname = matches[reg];
6292 if (dwarf_regs.find (regname) == dwarf_regs.end())
6293 throw SEMANTIC_ERROR(_F("unrecognized register '%s'", regname.c_str()));
6294
6295 for (int i=offset1; i <= (offset1 + 2); i++)
6296 if (matches[i].length())
6297 // should decode positive/negative hex/decimal
6298 // NB: let it throw if something happens
6299 disp += lex_cast<int64_t>(matches[i]);
6300
6301 // synthesize user_long(%{fetch_register(R)%} + D)
6302 embedded_expr *get_arg1 = new embedded_expr;
6303 get_arg1->tok = e->tok;
6304 get_arg1->code = string("/* unprivileged */ /* pure */")
a57b7534 6305 + string("u_fetch_register(")
8da56b62
JL
6306 + lex_cast(dwarf_regs[regname].first) + string(")");
6307 // XXX: may we ever need to cast that to a narrower type?
6308
6309 literal_number* inc = new literal_number(disp);
6310 inc->tok = e->tok;
6311
6312 binary_expression *be = new binary_expression;
6313 be->tok = e->tok;
6314 be->left = get_arg1;
6315 be->op = "+";
6316 be->right = inc;
6317
6318 functioncall *fc = new functioncall;
b15f98b2 6319 fc->function = precision_to_function(precision);
8da56b62
JL
6320 fc->tok = e->tok;
6321 fc->args.push_back(be);
6322
6323 argexpr = fc;
6324 }
6325
6326 return argexpr;
6327}
6328
10fcca15
JL
6329expression*
6330sdt_uprobe_var_expanding_visitor::try_parse_arg_effective_addr (target_symbol *e,
6331 const string& asmarg,
6332 long precision)
6333{
6334 expression *argexpr = NULL;
6335
6336 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
6337 // NB: Despite PR11821, we can use regnames here, since the parentheses
6338 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6339 string regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + "),(" +
6340 regnames + ")(,[1248])?[)]$";
6341 vector<string> matches;
6342 if (!regexp_match(asmarg, regexp, matches))
6343 {
6344 string baseregname;
6345 string indexregname;
6346 int64_t disp = 0;
6347 short scale = 1;
6348
6349 if (matches[6].length())
6350 // NB: let it throw if we can't cast
6351 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
6352
6353 if (matches[4].length())
6354 baseregname = matches[4];
6355 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6356 throw SEMANTIC_ERROR(_F("unrecognized base register '%s'", baseregname.c_str()));
6357
6358 if (matches[5].length())
6359 indexregname = matches[5];
6360 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6361 throw SEMANTIC_ERROR(_F("unrecognized index register '%s'", indexregname.c_str()));
6362
6363 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
6364 if (matches[i].length())
6365 // should decode positive/negative hex/decimal
6366 // NB: let it throw if something happens
6367 disp += lex_cast<int64_t>(matches[i]);
6368
6369 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6370
6371 embedded_expr *get_arg1 = new embedded_expr;
a57b7534 6372 string regfn = "u_fetch_register";
10fcca15
JL
6373
6374 get_arg1->tok = e->tok;
6375 get_arg1->code = string("/* unprivileged */ /* pure */")
6376 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6377 + string("+(")
6378 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6379 + string("*")
6380 + lex_cast(scale)
6381 + string(")");
6382
6383 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6384 literal_number* inc = new literal_number(disp);
6385 inc->tok = e->tok;
6386
6387 binary_expression *be = new binary_expression;
6388 be->tok = e->tok;
6389 be->left = get_arg1;
6390 be->op = "+";
6391 be->right = inc;
6392
6393 functioncall *fc = new functioncall;
b15f98b2 6394 fc->function = precision_to_function(precision);
10fcca15
JL
6395 fc->tok = e->tok;
6396 fc->args.push_back(be);
6397
6398 argexpr = fc;
6399 }
6400
6401 return argexpr;
6402}
6403
451c0c25
JL
6404expression*
6405sdt_uprobe_var_expanding_visitor::try_parse_arg_varname (target_symbol *e,
6406 const string& asmarg,
6407 long precision)
6ef331c8 6408{
b8688ee6 6409 static unsigned tick = 0;
451c0c25
JL
6410 expression *argexpr = NULL;
6411
6412 // test for [OFF+]VARNAME[+OFF][(REGISTER)], where VARNAME is a variable
6413 // name. NB: Despite PR11821, we can use regnames here, since the parentheses
6414 // make things unambiguous.
6415 string regex = "^(([0-9]+)[+])?([a-zA-Z_][a-zA-Z0-9_]*)([+][0-9]+)?([(]("
6416 + regnames + ")[)])?$";
6417 vector<string> matches;
6418 if (!regexp_match(asmarg, regex, matches))
6419 {
6420 assert(matches.size() >= 4);
6421 string varname = matches[3];
6422
6423 // OFF can be before VARNAME (put in matches[2]) or after (put in
6424 // matches[4]) (or both?). Seems like in most cases it comes after,
6425 // unless the code was compiled with -fPIC.
6426 int64_t offset = 0;
6427 if (!matches[2].empty())
6428 offset += lex_cast<int64_t>(matches[2]);
6429 if (matches.size() >= 5 && !matches[4].empty())
6430 offset += lex_cast<int64_t>(matches[4]);
6431
6432 string regname;
6433 if (matches.size() >= 7)
6434 regname = matches[6];
6435
6436 // If it's just VARNAME, then proceed. If it's VARNAME(REGISTER), then
6437 // only proceed if it's RIP-relative addressing on x86_64.
6438 if (regname.empty() || (regname == "%rip" && elf_machine == EM_X86_64))
6439 {
6440 dw.mod_info->get_symtab();
6441 if (dw.mod_info->symtab_status != info_present)
6442 throw SEMANTIC_ERROR(_("can't retrieve symbol table"));
6443
6444 assert(dw.mod_info->sym_table);
6445 map<string, Dwarf_Addr>& globals = dw.mod_info->sym_table->globals;
6446 map<string, Dwarf_Addr>& locals = dw.mod_info->sym_table->locals;
6447 Dwarf_Addr addr = 0;
6448
6449 // check symtab locals then globals
6450 if (locals.count(varname))
6451 addr = locals[varname];
6452 if (globals.count(varname))
6453 addr = globals[varname];
6454
6455 if (addr)
6456 {
6457 // add whatever offset is in the operand
6458 addr += offset;
6459
6460 // adjust for dw bias because relocate_address() expects a
6461 // libdw address and this addr is from the symtab
6462 dw.get_module_dwarf(false, false);
6463 addr -= dw.module_bias;
6464
6465 string reloc_section;
6466 Dwarf_Addr reloc_addr = dw.relocate_address(addr, reloc_section);
6467
6468 // OK, we have an address for the variable. Let's create a
6469 // function that will just relocate it at runtime, and then
6470 // call user_[u]int*() on the address it returns.
6471
6472 functioncall *user_int_call = new functioncall;
b15f98b2 6473 user_int_call->function = precision_to_function(precision);
451c0c25
JL
6474 user_int_call->tok = e->tok;
6475
6476 functiondecl *get_addr_decl = new functiondecl;
6477 get_addr_decl->tok = e->tok;
6478 get_addr_decl->synthetic = true;
6479 get_addr_decl->name = "_sdt_arg_get_addr_" + lex_cast(tick++);
6480 get_addr_decl->type = pe_long;
6481
6482 // build _stp_[ku]module_relocate(module, addr, current)
6483 stringstream ss;
6484 ss << " /* unprivileged */ /* pure */ /* pragma:vma */" << endl;
a57b7534
JL
6485 ss << "STAP_RETURN(_stp_umodule_relocate(";
6486 ss << "\"" << path_remove_sysroot(session, process_name) << "\", ";
6487 ss << "0x" << hex << reloc_addr << dec << ", ";
6488 ss << "current";
6489 ss << "));" << endl;
451c0c25
JL
6490
6491 embeddedcode *ec = new embeddedcode;
6492 ec->tok = e->tok;
6493 ec->code = ss.str();
6494 get_addr_decl->body = ec;
6495 get_addr_decl->join(session);
6496
6497 functioncall *get_addr_call = new functioncall;
6498 get_addr_call->tok = e->tok;
6499 get_addr_call->function = get_addr_decl->name;
6500 user_int_call->args.push_back(get_addr_call);
b8688ee6 6501
451c0c25
JL
6502 argexpr = user_int_call;
6503 }
6504 }
6505 }
6506
6507 return argexpr;
6508}
6509
6510void
6511sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
6512{
6ef331c8
SC
6513 try
6514 {
03c45fcb 6515 unsigned argno = get_target_symbol_argno_and_validate(e); // the N in $argN
8aabf152 6516 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 6517
8aabf152
FCE
6518 // Now we try to parse this thing, which is an assembler operand
6519 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 6520 // and hope for the best. Here is the syntax for a few architectures.
9859b766 6521 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157 6522 //
b6aaaf21
JL
6523 // literal reg reg reg+ base+index*size+ VAR VAR+off RIP-relative
6524 // indirect offset offset VAR+off
6525 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6526 // x86_64 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6527 // power iN R (R) N(R)
6528 // ia64 N rR [r16]
6529 // s390 N %rR 0(rR) N(r15)
6530 // arm #N rR [rR] [rR, #N]
b874bd52 6531
8aabf152
FCE
6532 expression* argexpr = 0; // filled in in case of successful parse
6533
ac074daf
JL
6534 // Parse (and remove from asmarg) the leading length
6535 long precision = parse_out_arg_precision(asmarg);
40fe32e0 6536
0fbf6fb8 6537 try
8aabf152 6538 {
0fbf6fb8
JL
6539 if ((argexpr = try_parse_arg_literal(e, asmarg, precision)) != NULL)
6540 goto matched;
2e6d617a
JL
6541
6542 // all other matches require registers
6543 if (regnames == "")
6544 throw SEMANTIC_ERROR("no registers to use for parsing");
95b78bc9
JL
6545
6546 if ((argexpr = try_parse_arg_register(e, asmarg, precision)) != NULL)
6547 goto matched;
8da56b62
JL
6548 if ((argexpr = try_parse_arg_offset_register(e, asmarg, precision)) != NULL)
6549 goto matched;
10fcca15
JL
6550 if ((argexpr = try_parse_arg_effective_addr(e, asmarg, precision)) != NULL)
6551 goto matched;
451c0c25
JL
6552 if ((argexpr = try_parse_arg_varname(e, asmarg, precision)) != NULL)
6553 goto matched;
0fbf6fb8
JL
6554 }
6555 catch (const semantic_error& err)
6556 {
6557 e->chain(err);
b8688ee6 6558 }
8aabf152 6559
8aabf152
FCE
6560 // The asmarg operand was not recognized. Back down to dwarf.
6561 if (! session.suppress_warnings)
84fef8ee
FCE
6562 {
6563 if (probe_type == UPROBE3_TYPE)
451c0c25
JL
6564 session.print_warning (_F("Can't parse SDT_V3 operand '%s' "
6565 "[man error::sdt]", asmarg.c_str()),
6566 e->tok);
84fef8ee 6567 else // must be *PROBE2; others don't get asm operands
451c0c25
JL
6568 session.print_warning (_F("Downgrading SDT_V2 probe argument to "
6569 "dwarf, can't parse '%s' [man error::sdt]",
6570 asmarg.c_str()),
6571 e->tok);
84fef8ee 6572 }
451c0c25 6573
8aabf152 6574 need_debug_info = true;
451c0c25
JL
6575 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo "
6576 "[man error::sdt]"), e->tok);
6577
6578 /* NOTREACHED */
366af4e7 6579
8aabf152
FCE
6580 matched:
6581 assert (argexpr != 0);
366af4e7
RM
6582
6583 if (session.verbose > 2)
1e41115c 6584 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6585 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6586
aff5d390 6587 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6588 {
6589 if (e->addressof)
dc09353a 6590 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152 6591 provide (argexpr);
8aabf152
FCE
6592 }
6593 else // $var->foo
6594 {
6595 cast_op *cast = new cast_op;
6596 cast->name = "@cast";
6597 cast->tok = e->tok;
6598 cast->operand = argexpr;
6599 cast->components = e->components;
6600 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6601 cast->module = process_name;
6602 cast->visit(this);
8aabf152 6603 }
aff5d390
SC
6604 }
6605 catch (const semantic_error &er)
6606 {
6607 e->chain (er);
6608 provide (e);
6609 }
6610}
6611
6612
6ef331c8
SC
6613void
6614sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6615{
6616 try
6617 {
49131a6d 6618 assert(e->name.size() > 0
bd1fcbad 6619 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6620
6621 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6622 visit_target_symbol_context (e);
6623 else
6624 visit_target_symbol_arg (e);
6625 }
6626 catch (const semantic_error &er)
6627 {
6628 e->chain (er);
6629 provide (e);
6630 }
6631}
6632
6633
bd1fcbad
YZ
6634void
6635sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6636{
6637 need_debug_info = true;
6638
6639 // Fill in our current module context if needed
6640 if (e->module.empty())
6641 e->module = process_name;
6642
6643 var_expanding_visitor::visit_atvar_op(e);
6644}
6645
6646
40a0c64e
JS
6647void
6648sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6649{
6650 // Fill in our current module context if needed
6651 if (e->module.empty())
6652 e->module = process_name;
6653
6654 var_expanding_visitor::visit_cast_op(e);
6655}
6656
6657
576eaefe
SC
6658void
6659plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6660{
6661 try
6662 {
6663 if (e->name == "$$name")
6664 {
6665 literal_string *myname = new literal_string (entry);
6666 myname->tok = e->tok;
6667 provide(myname);
6668 return;
6669 }
3d69c03f
JS
6670
6671 // variable not found -> throw a semantic error
6672 // (only to be caught right away, but this may be more complex later...)
6673 string alternatives = "$$name";
dc09353a 6674 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6675 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6676 }
6677 catch (const semantic_error &er)
6678 {
6679 e->chain (er);
6680 provide (e);
6681 }
6682}
6683
6684
edce5b67
JS
6685struct sdt_query : public base_query
6686{
6687 sdt_query(probe * base_probe, probe_point * base_loc,
6688 dwflpp & dw, literal_map_t const & params,
51d6bda3 6689 vector<derived_probe *> & results, const string user_lib);
edce5b67 6690
51d6bda3 6691 void query_library (const char *data);
576eaefe 6692 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6693 void handle_query_module();
6694
6695private:
15284963 6696 stap_sdt_probe_type probe_type;
d61ea602 6697 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6698 probe * base_probe;
6699 probe_point * base_loc;
6846cfc8 6700 literal_map_t const & params;
edce5b67 6701 vector<derived_probe *> & results;
a794dbeb
FCE
6702 string pp_mark;
6703 string pp_provider;
51d6bda3 6704 string user_lib;
edce5b67
JS
6705
6706 set<string> probes_handled;
6707
6708 Elf_Data *pdata;
6709 size_t probe_scn_offset;
6710 size_t probe_scn_addr;
aff5d390 6711 uint64_t arg_count;
40fe32e0 6712 GElf_Addr base;
c57ea854 6713 GElf_Addr pc;
aff5d390 6714 string arg_string;
edce5b67 6715 string probe_name;
a794dbeb 6716 string provider_name;
909ab234 6717 GElf_Addr semaphore_load_offset;
79a0ca08 6718 Dwarf_Addr semaphore;
edce5b67
JS
6719
6720 bool init_probe_scn();
6b51ee12 6721 bool get_next_probe();
c57ea854
SC
6722 void iterate_over_probe_entries();
6723 void handle_probe_entry();
edce5b67 6724
488d3c1b 6725 static void setup_note_probe_entry_callback (sdt_query *me,
dbd24034
JL
6726 const string& scn_name,
6727 const string& note_name,
488d3c1b
JL
6728 int type,
6729 const char *data,
6730 size_t len);
dbd24034
JL
6731 void setup_note_probe_entry (const string& scn_name,
6732 const string& note_name, int type,
6733 const char *data, size_t len);
40fe32e0 6734
edce5b67 6735 void convert_probe(probe *base);
4ddb6dd0 6736 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6737 probe* convert_location();
40fe32e0 6738 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6739 bool have_debuginfo_uprobe(bool need_debug_info)
6740 {return probe_type == uprobe1_type
40fe32e0 6741 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6742 && need_debug_info);}
40fe32e0 6743 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6744};
6745
6746
6747sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6748 dwflpp & dw, literal_map_t const & params,
51d6bda3 6749 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6750 base_query(dw, params), probe_type(unknown_probe_type),
6751 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6752 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6753 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6754 semaphore_load_offset(0), semaphore(0)
edce5b67 6755{
a794dbeb
FCE
6756 assert(get_string_param(params, TOK_MARK, pp_mark));
6757 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6758
ef428667
FCE
6759 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6760 // map it to double-underscores.
6761 size_t pos = 0;
6762 while (1) // there may be more than one
6763 {
a794dbeb 6764 size_t i = pp_mark.find("-", pos);
ef428667 6765 if (i == string::npos) break;
a794dbeb 6766 pp_mark.replace (i, 1, "__");
ef428667
FCE
6767 pos = i+1; // resume searching after the inserted __
6768 }
a794dbeb
FCE
6769
6770 // XXX: same for pp_provider?
edce5b67
JS
6771}
6772
6773
6774void
c57ea854 6775sdt_query::handle_probe_entry()
edce5b67 6776{
c57ea854
SC
6777 if (! have_uprobe()
6778 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6779 return;
6780
6781 if (sess.verbose > 3)
c57ea854 6782 {
b78a0fbb 6783 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
b530b5b3
LB
6784 //TRANSLATORS: is matched to.
6785 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6786 switch (probe_type)
6787 {
6788 case uprobe1_type:
6789 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6790 break;
6791 case uprobe2_type:
6792 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6793 break;
40fe32e0
SC
6794 case uprobe3_type:
6795 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6796 break;
d61ea602
JS
6797 default:
6798 clog << "unknown!" << endl;
6799 break;
c57ea854
SC
6800 }
6801 }
edce5b67 6802
c57ea854
SC
6803 // Extend the derivation chain
6804 probe *new_base = convert_location();
6805 probe_point *new_location = new_base->locations[0];
6806
c57ea854
SC
6807 bool need_debug_info = false;
6808
7d395255
JS
6809 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6810 // or dwfl_module_getelf(...). We only need it for the machine type, which
6811 // should be the same. The bias is used for relocating debuginfoless probes,
6812 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6813 Dwarf_Addr bias;
7d395255 6814 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6815
1cc41cd6
DS
6816 /* Figure out the architecture of this particular ELF file. The
6817 dwarfless register-name mappings depend on it. */
6818 GElf_Ehdr ehdr_mem;
6819 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 6820 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6821 assert(em);
1cc41cd6 6822 int elf_machine = em->e_machine;
b8688ee6
JL
6823 sdt_uprobe_var_expanding_visitor svv (sess, dw, elf_machine, module_val,
6824 provider_name, probe_name, probe_type,
6825 arg_string, arg_count);
1cc41cd6
DS
6826 svv.replace (new_base->body);
6827 need_debug_info = svv.need_debug_info;
c57ea854 6828
1cc41cd6
DS
6829 // XXX: why not derive_probes() in the uprobes case too?
6830 literal_map_t params;
6831 for (unsigned i = 0; i < new_location->components.size(); ++i)
6832 {
6833 probe_point::component *c = new_location->components[i];
6834 params[c->functor] = c->arg;
6835 }
c57ea854 6836
73d53dd2 6837 unsigned prior_results_size = results.size();
1cc41cd6
DS
6838 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6839 q.has_mark = true; // enables mid-statement probing
30263a73 6840
73d53dd2
JS
6841 // V1 probes always need dwarf info
6842 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6 6843 if (have_debuginfo_uprobe(need_debug_info))
06de3a04 6844 dw.iterate_over_modules<base_query>(&query_module, &q);
73d53dd2
JS
6845
6846 // For V2+ probes, if variable references weren't used or failed (PR14369),
6847 // then try with the more direct approach. Unresolved $vars might still
6848 // cause their own error, but this gives them a chance to be optimized out.
6849 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6850 {
6851 string section;
6852 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6853 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6854 {
6855 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6856 section = ".dynamic";
6857 }
6858 else
6859 section = ".absolute";
edce5b67 6860
1cc41cd6
DS
6861 uprobe_derived_probe* p =
6862 new uprobe_derived_probe ("", "", 0,
6863 path_remove_sysroot(sess,q.module_val),
6864 section,
6865 q.statement_num_val, reloc_addr, q, 0);
6866 p->saveargs (arg_count);
6867 results.push_back (p);
c57ea854 6868 }
487bf4e2 6869 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6870 record_semaphore(results, prior_results_size);
c57ea854 6871}
edce5b67 6872
4ddb6dd0 6873
c57ea854
SC
6874void
6875sdt_query::handle_query_module()
6876{
6877 if (!init_probe_scn())
6878 return;
edce5b67 6879
c57ea854
SC
6880 if (sess.verbose > 3)
6881 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6882
40fe32e0
SC
6883 if (probe_loc == note_section)
6884 {
6885 GElf_Shdr shdr_mem;
6886 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6887
909ab234
JS
6888 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6889 // effects. The 'semaphore_load_offset' accounts for the difference in
6890 // load addresses between text and data, so the semaphore can be
6891 // converted to a file offset if needed.
40fe32e0 6892 if (shdr)
909ab234
JS
6893 {
6894 base = shdr->sh_addr;
6895 GElf_Addr base_offset = shdr->sh_offset;
6896 shdr = dw.get_section (".probes", &shdr_mem);
6897 if (shdr)
6898 semaphore_load_offset =
6899 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6900 }
40fe32e0 6901 else
909ab234
JS
6902 base = semaphore_load_offset = 0;
6903
488d3c1b 6904 dw.iterate_over_notes (this, &sdt_query::setup_note_probe_entry_callback);
40fe32e0 6905 }
d61ea602 6906 else if (probe_loc == probe_section)
40fe32e0 6907 iterate_over_probe_entries ();
edce5b67
JS
6908}
6909
6910
6911bool
6912sdt_query::init_probe_scn()
6913{
448a86b7 6914 Elf* elf;
edce5b67 6915 GElf_Shdr shdr_mem;
40fe32e0
SC
6916
6917 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6918 if (shdr)
6919 {
6920 probe_loc = note_section;
6921 return true;
6922 }
edce5b67 6923
448a86b7 6924 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6925 if (shdr)
edce5b67 6926 {
fea74777
SC
6927 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6928 probe_scn_offset = 0;
6929 probe_scn_addr = shdr->sh_addr;
6930 assert (pdata != NULL);
6931 if (sess.verbose > 4)
ce0f6648
LB
6932 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6933 << pdata->d_size << endl;
40fe32e0 6934 probe_loc = probe_section;
fea74777 6935 return true;
edce5b67 6936 }
fea74777 6937 else
edce5b67 6938 return false;
edce5b67
JS
6939}
6940
40fe32e0 6941void
dbd24034
JL
6942sdt_query::setup_note_probe_entry_callback (sdt_query *me,
6943 const string& scn_name,
6944 const string& note_name, int type,
6945 const char *data, size_t len)
40fe32e0 6946{
dbd24034 6947 me->setup_note_probe_entry (scn_name, note_name, type, data, len);
40fe32e0
SC
6948}
6949
6950
6951void
dbd24034
JL
6952sdt_query::setup_note_probe_entry (const string& scn_name,
6953 const string& note_name, int type,
6954 const char *data, size_t len)
40fe32e0 6955{
dbd24034
JL
6956 if (scn_name.compare(".note.stapsdt"))
6957 return;
6958#define _SDT_NOTE_NAME "stapsdt"
6959 if (note_name.compare(_SDT_NOTE_NAME))
6960 return;
40fe32e0
SC
6961#define _SDT_NOTE_TYPE 3
6962 if (type != _SDT_NOTE_TYPE)
6963 return;
6964
dbd24034 6965 // we found a probe entry
40fe32e0
SC
6966 union
6967 {
6968 Elf64_Addr a64[3];
6969 Elf32_Addr a32[3];
6970 } buf;
6971 Dwarf_Addr bias;
6972 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6973 Elf_Data dst =
6974 {
6975 &buf, ELF_T_ADDR, EV_CURRENT,
6976 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6977 };
6978 assert (dst.d_size <= sizeof buf);
6979
6980 if (len < dst.d_size + 3)
6981 return;
6982
6983 Elf_Data src =
6984 {
6985 (void *) data, ELF_T_ADDR, EV_CURRENT,
6986 dst.d_size, 0, 0
6987 };
6988
6989 if (gelf_xlatetom (elf, &dst, &src,
6990 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6991 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6992
6993 probe_type = uprobe3_type;
6994 const char * provider = data + dst.d_size;
3f803f9e 6995
40fe32e0 6996 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6997 if(name++ == NULL)
6998 return;
6999
7000 const char *args = (const char*)memchr (name, '\0', data + len - name);
7001 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
7002 return;
7003
7004 provider_name = provider;
7005 probe_name = name;
7006 arg_string = args;
40fe32e0 7007
e90006d7
JL
7008 dw.mod_info->marks.insert(make_pair(provider, name));
7009
40fe32e0
SC
7010 // Did we find a matching probe?
7011 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
7012 && ((pp_provider == "")
7013 || dw.function_name_matches_pattern (provider_name, pp_provider))))
7014 return;
7015
e9a90eee
JS
7016 // PR13934: Assembly probes are not forced to use the N@OP form.
7017 // If we have '@' then great, else count based on space-delimiters.
7018 arg_count = count(arg_string.begin(), arg_string.end(), '@');
7019 if (!arg_count && !arg_string.empty())
7020 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
7021
40fe32e0
SC
7022 GElf_Addr base_ref;
7023 if (gelf_getclass (elf) == ELFCLASS32)
7024 {
7025 pc = buf.a32[0];
7026 base_ref = buf.a32[1];
7027 semaphore = buf.a32[2];
7028 }
7029 else
7030 {
7031 pc = buf.a64[0];
7032 base_ref = buf.a64[1];
7033 semaphore = buf.a64[2];
7034 }
7035
7036 semaphore += base - base_ref;
7037 pc += base - base_ref;
7038
7d395255
JS
7039 // The semaphore also needs the ELF bias added now, so
7040 // record_semaphore can properly relocate it later.
7041 semaphore += bias;
7042
40fe32e0 7043 if (sess.verbose > 4)
b530b5b3 7044 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
7045
7046 handle_probe_entry();
7047}
7048
7049
c57ea854
SC
7050void
7051sdt_query::iterate_over_probe_entries()
edce5b67 7052{
c57ea854 7053 // probes are in the .probe section
edce5b67
JS
7054 while (probe_scn_offset < pdata->d_size)
7055 {
aff5d390
SC
7056 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
7057 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 7058 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 7059 if (! have_uprobe())
edce5b67
JS
7060 {
7061 // Unless this is a mangled .probes section, this happens
7062 // because the name of the probe comes first, followed by
7063 // the sentinel.
7064 if (sess.verbose > 5)
b530b5b3 7065 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
7066 probe_scn_offset += sizeof(__uint32_t);
7067 continue;
7068 }
aff5d390
SC
7069 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
7070 {
7071 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 7072 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
7073 continue;
7074 }
7075
1cc41cd6 7076 if (probe_type == uprobe1_type)
aff5d390 7077 {
79a0ca08 7078 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 7079 return;
79a0ca08 7080 semaphore = 0;
aff5d390 7081 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 7082 provider_name = ""; // unknown
1cc41cd6
DS
7083 pc = pbe_v1->arg;
7084 arg_count = 0;
aff5d390
SC
7085 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
7086 }
08b5a50c 7087 else if (probe_type == uprobe2_type)
aff5d390 7088 {
79a0ca08 7089 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 7090 return;
79a0ca08 7091 semaphore = pbe_v2->semaphore;
aff5d390 7092 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 7093 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
7094 arg_count = pbe_v2->arg_count;
7095 pc = pbe_v2->pc;
7096 if (pbe_v2->arg_string)
7097 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
7098 // skip over pbe_v2, probe_name text and provider text
7099 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
7100 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 7101 }
edce5b67 7102 if (sess.verbose > 4)
b530b5b3 7103 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 7104 << "@0x" << hex << pc << dec << endl;
edce5b67 7105
e90006d7
JL
7106 dw.mod_info->marks.insert(make_pair(provider_name, probe_name));
7107
a794dbeb
FCE
7108 if (dw.function_name_matches_pattern (probe_name, pp_mark)
7109 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 7110 handle_probe_entry ();
edce5b67 7111 }
edce5b67
JS
7112}
7113
7114
6846cfc8 7115void
4ddb6dd0 7116sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 7117{
a794dbeb
FCE
7118 for (unsigned i=0; i<2; i++) {
7119 // prefer with-provider symbol; look without provider prefix for backward compatibility only
7120 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
7121 // XXX: multiple addresses?
7122 if (sess.verbose > 2)
b530b5b3 7123 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 7124
79a0ca08
SC
7125 Dwarf_Addr addr;
7126 if (this->semaphore)
7127 addr = this->semaphore;
7128 else
7129 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
7130 if (addr)
7131 {
7d395255 7132 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
7133 dwfl_module_relocate_address (dw.module, &addr);
7134 // XXX: relocation basis?
909ab234
JS
7135
7136 // Dyninst needs the *file*-based offset for semaphores,
7137 // so subtract the difference in load addresses between .text and .probes
7138 if (dw.sess.runtime_usermode_p())
7139 addr -= semaphore_load_offset;
7140
a794dbeb
FCE
7141 for (unsigned i = start; i < results.size(); ++i)
7142 results[i]->sdt_semaphore_addr = addr;
7143 if (sess.verbose > 2)
b530b5b3 7144 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
7145 return;
7146 }
7147 else
7148 if (sess.verbose > 2)
b530b5b3 7149 clog << _(", not found") << endl;
a794dbeb 7150 }
6846cfc8
SC
7151}
7152
7153
edce5b67
JS
7154void
7155sdt_query::convert_probe (probe *base)
7156{
7157 block *b = new block;
7158 b->tok = base->body->tok;
7159
edce5b67
JS
7160 // Generate: if (arg1 != mark("label")) next;
7161 functioncall *fc = new functioncall;
bbafcb1e 7162 fc->function = "ulong_arg";
edce5b67 7163 fc->tok = b->tok;
bbafcb1e 7164 literal_number* num = new literal_number(1);
edce5b67
JS
7165 num->tok = b->tok;
7166 fc->args.push_back(num);
7167
7168 functioncall *fcus = new functioncall;
7169 fcus->function = "user_string";
7170 fcus->type = pe_string;
7171 fcus->tok = b->tok;
7172 fcus->args.push_back(fc);
7173
7174 if_statement *is = new if_statement;
7175 is->thenblock = new next_statement;
7176 is->elseblock = NULL;
7177 is->tok = b->tok;
63ea4244 7178 is->thenblock->tok = b->tok;
edce5b67
JS
7179 comparison *be = new comparison;
7180 be->op = "!=";
7181 be->tok = b->tok;
7182 be->left = fcus;
7183 be->right = new literal_string(probe_name);
63ea4244 7184 be->right->tok = b->tok;
edce5b67
JS
7185 is->condition = be;
7186 b->statements.push_back(is);
7187
7188 // Now replace the body
7189 b->statements.push_back(base->body);
7190 base->body = b;
7191}
7192
7193
c72aa911
JS
7194probe*
7195sdt_query::convert_location ()
edce5b67 7196{
684b8718
JL
7197 string module = dw.module_name;
7198 if (has_process)
7199 module = path_remove_sysroot(sess, module);
7200
c72aa911 7201 probe_point* specific_loc = new probe_point(*base_loc);
684b8718
JL
7202 specific_loc->well_formed = true;
7203
662539d9 7204 vector<probe_point::component*> derived_comps;
edce5b67 7205
662539d9
JS
7206 vector<probe_point::component*>::iterator it;
7207 for (it = specific_loc->components.begin();
7208 it != specific_loc->components.end(); ++it)
7209 if ((*it)->functor == TOK_PROCESS)
7210 {
684b8718
JL
7211 // replace the possibly incomplete path to process
7212 *it = new probe_point::component(TOK_PROCESS,
7213 new literal_string(has_library ? path : module));
7214
1cc41cd6
DS
7215 // copy the process name
7216 derived_comps.push_back(*it);
662539d9
JS
7217 }
7218 else if ((*it)->functor == TOK_LIBRARY)
7219 {
1cc41cd6
DS
7220 // copy the library name for process probes
7221 derived_comps.push_back(*it);
662539d9
JS
7222 }
7223 else if ((*it)->functor == TOK_PROVIDER)
7224 {
7225 // replace the possibly wildcarded arg with the specific provider name
7226 *it = new probe_point::component(TOK_PROVIDER,
7227 new literal_string(provider_name));
7228 }
7229 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
7230 {
7231 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
7232 *it = new probe_point::component(TOK_MARK,
7233 new literal_string(probe_name));
a794dbeb 7234
aff5d390
SC
7235 if (sess.verbose > 3)
7236 switch (probe_type)
7237 {
7238 case uprobe1_type:
b530b5b3 7239 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
7240 << hex << pc << dec << endl;
7241 break;
7242 case uprobe2_type:
b530b5b3 7243 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
7244 << hex << pc << dec << endl;
7245 break;
40fe32e0 7246 case uprobe3_type:
b530b5b3 7247 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
7248 << hex << pc << dec << endl;
7249 break;
aff5d390 7250 default:
b530b5b3
LB
7251 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
7252 pp_mark.c_str()) << endl;
aff5d390
SC
7253 }
7254
c72aa911
JS
7255 switch (probe_type)
7256 {
aff5d390
SC
7257 case uprobe1_type:
7258 case uprobe2_type:
40fe32e0 7259 case uprobe3_type:
c72aa911 7260 // process("executable").statement(probe_arg)
662539d9
JS
7261 derived_comps.push_back
7262 (new probe_point::component(TOK_STATEMENT,
7263 new literal_number(pc, true)));
c72aa911
JS
7264 break;
7265
a794dbeb 7266 default: // deprecated
c72aa911 7267 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
7268 derived_comps.push_back
7269 (new probe_point::component(TOK_FUNCTION,
7270 new literal_string("*")));
7271 derived_comps.push_back
c72aa911 7272 (new probe_point::component(TOK_LABEL,
a794dbeb 7273 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
7274 break;
7275 }
7276 }
edce5b67 7277
662539d9
JS
7278 probe_point* derived_loc = new probe_point(*specific_loc);
7279 derived_loc->components = derived_comps;
8159bf55 7280 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
7281}
7282
7283
51d6bda3
SC
7284void
7285sdt_query::query_library (const char *library)
7286{
7287 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
7288}
7289
e90006d7
JL
7290string
7291suggest_marks(systemtap_session& sess,
7292 const set<string>& modules,
7293 const string& mark,
7294 const string& provider)
7295{
7296 if (mark.empty() || modules.empty() || sess.module_cache == NULL)
7297 return "";
7298
7299 set<string> marks;
7300 const map<string, module_info*> &cache = sess.module_cache->cache;
7301 bool dash_suggestions = (mark.find("-") != string::npos);
7302
7303 for (set<string>::iterator itmod = modules.begin();
7304 itmod != modules.end(); ++itmod)
7305 {
7306 map<string, module_info*>::const_iterator itcache;
7307 if ((itcache = cache.find(*itmod)) != cache.end())
7308 {
7309 set<pair<string,string> >::const_iterator itmarks;
7310 for (itmarks = itcache->second->marks.begin();
7311 itmarks != itcache->second->marks.end(); ++itmarks)
7312 {
7313 if (provider.empty()
7314 // simulating dw.function_name_matches_pattern()
7315 || (fnmatch(provider.c_str(), itmarks->first.c_str(), 0) == 0))
7316 {
7317 string marksug = itmarks->second;
7318 if (dash_suggestions)
7319 {
7320 size_t pos = 0;
7321 while (1) // there may be more than one
7322 {
7323 size_t i = marksug.find("__", pos);
7324 if (i == string::npos) break;
7325 marksug.replace (i, 2, "-");
7326 pos = i+1; // resume searching after the inserted -
7327 }
7328 }
7329 marks.insert(marksug);
7330 }
7331 }
7332 }
7333 }
7334
7335 if (sess.verbose > 2)
7336 {
7337 clog << "suggesting " << marks.size() << " marks "
7338 << "from modules:" << endl;
7339 for (set<string>::iterator itmod = modules.begin();
7340 itmod != modules.end(); ++itmod)
7341 clog << *itmod << endl;
7342 }
7343
7344 if (marks.empty())
7345 return "";
7346
7347 return levenshtein_suggest(mark, marks, 5); // print top 5 marks only
7348}
7349
40a70f52
JL
7350string
7351suggest_plt_functions(systemtap_session& sess,
7352 const set<string>& modules,
7353 const string& func)
7354{
7355 if (func.empty() || modules.empty() || sess.module_cache == NULL)
7356 return "";
7357
7358 set<string> funcs;
7359 const map<string, module_info*> &cache = sess.module_cache->cache;
7360
7361 for (set<string>::iterator itmod = modules.begin();
7362 itmod != modules.end(); ++itmod)
7363 {
7364 map<string, module_info*>::const_iterator itcache;
7365 if ((itcache = cache.find(*itmod)) != cache.end())
7366 funcs.insert(itcache->second->plt_funcs.begin(),
7367 itcache->second->plt_funcs.end());
7368 }
7369
7370 if (sess.verbose > 2)
d82dd71f
JL
7371 {
7372 clog << "suggesting " << funcs.size() << " plt functions "
7373 << "from modules:" << endl;
7374 for (set<string>::iterator itmod = modules.begin();
7375 itmod != modules.end(); ++itmod)
7376 clog << *itmod << endl;
7377 }
40a70f52
JL
7378
7379 if (funcs.empty())
7380 return "";
7381
7382 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
7383}
51d6bda3 7384
0508c45f
JL
7385string
7386suggest_dwarf_functions(systemtap_session& sess,
7387 const set<string>& modules,
7388 string func)
44ffe90c
JL
7389{
7390 // Trim any @ component
7391 size_t pos = func.find('@');
7392 if (pos != string::npos)
7393 func.erase(pos);
7394
0508c45f 7395 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
7396 return "";
7397
7398 // We must first aggregate all the functions from the cache
7399 set<string> funcs;
7400 const map<string, module_info*> &cache = sess.module_cache->cache;
7401
0508c45f
JL
7402 for (set<string>::iterator itmod = modules.begin();
7403 itmod != modules.end(); ++itmod)
44ffe90c 7404 {
6e6d9a3b
JL
7405 module_info *module;
7406
7407 // retrieve module_info from cache
44ffe90c
JL
7408 map<string, module_info*>::const_iterator itcache;
7409 if ((itcache = cache.find(*itmod)) != cache.end())
6e6d9a3b
JL
7410 module = itcache->second;
7411 else // module not found
7412 continue;
7413
7414 // add inlines
7415 funcs.insert(module->inlined_funcs.begin(),
7416 module->inlined_funcs.end());
7417
7418 // add all function symbols in cache
7419 if (module->symtab_status != info_present || module->sym_table == NULL)
7420 continue;
7421 map<string, func_info*>& modfuncs = module->sym_table->map_by_name;
7422 for (map<string, func_info*>::const_iterator itfuncs = modfuncs.begin();
7423 itfuncs != modfuncs.end(); ++itfuncs)
7424 funcs.insert(itfuncs->first);
44ffe90c
JL
7425 }
7426
7427 if (sess.verbose > 2)
d82dd71f
JL
7428 {
7429 clog << "suggesting " << funcs.size() << " dwarf functions "
7430 << "from modules:" << endl;
7431 for (set<string>::iterator itmod = modules.begin();
7432 itmod != modules.end(); ++itmod)
7433 clog << *itmod << endl;
7434 }
44ffe90c
JL
7435
7436 if (funcs.empty())
7437 return "";
7438
593f09eb 7439 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
7440}
7441
20c6c071 7442void
5227f1ea 7443dwarf_builder::build(systemtap_session & sess,
7a053d3b 7444 probe * base,
20c6c071 7445 probe_point * location,
86bf665e 7446 literal_map_t const & parameters,
20c6c071
GH
7447 vector<derived_probe *> & finished_results)
7448{
b20febf3
FCE
7449 // NB: the kernel/user dwlfpp objects are long-lived.
7450 // XXX: but they should be per-session, as this builder object
7451 // may be reused if we try to cross-instrument multiple targets.
84048984 7452
7a24d422 7453 dwflpp* dw = 0;
6d5d594e 7454 literal_map_t filled_parameters = parameters;
7a24d422 7455
7a24d422 7456 string module_name;
ae2552da
FCE
7457 if (has_null_param (parameters, TOK_KERNEL))
7458 {
7459 dw = get_kern_dw(sess, "kernel");
7460 }
7461 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 7462 {
c523a015
LB
7463 size_t dash_pos = 0;
7464 while((dash_pos=module_name.find('-'))!=string::npos)
7465 module_name.replace(int(dash_pos),1,"_");
7466 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
7467 // NB: glob patterns get expanded later, during the offline
7468 // elfutils module listing.
ae2552da 7469 dw = get_kern_dw(sess, module_name);
b8da0ad1 7470 }
6d5d594e 7471 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 7472 {
05fb3e0c 7473 module_name = sess.sysroot + module_name;
6d5d594e
LB
7474 if(has_null_param(filled_parameters, TOK_PROCESS))
7475 {
fc18e6c4
JL
7476 string file;
7477 try
7478 {
7479 file = sess.cmd_file();
7480 }
7481 catch (const semantic_error& e)
7482 {
7483 throw SEMANTIC_ERROR(_("invalid -c command for unspecified process"
7484 " probe [man stapprobes]"), NULL, NULL, &e);
7485 }
48cd804a 7486 if(file.empty())
fc18e6c4
JL
7487 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without"
7488 " a -c COMMAND [man stapprobes]"));
48cd804a 7489 module_name = sess.sysroot + file;
6d5d594e
LB
7490 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
7491 // in the case of TOK_MARK we need to modify locations as well
7492 if(location->components[0]->functor==TOK_PROCESS &&
7493 location->components[0]->arg == 0)
7494 location->components[0]->arg = new literal_string(module_name);
b78a0fbb 7495 }
5750ecc6 7496
37001baa
FCE
7497 // PR6456 process("/bin/*") glob handling
7498 if (contains_glob_chars (module_name))
7499 {
7500 // Expand glob via rewriting the probe-point process("....")
7501 // parameter, asserted to be the first one.
7502
7503 assert (location->components.size() > 0);
7504 assert (location->components[0]->functor == TOK_PROCESS);
7505 assert (location->components[0]->arg);
7506 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7507 assert (lit);
7508
7509 // Evaluate glob here, and call derive_probes recursively with each match.
7510 glob_t the_blob;
88f8e2c0 7511 set<string> dupes;
37001baa 7512 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 7513 if (rc)
dc09353a 7514 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 7515 unsigned results_pre = finished_results.size();
37001baa
FCE
7516 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
7517 {
e19ebcf7 7518 assert_no_interrupts();
37001baa
FCE
7519
7520 const char* globbed = the_blob.gl_pathv[i];
7521 struct stat st;
7522
7523 if (access (globbed, X_OK) == 0
7524 && stat (globbed, &st) == 0
7525 && S_ISREG (st.st_mode)) // see find_executable()
7526 {
7977a734
FCE
7527 // Need to call canonicalize here, in order to path-expand
7528 // patterns like process("stap*"). Otherwise it may go through
7529 // to the next round of expansion as ("stap"), leading to a $PATH
7530 // search that's not consistent with the glob search already done.
5bca76a8
JS
7531 string canononicalized = resolve_path (globbed);
7532 globbed = canononicalized.c_str();
7977a734 7533
88f8e2c0
JS
7534 // The canonical names can result in duplication, for example
7535 // having followed symlinks that are common with shared
7536 // libraries. Filter those out.
7537 if (!dupes.insert(canononicalized).second)
7538 continue;
7539
37001baa
FCE
7540 // synthesize a new probe_point, with the glob-expanded string
7541 probe_point *pp = new probe_point (*location);
ef0943df
JL
7542 pp->from_glob = true;
7543
5750ecc6
FCE
7544 // PR13338: quote results to prevent recursion
7545 string eglobbed = escape_glob_chars (globbed);
7546
7547 if (sess.verbose > 1)
7548 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7549 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 7550 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 7551
37001baa 7552 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7553 new literal_string (eglobbed_tgt));
37001baa
FCE
7554 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7555 pp->components[0] = ppc;
7556
d885563b 7557 probe* new_probe = new probe (base, pp);
7977a734
FCE
7558
7559 // We override "optional = true" here, as if the
7560 // wildcarded probe point was given a "?" suffix.
7561
7562 // This is because wildcard probes will be expected
7563 // by users to apply only to some subset of the
7564 // matching binaries, in the sense of "any", rather
7565 // than "all", sort of similarly how
7566 // module("*").function("...") patterns work.
7567
7568 derive_probes (sess, new_probe, finished_results,
7569 true /* NB: not location->optional */ );
37001baa
FCE
7570 }
7571 }
7572
7573 globfree (& the_blob);
44ffe90c
JL
7574
7575 unsigned results_post = finished_results.size();
7576
e90006d7 7577 // Did we fail to find a function/plt/mark by name? Let's suggest
44ffe90c
JL
7578 // something!
7579 string func;
7580 if (results_pre == results_post
7581 && get_param(filled_parameters, TOK_FUNCTION, func)
7582 && !func.empty())
7583 {
0508c45f 7584 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7585 modules_seen.clear();
7586 if (!sugs.empty())
dc09353a 7587 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7588 "no match (similar functions: %s)",
7589 sugs.find(',') == string::npos,
7590 sugs.c_str()));
7591 }
40a70f52
JL
7592 else if (results_pre == results_post
7593 && get_param(filled_parameters, TOK_PLT, func)
7594 && !func.empty())
7595 {
7596 string sugs = suggest_plt_functions(sess, modules_seen, func);
7597 modules_seen.clear();
7598 if (!sugs.empty())
7599 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7600 "no match (similar functions: %s)",
7601 sugs.find(',') == string::npos,
7602 sugs.c_str()));
7603 }
e90006d7
JL
7604 else if (results_pre == results_post
7605 && get_param(filled_parameters, TOK_MARK, func)
7606 && !func.empty())
7607 {
7608 string provider;
7609 get_param(filled_parameters, TOK_PROVIDER, provider);
7610
7611 string sugs = suggest_marks(sess, modules_seen, func, provider);
7612 modules_seen.clear();
7613 if (!sugs.empty())
7614 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7615 "no match (similar marks: %s)",
7616 sugs.find(',') == string::npos,
7617 sugs.c_str()));
7618 }
44ffe90c 7619
37001baa
FCE
7620 return; // avoid falling through
7621 }
7622
5750ecc6
FCE
7623 // PR13338: unquote glob results
7624 module_name = unescape_glob_chars (module_name);
05fb3e0c 7625 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
7626
7627 // if the executable starts with "#!", we look for the interpreter of the script
7628 {
7629 ifstream script_file (user_path.c_str () );
7630
7631 if (script_file.good ())
7632 {
7633 string line;
7634
7635 getline (script_file, line);
7636
7637 if (line.compare (0, 2, "#!") == 0)
7638 {
7639 string path_head = line.substr(2);
7640
7641 // remove white spaces at the beginning of the string
7642 size_t p2 = path_head.find_first_not_of(" \t");
7643
7644 if (p2 != string::npos)
7645 {
7646 string path = path_head.substr(p2);
7647
7648 // remove white spaces at the end of the string
7649 p2 = path.find_last_not_of(" \t\n");
7650 if (string::npos != p2)
7651 path.erase(p2+1);
7652
8e13c1a1
RH
7653 // handle "#!/usr/bin/env" redirect
7654 size_t offset = 0;
7655 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7656 {
7657 offset = sizeof("/bin/env")-1;
7658 }
7659 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7660 {
7661 offset = sizeof("/usr/bin/env")-1;
7662 }
7663
7664 if (offset != 0)
7665 {
7666 size_t p3 = path.find_first_not_of(" \t", offset);
7667
7668 if (p3 != string::npos)
7669 {
7670 string env_path = path.substr(p3);
05fb3e0c
WF
7671 user_path = find_executable (env_path, sess.sysroot,
7672 sess.sysenv);
8e13c1a1
RH
7673 }
7674 }
7675 else
7676 {
05fb3e0c 7677 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7678 }
d1bcbe71
RH
7679
7680 struct stat st;
7681
7682 if (access (user_path.c_str(), X_OK) == 0
7683 && stat (user_path.c_str(), &st) == 0
7684 && S_ISREG (st.st_mode)) // see find_executable()
7685 {
7686 if (sess.verbose > 1)
b530b5b3
LB
7687 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7688 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7689
7690 assert (location->components.size() > 0);
7691 assert (location->components[0]->functor == TOK_PROCESS);
7692 assert (location->components[0]->arg);
7693 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7694 assert (lit);
7695
7696 // synthesize a new probe_point, with the expanded string
7697 probe_point *pp = new probe_point (*location);
05fb3e0c 7698 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7699 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7700 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7701 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7702 pp->components[0] = ppc;
7703
d885563b 7704 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7705
7706 derive_probes (sess, new_probe, finished_results);
7707
7708 script_file.close();
7709 return;
7710 }
7711 }
7712 }
7713 }
7714 script_file.close();
7715 }
7716
47e226ed 7717 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7718 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7719 {
7720 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7721 "LD_LIBRARY_PATH");
7722 if (module_name.find('/') == string::npos)
7723 // We didn't find user_lib so use iterate_over_libraries
7724 module_name = user_path;
7725 }
63b4fd14 7726 else
b642c901 7727 module_name = user_path; // canonicalize it
d0a7f5a9 7728
3667d615 7729 // uretprobes aren't available everywhere
536f1261 7730 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7731 {
3667d615
JS
7732 if (kernel_supports_inode_uprobes(sess) &&
7733 !kernel_supports_inode_uretprobes(sess))
dc09353a 7734 throw SEMANTIC_ERROR
3ffeaf3c 7735 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7736 }
3667d615 7737
f4000852
MW
7738 // There is a similar check in pass 4 (buildrun), but it is
7739 // needed here too to make sure alternatives for optional
7740 // (? or !) process probes are disposed and/or alternatives
7741 // are selected.
3667d615
JS
7742 if (!sess.runtime_usermode_p())
7743 check_process_probe_kernel_support(sess);
e34d5d13 7744
7a24d422
FCE
7745 // user-space target; we use one dwflpp instance per module name
7746 // (= program or shared library)
707bf35e 7747 dw = get_user_dw(sess, module_name);
c8959a29 7748 }
20c6c071 7749
1acfc030
JS
7750 assert(dw);
7751
e90006d7
JL
7752 unsigned results_pre = finished_results.size();
7753
5896cd05 7754 if (sess.verbose > 3)
b530b5b3 7755 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7756
a794dbeb
FCE
7757 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7758 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7759 {
51d6bda3 7760 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
06de3a04 7761 dw->iterate_over_modules<base_query>(&query_module, &sdtq);
e90006d7
JL
7762
7763 // We need to update modules_seen with the modules we've visited
7764 modules_seen.insert(sdtq.visited_modules.begin(),
7765 sdtq.visited_modules.end());
7766
7767 // Did we fail to find a mark?
7768 if (results_pre == finished_results.size() && !location->from_glob)
7769 {
7770 string provider;
7771 get_param(filled_parameters, TOK_PROVIDER, provider);
7772
7773 string sugs = suggest_marks(sess, modules_seen, dummy_mark_name, provider);
7774 modules_seen.clear();
7775 if (!sugs.empty())
7776 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7777 "no match (similar marks: %s)",
7778 sugs.find(',') == string::npos,
7779 sugs.c_str()));
7780 }
7781
edce5b67 7782 return;
7a05f484 7783 }
20c6c071 7784
6d5d594e 7785 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7786
7787 // XXX: kernel.statement.absolute is a special case that requires no
7788 // dwfl processing. This code should be in a separate builder.
7a24d422 7789 if (q.has_kernel && q.has_absolute)
37ebca01 7790 {
4baf0e53 7791 // assert guru mode for absolute probes
37ebca01
FCE
7792 if (! q.base_probe->privileged)
7793 {
dc09353a 7794 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7795 q.base_probe->tok);
37ebca01
FCE
7796 }
7797
7798 // For kernel.statement(NUM).absolute probe points, we bypass
7799 // all the debuginfo stuff: We just wire up a
7800 // dwarf_derived_probe right here and now.
4baf0e53 7801 dwarf_derived_probe* p =
b8da0ad1
FCE
7802 new dwarf_derived_probe ("", "", 0, "kernel", "",
7803 q.statement_num_val, q.statement_num_val,
7804 q, 0);
37ebca01 7805 finished_results.push_back (p);
1a0dbc5a 7806 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7807 return;
7808 }
7809
06de3a04 7810 dw->iterate_over_modules<base_query>(&query_module, &q);
8f14e444 7811
44ffe90c
JL
7812 // We need to update modules_seen with the modules we've visited
7813 modules_seen.insert(q.visited_modules.begin(),
7814 q.visited_modules.end());
8f14e444
FCE
7815
7816 // PR11553 special processing: .return probes requested, but
7817 // some inlined function instances matched.
7818 unsigned i_n_r = q.inlined_non_returnable.size();
7819 unsigned results_post = finished_results.size();
7820 if (i_n_r > 0)
7821 {
7822 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7823 {
7824 string quicklist;
7825 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7826 it != q.inlined_non_returnable.end();
7827 it++)
7828 {
7829 quicklist += " " + (*it);
7830 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7831 {
7832 quicklist += " ...";
7833 break;
7834 }
7835 }
c57ea854 7836
52c2652f 7837 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7838 "cannot probe .return of %u inlined functions %s",
52c2652f 7839 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7840 // There will be also a "no matches" semantic error generated.
7841 }
7842 if (sess.verbose > 1)
52c2652f
NMA
7843 clog << _NF("skipped .return probe of %u inlined function",
7844 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7845 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7846 {
7847 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7848 it != q.inlined_non_returnable.end();
7849 it++)
7850 clog << (*it) << " ";
7851 clog << endl;
7852 }
7853 } // i_n_r > 0
44ffe90c 7854
e90006d7 7855 // If we just failed to resolve a function/plt by name, we can suggest
ef0943df
JL
7856 // something. We only suggest things for probe points that were not
7857 // synthesized from a glob, i.e. only for 'real' probes. This is also
7858 // required because modules_seen needs to accumulate across recursive
7859 // calls for process(glob)[.library(glob)] probes.
44ffe90c 7860 string func;
ef0943df 7861 if (results_pre == results_post && !location->from_glob
44ffe90c
JL
7862 && get_param(filled_parameters, TOK_FUNCTION, func)
7863 && !func.empty())
7864 {
0508c45f 7865 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7866 modules_seen.clear();
7867 if (!sugs.empty())
dc09353a 7868 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7869 "no match (similar functions: %s)",
7870 sugs.find(',') == string::npos,
7871 sugs.c_str()));
7872 }
ef0943df 7873 else if (results_pre == results_post && !location->from_glob
40a70f52
JL
7874 && get_param(filled_parameters, TOK_PLT, func)
7875 && !func.empty())
7876 {
7877 string sugs = suggest_plt_functions(sess, modules_seen, func);
7878 modules_seen.clear();
7879 if (!sugs.empty())
7880 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7881 "no match (similar functions: %s)",
7882 sugs.find(',') == string::npos,
7883 sugs.c_str()));
7884 }
44ffe90c
JL
7885 else if (results_pre != results_post)
7886 // Something was derived so we won't need to suggest something
7887 modules_seen.clear();
5f0a03a6
JK
7888}
7889
7890symbol_table::~symbol_table()
7891{
c9efa5c9 7892 delete_map(map_by_addr);
5f0a03a6
JK
7893}
7894
7895void
2867a2a1 7896symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7897 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7898{
ab91b232
JK
7899#ifdef __powerpc__
7900 // Map ".sys_foo" to "sys_foo".
7901 if (name[0] == '.')
7902 name++;
7903#endif
5f0a03a6
JK
7904 func_info *fi = new func_info();
7905 fi->addr = addr;
7906 fi->name = name;
ab91b232 7907 fi->weak = weak;
2867a2a1 7908 fi->descriptor = descriptor;
5f0a03a6
JK
7909 map_by_name[fi->name] = fi;
7910 // TODO: Use a multimap in case there are multiple static
7911 // functions with the same name?
1c6b77e5 7912 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7913}
7914
46f7b6be 7915void
f98c6346 7916symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7917{
7918#ifdef __powerpc__
7919 /*
7920 * The .opd section contains function descriptors that can look
7921 * just like function entry points. For example, there's a function
7922 * descriptor called "do_exit" that links to the entry point ".do_exit".
7923 * Reject all symbols in .opd.
7924 */
7925 opd_section = SHN_UNDEF;
7926 Dwarf_Addr bias;
7927 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7928 ?: dwfl_module_getelf (mod, &bias));
7929 Elf_Scn* scn = 0;
7930 size_t shstrndx;
7931
7932 if (!elf)
7933 return;
fcc30d6d 7934 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7935 return;
7936 while ((scn = elf_nextscn(elf, scn)) != NULL)
7937 {
7938 GElf_Shdr shdr_mem;
7939 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7940 if (!shdr)
7941 continue;
7942 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7943 if (!strcmp(name, ".opd"))
7944 {
7945 opd_section = elf_ndxscn(scn);
7946 return;
7947 }
7948 }
7949#endif
7950}
7951
7952bool
7953symbol_table::reject_section(GElf_Word section)
7954{
7955 if (section == SHN_UNDEF)
7956 return true;
7957#ifdef __powerpc__
7958 if (section == opd_section)
7959 return true;
7960#endif
7961 return false;
7962}
7963
5f0a03a6
JK
7964enum info_status
7965symbol_table::get_from_elf()
7966{
7967 Dwarf_Addr high_addr = 0;
7968 Dwfl_Module *mod = mod_info->mod;
7969 int syments = dwfl_module_getsymtab(mod);
7970 assert(syments);
46f7b6be 7971 prepare_section_rejection(mod);
5f0a03a6
JK
7972 for (int i = 1; i < syments; ++i)
7973 {
7974 GElf_Sym sym;
ab91b232 7975 GElf_Word section;
cba67d8f
MW
7976 const char *name;
7977 GElf_Addr addr;
7978 bool reject;
7979
7980/* Note that dwfl_module_getsym does adjust the sym.st_value but doesn't
7981 try to resolve it to a function address. dwfl_module_getsym_info leaves
7982 the st_value in tact (no adjustment applied) and returns the fully
7983 resolved address separately. In that case we can simply reject the
7984 symbol if it is SHN_UNDEF and don't need to call reject_section which
7985 does extra checks to see whether the address fall in an architecture
7986 specific descriptor table (which will never be the case when using the
7987 new dwfl_module_getsym_info). dwfl_module_getsym will only provide us
7988 with the (adjusted) st_value of the symbol, which might point into a
7989 function descriptor table. So in that case we still have to call
7990 reject_section. */
7991#if _ELFUTILS_PREREQ (0, 158)
7992 name = dwfl_module_getsym_info (mod, i, &sym, &addr, &section,
7993 NULL, NULL);
7994 reject = section == SHN_UNDEF;
7995#else
7996 name = dwfl_module_getsym (mod, i, &sym, &section);
b23098cd 7997 addr = sym.st_value;
cba67d8f
MW
7998 reject = reject_section(section);
7999#endif
8000
2867a2a1 8001 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 8002 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
cba67d8f 8003 reject, addr, &high_addr);
2a4acb09
JL
8004 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
8005 && GELF_ST_BIND(sym.st_info) == STB_GLOBAL)
8006 globals[name] = addr;
8007 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
8008 && GELF_ST_BIND(sym.st_info) == STB_LOCAL)
8009 locals[name] = addr;
5f0a03a6
JK
8010 }
8011 return info_present;
8012}
8013
5f0a03a6
JK
8014func_info *
8015symbol_table::get_func_containing_address(Dwarf_Addr addr)
8016{
1c6b77e5
JS
8017 iterator_t iter = map_by_addr.upper_bound(addr);
8018 if (iter == map_by_addr.begin())
5f0a03a6 8019 return NULL;
2e67a43b 8020 else
1c6b77e5 8021 return (--iter)->second;
5f0a03a6
JK
8022}
8023
3d372d6b
SC
8024func_info *
8025symbol_table::get_first_func()
8026{
8027 iterator_t iter = map_by_addr.begin();
8028 return (iter)->second;
8029}
8030
5f0a03a6
JK
8031func_info *
8032symbol_table::lookup_symbol(const string& name)
8033{
8034 map<string, func_info*>::iterator i = map_by_name.find(name);
8035 if (i == map_by_name.end())
8036 return NULL;
8037 return i->second;
8038}
8039
8040Dwarf_Addr
8041symbol_table::lookup_symbol_address(const string& name)
8042{
8043 func_info *fi = lookup_symbol(name);
8044 if (fi)
8045 return fi->addr;
8046 return 0;
8047}
8048
ab91b232
JK
8049// This is the kernel symbol table. The kernel macro cond_syscall creates
8050// a weak symbol for each system call and maps it to sys_ni_syscall.
8051// For system calls not implemented elsewhere, this weak symbol shows up
8052// in the kernel symbol table. Following the precedent of dwarfful stap,
8053// we refuse to consider such symbols. Here we delete them from our
8054// symbol table.
8055// TODO: Consider generalizing this and/or making it part of blacklist
8056// processing.
8057void
8058symbol_table::purge_syscall_stubs()
8059{
8060 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
8061 if (stub_addr == 0)
8062 return;
1c6b77e5 8063 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
8064 for (iterator_t iter = purge_range.first;
8065 iter != purge_range.second;
1c6b77e5 8066 )
ab91b232 8067 {
1c6b77e5 8068 func_info *fi = iter->second;
2e67a43b 8069 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 8070 {
2e67a43b 8071 map_by_name.erase(fi->name);
1c6b77e5 8072 map_by_addr.erase(iter++);
2e67a43b 8073 delete fi;
2e67a43b 8074 }
1c6b77e5
JS
8075 else
8076 iter++;
ab91b232
JK
8077 }
8078}
8079
5f0a03a6 8080void
5f52fafe 8081module_info::get_symtab()
5f0a03a6 8082{
1c6b77e5
JS
8083 if (symtab_status != info_unknown)
8084 return;
8085
5f0a03a6
JK
8086 sym_table = new symbol_table(this);
8087 if (!elf_path.empty())
8088 {
5f0a03a6
JK
8089 symtab_status = sym_table->get_from_elf();
8090 }
8091 else
8092 {
8093 assert(name == TOK_KERNEL);
ab3ed72d
DS
8094 symtab_status = info_absent;
8095 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
8096 }
8097 if (symtab_status == info_absent)
8098 {
8099 delete sym_table;
8100 sym_table = NULL;
8101 return;
8102 }
8103
ab91b232
JK
8104 if (name == TOK_KERNEL)
8105 sym_table->purge_syscall_stubs();
5f0a03a6
JK
8106}
8107
1c6b77e5
JS
8108// update_symtab reconciles data between the elf symbol table and the dwarf
8109// function enumeration. It updates the symbol table entries with the dwarf
8110// die that describes the function, which also signals to query_module_symtab
8111// that a statement probe isn't needed. In return, it also adds aliases to the
8112// function table for names that share the same addr/die.
8113void
8114module_info::update_symtab(cu_function_cache_t *funcs)
8115{
8116 if (!sym_table)
8117 return;
8118
8119 cu_function_cache_t new_funcs;
8120
8121 for (cu_function_cache_t::iterator func = funcs->begin();
8122 func != funcs->end(); func++)
8123 {
8124 // optimization: inlines will never be in the symbol table
8125 if (dwarf_func_inline(&func->second) != 0)
6e6d9a3b
JL
8126 {
8127 inlined_funcs.insert(func->first);
8128 continue;
8129 }
1c6b77e5 8130
1ffb8bd1
JS
8131 // XXX We may want to make additional efforts to match mangled elf names
8132 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
8133 // missing, so we may also need to try matching by address. See also the
8134 // notes about _Z in dwflpp::iterate_over_functions().
8135
1c6b77e5
JS
8136 func_info *fi = sym_table->lookup_symbol(func->first);
8137 if (!fi)
8138 continue;
8139
8140 // iterate over all functions at the same address
8141 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
8142 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
8143 {
8144 // update this function with the dwarf die
8145 it->second->die = func->second;
8146
8147 // if this function is a new alias, then
8148 // save it to merge into the function cache
8149 if (it->second != fi)
b7478964 8150 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
8151 }
8152 }
8153
8154 // add all discovered aliases back into the function cache
8155 // NB: this won't replace any names that dwarf may have already found
8156 funcs->insert(new_funcs.begin(), new_funcs.end());
8157}
8158
5f0a03a6
JK
8159module_info::~module_info()
8160{
8161 if (sym_table)
8162 delete sym_table;
b55bc428
FCE
8163}
8164
935447c8 8165// ------------------------------------------------------------------------
888af770 8166// user-space probes
935447c8
DS
8167// ------------------------------------------------------------------------
8168
935447c8 8169
888af770 8170struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 8171{
89ba3085
FCE
8172private:
8173 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 8174 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
8175 }
8176
cfcab6c7
JS
8177 void emit_module_maxuprobes (systemtap_session& s);
8178
2b69faaf
JS
8179 // Using our own utrace-based uprobes
8180 void emit_module_utrace_decls (systemtap_session& s);
8181 void emit_module_utrace_init (systemtap_session& s);
8182 void emit_module_utrace_exit (systemtap_session& s);
8183
8184 // Using the upstream inode-based uprobes
8185 void emit_module_inode_decls (systemtap_session& s);
8186 void emit_module_inode_init (systemtap_session& s);
8187 void emit_module_inode_exit (systemtap_session& s);
8188
3a894f7e
JS
8189 // Using the dyninst backend (via stapdyn)
8190 void emit_module_dyninst_decls (systemtap_session& s);
8191 void emit_module_dyninst_init (systemtap_session& s);
8192 void emit_module_dyninst_exit (systemtap_session& s);
8193
935447c8 8194public:
888af770 8195 void emit_module_decls (systemtap_session& s);
935447c8
DS
8196 void emit_module_init (systemtap_session& s);
8197 void emit_module_exit (systemtap_session& s);
8198};
8199
8200
888af770
FCE
8201void
8202uprobe_derived_probe::join_group (systemtap_session& s)
8203{
8204 if (! s.uprobe_derived_probes)
8205 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
8206 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
8207 if (s.runtime_usermode_p())
8208 enable_dynprobes(s);
8209 else
4441e344 8210 enable_task_finder(s);
a96d1db0 8211
8a03658e 8212 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
8213 // signal staprun to load that module. If we're using the builtin
8214 // inode-uprobes, we still need to know that it is required.
8a03658e 8215 s.need_uprobes = true;
a96d1db0
DN
8216}
8217
888af770 8218
c0f84e7b
SC
8219void
8220uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
8221{
8222 dwarf_derived_probe::getargs(arg_set);
8223 arg_set.insert(arg_set.end(), args.begin(), args.end());
8224}
8225
8226
8227void
8228uprobe_derived_probe::saveargs(int nargs)
8229{
8230 for (int i = 1; i <= nargs; i++)
8231 args.push_back("$arg" + lex_cast (i) + ":long");
8232}
8233
8234
2865d17a 8235void
42e38653 8236uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
8237{
8238 // These probes are allowed for unprivileged users, but only in the
8239 // context of processes which they own.
8240 emit_process_owner_assertion (o);
8241}
8242
8243
888af770 8244struct uprobe_builder: public derived_probe_builder
a96d1db0 8245{
888af770 8246 uprobe_builder() {}
2b69faaf 8247 virtual void build(systemtap_session & sess,
a96d1db0
DN
8248 probe * base,
8249 probe_point * location,
86bf665e 8250 literal_map_t const & parameters,
a96d1db0
DN
8251 vector<derived_probe *> & finished_results)
8252 {
888af770 8253 int64_t process, address;
a96d1db0 8254
2b69faaf 8255 if (kernel_supports_inode_uprobes(sess))
dc09353a 8256 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 8257
888af770 8258 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 8259 (void) b1;
888af770 8260 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 8261 (void) b2;
888af770
FCE
8262 bool rr = has_null_param (parameters, TOK_RETURN);
8263 assert (b1 && b2); // by pattern_root construction
a96d1db0 8264
0973d815 8265 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
8266 }
8267};
8268
8269
8270void
cfcab6c7 8271uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 8272{
43241c44
FCE
8273 // We'll probably need at least this many:
8274 unsigned minuprobes = probes.size();
8275 // .. but we don't want so many that .bss is inflated (PR10507):
8276 unsigned uprobesize = 64;
8277 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
8278 unsigned maxuprobes = maxuprobesmem / uprobesize;
8279
aaf7ffe8
FCE
8280 // Let's choose a value on the geometric middle. This should end up
8281 // between minuprobes and maxuprobes. It's OK if this number turns
8282 // out to be < minuprobes or > maxuprobes. At worst, we get a
8283 // run-time error of one kind (too few: missed uprobe registrations)
8284 // or another (too many: vmalloc errors at module load time).
8285 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 8286
6d0f3f0c 8287 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 8288 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 8289 s.op->newline() << "#endif";
cfcab6c7
JS
8290}
8291
8292
8293void
8294uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
8295{
8296 if (probes.empty()) return;
8297 s.op->newline() << "/* ---- utrace uprobes ---- */";
8298 // If uprobes isn't in the kernel, pull it in from the runtime.
8299
8300 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
8301 s.op->newline() << "#include <linux/uprobes.h>";
8302 s.op->newline() << "#else";
2ba1736a 8303 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
8304 s.op->newline() << "#endif";
8305 s.op->newline() << "#ifndef UPROBES_API_VERSION";
8306 s.op->newline() << "#define UPROBES_API_VERSION 1";
8307 s.op->newline() << "#endif";
8308
8309 emit_module_maxuprobes (s);
a96d1db0 8310
cc52276b 8311 // Forward decls
2ba1736a 8312 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 8313
5e112f92
FCE
8314 // In .bss, the shared pool of uprobe/uretprobe structs. These are
8315 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
8316 // XXX: consider a slab cache or somesuch for stap_uprobes
8317 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 8318 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 8319
89ba3085
FCE
8320 s.op->assert_0_indent();
8321
89ba3085
FCE
8322 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
8323 // This means we process probes[] in two passes.
8324 map <string,unsigned> module_index;
8325 unsigned module_index_ctr = 0;
8326
cc52276b
WC
8327 // not const since embedded task_finder_target struct changes
8328 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
8329 s.op->indent(1);
8330 for (unsigned i=0; i<probes.size(); i++)
8331 {
8332 uprobe_derived_probe *p = probes[i];
8333 string pbmkey = make_pbm_key (p);
8334 if (module_index.find (pbmkey) == module_index.end())
8335 {
8336 module_index[pbmkey] = module_index_ctr++;
8337
8338 s.op->newline() << "{";
8339 // NB: it's essential that make_pbm_key() use all of and
8340 // only the same fields as we're about to emit.
8341 s.op->line() << " .finder={";
1af100fc 8342 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 8343 if (p->pid != 0)
68910c97
JK
8344 s.op->line() << " .pid=" << p->pid << ",";
8345
8346 if (p->section == "") // .statement(addr).absolute
8347 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
8348 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8349 {
8350 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8351 s.op->line() << " .callback=&stap_uprobe_process_found,";
8352 }
68910c97 8353 else if (p->section != ".absolute") // ET_DYN
89ba3085 8354 {
4ad95bbc
SC
8355 if (p->has_library)
8356 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
8357 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
8358 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 8359 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 8360 }
89ba3085 8361 s.op->line() << " },";
68910c97
JK
8362 if (p->module != "")
8363 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
8364 s.op->line() << " },";
8365 }
c57ea854 8366 else
822a6a3d 8367 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
8368 }
8369 s.op->newline(-1) << "};";
8370
8371 s.op->assert_0_indent();
8372
3689db05
SC
8373 unsigned pci;
8374 for (pci=0; pci<probes.size(); pci++)
8375 {
8376 // List of perf counters used by each probe
8377 // This list is an index into struct stap_perf_probe,
8378 uprobe_derived_probe *p = probes[pci];
698de6cc 8379 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8380 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8381 for (pcii = p->perf_counter_refs.begin();
8382 pcii != p->perf_counter_refs.end(); pcii++)
8383 {
8384 map<string, pair<string,derived_probe*> >::iterator it;
8385 unsigned i = 0;
8386 // Find the associated perf.counter probe
8387 for (it=s.perf_counters.begin() ;
8388 it != s.perf_counters.end(); it++, i++)
8389 if ((*it).second.second == (*pcii))
8390 break;
8391 s.op->line() << lex_cast(i) << ", ";
8392 }
8393 s.op->newline() << "};";
8394 }
8395
cc52276b
WC
8396 // NB: read-only structure
8397 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 8398 s.op->indent(1);
888af770
FCE
8399 for (unsigned i =0; i<probes.size(); i++)
8400 {
8401 uprobe_derived_probe* p = probes[i];
8402 s.op->newline() << "{";
89ba3085
FCE
8403 string key = make_pbm_key (p);
8404 unsigned value = module_index[key];
759e1d76
FCE
8405 if (value != 0)
8406 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 8407 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 8408 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 8409
038c38c6 8410 if (p->sdt_semaphore_addr != 0)
63b4fd14 8411 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 8412 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 8413
0d049a1d 8414 // XXX: don't bother emit if array is empty
3689db05
SC
8415 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8416 // List of perf counters used by a probe from above
0d049a1d 8417 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 8418
4ddb6dd0
JS
8419 if (p->has_return)
8420 s.op->line() << " .return_p=1,";
888af770
FCE
8421 s.op->line() << " },";
8422 }
8423 s.op->newline(-1) << "};";
a96d1db0 8424
89ba3085
FCE
8425 s.op->assert_0_indent();
8426
48e685da 8427 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 8428 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 8429 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8430 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8431 "stp_probe_type_uprobe");
0e090c74 8432 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
8433 << "sup->spec_index >= " << probes.size() << ") {";
8434 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8435 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
8436 s.op->newline() << "goto probe_epilogue;";
8437 s.op->newline(-1) << "}";
d9aed31e 8438 s.op->newline() << "c->uregs = regs;";
e04b5d74 8439 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8440
8441 // Make it look like the IP is set as it would in the actual user
8442 // task when calling real probe handler. Reset IP regs on return, so
8443 // we don't confuse uprobes. PR10458
8444 s.op->newline() << "{";
8445 s.op->indent(1);
d9aed31e 8446 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 8447 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 8448 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8449 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8450 s.op->newline(-1) << "}";
8451
f887a8c9 8452 common_probe_entryfn_epilogue (s, true);
888af770 8453 s.op->newline(-1) << "}";
a96d1db0 8454
48e685da 8455 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 8456 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 8457 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8458 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8459 "stp_probe_type_uretprobe");
6dceb5c9 8460 s.op->newline() << "c->ips.ri = inst;";
0e090c74 8461 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
8462 << "sup->spec_index >= " << probes.size() << ") {";
8463 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8464 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
8465 s.op->newline() << "goto probe_epilogue;";
8466 s.op->newline(-1) << "}";
8467
d9aed31e 8468 s.op->newline() << "c->uregs = regs;";
e04b5d74 8469 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8470
8471 // Make it look like the IP is set as it would in the actual user
8472 // task when calling real probe handler. Reset IP regs on return, so
8473 // we don't confuse uprobes. PR10458
8474 s.op->newline() << "{";
8475 s.op->indent(1);
d9aed31e 8476 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 8477 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 8478 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8479 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8480 s.op->newline(-1) << "}";
8481
f887a8c9 8482 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
8483 s.op->newline(-1) << "}";
8484
89ba3085 8485 s.op->newline();
2ba1736a 8486 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 8487 s.op->newline();
888af770 8488}
935447c8
DS
8489
8490
888af770 8491void
2b69faaf 8492uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 8493{
888af770 8494 if (probes.empty()) return;
935447c8 8495
2b69faaf 8496 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 8497
01b05e2e 8498 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
8499 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
8500 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
8501 // NB: we assume the rest of the struct (specificaly, sup->up) is
8502 // initialized to zero. This is so that we can use
8503 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
8504 s.op->newline(-1) << "}";
8505 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 8506
89ba3085
FCE
8507 // Set up the task_finders
8508 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
8509 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 8510 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 8511 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 8512
5e112f92
FCE
8513 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
8514 // finders already registered, since mere registration does not
8515 // cause any utrace or memory allocation actions. That happens only
8516 // later, once the task finder engine starts running. So, for a
8517 // partial initialization requiring unwind, we need do nothing.
8518 s.op->newline() << "if (rc) break;";
a7a68293 8519
888af770
FCE
8520 s.op->newline(-1) << "}";
8521}
d0ea46ce 8522
d0a7f5a9 8523
888af770 8524void
2b69faaf 8525uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
8526{
8527 if (probes.empty()) return;
2b69faaf 8528 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 8529
6d0f3f0c
FCE
8530 // NB: there is no stap_unregister_task_finder_target call;
8531 // important stuff like utrace cleanups are done by
d41d451c
FCE
8532 // __stp_task_finder_cleanup() via stap_stop_task_finder().
8533 //
8534 // This function blocks until all callbacks are completed, so there
8535 // is supposed to be no possibility of any registration-related code starting
8536 // to run in parallel with our shutdown here. So we don't need to protect the
8537 // stap_uprobes[] array with the mutex.
d0a7f5a9 8538
01b05e2e 8539 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 8540 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 8541 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 8542 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 8543
8faa1fc5 8544 // PR10655: decrement that ENABLED semaphore
c116c31b 8545 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
8546 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
8547 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
8548 s.op->newline() << "struct task_struct *tsk;";
8549 s.op->newline() << "rcu_read_lock();";
6846cfc8 8550
86229a55
DS
8551 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
8552 // that the pid is always in the global namespace, not in any
8553 // private namespace.
8faa1fc5 8554 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
8555 // We'd like to call find_task_by_pid_ns() here, but it isn't
8556 // exported. So, we call what it calls...
8557 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
8558 s.op->newline() << "#else";
8559 s.op->newline() << " tsk = find_task_by_pid (pid);";
8560 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
8561
8562 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 8563 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 8564 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 8565 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 8566 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 8567 s.op->newline() << "#endif";
3c5b8e2b 8568 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 8569 s.op->newline(-1) << "}";
8faa1fc5
FCE
8570 // XXX: need to analyze possibility of race condition
8571 s.op->newline(-1) << "}";
8572 s.op->newline() << "rcu_read_unlock();";
8573 s.op->newline(-1) << "}";
6846cfc8 8574
3568f1dd
FCE
8575 s.op->newline() << "if (sups->return_p) {";
8576 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 8577 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 8578 s.op->newline() << "#endif";
80b4ad8b
FCE
8579 // NB: PR6829 does not change that we still need to unregister at
8580 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
8581 s.op->newline() << "unregister_uretprobe (& sup->urp);";
8582 s.op->newline(-1) << "} else {";
8583 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 8584 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
8585 s.op->newline() << "#endif";
8586 s.op->newline() << "unregister_uprobe (& sup->up);";
8587 s.op->newline(-1) << "}";
935447c8 8588
6d0f3f0c 8589 s.op->newline() << "sup->spec_index = -1;";
935447c8 8590
3568f1dd
FCE
8591 // XXX: uprobe missed counts?
8592
6d0f3f0c 8593 s.op->newline(-1) << "}";
935447c8 8594
5e112f92 8595 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8596}
8597
2b69faaf
JS
8598
8599void
8600uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8601{
8602 if (probes.empty()) return;
8603 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8604 emit_module_maxuprobes (s);
2ba1736a 8605 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8606
8607 // Write the probe handler.
79af55c3
JS
8608 s.op->newline() << "static int stapiu_probe_handler "
8609 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8610 s.op->newline(1);
2dbbd473
JS
8611
8612 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8613 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8614 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8615 probe_type);
8616
3bff6634 8617 s.op->newline() << "c->uregs = regs;";
e04b5d74 8618 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8619 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8620 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8621
f887a8c9 8622 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8623 s.op->newline() << "return 0;";
8624 s.op->newline(-1) << "}";
8625 s.op->assert_0_indent();
8626
8627 // Index of all the modules for which we need inodes.
8628 map<string, unsigned> module_index;
8629 unsigned module_index_ctr = 0;
8630
8631 // Discover and declare targets for each unique path.
cfcab6c7 8632 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8633 << "stap_inode_uprobe_targets[] = {";
8634 s.op->indent(1);
8635 for (unsigned i=0; i<probes.size(); i++)
8636 {
8637 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8638 const string key = make_pbm_key(p);
8639 if (module_index.find (key) == module_index.end())
2b69faaf 8640 {
cfcab6c7
JS
8641 module_index[key] = module_index_ctr++;
8642 s.op->newline() << "{";
8643 s.op->line() << " .finder={";
b78a0fbb 8644 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8645 if (p->pid != 0)
8646 s.op->line() << " .pid=" << p->pid << ",";
8647
8648 if (p->section == "") // .statement(addr).absolute XXX?
8649 s.op->line() << " .callback=&stapiu_process_found,";
8650 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8651 {
8652 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8653 s.op->line() << " .callback=&stapiu_process_found,";
8654 }
8655 else if (p->section != ".absolute") // ET_DYN
8656 {
8657 if (p->has_library)
8658 s.op->line() << " .procname=\"" << p->path << "\", ";
8659 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8660 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8661 s.op->line() << " .callback=&stapiu_process_munmap,";
8662 }
8663 s.op->line() << " },";
8664 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8665 s.op->line() << " },";
2b69faaf
JS
8666 }
8667 }
8668 s.op->newline(-1) << "};";
8669 s.op->assert_0_indent();
8670
8671 // Declare the actual probes.
3689db05
SC
8672 unsigned pci;
8673 for (pci=0; pci<probes.size(); pci++)
8674 {
8675 // List of perf counters used by each probe
8676 // This list is an index into struct stap_perf_probe,
8677 uprobe_derived_probe *p = probes[pci];
698de6cc 8678 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8679 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8680 for (pcii = p->perf_counter_refs.begin();
8681 pcii != p->perf_counter_refs.end(); pcii++)
8682 {
8683 map<string, pair<string,derived_probe*> >::iterator it;
8684 unsigned i = 0;
8685 // Find the associated perf.counter probe
4fa83377
SC
8686 for (it=s.perf_counters.begin() ;
8687 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8688 if ((*it).second.second == (*pcii))
8689 break;
8690 s.op->line() << lex_cast(i) << ", ";
8691 }
8692 s.op->newline() << "};";
8693 }
8694
cfcab6c7 8695 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8696 << "stap_inode_uprobe_consumers[] = {";
8697 s.op->indent(1);
8698 for (unsigned i=0; i<probes.size(); i++)
8699 {
8700 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8701 unsigned index = module_index[make_pbm_key(p)];
8702 s.op->newline() << "{";
79af55c3
JS
8703 if (p->has_return)
8704 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8705 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8706 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8707 if (p->sdt_semaphore_addr)
8708 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8709 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8710 // XXX: don't bother emit if array is empty
3689db05
SC
8711 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8712 // List of perf counters used by a probe from above
0d049a1d 8713 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8714 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8715 s.op->line() << " },";
2b69faaf
JS
8716 }
8717 s.op->newline(-1) << "};";
8718 s.op->assert_0_indent();
8719}
8720
8721
8722void
8723uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8724{
8725 if (probes.empty()) return;
8726 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8727 // Let stapiu_init() handle reporting errors by setting probe_point
8728 // to NULL.
8729 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8730 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8731 << "stap_inode_uprobe_targets, "
8732 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8733 << "stap_inode_uprobe_consumers, "
8734 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8735}
8736
8737
8738void
8739uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8740{
8741 if (probes.empty()) return;
8742 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8743 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8744 << "stap_inode_uprobe_targets, "
8745 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8746 << "stap_inode_uprobe_consumers, "
8747 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8748}
8749
8750
3a894f7e
JS
8751void
8752uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8753{
8754 if (probes.empty()) return;
8755 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8756 emit_module_maxuprobes (s);
e00f3fb7 8757 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8758
f31a77f5
DS
8759 // Let the dynprobe_derived_probe_group handle outputting targets
8760 // and probes. This allows us to merge different types of probes.
8761 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8762 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8763 {
8764 uprobe_derived_probe *p = probes[i];
e00f3fb7 8765
f31a77f5
DS
8766 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8767 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8768 common_probe_init(p));
3a894f7e 8769 }
874d38bf
JS
8770 // loc2c-generated code assumes pt_regs are available, so use this to make
8771 // sure we always have *something* for it to dereference...
f31a77f5 8772 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8773
3a894f7e
JS
8774 // Write the probe handler.
8775 // NB: not static, so dyninst can find it
8776 s.op->newline() << "int enter_dyninst_uprobe "
8777 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8778 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8779
8780 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8781 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8782 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8783 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8784 probe_type);
8785
874d38bf 8786 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8787 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8788 // XXX: once we have regs, check how dyninst sets the IP
8789 // XXX: the way that dyninst rewrites stuff is probably going to be
8790 // ... very confusing to our backtracer (at least if we stay in process)
8791 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8792 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8793 s.op->newline() << "return 0;";
8794 s.op->newline(-1) << "}";
3debb935 8795 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8796 s.op->assert_0_indent();
8797}
8798
8799
8800void
8801uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8802{
8803 if (probes.empty()) return;
8804
8805 /* stapdyn handles the dirty work via dyninst */
8806 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8807 s.op->newline() << "/* this section left intentionally blank */";
8808}
8809
8810
8811void
8812uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8813{
8814 if (probes.empty()) return;
8815
8816 /* stapdyn handles the dirty work via dyninst */
8817 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8818 s.op->newline() << "/* this section left intentionally blank */";
8819}
8820
8821
2b69faaf
JS
8822void
8823uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8824{
ac3af990 8825 if (s.runtime_usermode_p())
4441e344
JS
8826 emit_module_dyninst_decls (s);
8827 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8828 emit_module_inode_decls (s);
8829 else
8830 emit_module_utrace_decls (s);
8831}
8832
8833
8834void
8835uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8836{
ac3af990 8837 if (s.runtime_usermode_p())
4441e344
JS
8838 emit_module_dyninst_init (s);
8839 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8840 emit_module_inode_init (s);
8841 else
8842 emit_module_utrace_init (s);
8843}
8844
8845
8846void
8847uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8848{
ac3af990 8849 if (s.runtime_usermode_p())
4441e344
JS
8850 emit_module_dyninst_exit (s);
8851 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8852 emit_module_inode_exit (s);
8853 else
8854 emit_module_utrace_exit (s);
8855}
8856
8857
e6fe60e7
AM
8858// ------------------------------------------------------------------------
8859// Kprobe derived probes
8860// ------------------------------------------------------------------------
8861
4627ed58 8862static const string TOK_KPROBE("kprobe");
935447c8 8863
bae55db9 8864struct kprobe_derived_probe: public derived_probe
d0ea46ce 8865{
23dc94f6
DS
8866 kprobe_derived_probe (systemtap_session& sess,
8867 vector<derived_probe *> & results,
8868 probe *base,
bae55db9
JS
8869 probe_point *location,
8870 const string& name,
8871 int64_t stmt_addr,
e6afb07b 8872 bool has_call,
bae55db9
JS
8873 bool has_return,
8874 bool has_statement,
8875 bool has_maxactive,
b642c901
SC
8876 bool has_path,
8877 bool has_library,
8878 long maxactive_val,
8879 const string& path,
8880 const string& library
bae55db9
JS
8881 );
8882 string symbol_name;
8883 Dwarf_Addr addr;
e6afb07b 8884 bool has_call;
bae55db9
JS
8885 bool has_return;
8886 bool has_statement;
8887 bool has_maxactive;
b642c901
SC
8888 bool has_path;
8889 bool has_library;
bae55db9 8890 long maxactive_val;
b642c901
SC
8891 string path;
8892 string library;
bae55db9
JS
8893 bool access_var;
8894 void printsig (std::ostream &o) const;
8895 void join_group (systemtap_session& s);
8896};
d0ea46ce 8897
bae55db9
JS
8898struct kprobe_derived_probe_group: public derived_probe_group
8899{
8900private:
8901 multimap<string,kprobe_derived_probe*> probes_by_module;
8902 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8903
bae55db9
JS
8904public:
8905 void enroll (kprobe_derived_probe* probe);
8906 void emit_module_decls (systemtap_session& s);
8907 void emit_module_init (systemtap_session& s);
8908 void emit_module_exit (systemtap_session& s);
8909};
d0ea46ce 8910
23dc94f6
DS
8911struct kprobe_var_expanding_visitor: public var_expanding_visitor
8912{
8913 systemtap_session& sess;
8914 block *add_block;
8915 block *add_call_probe; // synthesized from .return probes with saved $vars
8916 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8917 bool has_return;
23dc94f6 8918
bd5b25e1 8919 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8920 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8921 add_block_tid(false), add_call_probe_tid(false),
8922 has_return(has_return) {}
23dc94f6
DS
8923
8924 void visit_entry_op (entry_op* e);
8925};
8926
8927
8928kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8929 vector<derived_probe *> & results,
8930 probe *base,
e6fe60e7 8931 probe_point *location,
b6371390 8932 const string& name,
e6fe60e7 8933 int64_t stmt_addr,
e6afb07b 8934 bool has_call,
b6371390
JS
8935 bool has_return,
8936 bool has_statement,
8937 bool has_maxactive,
b642c901
SC
8938 bool has_path,
8939 bool has_library,
8940 long maxactive_val,
8941 const string& path,
8942 const string& library
b6371390 8943 ):
4c5d1300 8944 derived_probe (base, location, true /* .components soon rewritten */ ),
e6afb07b 8945 symbol_name (name), addr (stmt_addr), has_call (has_call),
b6371390 8946 has_return (has_return), has_statement (has_statement),
b642c901
SC
8947 has_maxactive (has_maxactive), has_path (has_path),
8948 has_library (has_library),
8949 maxactive_val (maxactive_val),
8950 path (path), library (library)
e6fe60e7
AM
8951{
8952 this->tok = base->tok;
8953 this->access_var = false;
d0ea46ce 8954
e6fe60e7
AM
8955#ifndef USHRT_MAX
8956#define USHRT_MAX 32767
8957#endif
d0ea46ce 8958
46856d8d
JS
8959 // Expansion of $target variables in the probe body produces an error during
8960 // translate phase, since we're not using debuginfo
d0ea46ce 8961
e6fe60e7 8962 vector<probe_point::component*> comps;
46856d8d 8963 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8964
46856d8d
JS
8965 if (has_statement)
8966 {
9ea68eb9
JS
8967 comps.push_back (new probe_point::component(TOK_STATEMENT,
8968 new literal_number(addr, true)));
46856d8d
JS
8969 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8970 }
8971 else
8972 {
8973 size_t pos = name.find(':');
8974 if (pos != string::npos)
d0ea46ce 8975 {
46856d8d
JS
8976 string module = name.substr(0, pos);
8977 string function = name.substr(pos + 1);
8978 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8979 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8980 }
8981 else
8982 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8983 }
d0ea46ce 8984
e6afb07b
JL
8985 if (has_call)
8986 comps.push_back (new probe_point::component(TOK_CALL));
b6371390
JS
8987 if (has_return)
8988 comps.push_back (new probe_point::component(TOK_RETURN));
8989 if (has_maxactive)
8990 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8991
bd5b25e1 8992 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8993 v.replace (this->body);
8994
8995 // If during target-variable-expanding the probe, we added a new block
8996 // of code, add it to the start of the probe.
8997 if (v.add_block)
8998 this->body = new block(v.add_block, this->body);
8999
9000 // If when target-variable-expanding the probe, we need to
9001 // synthesize a sibling function-entry probe. We don't go through
9002 // the whole probe derivation business (PR10642) that could lead to
9003 // wildcard/alias resolution, or for that dwarf-induced duplication.
9004 if (v.add_call_probe)
9005 {
9006 assert (has_return);
9007
9008 // We temporarily replace base.
9009 statement* old_body = base->body;
9010 base->body = v.add_call_probe;
9011
9012 derived_probe *entry_handler
9013 = new kprobe_derived_probe (sess, results, base, location, name, 0,
e6afb07b
JL
9014 true /* has_call */, false /* has_return */,
9015 has_statement, has_maxactive, has_path,
9016 has_library, maxactive_val, path, library);
23dc94f6
DS
9017 results.push_back (entry_handler);
9018
9019 base->body = old_body;
9020 }
9021
e6fe60e7
AM
9022 this->sole_location()->components = comps;
9023}
d0ea46ce 9024
e6fe60e7
AM
9025void kprobe_derived_probe::printsig (ostream& o) const
9026{
9027 sole_location()->print (o);
9028 o << " /* " << " name = " << symbol_name << "*/";
9029 printsig_nested (o);
9030}
d0ea46ce 9031
e6fe60e7
AM
9032void kprobe_derived_probe::join_group (systemtap_session& s)
9033{
d0ea46ce 9034
e6fe60e7
AM
9035 if (! s.kprobe_derived_probes)
9036 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
9037 s.kprobe_derived_probes->enroll (this);
d0ea46ce 9038
e6fe60e7 9039}
d0ea46ce 9040
e6fe60e7
AM
9041void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
9042{
9043 probes_by_module.insert (make_pair (p->symbol_name, p));
9044 // probes of same symbol should share single kprobe/kretprobe
9045}
d0ea46ce 9046
e6fe60e7
AM
9047void
9048kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
9049{
9050 if (probes_by_module.empty()) return;
d0ea46ce 9051
e6fe60e7 9052 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 9053
e6fe60e7
AM
9054 // Warn of misconfigured kernels
9055 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
9056 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
9057 s.op->newline() << "#endif";
9058 s.op->newline();
d0ea46ce 9059
f07c3b68 9060 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 9061 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
9062 s.op->newline() << "#endif";
9063
e6fe60e7 9064 // Forward declare the master entry functions
88747011 9065 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 9066 s.op->line() << " struct pt_regs *regs);";
88747011 9067 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 9068 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 9069
e6fe60e7
AM
9070 // Emit an array of kprobe/kretprobe pointers
9071 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 9072 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 9073 s.op->newline() << "#endif";
d0ea46ce 9074
e6fe60e7 9075 // Emit the actual probe list.
d0ea46ce 9076
e6fe60e7
AM
9077 s.op->newline() << "static struct stap_dwarfless_kprobe {";
9078 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
9079 s.op->newline() << "#ifdef __ia64__";
9080 s.op->newline() << "struct kprobe dummy;";
9081 s.op->newline() << "#endif";
9082 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
9083 // NB: bss!
d0ea46ce 9084
e6fe60e7
AM
9085 s.op->newline() << "static struct stap_dwarfless_probe {";
9086 s.op->newline(1) << "const unsigned return_p:1;";
9087 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 9088 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
9089 s.op->newline() << "unsigned registered_p:1;";
9090 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 9091
e6fe60e7
AM
9092 // Function Names are mostly small and uniform enough to justify putting
9093 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 9094
faea5e16
JS
9095 size_t symbol_string_name_max = 0;
9096 size_t symbol_string_name_tot = 0;
e6fe60e7 9097 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 9098 {
e6fe60e7
AM
9099 kprobe_derived_probe* p = it->second;
9100#define DOIT(var,expr) do { \
9101 size_t var##_size = (expr) + 1; \
9102 var##_max = max (var##_max, var##_size); \
9103 var##_tot += var##_size; } while (0)
e6fe60e7
AM
9104 DOIT(symbol_string_name, p->symbol_name.size());
9105#undef DOIT
6270adc1
MH
9106 }
9107
e6fe60e7
AM
9108#define CALCIT(var) \
9109 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 9110
e6fe60e7
AM
9111 CALCIT(symbol_string);
9112#undef CALCIT
6270adc1 9113
bd659351 9114 s.op->newline() << "unsigned long address;";
7c3e97f4 9115 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
9116 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
9117 s.op->indent(1);
6270adc1 9118
e6fe60e7
AM
9119 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
9120 {
9121 kprobe_derived_probe* p = it->second;
9122 s.op->newline() << "{";
9123 if (p->has_return)
9124 s.op->line() << " .return_p=1,";
6270adc1 9125
e6fe60e7
AM
9126 if (p->has_maxactive)
9127 {
9128 s.op->line() << " .maxactive_p=1,";
9129 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
9130 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
9131 }
6270adc1 9132
b350f56b
JS
9133 if (p->locations[0]->optional)
9134 s.op->line() << " .optional_p=1,";
9135
e6fe60e7 9136 if (p->has_statement)
c8d9d15e 9137 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 9138 else
c8d9d15e 9139 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 9140
faea5e16 9141 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 9142 s.op->line() << " },";
935447c8
DS
9143 }
9144
e6fe60e7 9145 s.op->newline(-1) << "};";
5d67b47c 9146
e6fe60e7
AM
9147 // Emit the kprobes callback function
9148 s.op->newline();
88747011 9149 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
9150 s.op->line() << " struct pt_regs *regs) {";
9151 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9152 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9153 // Check that the index is plausible
9154 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9155 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9156 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9157 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9158 s.op->line() << "];";
71db462b 9159 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9160 "stp_probe_type_kprobe");
d9aed31e 9161 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
9162
9163 // Make it look like the IP is set as it wouldn't have been replaced
9164 // by a breakpoint instruction when calling real probe handler. Reset
9165 // IP regs on return, so we don't confuse kprobes. PR10458
9166 s.op->newline() << "{";
9167 s.op->indent(1);
d9aed31e 9168 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9169 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 9170 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9171 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9172 s.op->newline(-1) << "}";
9173
f887a8c9 9174 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9175 s.op->newline() << "return 0;";
9176 s.op->newline(-1) << "}";
935447c8 9177
e6fe60e7
AM
9178 // Same for kretprobes
9179 s.op->newline();
88747011 9180 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
9181 s.op->line() << " struct pt_regs *regs) {";
9182 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 9183
e6fe60e7
AM
9184 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9185 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9186 // Check that the index is plausible
9187 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9188 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9189 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9190 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9191 s.op->line() << "];";
935447c8 9192
71db462b 9193 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9194 "stp_probe_type_kretprobe");
d9aed31e 9195 s.op->newline() << "c->kregs = regs;";
6dceb5c9 9196 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
9197
9198 // Make it look like the IP is set as it wouldn't have been replaced
9199 // by a breakpoint instruction when calling real probe handler. Reset
9200 // IP regs on return, so we don't confuse kprobes. PR10458
9201 s.op->newline() << "{";
9202 s.op->indent(1);
d9aed31e 9203 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9204 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 9205 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9206 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9207 s.op->newline(-1) << "}";
9208
f887a8c9 9209 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9210 s.op->newline() << "return 0;";
9211 s.op->newline(-1) << "}";
bd659351 9212
03a4ec63 9213 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9214 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
9215 s.op->newline() << " struct module *owner,";
9216 s.op->newline() << " unsigned long val) {";
9217 s.op->newline(1) << "int i;";
fc1d2aa2
MW
9218 s.op->newline() << "int *p = (int *) data;";
9219 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
9220 << " && *p > 0; i++) {";
bd659351 9221 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
9222 s.op->newline() << "if (! sdp->address) {";
9223 s.op->indent(1);
9224 s.op->newline() << "const char *colon;";
9225 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
9226 s.op->indent(1);
9227 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
9228 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
9229 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
9230 s.op->newline(1) << "sdp->address = val;";
9231 s.op->newline() << "(*p)--;";
9232 s.op->newline(-1) << "}";
9233 s.op->newline(-1) << "}";
9234 s.op->newline() << "else {";
fc1d2aa2 9235 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 9236 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
9237 s.op->newline() << "(*p)--;";
9238 s.op->newline(-1) << "}";
8c272819
YW
9239 s.op->newline(-1) << "}";
9240 s.op->newline(-1) << "}";
9241 s.op->newline(-1) << "}";
fc1d2aa2 9242 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 9243 s.op->newline(-1) << "}";
03a4ec63 9244 s.op->newline() << "#endif";
935447c8
DS
9245}
9246
e6fe60e7 9247
6270adc1 9248void
e6fe60e7 9249kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 9250{
03a4ec63 9251 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
9252 s.op->newline() << "{";
9253 s.op->newline(1) << "int p = 0;";
9254 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
9255 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9256 s.op->newline() << "if (! sdp->address)";
9257 s.op->newline(1) << "p++;";
9258 s.op->newline(-2) << "}";
9259 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
9260 s.op->newline(-1) << "}";
03a4ec63 9261 s.op->newline() << "#endif";
bd659351 9262
e6fe60e7 9263 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 9264 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 9265 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 9266 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
9267 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
9268
9269 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9270 s.op->newline() << "if (! addr) {";
9271 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
9272 s.op->newline() << "if (!sdp->optional_p)";
9273 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
9274 s.op->newline(-1) << "continue;";
bd659351 9275 s.op->newline(-1) << "}";
03a4ec63
MW
9276 s.op->newline() << "#endif";
9277
26e63673 9278 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 9279 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 9280 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 9281 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9282 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 9283 s.op->newline() << "#endif";
e6fe60e7
AM
9284 s.op->newline() << "if (sdp->maxactive_p) {";
9285 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
9286 s.op->newline(-1) << "} else {";
f07c3b68 9287 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 9288 s.op->newline(-1) << "}";
88747011 9289 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
9290 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
9291 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9292 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 9293 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9294 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 9295 s.op->newline() << "#endif";
c8d9d15e 9296 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
9297 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9298 s.op->newline() << "if (rc == 0) {";
9299 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
9300 s.op->newline() << "if (rc != 0)";
9301 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9302 s.op->newline(-2) << "}";
9303 s.op->newline() << "#else";
9304 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
9305 s.op->newline() << "#endif";
9306 s.op->newline(-1) << "} else {";
9307 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 9308 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 9309 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9310 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 9311 s.op->newline() << "#endif";
88747011 9312 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 9313 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9314 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 9315 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 9316 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9317 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 9318 s.op->newline() << "#endif";
e6fe60e7
AM
9319 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9320 s.op->newline() << "if (rc == 0) {";
9321 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
9322 s.op->newline() << "if (rc != 0)";
9323 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9324 s.op->newline(-2) << "}";
9325 s.op->newline() << "#else";
9326 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
9327 s.op->newline() << "#endif";
9328 s.op->newline(-1) << "}";
9329 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
9330 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 9331 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 9332 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 9333 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
9334 // XXX: shall we increment numskipped?
9335 s.op->newline(-1) << "}";
6270adc1 9336
e6fe60e7
AM
9337 s.op->newline() << "else sdp->registered_p = 1;";
9338 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
9339}
9340
b4be7cbc 9341
e6fe60e7
AM
9342void
9343kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 9344{
e6fe60e7
AM
9345 //Unregister kprobes by batch interfaces.
9346 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
9347 s.op->newline() << "j = 0;";
9348 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9349 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9350 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9351 s.op->newline() << "if (! sdp->registered_p) continue;";
9352 s.op->newline() << "if (!sdp->return_p)";
c9116e99 9353 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 9354 s.op->newline(-2) << "}";
c9116e99 9355 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9356 s.op->newline() << "j = 0;";
9357 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9358 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9359 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9360 s.op->newline() << "if (! sdp->registered_p) continue;";
9361 s.op->newline() << "if (sdp->return_p)";
c9116e99 9362 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 9363 s.op->newline(-2) << "}";
c9116e99 9364 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9365 s.op->newline() << "#ifdef __ia64__";
9366 s.op->newline() << "j = 0;";
9367 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9368 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9369 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9370 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 9371 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 9372 s.op->newline(-1) << "}";
c9116e99 9373 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9374 s.op->newline() << "#endif";
9375 s.op->newline() << "#endif";
3e3bd7b6 9376
e6fe60e7
AM
9377 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9378 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9379 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9380 s.op->newline() << "if (! sdp->registered_p) continue;";
9381 s.op->newline() << "if (sdp->return_p) {";
9382 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9383 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
9384 s.op->newline() << "#endif";
065d5567 9385 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
9386 s.op->newline() << "#ifdef STP_TIMING";
9387 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 9388 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 9389 s.op->newline(-1) << "#endif";
065d5567 9390 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
9391 s.op->newline() << "#ifdef STP_TIMING";
9392 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 9393 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
9394 s.op->newline(-1) << "#endif";
9395 s.op->newline(-1) << "} else {";
9396 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9397 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
9398 s.op->newline() << "#endif";
065d5567 9399 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
9400 s.op->newline() << "#ifdef STP_TIMING";
9401 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 9402 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
9403 s.op->newline(-1) << "#endif";
9404 s.op->newline(-1) << "}";
9405 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
9406 s.op->newline() << "unregister_kprobe (&kp->dummy);";
9407 s.op->newline() << "#endif";
9408 s.op->newline() << "sdp->registered_p = 0;";
9409 s.op->newline(-1) << "}";
f8a968bc
JS
9410}
9411
e6fe60e7 9412struct kprobe_builder: public derived_probe_builder
3c1b3d06 9413{
9fdf787d 9414public:
2a639817 9415 kprobe_builder() {}
9fdf787d 9416
2a639817 9417 void build_no_more (systemtap_session &s) {}
9fdf787d 9418
e6fe60e7
AM
9419 virtual void build(systemtap_session & sess,
9420 probe * base,
9421 probe_point * location,
9422 literal_map_t const & parameters,
9423 vector<derived_probe *> & finished_results);
9424};
3c1b3d06
FCE
9425
9426
79189b84 9427void
05fb3e0c 9428kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
9429 probe * base,
9430 probe_point * location,
9431 literal_map_t const & parameters,
9432 vector<derived_probe *> & finished_results)
79189b84 9433{
e6fe60e7 9434 string function_string_val, module_string_val;
05fb3e0c 9435 string path, library, path_tgt, library_tgt;
b6371390
JS
9436 int64_t statement_num_val = 0, maxactive_val = 0;
9437 bool has_function_str, has_module_str, has_statement_num;
e6afb07b 9438 bool has_absolute, has_call, has_return, has_maxactive;
b642c901 9439 bool has_path, has_library;
79189b84 9440
b6371390
JS
9441 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
9442 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
e6afb07b 9443 has_call = has_null_param (parameters, TOK_CALL);
b6371390
JS
9444 has_return = has_null_param (parameters, TOK_RETURN);
9445 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
9446 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
9447 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
9448 has_path = get_param (parameters, TOK_PROCESS, path);
9449 has_library = get_param (parameters, TOK_LIBRARY, library);
9450
9451 if (has_path)
05fb3e0c
WF
9452 {
9453 path = find_executable (path, sess.sysroot, sess.sysenv);
9454 path_tgt = path_remove_sysroot(sess, path);
9455 }
b642c901 9456 if (has_library)
05fb3e0c
WF
9457 {
9458 library = find_executable (library, sess.sysroot, sess.sysenv,
9459 "LD_LIBRARY_PATH");
9460 library_tgt = path_remove_sysroot(sess, library);
9461 }
c57ea854 9462
b6371390 9463 if (has_function_str)
6fb70fb7 9464 {
2a639817 9465 if (has_module_str)
9fdf787d
DS
9466 {
9467 function_string_val = module_string_val + ":" + function_string_val;
9468 derived_probe *dp
23dc94f6
DS
9469 = new kprobe_derived_probe (sess, finished_results, base,
9470 location, function_string_val,
e6afb07b
JL
9471 0, has_call, has_return,
9472 has_statement_num, has_maxactive,
9473 has_path, has_library, maxactive_val,
9474 path_tgt, library_tgt);
9fdf787d
DS
9475 finished_results.push_back (dp);
9476 }
9477 else
9478 {
2a639817
JS
9479 vector<string> matches;
9480
9481 // Simple names can be found directly
9482 if (function_string_val.find_first_of("*?[") == string::npos)
9483 {
9484 if (sess.kernel_functions.count(function_string_val))
9485 matches.push_back(function_string_val);
9486 }
9487 else // Search function name list for matching names
9488 {
9489 for (set<string>::const_iterator it = sess.kernel_functions.begin();
9490 it != sess.kernel_functions.end(); it++)
9491 // fnmatch returns zero for matching.
9492 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
9493 matches.push_back(*it);
9494 }
86758d5f 9495
2a639817
JS
9496 for (vector<string>::const_iterator it = matches.begin();
9497 it != matches.end(); it++)
9fdf787d 9498 {
2a639817
JS
9499 derived_probe *dp
9500 = new kprobe_derived_probe (sess, finished_results, base,
e6afb07b
JL
9501 location, *it, 0, has_call,
9502 has_return, has_statement_num,
2a639817
JS
9503 has_maxactive, has_path,
9504 has_library, maxactive_val,
9505 path_tgt, library_tgt);
9506 finished_results.push_back (dp);
9fdf787d
DS
9507 }
9508 }
6fb70fb7 9509 }
e6fe60e7 9510 else
b6371390
JS
9511 {
9512 // assert guru mode for absolute probes
9513 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 9514 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 9515
23dc94f6
DS
9516 finished_results.push_back (new kprobe_derived_probe (sess,
9517 finished_results,
9518 base,
b6371390
JS
9519 location, "",
9520 statement_num_val,
e6afb07b 9521 has_call,
b6371390
JS
9522 has_return,
9523 has_statement_num,
9524 has_maxactive,
b642c901
SC
9525 has_path,
9526 has_library,
9527 maxactive_val,
05fb3e0c
WF
9528 path_tgt,
9529 library_tgt));
96b030fe 9530 }
79189b84
JS
9531}
9532
23dc94f6
DS
9533
9534void
9535kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
9536{
9537 expression *repl = e;
9538
bd5b25e1
JS
9539 if (has_return)
9540 {
9541 // expand the operand as if it weren't a return probe
9542 has_return = false;
9543 replace (e->operand);
9544 has_return = true;
23dc94f6 9545
bd5b25e1
JS
9546 // XXX it would be nice to use gen_kretprobe_saved_return when
9547 // available, but it requires knowing the types already, which is
9548 // problematic for arbitrary expressons.
9549 repl = gen_mapped_saved_return (sess, e->operand, "entry",
9550 add_block, add_block_tid,
9551 add_call_probe, add_call_probe_tid);
9552 }
23dc94f6
DS
9553 provide (repl);
9554}
9555
9556
dd225250
PS
9557// ------------------------------------------------------------------------
9558// Hardware breakpoint based probes.
9559// ------------------------------------------------------------------------
9560
9561static const string TOK_HWBKPT("data");
9562static const string TOK_HWBKPT_WRITE("write");
9563static const string TOK_HWBKPT_RW("rw");
9564static const string TOK_LENGTH("length");
9565
9566#define HWBKPT_READ 0
9567#define HWBKPT_WRITE 1
9568#define HWBKPT_RW 2
9569struct hwbkpt_derived_probe: public derived_probe
9570{
9571 hwbkpt_derived_probe (probe *base,
9572 probe_point *location,
9573 uint64_t addr,
9574 string symname,
9575 unsigned int len,
9576 bool has_only_read_access,
9577 bool has_only_write_access,
9578 bool has_rw_access
9579 );
9580 Dwarf_Addr hwbkpt_addr;
9581 string symbol_name;
9582 unsigned int hwbkpt_access,hwbkpt_len;
9583
9584 void printsig (std::ostream &o) const;
9585 void join_group (systemtap_session& s);
9586};
9587
9588struct hwbkpt_derived_probe_group: public derived_probe_group
9589{
dd225250 9590private:
dac77b80 9591 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
9592
9593public:
9594 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
9595 void emit_module_decls (systemtap_session& s);
9596 void emit_module_init (systemtap_session& s);
9597 void emit_module_exit (systemtap_session& s);
9598};
9599
9600hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
9601 probe_point *location,
9602 uint64_t addr,
9603 string symname,
9604 unsigned int len,
9605 bool has_only_read_access,
9606 bool has_only_write_access,
822a6a3d 9607 bool):
4c5d1300 9608 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9609 hwbkpt_addr (addr),
9610 symbol_name (symname),
9611 hwbkpt_len (len)
9612{
9613 this->tok = base->tok;
9614
9615 vector<probe_point::component*> comps;
9616 comps.push_back (new probe_point::component(TOK_KERNEL));
9617
9618 if (hwbkpt_addr)
9ea68eb9
JS
9619 comps.push_back (new probe_point::component (TOK_HWBKPT,
9620 new literal_number(hwbkpt_addr, true)));
9621 else if (symbol_name.size())
9622 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9623
9624 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9625
9626 if (has_only_read_access)
9ea68eb9 9627 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9628//TODO add code for comps.push_back for read, since this flag is not for x86
9629
9630 else
9ea68eb9
JS
9631 {
9632 if (has_only_write_access)
9633 {
9634 this->hwbkpt_access = HWBKPT_WRITE ;
9635 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9636 }
9637 else
9638 {
9639 this->hwbkpt_access = HWBKPT_RW ;
9640 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9641 }
9642 }
dd225250
PS
9643
9644 this->sole_location()->components = comps;
9645}
9646
9647void hwbkpt_derived_probe::printsig (ostream& o) const
9648{
9649 sole_location()->print (o);
9650 printsig_nested (o);
9651}
9652
9653void hwbkpt_derived_probe::join_group (systemtap_session& s)
9654{
dac77b80
FCE
9655 if (! s.hwbkpt_derived_probes)
9656 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9657 s.hwbkpt_derived_probes->enroll (this, s);
9658}
9659
9660void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9661{
dac77b80
FCE
9662 hwbkpt_probes.push_back (p);
9663
9664 unsigned max_hwbkpt_probes_by_arch = 0;
9665 if (s.architecture == "i386" || s.architecture == "x86_64")
9666 max_hwbkpt_probes_by_arch = 4;
9667 else if (s.architecture == "s390")
9668 max_hwbkpt_probes_by_arch = 1;
9669
c57ea854 9670 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9671 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9672 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9673}
9674
9675void
9676hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9677{
dac77b80 9678 if (hwbkpt_probes.empty()) return;
dd225250
PS
9679
9680 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9681
9682 s.op->newline() << "#include <linux/perf_event.h>";
9683 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9684 s.op->newline();
9685
9686 // Forward declare the master entry functions
23063de1 9687 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9688 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9689 s.op->line() << " int nmi,";
9690 s.op->line() << " struct perf_sample_data *data,";
9691 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9692 s.op->newline() << "#else";
9693 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9694 s.op->line() << " struct perf_sample_data *data,";
9695 s.op->line() << " struct pt_regs *regs);";
9696 s.op->newline() << "#endif";
79189b84 9697
dd225250
PS
9698 // Emit the actual probe list.
9699
9700 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9701 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9702
9703 s.op->newline() << "static struct perf_event **";
dac77b80 9704 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9705 s.op->newline() << "static struct stap_hwbkpt_probe {";
9706 s.op->newline() << "int registered_p:1;";
43650b10 9707// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9708// registered_p = 1 signifies a probe that got registered successfully
9709
faea5e16 9710 // Symbol Names are mostly small and uniform enough
dd225250 9711 // to justify putting const char*.
dac77b80 9712 s.op->newline() << "const char * const symbol;";
dd225250
PS
9713
9714 s.op->newline() << "const unsigned long address;";
9715 s.op->newline() << "uint8_t atype;";
bb0a4e12 9716 s.op->newline() << "unsigned int len;";
7c3e97f4 9717 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9718 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9719 s.op->indent(1);
9720
dac77b80 9721 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9722 {
dac77b80 9723 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9724 s.op->newline() << "{";
dd225250
PS
9725 if (p->symbol_name.size())
9726 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9727 else
9728 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9729 switch(p->hwbkpt_access){
9730 case HWBKPT_READ:
9731 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9732 break;
dd225250
PS
9733 case HWBKPT_WRITE:
9734 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9735 break;
dd225250
PS
9736 case HWBKPT_RW:
9737 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9738 break;
dd225250
PS
9739 };
9740 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9741 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9742 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9743 s.op->line() << " },";
9744 }
dac77b80 9745 s.op->newline(-1) << "};";
dd225250
PS
9746
9747 // Emit the hwbkpt callback function
9748 s.op->newline() ;
23063de1 9749 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9750 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9751 s.op->line() << " int nmi,";
9752 s.op->line() << " struct perf_sample_data *data,";
9753 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9754 s.op->newline() << "#else";
9755 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9756 s.op->line() << " struct perf_sample_data *data,";
9757 s.op->line() << " struct pt_regs *regs) {";
9758 s.op->newline() << "#endif";
dac77b80
FCE
9759 s.op->newline(1) << "unsigned int i;";
9760 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9761 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9762 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9763 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9764 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) {";
9765 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9766 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9767 "stp_probe_type_hwbkpt");
d9aed31e 9768 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9769 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9770 s.op->newline() << "c->uregs = regs;";
9771 s.op->newline(-1) << "} else {";
9772 s.op->newline(1) << "c->kregs = regs;";
9773 s.op->newline(-1) << "}";
26e63673 9774 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9775 common_probe_entryfn_epilogue (s, true);
dac77b80 9776 s.op->newline(-1) << "}";
dd225250
PS
9777 s.op->newline(-1) << "}";
9778 s.op->newline() << "return 0;";
dac77b80 9779 s.op->newline(-1) << "}";
dd225250
PS
9780}
9781
9782void
9783hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9784{
dac77b80 9785 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9786 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9787 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9788 s.op->newline() << "void *addr = (void *) sdp->address;";
9789 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9790 s.op->newline() << "hw_breakpoint_init(hp);";
9791 s.op->newline() << "if (addr)";
9792 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9793 s.op->newline(-1) << "else { ";
9794 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9795 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9796 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9797 s.op->newline() << "continue;";
9798 s.op->newline(-1) << "}";
9799 s.op->newline(-1) << "}";
9800 s.op->newline() << "hp->bp_type = sdp->atype;";
9801
9802 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9803 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9804 {
9805 s.op->newline() << "switch(sdp->len) {";
9806 s.op->newline() << "case 1:";
9807 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9808 s.op->newline() << "break;";
9809 s.op->newline(-1) << "case 2:";
9810 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9811 s.op->newline() << "break;";
9812 s.op->newline(-1) << "case 3:";
9813 s.op->newline() << "case 4:";
9814 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9815 s.op->newline() << "break;";
9816 s.op->newline(-1) << "case 5:";
9817 s.op->newline() << "case 6:";
9818 s.op->newline() << "case 7:";
9819 s.op->newline() << "case 8:";
9820 s.op->newline() << "default:"; // XXX: could instead reject
9821 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9822 s.op->newline() << "break;";
9823 s.op->newline(-1) << "}";
9824 }
9825 else // other architectures presumed straightforward
9826 s.op->newline() << "hp->bp_len = sdp->len;";
9827
26e63673 9828 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9829 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9830 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9831 s.op->newline() << "#else";
dac77b80 9832 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9833 s.op->newline() << "#endif";
43650b10 9834 s.op->newline() << "rc = 0;";
dac77b80 9835 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9836 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9837 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9838 s.op->newline(-1) << "}";
217ef1f4
WC
9839 s.op->newline() << "if (rc) {";
9840 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9841 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9842 s.op->newline(-1) << "}";
dd225250 9843 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9844 s.op->newline(-1) << "}"; // for loop
9845}
9846
9847void
9848hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9849{
9850 //Unregister hwbkpt probes.
dac77b80 9851 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9852 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9853 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9854 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9855 s.op->newline() << "sdp->registered_p = 0;";
9856 s.op->newline(-1) << "}";
9857}
9858
9859struct hwbkpt_builder: public derived_probe_builder
9860{
9861 hwbkpt_builder() {}
9862 virtual void build(systemtap_session & sess,
9863 probe * base,
9864 probe_point * location,
9865 literal_map_t const & parameters,
9866 vector<derived_probe *> & finished_results);
9867};
9868
9869void
9870hwbkpt_builder::build(systemtap_session & sess,
9871 probe * base,
9872 probe_point * location,
9873 literal_map_t const & parameters,
9874 vector<derived_probe *> & finished_results)
9875{
9876 string symbol_str_val;
9877 int64_t hwbkpt_address, len;
9878 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9879
b47f3a55 9880 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9881 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9882 location->components[0]->tok);
9883 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9884 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9885 location->components[0]->tok);
9886
dd225250
PS
9887 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9888 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9889 has_len = get_param (parameters, TOK_LENGTH, len);
9890 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9891 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9892
b31695eb
JL
9893 // Make an intermediate pp that is well-formed. It's pretty much the same as
9894 // the user-provided one, except that the addr literal is well-typed.
9895 probe_point* well_formed_loc = new probe_point(*location);
9896 well_formed_loc->well_formed = true;
9897
9898 vector<probe_point::component*> well_formed_comps;
9899 vector<probe_point::component*>::iterator it;
9900 for (it = location->components.begin();
9901 it != location->components.end(); ++it)
9902 if ((*it)->functor == TOK_HWBKPT && has_addr)
9903 well_formed_comps.push_back(new probe_point::component(TOK_HWBKPT,
9904 new literal_number(hwbkpt_address, true /* hex */ )));
9905 else
9906 well_formed_comps.push_back(*it);
9907 well_formed_loc->components = well_formed_comps;
9908 probe *new_base = new probe (base, well_formed_loc);
9909
dd225250
PS
9910 if (!has_len)
9911 len = 1;
9912
9913 if (has_addr)
b31695eb 9914 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9915 location,
9916 hwbkpt_address,
9917 "",len,0,
9918 has_write,
9919 has_rw));
5d8a0aea 9920 else if (has_symbol_str)
b31695eb 9921 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9922 location,
9923 0,
9924 symbol_str_val,len,0,
9925 has_write,
9926 has_rw));
5d8a0aea
FCE
9927 else
9928 assert (0);
dd225250 9929}
342d3f96 9930
0a6f5a3f
JS
9931// ------------------------------------------------------------------------
9932// statically inserted kernel-tracepoint derived probes
9933// ------------------------------------------------------------------------
9934
6fb70fb7 9935struct tracepoint_arg
79189b84 9936{
ad370dcc 9937 string name, c_type, typecast;
dcaa1a65 9938 bool usable, used, isptr;
f8a968bc 9939 Dwarf_Die type_die;
dcaa1a65 9940 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9941};
79189b84 9942
0a6f5a3f
JS
9943struct tracepoint_derived_probe: public derived_probe
9944{
79189b84
JS
9945 tracepoint_derived_probe (systemtap_session& s,
9946 dwflpp& dw, Dwarf_Die& func_die,
9947 const string& tracepoint_name,
9948 probe* base_probe, probe_point* location);
bc9a523d 9949
79189b84 9950 systemtap_session& sess;
6fb70fb7
JS
9951 string tracepoint_name, header;
9952 vector <struct tracepoint_arg> args;
bc9a523d 9953
6fb70fb7 9954 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9955 void getargs (std::list<std::string> &arg_set) const;
79189b84 9956 void join_group (systemtap_session& s);
3e3bd7b6 9957 void print_dupe_stamp(ostream& o);
0a6f5a3f 9958};
79189b84
JS
9959
9960
0a6f5a3f 9961struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9962{
79189b84
JS
9963 void emit_module_decls (systemtap_session& s);
9964 void emit_module_init (systemtap_session& s);
9965 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9966};
79189b84 9967
bc9a523d 9968
f8a968bc
JS
9969struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9970{
9971 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9972 vector <struct tracepoint_arg>& args):
9973 dw (dw), probe_name (probe_name), args (args) {}
9974 dwflpp& dw;
9975 const string& probe_name;
9976 vector <struct tracepoint_arg>& args;
bc9a523d 9977
f8a968bc
JS
9978 void visit_target_symbol (target_symbol* e);
9979 void visit_target_symbol_arg (target_symbol* e);
9980 void visit_target_symbol_context (target_symbol* e);
9981};
79189b84
JS
9982
9983
f8a968bc
JS
9984void
9985tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9986{
cc9001af 9987 string argname = e->sym_name();
75ead1f7 9988
f8a968bc
JS
9989 // search for a tracepoint parameter matching this name
9990 tracepoint_arg *arg = NULL;
9991 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9992 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9993 {
9994 arg = &args[i];
9995 arg->used = true;
9996 break;
9997 }
75ead1f7 9998
f8a968bc
JS
9999 if (arg == NULL)
10000 {
1d0499c2 10001 set<string> vars;
f8a968bc 10002 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
10003 vars.insert("$" + args[i].name);
10004 vars.insert("$$name");
10005 vars.insert("$$parms");
10006 vars.insert("$$vars");
10007 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 10008
f8a968bc
JS
10009 // We hope that this value ends up not being referenced after all, so it
10010 // can be optimized out quietly.
1d0499c2
JL
10011 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
10012 e->name.c_str(), sugs.empty() ? "" :
10013 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
10014 // NB: we use 'alternatives' because we list all
f8a968bc
JS
10015 // NB: we can have multiple errors, since a target variable
10016 // may be expanded in several different contexts:
10017 // trace ("*") { $foo->bar }
f8a968bc 10018 }
75ead1f7 10019
f8a968bc 10020 // make sure we're not dereferencing base types
dc5a09fc 10021 if (!arg->isptr)
d19a9a82 10022 e->assert_no_components("tracepoint", true);
75ead1f7 10023
f8a968bc
JS
10024 // we can only write to dereferenced fields, and only if guru mode is on
10025 bool lvalue = is_active_lvalue(e);
10026 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 10027 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 10028
ad370dcc
JS
10029 // XXX: if a struct/union arg is passed by value, then writing to its fields
10030 // is also meaningless until you dereference past a pointer member. It's
10031 // harder to detect and prevent that though...
75ead1f7 10032
f8a968bc
JS
10033 if (e->components.empty())
10034 {
03c75a4a 10035 if (e->addressof)
dc09353a 10036 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 10037
3e3bd7b6 10038 // Just grab the value from the probe locals
a45664f4
JS
10039 symbol* sym = new symbol;
10040 sym->tok = e->tok;
10041 sym->name = "__tracepoint_arg_" + arg->name;
10042 provide (sym);
f8a968bc
JS
10043 }
10044 else
10045 {
5f36109e
JS
10046 // make a copy of the original as a bare target symbol for the tracepoint
10047 // value, which will be passed into the dwarf dereferencing code
10048 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
10049 e2->components.clear();
10050
10051 if (e->components.back().type == target_symbol::comp_pretty_print)
10052 {
10053 if (lvalue)
dc09353a 10054 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 10055
d19a9a82 10056 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
10057 dpp.expand()->visit (this);
10058 return;
10059 }
10060
1c0be8c7 10061 bool userspace_p = false;
f8a968bc 10062 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 10063 + "_" + e->sym_name()
aca66a36 10064 + "_" + lex_cast(tick++));
75ead1f7 10065
1c0be8c7
JS
10066 exp_type type = pe_long;
10067 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 10068
1c0be8c7
JS
10069 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
10070 userspace_p, lvalue, e, e2);
75ead1f7 10071
f8a968bc
JS
10072 if (lvalue)
10073 {
10074 // Provide the functioncall to our parent, so that it can be
10075 // used to substitute for the assignment node immediately above
10076 // us.
10077 assert(!target_symbol_setter_functioncalls.empty());
10078 *(target_symbol_setter_functioncalls.top()) = n;
10079 }
75ead1f7 10080
1c0be8c7
JS
10081 // Revisit the functioncall so arguments can be expanded.
10082 n->visit (this);
f8a968bc 10083 }
75ead1f7
JS
10084}
10085
10086
f8a968bc
JS
10087void
10088tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 10089{
03c75a4a 10090 if (e->addressof)
dc09353a 10091 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 10092
f8a968bc 10093 if (is_active_lvalue (e))
dc09353a 10094 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 10095
277c21bc 10096 if (e->name == "$$name")
f8a968bc 10097 {
5f36109e
JS
10098 e->assert_no_components("tracepoint");
10099
bfdaad1e
DS
10100 // Synthesize an embedded expression.
10101 embedded_expr *expr = new embedded_expr;
10102 expr->tok = e->tok;
10103 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 10104 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 10105 provide (expr);
f8a968bc 10106 }
277c21bc 10107 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 10108 {
5f36109e
JS
10109 e->assert_no_components("tracepoint", true);
10110
1c922ad7 10111 print_format* pf = print_format::create(e->tok, "sprintf");
0a6f5a3f 10112
f8a968bc 10113 for (unsigned i = 0; i < args.size(); ++i)
b278033a 10114 {
dcaa1a65
JS
10115 if (!args[i].usable)
10116 continue;
f8a968bc
JS
10117 if (i > 0)
10118 pf->raw_components += " ";
10119 pf->raw_components += args[i].name;
3e3bd7b6 10120 target_symbol *tsym = new target_symbol;
f8a968bc 10121 tsym->tok = e->tok;
277c21bc 10122 tsym->name = "$" + args[i].name;
5f36109e 10123 tsym->components = e->components;
b278033a 10124
f8a968bc
JS
10125 // every variable should always be accessible!
10126 tsym->saved_conversion_error = 0;
8c2f50c0 10127 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
10128 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
10129 {
10130 if (dw.sess.verbose>2)
e26c2f83 10131 for (const semantic_error *c = tsym->saved_conversion_error;
c081af73 10132 c != 0; c = c->get_chain())
4c5d9906 10133 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
10134 pf->raw_components += "=?";
10135 continue;
10136 }
b278033a 10137
5f36109e
JS
10138 if (!e->components.empty() &&
10139 e->components[0].type == target_symbol::comp_pretty_print)
10140 pf->raw_components += "=%s";
10141 else
10142 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
10143 pf->args.push_back(texp);
10144 }
0a6f5a3f 10145
f8a968bc
JS
10146 pf->components = print_format::string_to_components(pf->raw_components);
10147 provide (pf);
b278033a 10148 }
f8a968bc
JS
10149 else
10150 assert(0); // shouldn't get here
0a6f5a3f
JS
10151}
10152
0a6f5a3f 10153void
f8a968bc 10154tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 10155{
aff5d390 10156 try
c69a87e0 10157 {
bd1fcbad 10158 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 10159
277c21bc 10160 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 10161 visit_target_symbol_context (e);
bd1fcbad 10162
c69a87e0
FCE
10163 else
10164 visit_target_symbol_arg (e);
10165 }
10166 catch (const semantic_error &er)
10167 {
1af1e62d 10168 e->chain (er);
c69a87e0
FCE
10169 provide (e);
10170 }
0a6f5a3f
JS
10171}
10172
10173
79189b84
JS
10174tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
10175 dwflpp& dw, Dwarf_Die& func_die,
10176 const string& tracepoint_name,
10177 probe* base, probe_point* loc):
4c5d1300 10178 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 10179 sess (s), tracepoint_name (tracepoint_name)
56894e91 10180{
79189b84
JS
10181 // create synthetic probe point name; preserve condition
10182 vector<probe_point::component*> comps;
10183 comps.push_back (new probe_point::component (TOK_KERNEL));
10184 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
10185 this->sole_location()->components = comps;
10186
6fb70fb7
JS
10187 // fill out the available arguments in this tracepoint
10188 build_args(dw, func_die);
56894e91 10189
6fb70fb7
JS
10190 // determine which header defined this tracepoint
10191 string decl_file = dwarf_decl_file(&func_die);
b78a0fbb 10192 header = decl_file;
d4393459
FCE
10193
10194#if 0 /* This convention is not enforced. */
6fb70fb7
JS
10195 size_t header_pos = decl_file.rfind("trace/");
10196 if (header_pos == string::npos)
dc09353a 10197 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
10198 + tracepoint_name + "' in '"
10199 + decl_file + "'");
10200 header = decl_file.substr(header_pos);
d4393459 10201#endif
56894e91 10202
6fb70fb7
JS
10203 // tracepoints from FOO_event_types.h should really be included from FOO.h
10204 // XXX can dwarf tell us the include hierarchy? it would be better to
10205 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 10206 // XXX: see also PR9993.
d4393459 10207 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
10208 if (header_pos != string::npos)
10209 header.erase(header_pos, 12);
56894e91 10210
f8a968bc
JS
10211 // Now expand the local variables in the probe body
10212 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 10213 v.replace (this->body);
a45664f4
JS
10214 for (unsigned i = 0; i < args.size(); i++)
10215 if (args[i].used)
10216 {
10217 vardecl* v = new vardecl;
10218 v->name = "__tracepoint_arg_" + args[i].name;
10219 v->tok = this->tok;
58701b78 10220 v->set_arity(0, this->tok);
a45664f4 10221 v->type = pe_long;
69aa668e 10222 v->synthetic = true;
a45664f4
JS
10223 this->locals.push_back (v);
10224 }
56894e91 10225
79189b84 10226 if (sess.verbose > 2)
ce0f6648 10227 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 10228}
dc38c0ae 10229
56894e91 10230
f8a968bc 10231static bool
dcaa1a65 10232resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 10233{
d19a9a82 10234 Dwarf_Die type;
dcaa1a65 10235 switch (dwarf_tag(&arg.type_die))
b20febf3 10236 {
f8a968bc
JS
10237 case DW_TAG_typedef:
10238 case DW_TAG_const_type:
10239 case DW_TAG_volatile_type:
10240 // iterate on the referent type
3d1ad340 10241 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 10242 && resolve_tracepoint_arg_type(arg));
f8a968bc 10243 case DW_TAG_base_type:
a52d2ac0 10244 case DW_TAG_enumeration_type:
f8a968bc 10245 // base types will simply be treated as script longs
dcaa1a65 10246 arg.isptr = false;
f8a968bc
JS
10247 return true;
10248 case DW_TAG_pointer_type:
dcaa1a65
JS
10249 // pointers can be treated as script longs,
10250 // and if we know their type, they can also be dereferenced
d19a9a82
JS
10251 type = arg.type_die;
10252 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
10253 {
10254 // It still might be a non-type, e.g. const void,
10255 // so we need to strip away all qualifiers.
10256 int tag = dwarf_tag(&arg.type_die);
10257 if (tag != DW_TAG_typedef &&
10258 tag != DW_TAG_const_type &&
10259 tag != DW_TAG_volatile_type)
10260 {
10261 arg.isptr = true;
10262 break;
10263 }
10264 }
10265 if (!arg.isptr)
10266 arg.type_die = type;
ad370dcc
JS
10267 arg.typecast = "(intptr_t)";
10268 return true;
10269 case DW_TAG_structure_type:
10270 case DW_TAG_union_type:
10271 // for structs/unions which are passed by value, we turn it into
10272 // a pointer that can be dereferenced.
10273 arg.isptr = true;
10274 arg.typecast = "(intptr_t)&";
dcaa1a65 10275 return true;
f8a968bc
JS
10276 default:
10277 // should we consider other types too?
10278 return false;
b20febf3 10279 }
56894e91
JS
10280}
10281
10282
10283void
822a6a3d 10284tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 10285{
6fb70fb7
JS
10286 Dwarf_Die arg;
10287 if (dwarf_child(&func_die, &arg) == 0)
10288 do
10289 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
10290 {
10291 // build a tracepoint_arg for this parameter
10292 tracepoint_arg tparg;
c60517ca 10293 tparg.name = dwarf_diename(&arg) ?: "";
56894e91 10294
6fb70fb7 10295 // read the type of this parameter
3d1ad340 10296 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 10297 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 10298 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 10299 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 10300
dcaa1a65 10301 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
10302 args.push_back(tparg);
10303 if (sess.verbose > 4)
a52d2ac0
JS
10304 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
10305 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
10306 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
10307 }
10308 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
10309}
10310
dc38c0ae 10311void
d0bfd2ac 10312tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 10313{
dcaa1a65
JS
10314 for (unsigned i = 0; i < args.size(); ++i)
10315 if (args[i].usable)
d0bfd2ac 10316 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
10317}
10318
79189b84
JS
10319void
10320tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 10321{
79189b84
JS
10322 if (! s.tracepoint_derived_probes)
10323 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
10324 s.tracepoint_derived_probes->enroll (this);
10325}
e38d6504 10326
56894e91 10327
197a4d62 10328void
3e3bd7b6 10329tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 10330{
3e3bd7b6
JS
10331 for (unsigned i = 0; i < args.size(); i++)
10332 if (args[i].used)
10333 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 10334}
56894e91 10335
3e3bd7b6 10336
c9ccb642 10337static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 10338{
3c1b3d06
FCE
10339 vector<string> they_live;
10340 // PR 9993
10341 // XXX: may need this to be configurable
d4393459 10342 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
10343
10344 // PR11649: conditional extra header
10345 // for kvm tracepoints in 2.6.33ish
10346 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
10347 they_live.push_back ("#include <linux/kvm_host.h>");
10348 }
10349
50b72692 10350 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 10351 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
10352 if (s.kernel_source_tree != "")
10353 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
10354 they_live.push_back ("struct xfs_mount;");
10355 they_live.push_back ("struct xfs_inode;");
10356 they_live.push_back ("struct xfs_buf;");
10357 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 10358 they_live.push_back ("struct xfs_trans;");
9e0cd21a 10359 }
d4393459 10360
50b72692 10361 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
10362 they_live.push_back ("struct rpc_task;");
10363 }
b64d65e2
FCE
10364 // RHEL6.3
10365 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
10366 they_live.push_back ("struct rpc_clnt;");
10367 they_live.push_back ("struct rpc_wait_queue;");
10368 }
d4393459
FCE
10369
10370 they_live.push_back ("#include <asm/cputime.h>");
10371
c2cf1b87
FCE
10372 // linux 3.0
10373 they_live.push_back ("struct cpu_workqueue_struct;");
10374
50b72692 10375 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
10376 if (s.kernel_source_tree != "")
10377 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
10378
d97d428e 10379 if (header.find("ext3") != string::npos)
50b72692
HP
10380 they_live.push_back ("struct ext3_reserve_window_node;");
10381
d97d428e
FCE
10382 if (header.find("workqueue") != string::npos)
10383 {
10384 they_live.push_back ("struct pool_workqueue;");
10385 they_live.push_back ("struct work_struct;");
10386 }
10387
10388 if (header.find("asoc") != string::npos)
10389 they_live.push_back ("struct snd_soc_dapm_path;");
10390
10391 if (header.find("9p") != string::npos)
10392 {
10393 they_live.push_back ("struct p9_client;");
10394 they_live.push_back ("struct p9_fcall;");
10395 }
10396
10397 if (header.find("bcache") != string::npos)
10398 {
10399 they_live.push_back ("struct bkey;");
10400 they_live.push_back ("struct btree;");
10401 they_live.push_back ("struct cache_set;");
10402 they_live.push_back ("struct cache;");
10403 }
10404
10405 if (header.find("f2fs") != string::npos)
10406 {
10407 // cannot get fs/f2fs/f2fs.h #included
10408 they_live.push_back ("typedef u32 block_t;");
10409 they_live.push_back ("typedef u32 nid_t;");
10410 }
10411
10412 if (header.find("radeon") != string::npos)
10413 they_live.push_back ("struct radeon_bo;");
10414
10415 // argh, 3.11, i915_trace.h -> i915_drv.h -> i915_reg.h without -I
10416 // also brcms_trace_events.h -> ... -> "types.h"
10417 // XXX: need a way to add a temporary -I flag
10418
10419 if (header.find("/ath/") != string::npos)
10420 they_live.push_back ("struct ath5k_hw;");
10421
10422
3c1b3d06
FCE
10423 return they_live;
10424}
47dd066d
WC
10425
10426
10427void
79189b84 10428tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 10429{
79189b84
JS
10430 if (probes.empty())
10431 return;
47dd066d 10432
96b030fe 10433 s.op->newline() << "/* ---- tracepoint probes ---- */";
3ef9830a 10434 s.op->newline() << "#include <linux/stp_tracepoint.h>" << endl;
96b030fe 10435 s.op->newline();
79189b84 10436
47dd066d 10437
a4b9c3b3
FCE
10438 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
10439 // to be separately compiled. That's because kernel tracepoint headers sometimes
10440 // conflict. PR13155.
10441
10442 map<string,translator_output*> per_header_aux;
10443 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 10444
6fb70fb7
JS
10445 for (unsigned i = 0; i < probes.size(); ++i)
10446 {
10447 tracepoint_derived_probe *p = probes[i];
75ae2ec9 10448 string header = p->header;
5f73a260 10449
a4b9c3b3
FCE
10450 // We cache the auxiliary output files on a per-header basis. We don't
10451 // need one aux file per tracepoint, only one per tracepoint-header.
10452 translator_output *tpop = per_header_aux[header];
10453 if (tpop == 0)
10454 {
10455 tpop = s.op_create_auxiliary();
10456 per_header_aux[header] = tpop;
10457
10458 // PR9993: Add extra headers to work around undeclared types in individual
10459 // include/trace/foo.h files
10460 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
10461 for (unsigned z=0; z<extra_decls.size(); z++)
10462 tpop->newline() << extra_decls[z] << "\n";
720c435f 10463
a4b9c3b3
FCE
10464 // strip include/ substring, the same way as done in get_tracequery_module()
10465 size_t root_pos = header.rfind("include/");
10466 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443 10467
3ef9830a 10468 tpop->newline() << "#include <linux/stp_tracepoint.h>" << endl;
a4b9c3b3 10469 tpop->newline() << "#include <" << header << ">";
a4b9c3b3
FCE
10470 }
10471
720c435f
JS
10472 // collect the args that are actually in use
10473 vector<const tracepoint_arg*> used_args;
6fb70fb7 10474 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
10475 if (p->args[j].used)
10476 used_args.push_back(&p->args[j]);
10477
3ef9830a
JS
10478 // forward-declare the generated-side tracepoint callback, and define the
10479 // generated-side tracepoint callback in the main translator-output
10480 string enter_real_fn = "enter_real_tracepoint_probe_" + lex_cast(i);
720c435f 10481 if (used_args.empty())
6fb70fb7 10482 {
3ef9830a
JS
10483 tpop->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
10484 s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ")";
6fb70fb7 10485 }
3ef9830a 10486 else
a4b9c3b3 10487 {
3ef9830a
JS
10488 tpop->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10489 s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10490 s.op->indent(2);
10491 for (unsigned j = 0; j < used_args.size(); ++j)
10492 {
10493 tpop->line() << ", int64_t";
10494 s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
10495 }
10496 tpop->line() << ");";
10497 s.op->newline() << ")";
10498 s.op->indent(-2);
6fb70fb7 10499 }
3ef9830a 10500 s.op->newline() << "{";
7c3e97f4 10501 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 10502 << common_probe_init (p) << ";";
71db462b 10503 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 10504 "stp_probe_type_tracepoint");
6dceb5c9 10505 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
10506 << lex_cast_qstring (p->tracepoint_name)
10507 << ";";
720c435f
JS
10508 for (unsigned j = 0; j < used_args.size(); ++j)
10509 {
10510 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 10511 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
10512 << " = __tracepoint_arg_" << used_args[j]->name << ";";
10513 }
26e63673 10514 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 10515 common_probe_entryfn_epilogue (s, true);
6fb70fb7 10516 s.op->newline(-1) << "}";
47dd066d 10517
a4b9c3b3 10518 // define the real tracepoint callback function
3ef9830a
JS
10519 string enter_fn = "enter_tracepoint_probe_" + lex_cast(i);
10520 if (p->args.empty())
10521 tpop->newline() << "static STP_TRACE_ENTER_NOARGS(" << enter_fn << ")";
10522 else
a4b9c3b3 10523 {
3ef9830a
JS
10524 tpop->newline() << "static STP_TRACE_ENTER(" << enter_fn;
10525 s.op->indent(2);
10526 for (unsigned j = 0; j < p->args.size(); ++j)
10527 {
10528 tpop->newline() << ", " << p->args[j].c_type
10529 << " __tracepoint_arg_" << p->args[j].name;
10530 }
10531 tpop->newline() << ")";
10532 s.op->indent(-2);
a4b9c3b3 10533 }
3ef9830a
JS
10534 tpop->newline() << "{";
10535 tpop->newline(1) << enter_real_fn << "(";
720c435f
JS
10536 tpop->indent(2);
10537 for (unsigned j = 0; j < used_args.size(); ++j)
10538 {
10539 if (j > 0)
10540 tpop->line() << ", ";
10541 tpop->newline() << "(int64_t)" << used_args[j]->typecast
10542 << "__tracepoint_arg_" << used_args[j]->name;
10543 }
10544 tpop->newline() << ");";
10545 tpop->newline(-3) << "}";
a4b9c3b3
FCE
10546
10547
96b030fe 10548 // emit normalized registration functions
720c435f 10549 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10550 tpop->newline(1) << "return STP_TRACE_REGISTER(" << p->tracepoint_name
10551 << ", " << enter_fn << ");";
a4b9c3b3 10552 tpop->newline(-1) << "}";
47dd066d 10553
86758d5f
JS
10554 // NB: we're not prepared to deal with unreg failures. However, failures
10555 // can only occur if the tracepoint doesn't exist (yet?), or if we
10556 // weren't even registered. The former should be OKed by the initial
10557 // registration call, and the latter is safe to ignore.
720c435f 10558 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10559 tpop->newline(1) << "(void) STP_TRACE_UNREGISTER(" << p->tracepoint_name
10560 << ", " << enter_fn << ");";
a4b9c3b3
FCE
10561 tpop->newline(-1) << "}";
10562 tpop->newline();
5f73a260 10563
720c435f
JS
10564 // declare normalized registration functions
10565 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
10566 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 10567
a4b9c3b3 10568 tpop->assert_0_indent();
af304783
DS
10569 }
10570
96b030fe
JS
10571 // emit an array of registration functions for easy init/shutdown
10572 s.op->newline() << "static struct stap_tracepoint_probe {";
10573 s.op->newline(1) << "int (*reg)(void);";
86758d5f 10574 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
10575 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
10576 s.op->indent(1);
10577 for (unsigned i = 0; i < probes.size(); ++i)
10578 {
10579 s.op->newline () << "{";
10580 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
10581 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
10582 s.op->line() << " },";
10583 }
10584 s.op->newline(-1) << "};";
10585 s.op->newline();
47dd066d
WC
10586}
10587
10588
79189b84
JS
10589void
10590tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 10591{
79189b84
JS
10592 if (probes.size () == 0)
10593 return;
47dd066d 10594
79189b84 10595 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
10596 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
10597 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
10598 s.op->newline() << "if (rc) {";
10599 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
10600 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
10601 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
10602 s.op->newline(-1) << "}";
10603 s.op->newline(-1) << "}";
47dd066d 10604
bc9a523d
FCE
10605 // This would be technically proper (on those autoconf-detectable
10606 // kernels that include this function in tracepoint.h), however we
10607 // already make several calls to synchronze_sched() during our
10608 // shutdown processes.
47dd066d 10609
bc9a523d
FCE
10610 // s.op->newline() << "if (rc)";
10611 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
10612 // s.op->indent(-1);
79189b84 10613}
47dd066d
WC
10614
10615
79189b84
JS
10616void
10617tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 10618{
79189b84
JS
10619 if (probes.empty())
10620 return;
47dd066d 10621
96b030fe
JS
10622 s.op->newline() << "/* deregister tracepoint probes */";
10623 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
10624 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
10625 s.op->indent(-1);
47dd066d 10626
bc9a523d 10627 // Not necessary: see above.
47dd066d 10628
bc9a523d 10629 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 10630}
b20febf3 10631
47dd066d 10632
75ead1f7 10633struct tracepoint_query : public base_query
47dd066d 10634{
75ead1f7
JS
10635 tracepoint_query(dwflpp & dw, const string & tracepoint,
10636 probe * base_probe, probe_point * base_loc,
10637 vector<derived_probe *> & results):
10638 base_query(dw, "*"), tracepoint(tracepoint),
10639 base_probe(base_probe), base_loc(base_loc),
10640 results(results) {}
47dd066d 10641
75ead1f7 10642 const string& tracepoint;
47dd066d 10643
75ead1f7
JS
10644 probe * base_probe;
10645 probe_point * base_loc;
10646 vector<derived_probe *> & results;
f982c59b 10647 set<string> probed_names;
47dd066d 10648
75ead1f7
JS
10649 void handle_query_module();
10650 int handle_query_cu(Dwarf_Die * cudie);
10651 int handle_query_func(Dwarf_Die * func);
822a6a3d 10652 void query_library (const char *) {}
576eaefe 10653 void query_plt (const char *entry, size_t addr) {}
b20febf3 10654
5c378838 10655 static int tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q);
7d007451 10656 static int tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q);
75ead1f7 10657};
47dd066d
WC
10658
10659
10660void
75ead1f7 10661tracepoint_query::handle_query_module()
47dd066d 10662{
75ead1f7 10663 // look for the tracepoints in each CU
337b7c44 10664 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10665}
10666
10667
75ead1f7
JS
10668int
10669tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10670{
75ead1f7 10671 dw.focus_on_cu (cudie);
5f52fafe 10672 dw.mod_info->get_symtab();
47dd066d 10673
75ead1f7
JS
10674 // look at each function to see if it's a tracepoint
10675 string function = "stapprobe_" + tracepoint;
10676 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10677}
10678
10679
75ead1f7
JS
10680int
10681tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10682{
75ead1f7 10683 dw.focus_on_function (func);
47dd066d 10684
60d98537 10685 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10686 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10687
10688 // check for duplicates -- sometimes tracepoint headers may be indirectly
10689 // included in more than one of our tracequery modules.
10690 if (!probed_names.insert(tracepoint_instance).second)
10691 return DWARF_CB_OK;
10692
79189b84
JS
10693 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10694 tracepoint_instance,
10695 base_probe, base_loc);
10696 results.push_back (dp);
75ead1f7 10697 return DWARF_CB_OK;
47dd066d
WC
10698}
10699
10700
75ead1f7 10701int
5c378838 10702tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q)
47dd066d 10703{
85007c04 10704 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10705 return q->handle_query_cu(cudie);
47dd066d
WC
10706}
10707
10708
75ead1f7 10709int
7d007451 10710tracepoint_query::tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q)
47dd066d 10711{
85007c04 10712 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10713 return q->handle_query_func(func);
47dd066d
WC
10714}
10715
10716
0a6f5a3f 10717struct tracepoint_builder: public derived_probe_builder
47dd066d 10718{
0a6f5a3f
JS
10719private:
10720 dwflpp *dw;
10721 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10722 void get_tracequery_modules(systemtap_session& s,
10723 const vector<string>& headers,
10724 vector<string>& modules);
47dd066d 10725
0a6f5a3f 10726public:
47dd066d 10727
0a6f5a3f
JS
10728 tracepoint_builder(): dw(0) {}
10729 ~tracepoint_builder() { delete dw; }
47dd066d 10730
0a6f5a3f
JS
10731 void build_no_more (systemtap_session& s)
10732 {
10733 if (dw && s.verbose > 3)
b530b5b3 10734 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10735 delete dw;
10736 dw = NULL;
435f53a7
FCE
10737
10738 delete_session_module_cache (s);
0a6f5a3f 10739 }
47dd066d 10740
0a6f5a3f
JS
10741 void build(systemtap_session& s,
10742 probe *base, probe_point *location,
10743 literal_map_t const& parameters,
10744 vector<derived_probe*>& finished_results);
10745};
47dd066d 10746
47dd066d 10747
c9ccb642 10748
2a0e62a8 10749// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10750// tracepoint-related header files given. Return the generated or cached
10751// modules[].
10752
10753void
10754tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10755 const vector<string>& headers,
10756 vector<string>& modules)
0a6f5a3f 10757{
c95eddf7 10758 if (s.verbose > 2)
55e50c24 10759 {
ce0f6648 10760 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10761 for (size_t i = 0; i < headers.size(); ++i)
10762 clog << " " << headers[i] << endl;
10763 }
c95eddf7 10764
2a0e62a8
JS
10765 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10766 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10767 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10768 // so we prefer not to repeat this.
10769 vector<string> uncached_headers;
10770 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10771 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10772
10773 // They may be in the cache already.
10774 if (s.use_cache && !s.poison_cache)
10775 for (size_t i=0; i<headers.size(); i++)
10776 {
10777 // see if the cached module exists
2a0e62a8 10778 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10779 if (!tracequery_path.empty() && file_exists(tracequery_path))
10780 {
10781 if (s.verbose > 2)
10782 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10783
c252fca2
JS
10784 // an empty file is a cached failure
10785 if (get_file_size(tracequery_path) > 0)
10786 modules.push_back (tracequery_path);
c9ccb642
FCE
10787 }
10788 else
10789 uncached_headers.push_back(headers[i]);
10790 }
10791 else
10792 uncached_headers = headers;
f982c59b 10793
c9ccb642
FCE
10794 // If we have nothing left to search for, quit
10795 if (uncached_headers.empty()) return;
55e50c24 10796
c9ccb642 10797 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10798
c9ccb642
FCE
10799 // We could query several subsets of headers[] to make this go
10800 // faster, but let's KISS and do one at a time.
10801 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10802 {
c9ccb642
FCE
10803 const string& header = uncached_headers[i];
10804
10805 // create a tracequery source file
10806 ostringstream osrc;
10807
10808 // PR9993: Add extra headers to work around undeclared types in individual
10809 // include/trace/foo.h files
10810 vector<string> short_decls = tracepoint_extra_decls(s, header);
10811
10812 // add each requested tracepoint header
75ae2ec9 10813 size_t root_pos = header.rfind("include/");
832f100d 10814 short_decls.push_back(string("#include <") +
75ae2ec9 10815 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10816 string(">"));
f982c59b 10817
c9ccb642
FCE
10818 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10819 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10820
10821 // the kernel has changed this naming a few times, previously TPPROTO,
10822 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10823 osrc << "#ifndef PARAMS" << endl;
10824 osrc << "#define PARAMS(args...) args" << endl;
10825 osrc << "#endif" << endl;
10826
c9ccb642
FCE
10827 // override DECLARE_TRACE to synthesize probe functions for us
10828 osrc << "#undef DECLARE_TRACE" << endl;
10829 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10830 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10831
c9ccb642
FCE
10832 // 2.6.35 added the NOARGS variant, but it's the same for us
10833 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10834 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10835 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10836
10837 // 2.6.38 added the CONDITION variant, which can also just redirect
10838 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10839 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10840 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10841
c9ccb642
FCE
10842 // older tracepoints used DEFINE_TRACE, so redirect that too
10843 osrc << "#undef DEFINE_TRACE" << endl;
10844 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10845 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10846
c9ccb642
FCE
10847 // add the specified decls/#includes
10848 for (unsigned z=0; z<short_decls.size(); z++)
10849 osrc << "#undef TRACE_INCLUDE_FILE\n"
10850 << "#undef TRACE_INCLUDE_PATH\n"
10851 << short_decls[z] << "\n";
10852
10853 // finish up the module source
10854 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10855
c9ccb642
FCE
10856 // save the source file away
10857 headers_tracequery_src[header] = osrc.str();
55e50c24 10858 }
f982c59b 10859
c9ccb642 10860 // now build them all together
2a0e62a8 10861 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10862
c9ccb642 10863 // now plop them into the cache
b278033a 10864 if (s.use_cache)
c9ccb642
FCE
10865 for (size_t i=0; i<uncached_headers.size(); i++)
10866 {
10867 const string& header = uncached_headers[i];
2a0e62a8
JS
10868 const string& tracequery_obj = tracequery_objs[header];
10869 const string& tracequery_path = headers_cache_obj[header];
10870 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10871 {
2a0e62a8 10872 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10873 modules.push_back (tracequery_path);
10874 }
c252fca2
JS
10875 else
10876 // cache an empty file for failures
10877 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10878 }
f982c59b
JS
10879}
10880
10881
d4393459 10882
f982c59b
JS
10883bool
10884tracepoint_builder::init_dw(systemtap_session& s)
10885{
10886 if (dw != NULL)
10887 return true;
10888
10889 vector<string> tracequery_modules;
55e50c24 10890 vector<string> system_headers;
f982c59b
JS
10891
10892 glob_t trace_glob;
d4393459
FCE
10893
10894 // find kernel_source_tree
10895 if (s.kernel_source_tree == "")
f982c59b 10896 {
d4393459 10897 unsigned found;
ccf2c922 10898 Dwfl *dwfl = setup_dwfl_kernel ("kernel", &found, s);
d4393459
FCE
10899 if (found)
10900 {
10901 Dwarf_Die *cudie = 0;
10902 Dwarf_Addr bias;
10903 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10904 {
e19ebcf7 10905 assert_no_interrupts();
d4393459
FCE
10906 Dwarf_Attribute attr;
10907 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10908 if (name)
d4393459 10909 {
36d65b45
JS
10910 // check that the path actually exists locally before we try to use it
10911 if (file_exists(name))
10912 {
10913 if (s.verbose > 2)
10914 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10915 s.kernel_source_tree = name;
10916 }
10917 else
10918 {
10919 if (s.verbose > 2)
10920 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10921 }
61f1a63b 10922
d4393459
FCE
10923 break; // skip others; modern Kbuild uses same comp_dir for them all
10924 }
10925 }
10926 }
44392d73 10927 dwfl_end (dwfl);
d4393459
FCE
10928 }
10929
10930 // prefixes
10931 vector<string> glob_prefixes;
10932 glob_prefixes.push_back (s.kernel_build_tree);
10933 if (s.kernel_source_tree != "")
10934 glob_prefixes.push_back (s.kernel_source_tree);
10935
10936 // suffixes
10937 vector<string> glob_suffixes;
10938 glob_suffixes.push_back("include/trace/events/*.h");
10939 glob_suffixes.push_back("include/trace/*.h");
d97d428e 10940 glob_suffixes.push_back("include/ras/*_event.h");
d4393459 10941 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
d97d428e
FCE
10942 glob_suffixes.push_back("arch/x86/kernel/*trace.h");
10943 glob_suffixes.push_back("arch/*/include/asm/trace*.h");
10944 glob_suffixes.push_back("arch/*/include/asm/trace/*.h");
f89ff3e2 10945 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d97d428e
FCE
10946 glob_suffixes.push_back("fs/*/*trace*.h");
10947 glob_suffixes.push_back("net/*/*trace*.h");
10948 glob_suffixes.push_back("sound/pci/hda/*_trace.h");
10949 glob_suffixes.push_back("drivers/gpu/drm/*_trace.h");
10950 glob_suffixes.push_back("drivers/gpu/drm/*/*_trace.h");
10951 glob_suffixes.push_back("drivers/net/wireless/*/*/*trace*.h");
10952 glob_suffixes.push_back("drivers/usb/host/*trace*.h");
10953
10954 // see also tracepoint_extra_decls above
d4393459
FCE
10955
10956 // compute cartesian product
10957 vector<string> globs;
10958 for (unsigned i=0; i<glob_prefixes.size(); i++)
10959 for (unsigned j=0; j<glob_suffixes.size(); j++)
10960 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10961
8aa43b8d 10962 set<string> duped_headers;
d4393459
FCE
10963 for (unsigned z = 0; z < globs.size(); z++)
10964 {
10965 string glob_str = globs[z];
10966 if (s.verbose > 3)
b530b5b3 10967 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10968
067cc66f
CM
10969 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10970 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10971 throw runtime_error("Error globbing tracepoint");
10972
f982c59b
JS
10973 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10974 {
10975 string header(trace_glob.gl_pathv[i]);
10976
10977 // filter out a few known "internal-only" headers
60d98537
JS
10978 if (endswith(header, "/define_trace.h") ||
10979 endswith(header, "/ftrace.h") ||
10980 endswith(header, "/trace_events.h") ||
10981 endswith(header, "_event_types.h"))
f982c59b
JS
10982 continue;
10983
b1966849
FCE
10984 // With headers now plopped under arch/FOO/include/asm/*,
10985 // the following logic miss some tracepoints.
10986#if 0
8aa43b8d
JS
10987 // skip identical headers from the build and source trees.
10988 size_t root_pos = header.rfind("include/");
10989 if (root_pos != string::npos &&
10990 !duped_headers.insert(header.substr(root_pos + 8)).second)
10991 continue;
b1966849 10992#endif
8aa43b8d 10993
55e50c24 10994 system_headers.push_back(header);
f982c59b
JS
10995 }
10996 globfree(&trace_glob);
10997 }
10998
c9ccb642
FCE
10999 // Build tracequery modules
11000 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 11001
f982c59b
JS
11002 // TODO: consider other sources of tracepoint headers too, like from
11003 // a command-line parameter or some environment or .systemtaprc
47dd066d 11004
59c11f91 11005 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
11006 return true;
11007}
47dd066d 11008
0a6f5a3f
JS
11009void
11010tracepoint_builder::build(systemtap_session& s,
11011 probe *base, probe_point *location,
11012 literal_map_t const& parameters,
11013 vector<derived_probe*>& finished_results)
11014{
11015 if (!init_dw(s))
11016 return;
47dd066d 11017
75ead1f7
JS
11018 string tracepoint;
11019 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 11020
75ead1f7 11021 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
d906ab9d 11022 unsigned results_pre = finished_results.size();
06de3a04 11023 dw->iterate_over_modules<base_query>(&query_module, &q);
d906ab9d
JL
11024 unsigned results_post = finished_results.size();
11025
11026 // Did we fail to find a match? Let's suggest something!
11027 if (results_pre == results_post)
11028 {
11029 size_t pos;
11030 string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
11031 while ((pos = sugs.find("stapprobe_")) != string::npos)
11032 sugs.erase(pos, string("stapprobe_").size());
11033 if (!sugs.empty())
ece93f53
JL
11034 throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
11035 "no match (similar tracepoints: %s)",
d906ab9d
JL
11036 sugs.find(',') == string::npos,
11037 sugs.c_str()));
11038 }
47dd066d 11039}
47dd066d 11040
e6fe60e7 11041
b55bc428 11042// ------------------------------------------------------------------------
bd2b1e68 11043// Standard tapset registry.
b55bc428
FCE
11044// ------------------------------------------------------------------------
11045
7a053d3b 11046void
f8220a7b 11047register_standard_tapsets(systemtap_session & s)
b55bc428 11048{
47e0478e 11049 register_tapset_been(s);
93646f4d 11050 register_tapset_itrace(s);
dd0e4fa7 11051 register_tapset_mark(s);
7a212aa8 11052 register_tapset_procfs(s);
912e8c59 11053 register_tapset_timers(s);
8d9609f5 11054 register_tapset_netfilter(s);
b84779a5 11055 register_tapset_utrace(s);
b98a8d73 11056
7a24d422 11057 // dwarf-based kprobe/uprobe parts
c4ce66a1 11058 dwarf_derived_probe::register_patterns(s);
30a279be 11059
888af770
FCE
11060 // XXX: user-space starter set
11061 s.pattern_root->bind_num(TOK_PROCESS)
11062 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 11063 ->bind_privilege(pr_all)
888af770
FCE
11064 ->bind(new uprobe_builder ());
11065 s.pattern_root->bind_num(TOK_PROCESS)
11066 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 11067 ->bind_privilege(pr_all)
888af770
FCE
11068 ->bind(new uprobe_builder ());
11069
0a6f5a3f
JS
11070 // kernel tracepoint probes
11071 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
11072 ->bind(new tracepoint_builder());
11073
e6fe60e7
AM
11074 // Kprobe based probe
11075 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
11076 ->bind(new kprobe_builder());
3c57fe1f
JS
11077 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
11078 ->bind(new kprobe_builder());
e6fe60e7
AM
11079 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11080 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
11081 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11082 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
11083 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11084 ->bind(new kprobe_builder());
b6371390
JS
11085 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11086 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
11087 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11088 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
11089 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11090 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11091 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
11092 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
11093 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
11094
11095 //Hwbkpt based probe
b47f3a55
FCE
11096 // NB: we formerly registered the probe point types only if the kernel configuration
11097 // allowed it. However, we get better error messages if we allow probes to resolve.
11098 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11099 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11100 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11101 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11102 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11103 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11104 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11105 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11106 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11107 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11108 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11109 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11110 // length supported with address only, not symbol names
83ea76b1
WC
11111
11112 //perf event based probe
4763f713 11113 register_tapset_perf(s);
a29858ef 11114 register_tapset_java(s);
b55bc428 11115}
dc38c0ae
DS
11116
11117
b20febf3
FCE
11118vector<derived_probe_group*>
11119all_session_groups(systemtap_session& s)
dc38c0ae 11120{
b20febf3 11121 vector<derived_probe_group*> g;
912e8c59
JS
11122
11123#define DOONE(x) \
11124 if (s. x##_derived_probes) \
11125 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
11126
11127 // Note that order *is* important here. We want to make sure we
11128 // register (actually run) begin probes before any other probe type
11129 // is run. Similarly, when unregistering probes, we want to
11130 // unregister (actually run) end probes after every other probe type
11131 // has be unregistered. To do the latter,
11132 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
11133 DOONE(be);
11134 DOONE(dwarf);
888af770 11135 DOONE(uprobe);
b20febf3
FCE
11136 DOONE(timer);
11137 DOONE(profile);
11138 DOONE(mark);
0a6f5a3f 11139 DOONE(tracepoint);
e6fe60e7 11140 DOONE(kprobe);
dd225250 11141 DOONE(hwbkpt);
83ea76b1 11142 DOONE(perf);
b20febf3 11143 DOONE(hrtimer);
ce82316f 11144 DOONE(procfs);
8d9609f5 11145 DOONE(netfilter);
935447c8
DS
11146
11147 // Another "order is important" item. We want to make sure we
11148 // "register" the dummy task_finder probe group after all probe
11149 // groups that use the task_finder.
11150 DOONE(utrace);
a96d1db0 11151 DOONE(itrace);
f31a77f5 11152 DOONE(dynprobe);
e7d4410d 11153 DOONE(java);
935447c8 11154 DOONE(task_finder);
b20febf3
FCE
11155#undef DOONE
11156 return g;
46b84a80 11157}
73267b89
JS
11158
11159/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.765093 seconds and 5 git commands to generate.