]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
process probes: throw error upon unresolved executable
[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)
5fa0d811
JL
632 {
633 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
634 if (!is_fully_resolved(module_val, sess.sysroot, sess.sysenv))
635 throw SEMANTIC_ERROR(_F("cannot find executable '%s'",
636 module_val.c_str()));
637 }
dbe9d133
JL
638
639 // Library probe? Let's target that instead if it is fully resolved (such
640 // as what query_one_library() would have done for us). Otherwise, we
641 // resort to iterate_over_libraries().
642 if (has_library && is_fully_resolved(library_name, sess.sysroot, sess.sysenv,
643 "LD_LIBRARY_PATH"))
84c84ac4 644 {
dbe9d133
JL
645 path = path_remove_sysroot(sess, module_val);
646 module_val = library_name;
84c84ac4 647 }
d0a7f5a9 648 }
91af0778
FCE
649
650 assert (has_kernel || has_process || has_module);
2c384610
DS
651}
652
c4ce66a1 653base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
654 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
655 module_val(module_val)
c4ce66a1
JS
656{
657 // NB: This uses '/' to distinguish between kernel modules and userspace,
658 // which means that userspace modules won't get any PATH searching.
659 if (module_val.find('/') == string::npos)
660 {
661 has_kernel = (module_val == TOK_KERNEL);
662 has_module = !has_kernel;
663 has_process = false;
664 }
665 else
666 {
667 has_kernel = has_module = false;
668 has_process = true;
669 }
670}
671
2c384610 672bool
86bf665e 673base_query::has_null_param(literal_map_t const & params,
2c384610
DS
674 string const & k)
675{
888af770 676 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
677}
678
679
680bool
86bf665e 681base_query::get_string_param(literal_map_t const & params,
2c384610
DS
682 string const & k, string & v)
683{
684 return derived_probe_builder::get_param (params, k, v);
685}
686
687
688bool
86bf665e 689base_query::get_number_param(literal_map_t const & params,
2c384610
DS
690 string const & k, long & v)
691{
692 int64_t value;
693 bool present = derived_probe_builder::get_param (params, k, value);
694 v = (long) value;
695 return present;
696}
697
698
699bool
86bf665e 700base_query::get_number_param(literal_map_t const & params,
2c384610
DS
701 string const & k, Dwarf_Addr & v)
702{
703 int64_t value;
704 bool present = derived_probe_builder::get_param (params, k, value);
705 v = (Dwarf_Addr) value;
706 return present;
707}
708
2c384610
DS
709struct dwarf_query : public base_query
710{
e1278bd4 711 dwarf_query(probe * base_probe,
2c384610
DS
712 probe_point * base_loc,
713 dwflpp & dw,
86bf665e 714 literal_map_t const & params,
b642c901
SC
715 vector<derived_probe *> & results,
716 const string user_path,
717 const string user_lib);
2c384610 718
c4ce66a1 719 vector<derived_probe *> & results;
8f14e444 720 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
721 probe * base_probe;
722 probe_point * base_loc;
b642c901
SC
723 string user_path;
724 string user_lib;
c4ce66a1 725
2c384610 726 virtual void handle_query_module();
5f0a03a6
JK
727 void query_module_dwarf();
728 void query_module_symtab();
5d5bd369 729 void query_library (const char *data);
576eaefe 730 void query_plt (const char *entry, size_t addr);
2c384610 731
2930abc7
FCE
732 void add_probe_point(string const & funcname,
733 char const * filename,
734 int line,
735 Dwarf_Die *scope_die,
736 Dwarf_Addr addr);
36f9dd1d 737
613c8675
JL
738 void mount_well_formed_probe_point();
739 void unmount_well_formed_probe_point();
740 stack<pair<probe_point*, probe*> > previous_bases;
741
71dfce11
JL
742 void replace_probe_point_component_arg(const string& functor,
743 const string& new_functor,
744 int64_t new_arg,
745 bool hex = false);
746 void replace_probe_point_component_arg(const string& functor,
747 int64_t new_arg,
748 bool hex = false);
749 void replace_probe_point_component_arg(const string& functor,
750 const string& new_functor,
751 const string& new_arg);
752 void replace_probe_point_component_arg(const string& functor,
753 const string& new_arg);
754 void remove_probe_point_component(const string& functor);
755
857bdfd1
JS
756 // Track addresses we've already seen in a given module
757 set<Dwarf_Addr> alias_dupes;
758
7fdd3e2c
JS
759 // Track inlines we've already seen as well
760 // NB: this can't be compared just by entrypc, as inlines can overlap
761 set<inline_instance_info> inline_dupes;
762
e2941743
JL
763 // Used in .callee[s] probes, when calling iterate_over_callees() (which
764 // provides the actual stack). Retains the addrs of the callers unwind addr
765 // where the callee is found. Specifies multiple callers. E.g. when a callee
766 // at depth 2 is found, callers[1] has the addr of the caller, and callers[0]
767 // has the addr of the caller's caller.
768 stack<Dwarf_Addr> *callers;
769
20c6c071
GH
770 bool has_function_str;
771 bool has_statement_str;
772 bool has_function_num;
773 bool has_statement_num;
7a053d3b
RM
774 string statement_str_val;
775 string function_str_val;
c239d28c
GH
776 Dwarf_Addr statement_num_val;
777 Dwarf_Addr function_num_val;
20c6c071 778
b8da0ad1 779 bool has_call;
4bda987e 780 bool has_exported;
b8da0ad1 781 bool has_inline;
20c6c071
GH
782 bool has_return;
783
c9bad430
DS
784 bool has_maxactive;
785 long maxactive_val;
786
20c6c071
GH
787 bool has_label;
788 string label_val;
789
c31add50
JL
790 bool has_callee;
791 string callee_val;
792
793 bool has_callees_num;
794 long callees_num_val;
795
20c6c071
GH
796 bool has_relative;
797 long relative_val;
798
37ebca01
FCE
799 bool has_absolute;
800
467bea43
SC
801 bool has_mark;
802
5f0a03a6
JK
803 enum dbinfo_reqt dbinfo_reqt;
804 enum dbinfo_reqt assess_dbinfo_reqt();
805
7d6d0afc 806 void parse_function_spec(const string & spec);
20c6c071 807 function_spec_type spec_type;
7d6d0afc 808 vector<string> scopes;
20c6c071
GH
809 string function;
810 string file;
4a81c0d9
JL
811 lineno_t lineno_type;
812 int linenos[2];
5f0a03a6 813 bool query_done; // Found exact match
20c6c071 814
5a617dc6
JL
815 // Holds the prologue end of the current function
816 Dwarf_Addr prologue_end;
817
bd25380d 818 set<string> filtered_srcfiles;
7e1279ea
FCE
819
820 // Map official entrypc -> func_info object
86bf665e
TM
821 inline_instance_map_t filtered_inlines;
822 func_info_map_t filtered_functions;
4df79aaf 823
959ccfed
JL
824 // Helper when we want to iterate over both
825 base_func_info_map_t filtered_all();
826
4df79aaf 827 void query_module_functions ();
e772a6e7
JL
828
829 string final_function_name(const string& final_func,
79954c0f 830 const char* final_file,
e772a6e7 831 int final_line);
b55bc428
FCE
832};
833
98afd80e 834
435f53a7
FCE
835static void delete_session_module_cache (systemtap_session& s); // forward decl
836
837
98afd80e 838struct dwarf_builder: public derived_probe_builder
b55bc428 839{
665e1256 840 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 841 map <string,dwflpp*> user_dw;
b642c901
SC
842 string user_path;
843 string user_lib;
44ffe90c
JL
844
845 // Holds modules to suggest functions from. NB: aggregates over
846 // recursive calls to build() when deriving globby probes.
847 set <string> modules_seen;
848
ae2552da 849 dwarf_builder() {}
aa30ccd3 850
ae2552da 851 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 852 {
ea14cf67
FCE
853 if (kern_dw[module] == 0)
854 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 855 return kern_dw[module];
707bf35e
JS
856 }
857
858 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
859 {
ea14cf67
FCE
860 if (user_dw[module] == 0)
861 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
862 return user_dw[module];
863 }
7a24d422
FCE
864
865 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 866 void dwarf_build_no_more (bool)
aa30ccd3 867 {
435f53a7
FCE
868 delete_map(kern_dw);
869 delete_map(user_dw);
7a24d422
FCE
870 }
871
872 void build_no_more (systemtap_session &s)
873 {
874 dwarf_build_no_more (s.verbose > 3);
435f53a7 875 delete_session_module_cache (s);
aa30ccd3
FCE
876 }
877
e38d6504
RM
878 ~dwarf_builder()
879 {
7a24d422 880 dwarf_build_no_more (false);
c8959a29 881 }
aa30ccd3 882
5227f1ea 883 virtual void build(systemtap_session & sess,
7a053d3b 884 probe * base,
20c6c071 885 probe_point * location,
86bf665e 886 literal_map_t const & parameters,
20c6c071 887 vector<derived_probe *> & finished_results);
b55bc428
FCE
888};
889
5111fc3e 890
e1278bd4 891dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
892 probe_point * base_loc,
893 dwflpp & dw,
86bf665e 894 literal_map_t const & params,
b642c901
SC
895 vector<derived_probe *> & results,
896 const string user_path,
897 const string user_lib)
e2941743
JL
898 : base_query(dw, params), results(results), base_probe(base_probe),
899 base_loc(base_loc), user_path(user_path), user_lib(user_lib),
5a617dc6 900 callers(NULL), has_relative(false), relative_val(0), prologue_end(0)
bd2b1e68
GH
901{
902 // Reduce the query to more reasonable semantic values (booleans,
903 // extracted strings, numbers, etc).
bd2b1e68
GH
904 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
905 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
906
907 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
908 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
909
0f336e95 910 has_label = get_string_param(params, TOK_LABEL, label_val);
c31add50
JL
911 has_callee = get_string_param(params, TOK_CALLEE, callee_val);
912 if (has_null_param(params, TOK_CALLEES))
913 { // .callees ==> .callees(1) (also equivalent to .callee("*"))
914 has_callees_num = true;
915 callees_num_val = 1;
916 }
917 else
918 {
919 has_callees_num = get_number_param(params, TOK_CALLEES, callees_num_val);
920 if (has_callees_num && callees_num_val < 1)
921 throw SEMANTIC_ERROR(_(".callees(N) only acceptable for N >= 1"),
922 base_probe->tok);
923 }
0f336e95 924
b8da0ad1 925 has_call = has_null_param(params, TOK_CALL);
4bda987e 926 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 927 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 928 has_return = has_null_param(params, TOK_RETURN);
c9bad430 929 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 930 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 931 has_mark = false;
37ebca01 932
bd2b1e68 933 if (has_function_str)
7d6d0afc 934 parse_function_spec(function_str_val);
bd2b1e68 935 else if (has_statement_str)
7d6d0afc 936 parse_function_spec(statement_str_val);
0daad364 937
5f0a03a6
JK
938 dbinfo_reqt = assess_dbinfo_reqt();
939 query_done = false;
0daad364
JS
940}
941
942
2c384610 943void
5f0a03a6 944dwarf_query::query_module_dwarf()
2c384610
DS
945{
946 if (has_function_num || has_statement_num)
947 {
948 // If we have module("foo").function(0xbeef) or
949 // module("foo").statement(0xbeef), the address is relative
950 // to the start of the module, so we seek the function
951 // number plus the module's bias.
6b517475
JS
952 Dwarf_Addr addr = has_function_num ?
953 function_num_val : statement_num_val;
08d1d520
MW
954
955 // These are raw addresses, we need to know what the elf_bias
956 // is to feed it to libdwfl based functions.
957 Dwarf_Addr elf_bias;
958 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
959 assert(elf);
960 addr += elf_bias;
6b517475 961 query_addr(addr, this);
2c384610
DS
962 }
963 else
964 {
965 // Otherwise if we have a function("foo") or statement("foo")
966 // specifier, we have to scan over all the CUs looking for
967 // the function(s) in question
968 assert(has_function_str || has_statement_str);
4df79aaf
JS
969
970 // For simple cases, no wildcard and no source:line, we can do a very
971 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
972 if (spec_type == function_alone &&
973 !dw.name_has_wildcard(function) &&
974 !startswith(function, "_Z"))
4df79aaf
JS
975 query_module_functions();
976 else
337b7c44 977 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
978 }
979}
980
5f0a03a6
JK
981static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
982 dwarf_query * q);
983
91bb9081
LB
984static void
985query_symtab_func_info (func_info & fi, dwarf_query * q)
986{
987 assert(null_die(&fi.die));
988
989 Dwarf_Addr addr = fi.addr;
990
991 // Now compensate for the dw bias because the addresses come
992 // from dwfl_module_symtab, so fi->addr is NOT a normal dw address.
993 q->dw.get_module_dwarf(false, false);
994 addr -= q->dw.module_bias;
995
996 // If there are already probes in this module, lets not duplicate.
997 // This can come from other weak symbols/aliases or existing
a41f2ad7
JS
998 // matches from Dwarf DIE functions. Try to add this addr to the
999 // collection, and only continue if it was new.
1000 if (q->alias_dupes.insert(addr).second)
1001 query_func_info(addr, fi, q);
91bb9081
LB
1002}
1003
5f0a03a6
JK
1004void
1005dwarf_query::query_module_symtab()
1006{
1007 // Get the symbol table if it's necessary, sufficient, and not already got.
1008 if (dbinfo_reqt == dbr_need_dwarf)
1009 return;
1010
1011 module_info *mi = dw.mod_info;
1012 if (dbinfo_reqt == dbr_need_symtab)
1013 {
1014 if (mi->symtab_status == info_unknown)
5f52fafe 1015 mi->get_symtab();
5f0a03a6
JK
1016 if (mi->symtab_status == info_absent)
1017 return;
1018 }
1019
1020 func_info *fi = NULL;
1021 symbol_table *sym_table = mi->sym_table;
1022
1023 if (has_function_str)
1024 {
1025 // Per dwarf_query::assess_dbinfo_reqt()...
1026 assert(spec_type == function_alone);
1027 if (dw.name_has_wildcard(function_str_val))
1028 {
2e67a43b 1029 symbol_table::iterator_t iter;
1c6b77e5
JS
1030 for (iter = sym_table->map_by_addr.begin();
1031 iter != sym_table->map_by_addr.end();
2e67a43b 1032 ++iter)
5f0a03a6 1033 {
1c6b77e5 1034 fi = iter->second;
5f0a03a6
JK
1035 if (!null_die(&fi->die))
1036 continue; // already handled in query_module_dwarf()
1037 if (dw.function_name_matches_pattern(fi->name, function_str_val))
91bb9081 1038 query_symtab_func_info(*fi, this);
5f0a03a6
JK
1039 }
1040 }
1041 else
1042 {
1043 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1044 if (fi && !fi->descriptor && null_die(&fi->die))
91bb9081 1045 query_symtab_func_info(*fi, this);
5f0a03a6 1046 }
5f0a03a6
JK
1047 }
1048}
1049
1050void
1051dwarf_query::handle_query_module()
1052{
f4faaf86
JS
1053 if (has_plt && has_statement_num)
1054 {
1055 query_plt_statement (this);
1056 return;
1057 }
1058
0035051e 1059 bool report = dbinfo_reqt == dbr_need_dwarf;
1c6b77e5
JS
1060 dw.get_module_dwarf(false, report);
1061
1062 // prebuild the symbol table to resolve aliases
5f52fafe 1063 dw.mod_info->get_symtab();
1c6b77e5 1064
857bdfd1
JS
1065 // reset the dupe-checking for each new module
1066 alias_dupes.clear();
7fdd3e2c 1067 inline_dupes.clear();
857bdfd1 1068
5f0a03a6
JK
1069 if (dw.mod_info->dwarf_status == info_present)
1070 query_module_dwarf();
1c6b77e5 1071
91bb9081
LB
1072 // Consult the symbol table, asm and weak functions can show up
1073 // in the symbol table but not in dwarf and minidebuginfo is
1074 // located in the gnu_debugdata section, alias_dupes checking
1075 // is done before adding any probe points
1076 if (!query_done && !pending_interrupts)
5f0a03a6
JK
1077 query_module_symtab();
1078}
1079
2c384610 1080
7d6d0afc
JS
1081void
1082dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1083{
4a81c0d9
JL
1084 lineno_type = ABSOLUTE;
1085 linenos[0] = linenos[1] = 0;
1d12a9b2 1086
91699a70 1087 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1088
7d6d0afc 1089 // look for named scopes
91699a70
JS
1090 scope_pos = spec.rfind("::");
1091 if (scope_pos != string::npos)
bd2b1e68 1092 {
91699a70
JS
1093 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1094 scope_pos += 2;
bd2b1e68 1095 }
91699a70
JS
1096 else
1097 scope_pos = 0;
bd2b1e68 1098
7d6d0afc
JS
1099 // look for a source separator
1100 src_pos = spec.find('@', scope_pos);
1101 if (src_pos == string::npos)
bd2b1e68 1102 {
7d6d0afc
JS
1103 function = spec.substr(scope_pos);
1104 spec_type = function_alone;
bd2b1e68 1105 }
7d6d0afc 1106 else
879eb9e9 1107 {
7d6d0afc 1108 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1109
7d6d0afc
JS
1110 // look for a line-number separator
1111 line_pos = spec.find_first_of(":+", src_pos);
1112 if (line_pos == string::npos)
1113 {
1114 file = spec.substr(src_pos + 1);
1115 spec_type = function_and_file;
1116 }
1117 else
1118 {
1119 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1120
1121 // classify the line spec
1122 spec_type = function_file_and_line;
1123 if (spec[line_pos] == '+')
4a81c0d9 1124 lineno_type = RELATIVE;
7d6d0afc
JS
1125 else if (spec[line_pos + 1] == '*' &&
1126 spec.length() == line_pos + 2)
4a81c0d9 1127 lineno_type = WILDCARD;
7d6d0afc 1128 else
4a81c0d9 1129 lineno_type = ABSOLUTE;
7d6d0afc 1130
4a81c0d9 1131 if (lineno_type != WILDCARD)
7d6d0afc
JS
1132 try
1133 {
1134 // try to parse either N or N-M
1135 dash_pos = spec.find('-', line_pos + 1);
1136 if (dash_pos == string::npos)
4a81c0d9 1137 linenos[0] = linenos[1] = lex_cast<int>(spec.substr(line_pos + 1));
7d6d0afc
JS
1138 else
1139 {
4a81c0d9
JL
1140 lineno_type = RANGE;
1141 linenos[0] = lex_cast<int>(spec.substr(line_pos + 1,
7d6d0afc 1142 dash_pos - line_pos - 1));
4a81c0d9
JL
1143 linenos[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1144 if (linenos[0] > linenos[1])
1145 throw runtime_error("bad range");
7d6d0afc
JS
1146 }
1147 }
1148 catch (runtime_error & exn)
1149 {
1150 goto bad;
1151 }
1152 }
bd2b1e68
GH
1153 }
1154
7d6d0afc
JS
1155 if (function.empty() ||
1156 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1157 goto bad;
1158
7d6d0afc 1159 if (sess.verbose > 2)
bd2b1e68 1160 {
b530b5b3
LB
1161 //clog << "parsed '" << spec << "'";
1162 clog << _F("parse '%s'", spec.c_str());
41c262f3 1163
7d6d0afc
JS
1164 if (!scopes.empty())
1165 clog << ", scope '" << scopes[0] << "'";
1166 for (unsigned i = 1; i < scopes.size(); ++i)
1167 clog << "::'" << scopes[i] << "'";
41c262f3 1168
7d6d0afc
JS
1169 clog << ", func '" << function << "'";
1170
1171 if (spec_type != function_alone)
1172 clog << ", file '" << file << "'";
1173
1174 if (spec_type == function_file_and_line)
1175 {
1176 clog << ", line ";
4a81c0d9 1177 switch (lineno_type)
7d6d0afc
JS
1178 {
1179 case ABSOLUTE:
4a81c0d9 1180 clog << linenos[0];
7d6d0afc
JS
1181 break;
1182
1183 case RELATIVE:
4a81c0d9 1184 clog << "+" << linenos[0];
7d6d0afc
JS
1185 break;
1186
1187 case RANGE:
4a81c0d9 1188 clog << linenos[0] << " - " << linenos[1];
7d6d0afc
JS
1189 break;
1190
1191 case WILDCARD:
1192 clog << "*";
1193 break;
1194 }
1195 }
1196
1197 clog << endl;
bd2b1e68
GH
1198 }
1199
7d6d0afc
JS
1200 return;
1201
1202bad:
dc09353a 1203 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1204 base_probe->tok);
bd2b1e68
GH
1205}
1206
05fb3e0c
WF
1207string path_remove_sysroot(const systemtap_session& sess, const string& path)
1208{
1209 size_t pos;
1210 string retval = path;
1211 if (!sess.sysroot.empty() &&
1212 (pos = retval.find(sess.sysroot)) != string::npos)
1213 retval.replace(pos, sess.sysroot.length(), "/");
1214 return retval;
1215}
bd2b1e68 1216
36f9dd1d 1217void
1ffb8bd1 1218dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1219 const char* filename,
36f9dd1d 1220 int line,
b20febf3 1221 Dwarf_Die* scope_die,
36f9dd1d
FCE
1222 Dwarf_Addr addr)
1223{
b20febf3 1224 string reloc_section; // base section for relocation purposes
27646582 1225 Dwarf_Addr reloc_addr; // relocated
b20febf3 1226 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1227 string funcname = dw_funcname;
36f9dd1d 1228
37ebca01
FCE
1229 assert (! has_absolute); // already handled in dwarf_builder::build()
1230
f4faaf86 1231 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1232
1ffb8bd1 1233 // If we originally used the linkage name, then let's call it that way
1ffb8bd1 1234 const char* linkage_name;
91bb9081 1235 if (!null_die(scope_die) && startswith (this->function, "_Z")
f450a7e3 1236 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1237 funcname = linkage_name;
1238
7f9f3386
FCE
1239 if (sess.verbose > 1)
1240 {
b530b5b3 1241 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1242 if (string(module) == TOK_KERNEL)
b530b5b3 1243 clog << _(" kernel");
91af0778 1244 else if (has_module)
b530b5b3 1245 clog << _(" module=") << module;
91af0778 1246 else if (has_process)
b530b5b3 1247 clog << _(" process=") << module;
b20febf3 1248 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1249 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1250 }
4baf0e53 1251
2f18e69b
JL
1252 dwflpp::blacklisted_type blacklisted = dw.blacklisted_p (funcname, filename,
1253 line, module, addr,
1254 has_return);
b20febf3
FCE
1255 if (sess.verbose > 1)
1256 clog << endl;
7f9f3386 1257
84048984
FCE
1258 if (module == TOK_KERNEL)
1259 {
1260 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1261 reloc_addr = addr - sess.sym_stext;
37ebca01 1262 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1263 }
1264
2f18e69b 1265 if (!blacklisted)
b20febf3 1266 {
1a0dbc5a 1267 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1268
1269 if (has_process)
1270 {
05fb3e0c 1271 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1272 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1273 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1274 *this, scope_die));
1275 }
1276 else
1277 {
1278 assert (has_kernel || has_module);
1279 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1280 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1281 *this, scope_die));
1282 }
b20febf3 1283 }
2f18e69b
JL
1284 else
1285 {
1286 switch (blacklisted)
1287 {
1288 case dwflpp::blacklisted_section:
1289 sess.print_warning(_F("function %s is in blacklisted section",
1290 funcname.c_str()), base_probe->tok);
1291 break;
1292 case dwflpp::blacklisted_kprobes:
1293 sess.print_warning(_F("kprobes function %s is blacklisted",
1294 funcname.c_str()), base_probe->tok);
1295 break;
1296 case dwflpp::blacklisted_function_return:
1297 sess.print_warning(_F("function %s return probe is blacklisted",
1298 funcname.c_str()), base_probe->tok);
1299 break;
1300 case dwflpp::blacklisted_file:
1301 sess.print_warning(_F("function %s is in blacklisted file",
1302 funcname.c_str()), base_probe->tok);
1303 break;
1304 case dwflpp::blacklisted_function:
1305 default:
1306 sess.print_warning(_F("function %s is blacklisted",
1307 funcname.c_str()), base_probe->tok);
1308 break;
1309 }
1310 }
2930abc7
FCE
1311}
1312
613c8675
JL
1313void
1314dwarf_query::mount_well_formed_probe_point()
1315{
1316 string module = dw.module_name;
1317 if (has_process)
1318 module = path_remove_sysroot(sess, module);
1319
1320 vector<probe_point::component*> comps;
1321 vector<probe_point::component*>::iterator it;
1322 for (it = base_loc->components.begin();
1323 it != base_loc->components.end(); ++it)
1324 {
1325 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1326 comps.push_back(new probe_point::component((*it)->functor,
1327 new literal_string(has_library ? path : module)));
1328 else
1329 comps.push_back(*it);
1330 }
1331
1332 probe_point *pp = new probe_point(*base_loc);
1333 pp->well_formed = true;
1334 pp->components = comps;
1335
1336 previous_bases.push(make_pair(base_loc, base_probe));
1337
1338 base_loc = pp;
1339 base_probe = new probe(base_probe, pp);
1340}
1341
1342void
1343dwarf_query::unmount_well_formed_probe_point()
1344{
1345 assert(!previous_bases.empty());
1346
1347 base_loc = previous_bases.top().first;
1348 base_probe = previous_bases.top().second;
1349
1350 previous_bases.pop();
1351}
1352
71dfce11
JL
1353void
1354dwarf_query::replace_probe_point_component_arg(const string& functor,
1355 const string& new_functor,
1356 int64_t new_arg,
1357 bool hex)
1358{
1359 // only allow these operations if we're editing the well-formed loc
1360 assert(!previous_bases.empty());
1361
1362 vector<probe_point::component*>::iterator it;
1363 for (it = base_loc->components.begin();
1364 it != base_loc->components.end(); ++it)
1365 if ((*it)->functor == functor)
1366 *it = new probe_point::component(new_functor,
1367 new literal_number(new_arg, hex));
1368}
1369
1370void
1371dwarf_query::replace_probe_point_component_arg(const string& functor,
1372 int64_t new_arg,
1373 bool hex)
1374{
1375 replace_probe_point_component_arg(functor, functor, new_arg, hex);
1376}
1377
1378void
1379dwarf_query::replace_probe_point_component_arg(const string& functor,
1380 const string& new_functor,
1381 const string& new_arg)
1382{
1383 // only allow these operations if we're editing the well-formed loc
1384 assert(!previous_bases.empty());
1385
1386 vector<probe_point::component*>::iterator it;
1387 for (it = base_loc->components.begin();
1388 it != base_loc->components.end(); ++it)
1389 if ((*it)->functor == functor)
1390 *it = new probe_point::component(new_functor,
1391 new literal_string(new_arg));
1392}
1393
1394void
1395dwarf_query::replace_probe_point_component_arg(const string& functor,
1396 const string& new_arg)
1397{
1398 replace_probe_point_component_arg(functor, functor, new_arg);
1399}
1400
1401void
1402dwarf_query::remove_probe_point_component(const string& functor)
1403{
1404 // only allow these operations if we're editing the well-formed loc
1405 assert(!previous_bases.empty());
1406
1407 vector<probe_point::component*> new_comps;
1408 vector<probe_point::component*>::iterator it;
1409 for (it = base_loc->components.begin();
1410 it != base_loc->components.end(); ++it)
1411 if ((*it)->functor != functor)
1412 new_comps.push_back(*it);
1413
1414 base_loc->components = new_comps;
1415}
1416
5f0a03a6
JK
1417enum dbinfo_reqt
1418dwarf_query::assess_dbinfo_reqt()
1419{
1420 if (has_absolute)
1421 {
1422 // kernel.statement(NUM).absolute
1423 return dbr_none;
1424 }
c31add50 1425 if (has_inline || has_label || has_callee || has_callees_num)
5f0a03a6
JK
1426 {
1427 // kernel.function("f").inline or module("m").function("f").inline
1428 return dbr_need_dwarf;
1429 }
1430 if (has_function_str && spec_type == function_alone)
1431 {
1432 // kernel.function("f") or module("m").function("f")
1433 return dbr_need_symtab;
1434 }
1435 if (has_statement_num)
1436 {
1437 // kernel.statement(NUM) or module("m").statement(NUM)
1438 // Technically, all we need is the module offset (or _stext, for
1439 // the kernel). But for that we need either the ELF file or (for
1440 // _stext) the symbol table. In either case, the symbol table
1441 // is available, and that allows us to map the NUM (address)
1442 // to a function, which is goodness.
1443 return dbr_need_symtab;
1444 }
1445 if (has_function_num)
1446 {
1447 // kernel.function(NUM) or module("m").function(NUM)
1448 // Need the symbol table so we can back up from NUM to the
1449 // start of the function.
1450 return dbr_need_symtab;
1451 }
1452 // Symbol table tells us nothing about source files or line numbers.
1453 return dbr_need_dwarf;
1454}
2930abc7 1455
e772a6e7
JL
1456string
1457dwarf_query::final_function_name(const string& final_func,
79954c0f 1458 const char* final_file,
e772a6e7
JL
1459 int final_line)
1460{
1461 string final_name = final_func;
79954c0f 1462 if (final_file && *final_file != '\0')
e772a6e7 1463 {
79954c0f 1464 final_name += ("@" + string(final_file));
e772a6e7
JL
1465 if (final_line > 0)
1466 final_name += (":" + lex_cast(final_line));
1467 }
1468 return final_name;
1469}
2930abc7 1470
959ccfed
JL
1471base_func_info_map_t
1472dwarf_query::filtered_all(void)
1473{
1474 vector<base_func_info> r;
1475 func_info_map_t::const_iterator f;
1476 for (f = filtered_functions.begin();
1477 f != filtered_functions.end(); ++f)
1478 r.push_back(*f);
1479 inline_instance_map_t::const_iterator i;
1480 for (i = filtered_inlines.begin();
1481 i != filtered_inlines.end(); ++i)
1482 r.push_back(*i);
1483 return r;
1484}
1485
b8da0ad1
FCE
1486// The critical determining factor when interpreting a pattern
1487// string is, perhaps surprisingly: "presence of a lineno". The
1488// presence of a lineno changes the search strategy completely.
1489//
1490// Compare the two cases:
1491//
1492// 1. {statement,function}(foo@file.c:lineno)
1493// - find the files matching file.c
1494// - in each file, find the functions matching foo
1495// - query the file for line records matching lineno
1496// - iterate over the line records,
1497// - and iterate over the functions,
1498// - if(haspc(function.DIE, line.addr))
1499// - if looking for statements: probe(lineno.addr)
1500// - if looking for functions: probe(function.{entrypc,return,etc.})
1501//
1502// 2. {statement,function}(foo@file.c)
1503// - find the files matching file.c
1504// - in each file, find the functions matching foo
1505// - probe(function.{entrypc,return,etc.})
1506//
1507// Thus the first decision we make is based on the presence of a
1508// lineno, and we enter entirely different sets of callbacks
1509// depending on that decision.
1510//
1511// Note that the first case is a generalization fo the second, in that
1512// we could theoretically search through line records for matching
1513// file names (a "table scan" in rdbms lingo). Luckily, file names
1514// are already cached elsewhere, so we can do an "index scan" as an
1515// optimization.
7e1279ea 1516
bd2b1e68 1517static void
4cd232e4 1518query_statement (string const & func,
20e4a32c 1519 char const * file,
4cd232e4 1520 int line,
bcc12710 1521 Dwarf_Die *scope_die,
20e4a32c 1522 Dwarf_Addr stmt_addr,
4cd232e4 1523 dwarf_query * q)
bd2b1e68 1524{
39bcd429
FCE
1525 try
1526 {
cee35f73 1527 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1528 line, scope_die, stmt_addr);
39bcd429
FCE
1529 }
1530 catch (const semantic_error& e)
1531 {
1532 q->sess.print_error (e);
1533 }
bd2b1e68
GH
1534}
1535
6b517475
JS
1536static void
1537query_addr(Dwarf_Addr addr, dwarf_query *q)
1538{
7a71819c
JL
1539 assert(q->has_function_num || q->has_statement_num);
1540
6b517475
JS
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
7a71819c
JL
1649 // We're ready to build a probe, but before, we need to create the final,
1650 // well-formed version of this location with all the components filled in
1651 q->mount_well_formed_probe_point();
1652 q->replace_probe_point_component_arg(TOK_FUNCTION, addr, true /* hex */ );
1653 q->replace_probe_point_component_arg(TOK_STATEMENT, addr, true /* hex */ );
1654
6b517475
JS
1655 // Build a probe at this point
1656 query_statement(dw.function_name, file, line, scope, addr, q);
7a71819c
JL
1657
1658 q->unmount_well_formed_probe_point();
6b517475
JS
1659}
1660
f4faaf86
JS
1661static void
1662query_plt_statement(dwarf_query *q)
1663{
1664 assert (q->has_plt && q->has_statement_num);
1665
1666 Dwarf_Addr addr = q->statement_num_val;
1667 if (q->sess.verbose > 2)
1668 clog << "query_plt_statement 0x" << hex << addr << dec << endl;
1669
1670 // First adjust the raw address to dwfl's elf bias.
1671 Dwarf_Addr elf_bias;
1672 Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
1673 assert(elf);
1674 addr += elf_bias;
1675
1676 // Now compensate for the dw bias
1677 q->dw.get_module_dwarf(false, false);
1678 addr -= q->dw.module_bias;
1679
93b44c2a
JL
1680 // Create the final well-formed probe point
1681 q->mount_well_formed_probe_point();
1682 q->replace_probe_point_component_arg(TOK_STATEMENT, q->statement_num_val, true /* hex */ );
1683
1684 // We remove the .plt part here, since if the user provided a .plt probe, then
1685 // the higher-level probe point is already well-formed. On the other hand, if
1686 // the user provides a .plt(PATTERN).statement(0xABCD), the PATTERN is
1687 // irrelevant (we won't iterate over plts) so just take it out.
1688 q->remove_probe_point_component(TOK_PLT);
1689
f4faaf86
JS
1690 // Build a probe at this point
1691 query_statement(q->plt_val, NULL, -1, NULL, addr, q);
93b44c2a
JL
1692
1693 q->unmount_well_formed_probe_point();
f4faaf86
JS
1694}
1695
8096dd7d 1696static void
600d39f1 1697query_label (const base_func_info& func,
8096dd7d
JS
1698 char const * label,
1699 char const * file,
1700 int line,
1701 Dwarf_Die *scope_die,
1702 Dwarf_Addr stmt_addr,
1703 dwarf_query * q)
1704{
6b517475
JS
1705 assert (q->has_statement_str || q->has_function_str);
1706
8096dd7d
JS
1707 // weed out functions whose decl_file isn't one of
1708 // the source files that we actually care about
6b517475 1709 if (q->spec_type != function_alone &&
8096dd7d
JS
1710 q->filtered_srcfiles.count(file) == 0)
1711 return;
1712
cdabbe86 1713 // Create the final well-formed probe
600d39f1 1714 string canon_func = q->final_function_name(func.name, file, line);
9891c543 1715
cdabbe86
JL
1716 q->mount_well_formed_probe_point();
1717 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
1718 q->replace_probe_point_component_arg(TOK_LABEL, label);
8096dd7d 1719
600d39f1 1720 query_statement(func.name, file, line, scope_die, stmt_addr, q);
9891c543 1721
cdabbe86 1722 q->unmount_well_formed_probe_point();
8096dd7d
JS
1723}
1724
67959c62 1725static void
e772a6e7
JL
1726query_callee (base_func_info& callee,
1727 base_func_info& caller,
67959c62
JL
1728 stack<Dwarf_Addr> *callers,
1729 dwarf_query * q)
1730{
1731 assert (q->has_function_str);
e772a6e7
JL
1732 assert (q->has_callee || q->has_callees_num);
1733
1734 // OK, we found a callee for a targeted caller. To help users see the
04a89a2a 1735 // derivation, we add the well-formed form .function(caller).callee(callee).
e772a6e7 1736
e772a6e7
JL
1737 string canon_caller = q->final_function_name(caller.name, caller.decl_file,
1738 caller.decl_line);
1739 string canon_callee = q->final_function_name(callee.name, callee.decl_file,
1740 callee.decl_line);
1741
04a89a2a
JL
1742 q->mount_well_formed_probe_point();
1743 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_caller);
1744 q->replace_probe_point_component_arg(TOK_CALLEES, TOK_CALLEE, canon_callee);
1745 q->replace_probe_point_component_arg(TOK_CALLEE, canon_callee);
e772a6e7
JL
1746
1747 // Pass on the callers we'll need to add checks for
04a89a2a 1748 q->callers = callers;
e772a6e7
JL
1749
1750 query_statement(callee.name, callee.decl_file, callee.decl_line,
04a89a2a
JL
1751 &callee.die, callee.entrypc, q);
1752
1753 q->unmount_well_formed_probe_point();
67959c62
JL
1754}
1755
7e1279ea 1756static void
3e961ba6 1757query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1758 dwarf_query * q)
1759{
b6581717 1760 try
7e1279ea 1761 {
8f14e444 1762 assert (! q->has_return); // checked by caller already
8debd4e7
JL
1763 assert (q->has_function_str || q->has_statement_str);
1764
8f14e444 1765 if (q->sess.verbose>2)
b530b5b3
LB
1766 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1767 ii.entrypc, ii.name.c_str());
8debd4e7
JL
1768
1769 string canon_func = q->final_function_name(ii.name, ii.decl_file,
1770 ii.decl_line);
1771
1772 q->mount_well_formed_probe_point();
1773 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
1774 q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
1775
8f14e444
FCE
1776 query_statement (ii.name, ii.decl_file, ii.decl_line,
1777 &ii.die, ii.entrypc, q);
8debd4e7
JL
1778
1779 q->unmount_well_formed_probe_point();
7e1279ea 1780 }
b6581717 1781 catch (semantic_error &e)
7e1279ea 1782 {
b6581717 1783 q->sess.print_error (e);
7e1279ea
FCE
1784 }
1785}
1786
1787static void
1788query_func_info (Dwarf_Addr entrypc,
bcc12710 1789 func_info & fi,
7e1279ea
FCE
1790 dwarf_query * q)
1791{
e5745975
JL
1792 assert(q->has_function_str || q->has_statement_str);
1793
b6581717 1794 try
7e1279ea 1795 {
e5745975
JL
1796 string canon_func = q->final_function_name(fi.name, fi.decl_file,
1797 fi.decl_line);
1798
1799 q->mount_well_formed_probe_point();
1800 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
1801 q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
1802
5a617dc6
JL
1803 // If it's a .return probe, we need to emit a *retprobe based on the
1804 // entrypc (PR13200). Note however that if prologue_end is valid,
1805 // dwarf_derived_probe will still take advantage of it by creating a new
1806 // probe there if necessary to pick up target vars (PR14436).
1807 if (fi.prologue_end == 0 || q->has_return)
1808 {
170ccf10 1809 q->prologue_end = fi.prologue_end;
5a617dc6
JL
1810 query_statement (fi.name, fi.decl_file, fi.decl_line,
1811 &fi.die, entrypc, q);
1812 }
b6581717 1813 else
5a617dc6 1814 {
5a617dc6
JL
1815 query_statement (fi.name, fi.decl_file, fi.decl_line,
1816 &fi.die, fi.prologue_end, q);
1817 }
e5745975
JL
1818
1819 q->unmount_well_formed_probe_point();
7e1279ea 1820 }
b6581717 1821 catch (semantic_error &e)
7e1279ea 1822 {
b6581717 1823 q->sess.print_error (e);
7e1279ea
FCE
1824 }
1825}
1826
7e1279ea 1827static void
de797211 1828query_srcfile_line (Dwarf_Addr addr, int lineno, dwarf_query * q)
7e1279ea 1829{
8fb810d7
JL
1830 assert (q->has_statement_str || q->has_function_str);
1831 assert (q->spec_type == function_file_and_line);
1832
959ccfed
JL
1833 base_func_info_map_t bfis = q->filtered_all();
1834 base_func_info_map_t::iterator i;
1835 for (i = bfis.begin(); i != bfis.end(); ++i)
897820ca 1836 {
3e961ba6 1837 if (q->dw.die_has_pc (i->die, addr))
959ccfed
JL
1838 {
1839 if (q->sess.verbose>3)
1840 clog << _("filtered DIE lands on srcfile\n");
1841 Dwarf_Die scope;
1842 q->dw.inner_die_containing_pc(i->die, addr, scope);
e5bc2e52
JL
1843
1844 string canon_func = q->final_function_name(i->name, i->decl_file,
1845 lineno /* NB: not i->decl_line */ );
1846
1847 q->mount_well_formed_probe_point();
1848 q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
1849 q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
1850
959ccfed
JL
1851 query_statement (i->name, i->decl_file,
1852 lineno, // NB: not q->line !
1853 &scope, addr, q);
e5bc2e52
JL
1854
1855 q->unmount_well_formed_probe_point();
959ccfed 1856 }
20e4a32c 1857 }
7e1279ea
FCE
1858}
1859
7fdd3e2c
JS
1860bool
1861inline_instance_info::operator<(const inline_instance_info& other) const
1862{
1863 if (entrypc != other.entrypc)
1864 return entrypc < other.entrypc;
1865
1866 if (decl_line != other.decl_line)
1867 return decl_line < other.decl_line;
1868
1869 int cmp = name.compare(other.name);
c60517ca
FCE
1870
1871 if (!cmp)
1872 {
1873 assert (decl_file);
1874 assert (other.decl_file);
1875 cmp = strcmp(decl_file, other.decl_file);
1876 }
1877
7fdd3e2c
JS
1878 return cmp < 0;
1879}
1880
1881
4fa7b22b 1882static int
3956fccb 1883query_dwarf_inline_instance (Dwarf_Die * die, dwarf_query * q)
4fa7b22b 1884{
6b517475 1885 assert (q->has_statement_str || q->has_function_str);
4bda987e 1886 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1887
39bcd429 1888 try
7a053d3b 1889 {
b0ee93c4 1890 if (q->sess.verbose>2)
b530b5b3 1891 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1892
6b517475
JS
1893 Dwarf_Addr entrypc;
1894 if (q->dw.die_entrypc (die, &entrypc))
1895 {
1896 inline_instance_info inl;
1897 inl.die = *die;
1898 inl.name = q->dw.function_name;
1899 inl.entrypc = entrypc;
1900 q->dw.function_file (&inl.decl_file);
1901 q->dw.function_line (&inl.decl_line);
1902
1903 // make sure that this inline hasn't already
1904 // been matched from a different CU
1905 if (q->inline_dupes.insert(inl).second)
1906 q->filtered_inlines.push_back(inl);
1907 }
7e1279ea
FCE
1908 return DWARF_CB_OK;
1909 }
1910 catch (const semantic_error& e)
1911 {
1912 q->sess.print_error (e);
1913 return DWARF_CB_ABORT;
1914 }
1915}
bb788f9f 1916
7e1279ea 1917static int
7d007451 1918query_dwarf_func (Dwarf_Die * func, dwarf_query * q)
7e1279ea 1919{
6b517475 1920 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1921
bd25380d
JS
1922 // weed out functions whose decl_file isn't one of
1923 // the source files that we actually care about
6b517475 1924 if (q->spec_type != function_alone &&
bd25380d 1925 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1926 return DWARF_CB_OK;
bd25380d 1927
7e1279ea
FCE
1928 try
1929 {
7e1279ea
FCE
1930 q->dw.focus_on_function (func);
1931
7d6d0afc
JS
1932 if (!q->dw.function_scope_matches(q->scopes))
1933 return DWARF_CB_OK;
1934
857bdfd1
JS
1935 // make sure that this function address hasn't
1936 // already been matched under an aliased name
1937 Dwarf_Addr addr;
1938 if (!q->dw.func_is_inline() &&
1939 dwarf_entrypc(func, &addr) == 0 &&
1940 !q->alias_dupes.insert(addr).second)
1941 return DWARF_CB_OK;
1942
4bda987e 1943 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1944 {
4bda987e 1945 if (q->sess.verbose>3)
b530b5b3 1946 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1947 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1948 }
8f14e444
FCE
1949 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1950 {
1951 q->inlined_non_returnable.insert (q->dw.function_name);
1952 }
396afcee 1953 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1954 {
4bda987e
SC
1955 if (q->has_exported && !q->dw.func_is_exported ())
1956 return DWARF_CB_OK;
6b517475 1957 if (q->sess.verbose>2)
b530b5b3 1958 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1959
1960 func_info func;
1961 q->dw.function_die (&func.die);
1962 func.name = q->dw.function_name;
1963 q->dw.function_file (&func.decl_file);
1964 q->dw.function_line (&func.decl_line);
1965
1966 Dwarf_Addr entrypc;
1967 if (q->dw.function_entrypc (&entrypc))
1968 {
1969 func.entrypc = entrypc;
1970 q->filtered_functions.push_back (func);
1971 }
1972 /* else this function is fully inlined, just ignore it */
7e1279ea 1973 }
39bcd429 1974 return DWARF_CB_OK;
bd2b1e68 1975 }
39bcd429 1976 catch (const semantic_error& e)
bd2b1e68 1977 {
39bcd429
FCE
1978 q->sess.print_error (e);
1979 return DWARF_CB_ABORT;
bd2b1e68 1980 }
bd2b1e68
GH
1981}
1982
1983static int
5c378838 1984query_cu (Dwarf_Die * cudie, dwarf_query * q)
bd2b1e68 1985{
6b517475
JS
1986 assert (q->has_statement_str || q->has_function_str);
1987
85007c04 1988 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1989
39bcd429 1990 try
bd2b1e68 1991 {
7e1279ea 1992 q->dw.focus_on_cu (cudie);
b5d77020 1993
b0ee93c4 1994 if (false && q->sess.verbose>2)
b530b5b3
LB
1995 clog << _F("focused on CU '%s', in module '%s'\n",
1996 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1997
6b517475
JS
1998 q->filtered_srcfiles.clear();
1999 q->filtered_functions.clear();
2000 q->filtered_inlines.clear();
2001
2002 // In this path, we find "abstract functions", record
2003 // information about them, and then (depending on lineno
2004 // matching) possibly emit one or more of the function's
2005 // associated addresses. Unfortunately the control of this
2006 // cannot easily be turned inside out.
2007
2008 if (q->spec_type != function_alone)
39bcd429 2009 {
6b517475
JS
2010 // If we have a pattern string with a filename, we need
2011 // to elaborate the srcfile mask in question first.
2012 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
2013
2014 // If we have a file pattern and *no* srcfile matches, there's
2015 // no need to look further into this CU, so skip.
2016 if (q->filtered_srcfiles.empty())
2017 return DWARF_CB_OK;
2018 }
e4c58386 2019
6b517475
JS
2020 // Pick up [entrypc, name, DIE] tuples for all the functions
2021 // matching the query, and fill in the prologue endings of them
2022 // all in a single pass.
5898b6e1 2023 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
2024 if (rc != DWARF_CB_OK)
2025 q->query_done = true;
2026
277a2b96
JL
2027 if (!q->filtered_functions.empty() &&
2028 !q->has_statement_str && // PR 2608
2029 (q->sess.prologue_searching ||
2030 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
2031 q->dw.resolve_prologue_endings (q->filtered_functions);
6b517475 2032
600d39f1 2033 if (q->has_label)
6b517475 2034 {
600d39f1
JL
2035 enum lineno_t lineno_type = WILDCARD;
2036 if (q->spec_type == function_file_and_line)
2037 lineno_type = q->lineno_type;
959ccfed
JL
2038 base_func_info_map_t bfis = q->filtered_all();
2039 base_func_info_map_t::iterator i;
2040 for (i = bfis.begin(); i != bfis.end(); ++i)
600d39f1
JL
2041 q->dw.iterate_over_labels (&i->die, q->label_val, *i, q->linenos,
2042 lineno_type, q, query_label);
39bcd429 2043 }
67959c62
JL
2044 else if (q->has_callee || q->has_callees_num)
2045 {
2046 // .callee(str) --> str, .callees[(N)] --> "*"
2047 string callee_val = q->has_callee ? q->callee_val : "*";
2048 long callees_num_val = q->has_callees_num ? q->callees_num_val : 1;
2049
2050 // NB: We filter functions that do not match the file here rather than
2051 // in query_callee because we only want the filtering to apply to the
2052 // first level, not to callees that are recursed into if
2053 // callees_num_val > 1.
959ccfed
JL
2054 base_func_info_map_t bfis = q->filtered_all();
2055 base_func_info_map_t::iterator i;
2056 for (i = bfis.begin(); i != bfis.end(); ++i)
67959c62
JL
2057 {
2058 if (q->spec_type != function_alone &&
2059 q->filtered_srcfiles.count(i->decl_file) == 0)
2060 continue;
2061 q->dw.iterate_over_callees (&i->die, callee_val,
2062 callees_num_val,
e772a6e7 2063 q, query_callee, *i);
67959c62
JL
2064 }
2065 }
600d39f1
JL
2066 else if (q->spec_type == function_file_and_line)
2067 {
2068 // .statement(...:NN) often gets mixed up with .function(...:NN)
2069 if (q->has_function_str)
2070 q->sess.print_warning (_("For probing a particular line, use a "
2071 ".statement() probe, not .function()"),
2072 q->base_probe->tok);
2073
2074 base_func_info_map_t bfis = q->filtered_all();
2075
2076 set<string>::const_iterator srcfile;
2077 for (srcfile = q->filtered_srcfiles.begin();
2078 srcfile != q->filtered_srcfiles.end(); ++srcfile)
2079 q->dw.iterate_over_srcfile_lines(srcfile->c_str(), q->linenos,
2080 q->lineno_type, bfis,
2081 query_srcfile_line, q);
2082 }
6b517475
JS
2083 else
2084 {
2085 // Otherwise, simply probe all resolved functions.
2086 for (func_info_map_t::iterator i = q->filtered_functions.begin();
2087 i != q->filtered_functions.end(); ++i)
2088 query_func_info (i->entrypc, *i, q);
2089
2090 // And all inline instances (if we're not excluding inlines with ".call")
2091 if (! q->has_call)
2092 for (inline_instance_map_t::iterator i
2093 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
2094 query_inline_instance_info (*i, q);
e772a6e7 2095 }
39bcd429 2096 return DWARF_CB_OK;
bd2b1e68 2097 }
39bcd429 2098 catch (const semantic_error& e)
bd2b1e68 2099 {
39bcd429
FCE
2100 q->sess.print_error (e);
2101 return DWARF_CB_ABORT;
bd2b1e68 2102 }
bd2b1e68
GH
2103}
2104
0ce64fb8 2105
4df79aaf
JS
2106void
2107dwarf_query::query_module_functions ()
2108{
2109 try
2110 {
2111 filtered_srcfiles.clear();
2112 filtered_functions.clear();
2113 filtered_inlines.clear();
2114
2115 // Collect all module functions so we know which CUs are interesting
2116 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
2117 if (rc != DWARF_CB_OK)
2118 {
2119 query_done = true;
2120 return;
2121 }
2122
2123 set<void*> used_cus; // by cu->addr
2124 vector<Dwarf_Die> cus;
2125 Dwarf_Die cu_mem;
2126
959ccfed
JL
2127 base_func_info_map_t bfis = filtered_all();
2128 base_func_info_map_t::iterator i;
2129 for (i = bfis.begin(); i != bfis.end(); ++i)
4df79aaf
JS
2130 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
2131 used_cus.insert(cu_mem.addr).second)
2132 cus.push_back(cu_mem);
2133
2134 // Reset the dupes since we didn't actually collect them the first time
2135 alias_dupes.clear();
2136 inline_dupes.clear();
2137
2138 // Run the query again on the individual CUs
91bb9081
LB
2139 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i){
2140 rc = query_cu(&*i, this);
2141 if (rc != DWARF_CB_OK)
2142 {
2143 query_done = true;
2144 return;
2145 }
2146 }
4df79aaf
JS
2147 }
2148 catch (const semantic_error& e)
2149 {
2150 sess.print_error (e);
2151 }
2152}
2153
2154
5f0a03a6
JK
2155static void
2156validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
2157{
2158 // Validate the machine code in this elf file against the
2159 // session machine. This is important, in case the wrong kind
2160 // of debuginfo is being automagically processed by elfutils.
2161 // While we can tell i686 apart from x86-64, unfortunately
2162 // we can't help confusing i586 vs i686 (both EM_386).
2163
2164 Dwarf_Addr bias;
2165 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
2166 // because dwfl_module_getelf can force costly section relocations
2167 // we don't really need, while either will do for this purpose.
2168 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
2169 ?: dwfl_module_getelf (mod, &bias));
2170
2171 GElf_Ehdr ehdr_mem;
2172 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 2173 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 2174 assert(em);
5f0a03a6
JK
2175 int elf_machine = em->e_machine;
2176 const char* debug_filename = "";
2177 const char* main_filename = "";
2178 (void) dwfl_module_info (mod, NULL, NULL,
2179 NULL, NULL, NULL,
2180 & main_filename,
2181 & debug_filename);
2182 const string& sess_machine = q->sess.architecture;
756c9462
FCE
2183
2184 string expect_machine; // to match sess.machine (i.e., kernel machine)
2185 string expect_machine2;
5f0a03a6 2186
d27e6fd5 2187 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
2188 switch (elf_machine)
2189 {
756c9462
FCE
2190 // x86 and ppc are bi-architecture; a 64-bit kernel
2191 // can normally run either 32-bit or 64-bit *userspace*.
2192 case EM_386:
2193 expect_machine = "i?86";
2194 if (! q->has_process) break; // 32-bit kernel/module
2195 /* FALLSTHROUGH */
2196 case EM_X86_64:
2197 expect_machine2 = "x86_64";
2198 break;
2199 case EM_PPC:
756c9462 2200 case EM_PPC64:
5a1c472e 2201 expect_machine = "powerpc";
756c9462 2202 break;
3fe7d888 2203 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2204 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2205 case EM_ARM: expect_machine = "arm*"; break;
86aae990 2206 case EM_AARCH64: expect_machine = "arm64"; break;
5f0a03a6
JK
2207 // XXX: fill in some more of these
2208 default: expect_machine = "?"; break;
2209 }
2210
2211 if (! debug_filename) debug_filename = main_filename;
2212 if (! debug_filename) debug_filename = name;
2213
756c9462
FCE
2214 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2215 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2216 {
2217 stringstream msg;
b530b5b3
LB
2218 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2219 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2220 sess_machine.c_str(), debug_filename);
dc09353a 2221 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2222 }
2223
b57082de 2224 if (q->sess.verbose>1)
b78a0fbb 2225 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2226 " file %s ELF machine %s|%s (code %d)\n",
2227 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2228 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2229 expect_machine2.c_str(), elf_machine);
5f0a03a6 2230}
1d3a40b6 2231
91af0778
FCE
2232
2233
2234static Dwarf_Addr
2235lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2236{
2237 int syments = dwfl_module_getsymtab(m);
2238 assert(syments);
2239 for (int i = 1; i < syments; ++i)
2240 {
2241 GElf_Sym sym;
2242 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2243 if (name != NULL && strcmp(name, wanted) == 0)
2244 return sym.st_value;
2245 }
2246
2247 return 0;
2248}
2249
2250
2251
bd2b1e68 2252static int
b8da0ad1 2253query_module (Dwfl_Module *mod,
91af0778 2254 void **,
b8da0ad1 2255 const char *name,
6f4c1275 2256 Dwarf_Addr addr,
06de3a04 2257 base_query *q)
bd2b1e68 2258{
39bcd429 2259 try
e38d6504 2260 {
91af0778
FCE
2261 module_info* mi = q->sess.module_cache->cache[name];
2262 if (mi == 0)
2263 {
2264 mi = q->sess.module_cache->cache[name] = new module_info(name);
2265
6f4c1275
FCE
2266 mi->mod = mod;
2267 mi->addr = addr;
91af0778 2268
6f4c1275
FCE
2269 const char* debug_filename = "";
2270 const char* main_filename = "";
2271 (void) dwfl_module_info (mod, NULL, NULL,
2272 NULL, NULL, NULL,
2273 & main_filename,
2274 & debug_filename);
2275
ab3ed72d 2276 if (debug_filename || main_filename)
91af0778 2277 {
6f4c1275
FCE
2278 mi->elf_path = debug_filename ?: main_filename;
2279 }
2280 else if (name == TOK_KERNEL)
2281 {
2282 mi->dwarf_status = info_absent;
91af0778 2283 }
91af0778
FCE
2284 }
2285 // OK, enough of that module_info caching business.
2286
5f0a03a6 2287 q->dw.focus_on_module(mod, mi);
d9b516ca 2288
39bcd429
FCE
2289 // If we have enough information in the pattern to skip a module and
2290 // the module does not match that information, return early.
b8da0ad1 2291 if (!q->dw.module_name_matches(q->module_val))
85007c04 2292 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2293
2294 // Don't allow module("*kernel*") type expressions to match the
2295 // elfutils module "kernel", which we refer to in the probe
2296 // point syntax exclusively as "kernel.*".
2297 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2298 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2299
5f0a03a6
JK
2300 if (mod)
2301 validate_module_elf(mod, name, q);
2302 else
91af0778
FCE
2303 assert(q->has_kernel); // and no vmlinux to examine
2304
2305 if (q->sess.verbose>2)
b530b5b3 2306 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2307
2308
2309 // Collect a few kernel addresses. XXX: these belong better
2310 // to the sess.module_info["kernel"] struct.
2311 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2312 {
91af0778
FCE
2313 if (! q->sess.sym_kprobes_text_start)
2314 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2315 if (! q->sess.sym_kprobes_text_end)
2316 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2317 if (! q->sess.sym_stext)
2318 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2319 }
2320
dbe9d133
JL
2321 // If there is a .library component, then q->path will hold the path to
2322 // the executable if the library was fully resolved. If not (e.g. not
2323 // absolute, or globby), resort to iterate_over_libraries().
2324 if (q->has_library && q->path.empty())
84c84ac4 2325 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2326 // .plt is translated to .plt.statement(N). We only want to iterate for the
2327 // .plt case
2328 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2329 {
2330 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2331 q->visited_modules.insert(name);
2332 }
84c84ac4 2333 else
070764c0
JL
2334 {
2335 // search the module for matches of the probe point.
2336 q->handle_query_module();
2337 q->visited_modules.insert(name);
2338 }
bb788f9f 2339
b8da0ad1 2340 // If we know that there will be no more matches, abort early.
85007c04 2341 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2342 return DWARF_CB_ABORT;
2343 else
2344 return DWARF_CB_OK;
7a053d3b 2345 }
39bcd429 2346 catch (const semantic_error& e)
bd2b1e68 2347 {
39bcd429
FCE
2348 q->sess.print_error (e);
2349 return DWARF_CB_ABORT;
bd2b1e68 2350 }
bd2b1e68
GH
2351}
2352
35d4ab18 2353
84c84ac4 2354void
bbbc7241 2355base_query::query_library_callback (base_query *me, const char *data)
84c84ac4 2356{
5d5bd369 2357 me->query_library (data);
84c84ac4
SC
2358}
2359
2360
2cbcfa9c 2361string
51d6bda3
SC
2362query_one_library (const char *library, dwflpp & dw,
2363 const string user_lib, probe * base_probe, probe_point *base_loc,
2364 vector<derived_probe *> & results)
84c84ac4 2365{
47e226ed 2366 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2367 {
05fb3e0c
WF
2368 string library_path = find_executable (library, "", dw.sess.sysenv,
2369 "LD_LIBRARY_PATH");
84c84ac4
SC
2370 probe_point* specific_loc = new probe_point(*base_loc);
2371 specific_loc->optional = true;
ef0943df 2372 specific_loc->from_glob = true;
84c84ac4
SC
2373 vector<probe_point::component*> derived_comps;
2374
5d25dfb6
JL
2375 // Create new probe point for the matching library. This is what will be
2376 // shown in listing mode. Also replace the process(str) with the real
2377 // absolute path rather than keeping what the user typed in.
84c84ac4
SC
2378 vector<probe_point::component*>::iterator it;
2379 for (it = specific_loc->components.begin();
2380 it != specific_loc->components.end(); ++it)
5d25dfb6
JL
2381 if ((*it)->functor == TOK_PROCESS)
2382 derived_comps.push_back(new probe_point::component(TOK_PROCESS,
2383 new literal_string(path_remove_sysroot(dw.sess, dw.module_name))));
2384 else if ((*it)->functor == TOK_LIBRARY)
84c84ac4
SC
2385 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2386 new literal_string(library_path)));
2387 else
2388 derived_comps.push_back(*it);
2389 probe_point* derived_loc = new probe_point(*specific_loc);
2390 derived_loc->components = derived_comps;
8159bf55 2391 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2392 derive_probes(dw.sess, new_base, results);
2393 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2394 clog << _("module=") << library_path << endl;
2395 return library_path;
84c84ac4 2396 }
2cbcfa9c 2397 return "";
84c84ac4
SC
2398}
2399
2400
51d6bda3
SC
2401void
2402dwarf_query::query_library (const char *library)
2403{
2a52b3e4 2404 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
51d6bda3
SC
2405}
2406
576eaefe
SC
2407struct plt_expanding_visitor: public var_expanding_visitor
2408{
2409 plt_expanding_visitor(const string & entry):
2410 entry (entry)
2411 {
2412 }
2413 const string & entry;
2414
2415 void visit_target_symbol (target_symbol* e);
2416};
2417
2418
2419void
45cdb40e 2420base_query::query_plt_callback (base_query *me, const char *entry, size_t address)
576eaefe 2421{
576eaefe
SC
2422 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2423 me->query_plt (entry, address);
7f4964f1 2424 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2425}
2426
2427
2428void
2429query_one_plt (const char *entry, long addr, dwflpp & dw,
2430 probe * base_probe, probe_point *base_loc,
93b44c2a 2431 vector<derived_probe *> & results, base_query *q)
576eaefe 2432{
93b44c2a
JL
2433 string module = dw.module_name;
2434 if (q->has_process)
2435 module = path_remove_sysroot(dw.sess, module);
2436
576eaefe 2437 probe_point* specific_loc = new probe_point(*base_loc);
93b44c2a
JL
2438 specific_loc->well_formed = true;
2439
576eaefe
SC
2440 vector<probe_point::component*> derived_comps;
2441
2442 if (dw.sess.verbose > 2)
2443 clog << _F("plt entry=%s\n", entry);
2444
576eaefe
SC
2445 vector<probe_point::component*>::iterator it;
2446 for (it = specific_loc->components.begin();
2447 it != specific_loc->components.end(); ++it)
93b44c2a
JL
2448 if ((*it)->functor == TOK_PROCESS)
2449 {
2450 // Replace with fully resolved path
2451 *it = new probe_point::component(TOK_PROCESS,
2452 new literal_string(q->has_library ? q->path : module));
2453 derived_comps.push_back(*it);
2454 }
2455 else if ((*it)->functor == TOK_PLT)
3d372d6b 2456 {
93b44c2a 2457 // Replace possibly globby component
8159bf55
FCE
2458 *it = new probe_point::component(TOK_PLT,
2459 new literal_string(entry));
3d372d6b
SC
2460 derived_comps.push_back(*it);
2461 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2462 new literal_number(addr, true)));
3d372d6b 2463 }
576eaefe
SC
2464 else
2465 derived_comps.push_back(*it);
2466 probe_point* derived_loc = new probe_point(*specific_loc);
2467 derived_loc->components = derived_comps;
02c34e38
FCE
2468 probe *new_base = new probe (new probe (base_probe, specific_loc),
2469 derived_loc);
576eaefe
SC
2470 string e = string(entry);
2471 plt_expanding_visitor pltv (e);
2472 pltv.replace (new_base->body);
2473 derive_probes(dw.sess, new_base, results);
2474}
2475
2476
2477void
2478dwarf_query::query_plt (const char *entry, size_t address)
2479{
93b44c2a 2480 query_one_plt (entry, address, dw, base_probe, base_loc, results, this);
576eaefe 2481}
51d6bda3 2482
435f53a7
FCE
2483// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2484// but the needed declaration for module_cache is not available there.
2485// Nor for that matter in session.cxx. Only in this CU is that field ever
2486// set (in query_module() above), so we clean it up here too.
2487static void
2488delete_session_module_cache (systemtap_session& s)
2489{
2490 if (s.module_cache) {
2491 if (s.verbose > 3)
b530b5b3 2492 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2493 delete s.module_cache;
2494 s.module_cache = 0;
2495 }
2496}
2497
2498
de688825 2499struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2500{
77de5e9e 2501 dwarf_query & q;
bcc12710 2502 Dwarf_Die *scope_die;
77de5e9e 2503 Dwarf_Addr addr;
8c819921 2504 block *add_block;
2260f4e3 2505 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2506 // NB: tids are not always collected in add_block & add_call_probe, because
2507 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2508 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2509 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2510 unsigned saved_longs, saved_strings; // data saved within kretprobes
2511 map<std::string, expression *> return_ts_map;
729455a7 2512 vector<Dwarf_Die> scopes;
3689db05 2513 // probe counter name -> pointer of associated probe
698de6cc 2514 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2515 bool visited;
77de5e9e 2516
de688825 2517 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2518 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2519 add_block_tid(false), add_call_probe_tid(false),
af234c40 2520 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2521 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2522 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2523 void visit_target_symbol_saved_return (target_symbol* e);
2524 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2525 void visit_target_symbol (target_symbol* e);
bd1fcbad 2526 void visit_atvar_op (atvar_op* e);
c24447be 2527 void visit_cast_op (cast_op* e);
8cc799a5 2528 void visit_entry_op (entry_op* e);
3689db05 2529 void visit_perf_op (perf_op* e);
729455a7
JS
2530private:
2531 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2532};
2533
2534
de688825 2535unsigned var_expanding_visitor::tick = 0;
77de5e9e 2536
a50de939 2537
74fe61bc 2538var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2539{
2540 // FIXME: for the time being, by default we only support plain '$foo
2541 // = bar', not '+=' or any other op= variant. This is fixable, but a
2542 // bit ugly.
2543 //
2544 // If derived classes desire to add additional operator support, add
2545 // new operators to this list in the derived class constructor.
2546 valid_ops.insert ("=");
2547}
2548
2549
87214add
JS
2550bool
2551var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2552 expression*& lvalue, expression*& rvalue)
77de5e9e 2553{
e57b735a
GH
2554 // Our job would normally be to require() the left and right sides
2555 // into a new assignment. What we're doing is slightly trickier:
2556 // we're pushing a functioncall** onto a stack, and if our left
2557 // child sets the functioncall* for that value, we're going to
2558 // assume our left child was a target symbol -- transformed into a
2559 // set_target_foo(value) call, and it wants to take our right child
2560 // as the argument "value".
2561 //
2562 // This is why some people claim that languages with
2563 // constructor-decomposing case expressions have a leg up on
2564 // visitors.
2565
2566 functioncall *fcall = NULL;
d9b516ca 2567
a50de939 2568 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2569 const string* old_op = op;
2570 op = &eop;
a50de939 2571
e57b735a 2572 target_symbol_setter_functioncalls.push (&fcall);
87214add 2573 replace (lvalue);
e57b735a 2574 target_symbol_setter_functioncalls.pop ();
87214add
JS
2575 replace (rvalue);
2576
2577 op = old_op;
e57b735a
GH
2578
2579 if (fcall != NULL)
77de5e9e 2580 {
e57b735a
GH
2581 // Our left child is informing us that it was a target variable
2582 // and it has been replaced with a set_target_foo() function
2583 // call; we are going to provide that function call -- with the
2584 // right child spliced in as sole argument -- in place of
de688825 2585 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2586
87214add 2587 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2588 {
2589 // Build up a list of supported operators.
2590 string ops;
2591 std::set<string>::iterator i;
b530b5b3 2592 int valid_ops_size = 0;
a50de939 2593 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2594 {
a50de939 2595 ops += " " + *i + ",";
b530b5b3
LB
2596 valid_ops_size++;
2597 }
a50de939
DS
2598 ops.resize(ops.size() - 1); // chop off the last ','
2599
2600 // Throw the error.
dc09353a 2601 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2602 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2603 valid_ops_size, ops.c_str()), tok);
b530b5b3 2604
a50de939 2605 }
e57b735a 2606
87214add
JS
2607 assert (lvalue == fcall);
2608 if (rvalue)
2609 fcall->args.push_back (rvalue);
4ed05b15 2610 provide (fcall);
87214add 2611 return true;
77de5e9e 2612 }
e57b735a 2613 else
87214add
JS
2614 return false;
2615}
2616
2617
2618void
2619var_expanding_visitor::visit_assignment (assignment* e)
2620{
2621 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2622 provide (e);
2623}
2624
2625
2626void
2627var_expanding_visitor::visit_pre_crement (pre_crement* e)
2628{
2629 expression *dummy = NULL;
2630 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2631 provide (e);
2632}
2633
2634
2635void
2636var_expanding_visitor::visit_post_crement (post_crement* e)
2637{
2638 expression *dummy = NULL;
2639 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2640 provide (e);
2641}
2642
2643
2644void
2645var_expanding_visitor::visit_delete_statement (delete_statement* s)
2646{
2647 string fakeop = "delete";
2648 expression *dummy = NULL;
2649 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2650 provide (s);
e57b735a 2651}
d9b516ca 2652
d7f3e0c5 2653
30263a73
FCE
2654void
2655var_expanding_visitor::visit_defined_op (defined_op* e)
2656{
2657 bool resolved = true;
2658
2659 defined_ops.push (e);
2660 try {
2661 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2662 // defined with a target_symbol* operand, a subsidiary call may attempt to
2663 // rewrite it to a general expression* instead, and require<> happily
2664 // casts to/from void*, causing possible memory corruption. We use
2665 // expression* here, being the general case of rewritten $variable.
2666 expression *foo1 = e->operand;
2667 foo1 = require (foo1);
2668
c69a87e0 2669 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2670 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2671 // erroneous resolutions. Some would signal a visit_target_symbol failure
2672 // with an exception, with a set flag within the target_symbol, or nothing
2673 // at all.
30263a73 2674 //
c69a87e0
FCE
2675 // Now, failures always have to be signalled with a
2676 // saved_conversion_error being chained to the target_symbol.
2677 // Successes have to result in an attempted rewrite of the
850bfddd 2678 // target_symbol (via provide()).
780f11ff 2679 //
c69a87e0
FCE
2680 // Edna Mode: "no capes". fche: "no exceptions".
2681
30263a73
FCE
2682 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2683 //
2684 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2685 //
2686 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2687 // dwarf probe to take care of it.
2688 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2689 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2690 //
30263a73
FCE
2691 // utrace: success: rewrites to function; failure: semantic_error
2692 //
850bfddd 2693 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2694
2695 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2696 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2697 resolved = false;
a45664f4 2698 else if (foo2) // unresolved but not marked failing
b7aedf26 2699 {
780f11ff
JS
2700 // There are some visitors that won't touch certain target_symbols,
2701 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2702 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2703 e->operand = foo2;
2704 provide (e);
2705 return;
2706 }
30263a73
FCE
2707 else // resolved, rewritten to some other expression type
2708 resolved = true;
780f11ff 2709 } catch (const semantic_error& e) {
c69a87e0 2710 assert (0); // should not happen
30263a73
FCE
2711 }
2712 defined_ops.pop ();
2713
2714 literal_number* ln = new literal_number (resolved ? 1 : 0);
2715 ln->tok = e->tok;
2716 provide (ln);
2717}
2718
2719
5f36109e
JS
2720struct dwarf_pretty_print
2721{
2722 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2723 const string& local, bool userspace_p,
2724 const target_symbol& e):
d19a9a82
JS
2725 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2726 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2727 {
2728 init_ts (e);
2729 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2730 }
2731
2732 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2733 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2734 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2735 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2736 {
2737 init_ts (e);
2738 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2739 }
2740
2741 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2742 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2743 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2744 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2745 {
2746 init_ts (e);
2747 dw.type_die_for_pointer (type_die, ts, &base_type);
2748 }
2749
2750 functioncall* expand ();
ce83ff57 2751 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2752
2753private:
2754 dwflpp& dw;
2755 target_symbol* ts;
7d11d8c9 2756 bool print_full;
5f36109e
JS
2757 Dwarf_Die base_type;
2758
2759 string local;
2760 vector<Dwarf_Die> scopes;
2761 Dwarf_Addr pc;
2762
2763 expression* pointer;
2764 Dwarf_Die pointer_type;
2765
d19a9a82 2766 const bool userspace_p, deref_p;
5f36109e
JS
2767
2768 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2769 print_format* pf, bool top=false);
600551ca
JS
2770 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2771 print_format* pf);
5f36109e 2772 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2773 print_format* pf);
5f36109e 2774 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2775 print_format* pf, bool top);
5f36109e 2776 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2777 print_format* pf, bool top);
5f36109e 2778 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2779 print_format* pf, bool top);
5f36109e 2780 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2781 print_format* pf, int& count);
bbee5bb8 2782 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2783
2784 void init_ts (const target_symbol& e);
2785 expression* deref (target_symbol* e);
c55ea10d 2786 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2787};
2788
2789
2790void
2791dwarf_pretty_print::init_ts (const target_symbol& e)
2792{
2793 // Work with a new target_symbol so we can modify arguments
2794 ts = new target_symbol (e);
2795
2796 if (ts->addressof)
dc09353a 2797 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2798
2799 if (ts->components.empty() ||
2800 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2801 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2802 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2803 ts->components.pop_back();
2804}
2805
2806
2807functioncall*
2808dwarf_pretty_print::expand ()
2809{
2810 static unsigned tick = 0;
2811
2812 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2813 // try {
2814 // return sprintf("{.foo=...}", (ts)->foo, ...)
2815 // } catch {
2816 // return "ERROR"
2817 // }
5f36109e
JS
2818 // }
2819
2820 // Create the function decl and call.
2821
2822 functiondecl *fdecl = new functiondecl;
2823 fdecl->tok = ts->tok;
2824 fdecl->synthetic = true;
2825 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2826 fdecl->type = pe_string;
2827
2828 functioncall* fcall = new functioncall;
2829 fcall->tok = ts->tok;
2830 fcall->function = fdecl->name;
140be17a 2831 fcall->type = pe_string;
5f36109e
JS
2832
2833 // If there's a <pointer>, replace it with a new var and make that
2834 // the first function argument.
2835 if (pointer)
2836 {
2837 vardecl *v = new vardecl;
2838 v->type = pe_long;
2839 v->name = "pointer";
2840 v->tok = ts->tok;
2841 fdecl->formal_args.push_back (v);
2842 fcall->args.push_back (pointer);
2843
2844 symbol* sym = new symbol;
2845 sym->tok = ts->tok;
2846 sym->name = v->name;
5f36109e
JS
2847 pointer = sym;
2848 }
2849
2850 // For each expression argument, replace it with a function argument.
2851 for (unsigned i = 0; i < ts->components.size(); ++i)
2852 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2853 {
2854 vardecl *v = new vardecl;
2855 v->type = pe_long;
2856 v->name = "index" + lex_cast(i);
2857 v->tok = ts->tok;
2858 fdecl->formal_args.push_back (v);
2859 fcall->args.push_back (ts->components[i].expr_index);
2860
2861 symbol* sym = new symbol;
2862 sym->tok = ts->tok;
2863 sym->name = v->name;
5f36109e
JS
2864 ts->components[i].expr_index = sym;
2865 }
2866
2867 // Create the return sprintf.
1c922ad7 2868 print_format* pf = print_format::create(ts->tok, "sprintf");
5f36109e
JS
2869 return_statement* rs = new return_statement;
2870 rs->tok = ts->tok;
2871 rs->value = pf;
5f36109e
JS
2872
2873 // Recurse into the actual values.
7d11d8c9 2874 recurse (&base_type, ts, pf, true);
5f36109e
JS
2875 pf->components = print_format::string_to_components(pf->raw_components);
2876
7d11d8c9
JS
2877 // Create the try-catch net
2878 try_block* tb = new try_block;
2879 tb->tok = ts->tok;
2880 tb->try_block = rs;
2881 tb->catch_error_var = 0;
2882 return_statement* rs2 = new return_statement;
2883 rs2->tok = ts->tok;
2884 rs2->value = new literal_string ("ERROR");
2885 rs2->value->tok = ts->tok;
2886 tb->catch_block = rs2;
2887 fdecl->body = tb;
2888
f8809d54 2889 fdecl->join (dw.sess);
5f36109e
JS
2890 return fcall;
2891}
2892
2893
2894void
2895dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2896 print_format* pf, bool top)
5f36109e
JS
2897{
2898 Dwarf_Die type;
2899 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2900
2901 switch (dwarf_tag(&type))
2902 {
2903 default:
2904 // XXX need a warning?
2905 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2906 // + ") for " + dwarf_type_name(&type), e->tok);
2907 pf->raw_components.append("?");
2908 break;
2909
2910 case DW_TAG_enumeration_type:
2911 case DW_TAG_base_type:
7d11d8c9 2912 recurse_base (&type, e, pf);
5f36109e
JS
2913 break;
2914
2915 case DW_TAG_array_type:
7d11d8c9 2916 recurse_array (&type, e, pf, top);
5f36109e
JS
2917 break;
2918
2919 case DW_TAG_pointer_type:
2920 case DW_TAG_reference_type:
2921 case DW_TAG_rvalue_reference_type:
7d11d8c9 2922 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2923 break;
2924
2925 case DW_TAG_subroutine_type:
c55ea10d 2926 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2927 break;
2928
2929 case DW_TAG_union_type:
5f36109e
JS
2930 case DW_TAG_structure_type:
2931 case DW_TAG_class_type:
7d11d8c9 2932 recurse_struct (&type, e, pf, top);
5f36109e
JS
2933 break;
2934 }
2935}
2936
2937
600551ca
JS
2938// Bit fields are handled as a special-case combination of recurse() and
2939// recurse_base(), only called from recurse_struct_members(). The main
2940// difference is that the value is always printed numerically, even if the
2941// underlying type is a char.
2942void
2943dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2944 print_format* pf)
2945{
2946 Dwarf_Die type;
2947 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2948
2949 int tag = dwarf_tag(&type);
2950 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2951 {
2952 // XXX need a warning?
2953 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2954 // + ") for " + dwarf_type_name(&type), e->tok);
2955 pf->raw_components.append("?");
2956 return;
2957 }
2958
2959 Dwarf_Attribute attr;
2960 Dwarf_Word encoding = (Dwarf_Word) -1;
2961 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2962 &encoding);
2963 switch (encoding)
2964 {
2965 case DW_ATE_float:
2966 case DW_ATE_complex_float:
2967 // XXX need a warning?
2968 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2969 // + ") for " + dwarf_type_name(&type), e->tok);
2970 pf->raw_components.append("?");
2971 break;
2972
2973 case DW_ATE_unsigned:
2974 case DW_ATE_unsigned_char:
2975 push_deref (pf, "%u", e);
2976 break;
2977
2978 case DW_ATE_signed:
2979 case DW_ATE_signed_char:
2980 default:
2981 push_deref (pf, "%i", e);
2982 break;
2983 }
2984}
2985
2986
5f36109e
JS
2987void
2988dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2989 print_format* pf)
5f36109e
JS
2990{
2991 Dwarf_Attribute attr;
2992 Dwarf_Word encoding = (Dwarf_Word) -1;
2993 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2994 &encoding);
5f36109e
JS
2995 switch (encoding)
2996 {
2997 case DW_ATE_float:
2998 case DW_ATE_complex_float:
2999 // XXX need a warning?
3000 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
3001 // + ") for " + dwarf_type_name(type), e->tok);
3002 pf->raw_components.append("?");
5f36109e
JS
3003 break;
3004
6561d8d1 3005 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
3006 case DW_ATE_signed_char:
3007 case DW_ATE_unsigned_char:
941101c1
JS
3008 // Use escapes to make sure that non-printable characters
3009 // don't interrupt our stream (especially '\0' values).
3010 push_deref (pf, "'%#c'", e);
5f36109e
JS
3011 break;
3012
3013 case DW_ATE_unsigned:
c55ea10d 3014 push_deref (pf, "%u", e);
5f36109e
JS
3015 break;
3016
600551ca 3017 case DW_ATE_signed:
5f36109e 3018 default:
c55ea10d 3019 push_deref (pf, "%i", e);
5f36109e
JS
3020 break;
3021 }
5f36109e
JS
3022}
3023
3024
3025void
3026dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3027 print_format* pf, bool top)
5f36109e 3028{
7d11d8c9
JS
3029 if (!top && !print_full)
3030 {
3031 pf->raw_components.append("[...]");
3032 return;
3033 }
3034
5f36109e
JS
3035 Dwarf_Die childtype;
3036 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
3037
3038 if (print_chars (&childtype, e, pf))
3039 return;
3040
5f36109e
JS
3041 pf->raw_components.append("[");
3042
3043 // We print the array up to the first 5 elements.
3044 // XXX how can we determine the array size?
3045 // ... for now, just print the first element
64cddf39 3046 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 3047 unsigned i, size = 1;
64cddf39 3048 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
3049 {
3050 if (i > 0)
3051 pf->raw_components.append(", ");
3052 target_symbol* e2 = new target_symbol(*e);
3053 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 3054 recurse (&childtype, e2, pf);
5f36109e
JS
3055 }
3056 if (i < size || 1/*XXX until real size is known */)
3057 pf->raw_components.append(", ...");
3058 pf->raw_components.append("]");
3059}
3060
3061
3062void
3063dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3064 print_format* pf, bool top)
5f36109e 3065{
7d11d8c9 3066 // We chase to top-level pointers, but leave the rest alone
d19a9a82 3067 bool void_p = true;
7d11d8c9 3068 Dwarf_Die pointee;
bbee5bb8 3069 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
3070 {
3071 try
3072 {
3073 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
3074 void_p = false;
3075 }
3076 catch (const semantic_error&) {}
3077 }
3078
3079 if (!void_p)
5f36109e 3080 {
bbee5bb8
JS
3081 if (print_chars (&pointee, e, pf))
3082 return;
3083
3084 if (top)
3085 {
3086 recurse (&pointee, e, pf, top);
3087 return;
3088 }
5f36109e 3089 }
bbee5bb8 3090
c55ea10d 3091 push_deref (pf, "%p", e);
5f36109e
JS
3092}
3093
3094
3095void
3096dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3097 print_format* pf, bool top)
5f36109e 3098{
bdec0e18
JS
3099 if (dwarf_hasattr(type, DW_AT_declaration))
3100 {
a44a7cb5 3101 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
3102 if (!resolved)
3103 {
3104 // could be an error, but for now just stub it
3105 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
3106 pf->raw_components.append("{...}");
3107 return;
3108 }
3109 type = resolved;
3110 }
3111
5f36109e
JS
3112 int count = 0;
3113 pf->raw_components.append("{");
7d11d8c9
JS
3114 if (top || print_full)
3115 recurse_struct_members (type, e, pf, count);
3116 else
3117 pf->raw_components.append("...");
5f36109e
JS
3118 pf->raw_components.append("}");
3119}
3120
3121
3122void
3123dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 3124 print_format* pf, int& count)
5f36109e 3125{
a80f28d8
JS
3126 /* With inheritance, a subclass may mask member names of parent classes, so
3127 * our search among the inheritance tree must be breadth-first rather than
3128 * depth-first (recursive). The type die is still our starting point. When
3129 * we encounter a masked name, just skip it. */
3130 set<string> dupes;
3131 deque<Dwarf_Die> inheritees(1, *type);
3132 for (; !inheritees.empty(); inheritees.pop_front())
3133 {
dee830d9 3134 Dwarf_Die child, childtype, import;
a80f28d8
JS
3135 if (dwarf_child (&inheritees.front(), &child) == 0)
3136 do
3137 {
3138 target_symbol* e2 = e;
5f36109e 3139
a80f28d8
JS
3140 // skip static members
3141 if (dwarf_hasattr(&child, DW_AT_declaration))
3142 continue;
5f36109e 3143
a80f28d8 3144 int tag = dwarf_tag (&child);
5f36109e 3145
dee830d9
MW
3146 /* Pretend imported units contain members by recursing into
3147 struct_member printing with the same count. */
3148 if (tag == DW_TAG_imported_unit
3149 && dwarf_attr_die (&child, DW_AT_import, &import))
3150 recurse_struct_members (&import, e2, pf, count);
3151
a80f28d8
JS
3152 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
3153 continue;
5f36109e 3154
a80f28d8 3155 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 3156
a80f28d8
JS
3157 if (tag == DW_TAG_inheritance)
3158 {
3159 inheritees.push_back(childtype);
3160 continue;
3161 }
5f36109e 3162
a80f28d8
JS
3163 int childtag = dwarf_tag (&childtype);
3164 const char *member = dwarf_diename (&child);
3a147004 3165
a80f28d8
JS
3166 // "_vptr.foo" members are C++ virtual function tables,
3167 // which (generally?) aren't interesting for users.
3168 if (member && startswith(member, "_vptr."))
3169 continue;
3a147004 3170
a80f28d8
JS
3171 // skip inheritance-masked duplicates
3172 if (member && !dupes.insert(member).second)
3173 continue;
64cddf39 3174
a80f28d8
JS
3175 if (++count > 1)
3176 pf->raw_components.append(", ");
64cddf39 3177
a80f28d8
JS
3178 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
3179 if (pf->args.size() >= 32)
3180 {
3181 pf->raw_components.append("...");
3182 break;
3183 }
3184
3185 if (member)
3186 {
3187 pf->raw_components.append(".");
3188 pf->raw_components.append(member);
5f36109e 3189
a80f28d8
JS
3190 e2 = new target_symbol(*e);
3191 e2->components.push_back (target_symbol::component(e->tok, member));
3192 }
3193 else if (childtag == DW_TAG_union_type)
3194 pf->raw_components.append("<union>");
3195 else if (childtag == DW_TAG_structure_type)
3196 pf->raw_components.append("<class>");
3197 else if (childtag == DW_TAG_class_type)
3198 pf->raw_components.append("<struct>");
3199 pf->raw_components.append("=");
600551ca
JS
3200
3201 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
3202 recurse_bitfield (&childtype, e2, pf);
3203 else
3204 recurse (&childtype, e2, pf);
5f36109e 3205 }
a80f28d8
JS
3206 while (dwarf_siblingof (&child, &child) == 0);
3207 }
5f36109e
JS
3208}
3209
3210
bbee5bb8
JS
3211bool
3212dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
3213 print_format* pf)
3214{
3215 Dwarf_Die type;
3216 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
3217
3218 Dwarf_Attribute attr;
3219 Dwarf_Word encoding = (Dwarf_Word) -1;
3220 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3221 &encoding);
3222 switch (encoding)
bbee5bb8 3223 {
6561d8d1
JS
3224 case DW_ATE_UTF:
3225 case DW_ATE_signed_char:
3226 case DW_ATE_unsigned_char:
3227 break;
3228 default:
3229 return false;
3230 }
3231
3232 string function = userspace_p ? "user_string2" : "kernel_string2";
3233 Dwarf_Word size = (Dwarf_Word) -1;
3234 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3235 switch (size)
3236 {
3237 case 1:
3238 break;
3239 case 2:
3240 function += "_utf16";
3241 break;
3242 case 4:
3243 function += "_utf32";
3244 break;
3245 default:
3246 return false;
3247 }
3248
3249 if (push_deref (pf, "\"%s\"", e))
3250 {
3251 // steal the last arg for a string access
3252 assert (!pf->args.empty());
3253 functioncall* fcall = new functioncall;
3254 fcall->tok = e->tok;
3255 fcall->function = function;
3256 fcall->args.push_back (pf->args.back());
3257 expression *err_msg = new literal_string ("<unknown>");
3258 err_msg->tok = e->tok;
3259 fcall->args.push_back (err_msg);
3260 pf->args.back() = fcall;
bbee5bb8 3261 }
6561d8d1 3262 return true;
bbee5bb8
JS
3263}
3264
a5ce5211
MW
3265// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3266static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3267 + "#define fetch_register k_fetch_register\n"
3268 + "#define store_register k_store_register\n"
3269 + "#define deref kderef\n"
3270 + "#define store_deref store_kderef\n";
a5ce5211
MW
3271
3272static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3273 + "#define fetch_register u_fetch_register\n"
3274 + "#define store_register u_store_register\n"
3275 + "#define deref uderef\n"
3276 + "#define store_deref store_uderef\n";
a5ce5211
MW
3277
3278#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3279 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3280
3281static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3282 + "#undef fetch_register\n"
3283 + "#undef store_register\n"
3284 + "#undef deref\n"
3285 + "#undef store_deref\n";
bbee5bb8 3286
1c0be8c7
JS
3287static functioncall*
3288synthetic_embedded_deref_call(systemtap_session& session,
3289 const string& function_name,
3290 const string& function_code,
3291 exp_type function_type,
3292 bool userspace_p,
3293 bool lvalue_p,
3294 target_symbol* e,
3295 expression* pointer=NULL)
3296{
3297 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3298 functiondecl *fdecl = new functiondecl;
3299 fdecl->synthetic = true;
3300 fdecl->tok = e->tok;
1c0be8c7
JS
3301 fdecl->name = function_name;
3302 fdecl->type = function_type;
3303
5f36109e
JS
3304 embeddedcode *ec = new embeddedcode;
3305 ec->tok = e->tok;
1c0be8c7
JS
3306 ec->code += "/* unprivileged */";
3307 if (! lvalue_p)
3308 ec->code += "/* pure */";
3309 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3310 ec->code += function_code;
3311 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3312 fdecl->body = ec;
3313
3314 // Synthesize a functioncall.
3315 functioncall* fcall = new functioncall;
3316 fcall->tok = e->tok;
3317 fcall->function = fdecl->name;
1c0be8c7 3318 fcall->type = fdecl->type;
5f36109e 3319
1c0be8c7
JS
3320 // If this code snippet uses a precomputed pointer,
3321 // pass that as the first argument.
5f36109e
JS
3322 if (pointer)
3323 {
5f36109e
JS
3324 vardecl *v = new vardecl;
3325 v->type = pe_long;
3326 v->name = "pointer";
3327 v->tok = e->tok;
3328 fdecl->formal_args.push_back(v);
3329 fcall->args.push_back(pointer);
3330 }
5f36109e 3331
1c0be8c7 3332 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3333 for (unsigned i = 0; i < e->components.size(); ++i)
3334 if (e->components[i].type == target_symbol::comp_expression_array_index)
3335 {
3336 vardecl *v = new vardecl;
3337 v->type = pe_long;
3338 v->name = "index" + lex_cast(i);
3339 v->tok = e->tok;
3340 fdecl->formal_args.push_back(v);
3341 fcall->args.push_back(e->components[i].expr_index);
3342 }
3343
1c0be8c7
JS
3344 // If this code snippet is assigning to an lvalue,
3345 // add a final argument for the rvalue.
3346 if (lvalue_p)
3347 {
3348 // Modify the fdecl so it carries a single pe_long formal
3349 // argument called "value".
5f36109e 3350
1c0be8c7
JS
3351 // FIXME: For the time being we only support setting target
3352 // variables which have base types; these are 'pe_long' in
3353 // stap's type vocabulary. Strings and pointers might be
3354 // reasonable, some day, but not today.
5f36109e 3355
1c0be8c7
JS
3356 vardecl *v = new vardecl;
3357 v->type = pe_long;
3358 v->name = "value";
3359 v->tok = e->tok;
3360 fdecl->formal_args.push_back(v);
3361 // NB: We don't know the value for fcall argument yet.
3362 // (see target_symbol_setter_functioncalls)
3363 }
3364
3365 // Add the synthesized decl to the session, and return the call.
3366 fdecl->join (session);
5f36109e
JS
3367 return fcall;
3368}
3369
1c0be8c7
JS
3370expression*
3371dwarf_pretty_print::deref (target_symbol* e)
3372{
3373 static unsigned tick = 0;
3374
3375 if (!deref_p)
3376 {
3377 assert (pointer && e->components.empty());
3378 return pointer;
3379 }
3380
3381 bool lvalue_p = false;
3382 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3383
3384 string code;
3385 exp_type type = pe_long;
3386 if (pointer)
3387 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3388 else if (!local.empty())
3389 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3390 else
3391 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3392
3393 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3394 userspace_p, lvalue_p, e, pointer);
3395}
3396
5f36109e 3397
c55ea10d
JS
3398bool
3399dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3400 target_symbol* e)
3401{
3402 expression* e2 = NULL;
3403 try
3404 {
3405 e2 = deref (e);
3406 }
3407 catch (const semantic_error&)
3408 {
3409 pf->raw_components.append ("?");
3410 return false;
3411 }
3412 pf->raw_components.append (fmt);
3413 pf->args.push_back (e2);
3414 return true;
3415}
3416
3417
e57b735a 3418void
a7999c82 3419dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3420{
a7999c82
JS
3421 // Get the full name of the target symbol.
3422 stringstream ts_name_stream;
3423 e->print(ts_name_stream);
3424 string ts_name = ts_name_stream.str();
3425
3426 // Check and make sure we haven't already seen this target
3427 // variable in this return probe. If we have, just return our
3428 // last replacement.
af234c40 3429 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3430 if (i != return_ts_map.end())
85ecf79a 3431 {
a7999c82
JS
3432 provide (i->second);
3433 return;
3434 }
85ecf79a 3435
70208613
JS
3436 // Attempt the expansion directly first, so if there's a problem with the
3437 // variable we won't have a bogus entry probe lying around. Like in
3438 // saveargs(), we pretend for a moment that we're not in a .return.
3439 bool saved_has_return = q.has_return;
3440 q.has_return = false;
3441 expression *repl = e;
3442 replace (repl);
3443 q.has_return = saved_has_return;
3444 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3445 if (n && n->saved_conversion_error)
3446 {
3447 provide (repl);
3448 return;
3449 }
3450
af234c40
JS
3451 expression *exp;
3452 if (!q.has_process &&
3453 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3454 exp = gen_kretprobe_saved_return(repl);
af234c40 3455 else
cc9001af 3456 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3457
3458 // Provide the variable to our parent so it can be used as a
3459 // substitute for the target symbol.
3460 provide (exp);
3461
3462 // Remember this replacement since we might be able to reuse
3463 // it later if the same return probe references this target
3464 // symbol again.
3465 return_ts_map[ts_name] = exp;
3466}
3467
4a2970a3 3468static expression*
23dc94f6
DS
3469gen_mapped_saved_return(systemtap_session &sess, expression* e,
3470 const string& name,
3471 block *& add_block, bool& add_block_tid,
3472 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3473{
23dc94f6
DS
3474 static unsigned tick = 0;
3475
a7999c82
JS
3476 // We've got to do several things here to handle target
3477 // variables in return probes.
85ecf79a 3478
a7999c82
JS
3479 // (1) Synthesize two global arrays. One is the cache of the
3480 // target variable and the other contains a thread specific
3481 // nesting level counter. The arrays will look like
3482 // this:
3483 //
23dc94f6
DS
3484 // _entry_tvar_{name}_{num}
3485 // _entry_tvar_{name}_{num}_ctr
a7999c82 3486
23dc94f6 3487 string aname = (string("_entry_tvar_")
cc9001af 3488 + name
aca66a36 3489 + "_" + lex_cast(tick++));
a7999c82
JS
3490 vardecl* vd = new vardecl;
3491 vd->name = aname;
3492 vd->tok = e->tok;
23dc94f6 3493 sess.globals.push_back (vd);
a7999c82
JS
3494
3495 string ctrname = aname + "_ctr";
3496 vd = new vardecl;
3497 vd->name = ctrname;
3498 vd->tok = e->tok;
23dc94f6 3499 sess.globals.push_back (vd);
a7999c82
JS
3500
3501 // (2) Create a new code block we're going to insert at the
3502 // beginning of this probe to get the cached value into a
3503 // temporary variable. We'll replace the target variable
3504 // reference with the temporary variable reference. The code
3505 // will look like this:
3506 //
23dc94f6
DS
3507 // _entry_tvar_tid = tid()
3508 // _entry_tvar_{name}_{num}_tmp
3509 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3510 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3511 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3512 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3513 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3514 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3515
3516 // (2a) Synthesize the tid temporary expression, which will look
3517 // like this:
3518 //
23dc94f6 3519 // _entry_tvar_tid = tid()
a7999c82 3520 symbol* tidsym = new symbol;
23dc94f6 3521 tidsym->name = string("_entry_tvar_tid");
a7999c82 3522 tidsym->tok = e->tok;
85ecf79a 3523
a7999c82
JS
3524 if (add_block == NULL)
3525 {
3526 add_block = new block;
3527 add_block->tok = e->tok;
8cc799a5 3528 }
8c819921 3529
8cc799a5
JS
3530 if (!add_block_tid)
3531 {
a7999c82
JS
3532 // Synthesize a functioncall to grab the thread id.
3533 functioncall* fc = new functioncall;
3534 fc->tok = e->tok;
3535 fc->function = string("tid");
8c819921 3536
23dc94f6 3537 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3538 assignment* a = new assignment;
3539 a->tok = e->tok;
3540 a->op = "=";
a7999c82
JS
3541 a->left = tidsym;
3542 a->right = fc;
8c819921
DS
3543
3544 expr_statement* es = new expr_statement;
3545 es->tok = e->tok;
3546 es->value = a;
8c819921 3547 add_block->statements.push_back (es);
8cc799a5 3548 add_block_tid = true;
a7999c82 3549 }
8c819921 3550
a7999c82
JS
3551 // (2b) Synthesize an array reference and assign it to a
3552 // temporary variable (that we'll use as replacement for the
3553 // target variable reference). It will look like this:
3554 //
23dc94f6
DS
3555 // _entry_tvar_{name}_{num}_tmp
3556 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3557 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3558
3559 arrayindex* ai_tvar_base = new arrayindex;
3560 ai_tvar_base->tok = e->tok;
3561
3562 symbol* sym = new symbol;
3563 sym->name = aname;
3564 sym->tok = e->tok;
3565 ai_tvar_base->base = sym;
3566
3567 ai_tvar_base->indexes.push_back(tidsym);
3568
3569 // We need to create a copy of the array index in its current
3570 // state so we can have 2 variants of it (the original and one
3571 // that post-decrements the second index).
3572 arrayindex* ai_tvar = new arrayindex;
3573 arrayindex* ai_tvar_postdec = new arrayindex;
3574 *ai_tvar = *ai_tvar_base;
3575 *ai_tvar_postdec = *ai_tvar_base;
3576
3577 // Synthesize the
23dc94f6 3578 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3579 // second index into the array.
3580 arrayindex* ai_ctr = new arrayindex;
3581 ai_ctr->tok = e->tok;
3582
3583 sym = new symbol;
3584 sym->name = ctrname;
3585 sym->tok = e->tok;
3586 ai_ctr->base = sym;
3587 ai_ctr->indexes.push_back(tidsym);
3588 ai_tvar->indexes.push_back(ai_ctr);
3589
3590 symbol* tmpsym = new symbol;
3591 tmpsym->name = aname + "_tmp";
3592 tmpsym->tok = e->tok;
3593
3594 assignment* a = new assignment;
3595 a->tok = e->tok;
3596 a->op = "=";
3597 a->left = tmpsym;
3598 a->right = ai_tvar;
3599
3600 expr_statement* es = new expr_statement;
3601 es->tok = e->tok;
3602 es->value = a;
3603
3604 add_block->statements.push_back (es);
3605
3606 // (2c) Add a post-decrement to the second array index and
3607 // delete the array value. It will look like this:
3608 //
23dc94f6
DS
3609 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3610 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3611
3612 post_crement* pc = new post_crement;
3613 pc->tok = e->tok;
3614 pc->op = "--";
3615 pc->operand = ai_ctr;
3616 ai_tvar_postdec->indexes.push_back(pc);
3617
3618 delete_statement* ds = new delete_statement;
3619 ds->tok = e->tok;
3620 ds->value = ai_tvar_postdec;
3621
3622 add_block->statements.push_back (ds);
3623
3624 // (2d) Delete the counter value if it is 0. It will look like
3625 // this:
23dc94f6
DS
3626 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3627 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3628
3629 ds = new delete_statement;
3630 ds->tok = e->tok;
3631 ds->value = ai_ctr;
3632
3633 unary_expression *ue = new unary_expression;
3634 ue->tok = e->tok;
3635 ue->op = "!";
3636 ue->operand = ai_ctr;
3637
3638 if_statement *ifs = new if_statement;
3639 ifs->tok = e->tok;
3640 ifs->condition = ue;
3641 ifs->thenblock = ds;
3642 ifs->elseblock = NULL;
3643
3644 add_block->statements.push_back (ifs);
3645
3646 // (3) We need an entry probe that saves the value for us in the
3647 // global array we created. Create the entry probe, which will
3648 // look like this:
3649 //
2260f4e3 3650 // probe kernel.function("{function}").call {
23dc94f6
DS
3651 // _entry_tvar_tid = tid()
3652 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3653 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3654 // = ${param}
3655 // }
3656
2260f4e3 3657 if (add_call_probe == NULL)
a7999c82 3658 {
2260f4e3
FCE
3659 add_call_probe = new block;
3660 add_call_probe->tok = e->tok;
8cc799a5 3661 }
4baf0e53 3662
8cc799a5
JS
3663 if (!add_call_probe_tid)
3664 {
a7999c82
JS
3665 // Synthesize a functioncall to grab the thread id.
3666 functioncall* fc = new functioncall;
3667 fc->tok = e->tok;
3668 fc->function = string("tid");
4baf0e53 3669
23dc94f6 3670 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3671 assignment* a = new assignment;
8fc05e57
DS
3672 a->tok = e->tok;
3673 a->op = "=";
a7999c82
JS
3674 a->left = tidsym;
3675 a->right = fc;
8fc05e57 3676
a7999c82 3677 expr_statement* es = new expr_statement;
8fc05e57
DS
3678 es->tok = e->tok;
3679 es->value = a;
2260f4e3 3680 add_call_probe = new block(add_call_probe, es);
8cc799a5 3681 add_call_probe_tid = true;
85ecf79a 3682 }
cf2a1f85 3683
a7999c82 3684 // Save the value, like this:
23dc94f6
DS
3685 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3686 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3687 // = ${param}
3688 arrayindex* ai_tvar_preinc = new arrayindex;
3689 *ai_tvar_preinc = *ai_tvar_base;
3690
3691 pre_crement* preinc = new pre_crement;
3692 preinc->tok = e->tok;
3693 preinc->op = "++";
3694 preinc->operand = ai_ctr;
3695 ai_tvar_preinc->indexes.push_back(preinc);
3696
3697 a = new assignment;
3698 a->tok = e->tok;
3699 a->op = "=";
3700 a->left = ai_tvar_preinc;
3701 a->right = e;
3702
3703 es = new expr_statement;
3704 es->tok = e->tok;
3705 es->value = a;
3706
2260f4e3 3707 add_call_probe = new block(add_call_probe, es);
a7999c82 3708
23dc94f6 3709 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3710 // our parent so it can be used as a substitute for the target
3711 // symbol.
3f803f9e 3712 delete ai_tvar_base;
af234c40
JS
3713 return tmpsym;
3714}
a7999c82 3715
af234c40 3716
23dc94f6
DS
3717expression*
3718dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3719 const string& name)
3720{
3721 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3722 add_block_tid, add_call_probe,
3723 add_call_probe_tid);
3724}
3725
3726
af234c40 3727expression*
140be17a 3728dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3729{
3730 // The code for this is simple.
3731 //
3732 // .call:
3733 // _set_kretprobe_long(index, $value)
3734 //
3735 // .return:
3736 // _get_kretprobe_long(index)
3737 //
3738 // (or s/long/string/ for things like $$parms)
3739
3740 unsigned index;
3741 string setfn, getfn;
3742
140be17a
JS
3743 // We need the caller to predetermine the type of the expression!
3744 switch (e->type)
af234c40 3745 {
140be17a 3746 case pe_string:
af234c40
JS
3747 index = saved_strings++;
3748 setfn = "_set_kretprobe_string";
3749 getfn = "_get_kretprobe_string";
140be17a
JS
3750 break;
3751 case pe_long:
af234c40
JS
3752 index = saved_longs++;
3753 setfn = "_set_kretprobe_long";
3754 getfn = "_get_kretprobe_long";
140be17a
JS
3755 break;
3756 default:
dc09353a 3757 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3758 }
3759
3760 // Create the entry code
3761 // _set_kretprobe_{long|string}(index, $value)
3762
3763 if (add_call_probe == NULL)
3764 {
3765 add_call_probe = new block;
3766 add_call_probe->tok = e->tok;
3767 }
3768
3769 functioncall* set_fc = new functioncall;
3770 set_fc->tok = e->tok;
3771 set_fc->function = setfn;
3772 set_fc->args.push_back(new literal_number(index));
3773 set_fc->args.back()->tok = e->tok;
3774 set_fc->args.push_back(e);
3775
3776 expr_statement* set_es = new expr_statement;
3777 set_es->tok = e->tok;
3778 set_es->value = set_fc;
3779
3780 add_call_probe->statements.push_back(set_es);
3781
3782 // Create the return code
3783 // _get_kretprobe_{long|string}(index)
3784
3785 functioncall* get_fc = new functioncall;
3786 get_fc->tok = e->tok;
3787 get_fc->function = getfn;
3788 get_fc->args.push_back(new literal_number(index));
3789 get_fc->args.back()->tok = e->tok;
3790
3791 return get_fc;
a7999c82 3792}
a43ba433 3793
2cb3fe26 3794
a7999c82
JS
3795void
3796dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3797{
b78a0fbb 3798 if (null_die(scope_die)) {
04c8e51b
JL
3799 literal_string *empty = new literal_string("");
3800 empty->tok = e->tok;
3801 provide(empty);
a7999c82 3802 return;
b78a0fbb 3803 }
2cb3fe26 3804
5f36109e
JS
3805 target_symbol *tsym = new target_symbol(*e);
3806
fde50242
JS
3807 bool pretty = (!e->components.empty() &&
3808 e->components[0].type == target_symbol::comp_pretty_print);
3809 string format = pretty ? "=%s" : "=%#x";
a43ba433 3810
a7999c82
JS
3811 // Convert $$parms to sprintf of a list of parms and active local vars
3812 // which we recursively evaluate
a43ba433 3813
1c922ad7 3814 print_format* pf = print_format::create(e->tok, "sprintf");
a7999c82 3815
277c21bc 3816 if (q.has_return && (e->name == "$$return"))
a7999c82 3817 {
277c21bc 3818 tsym->name = "$return";
a7999c82
JS
3819
3820 // Ignore any variable that isn't accessible.
3821 tsym->saved_conversion_error = 0;
3822 expression *texp = tsym;
8b095b45 3823 replace (texp); // NB: throws nothing ...
a7999c82 3824 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3825 {
2cb3fe26 3826
a43ba433
FCE
3827 }
3828 else
3829 {
a7999c82 3830 pf->raw_components += "return";
5f36109e 3831 pf->raw_components += format;
a7999c82
JS
3832 pf->args.push_back(texp);
3833 }
3834 }
3835 else
3836 {
3837 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3838 bool first = true;
a7999c82 3839 Dwarf_Die result;
d48bc7eb
JS
3840 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3841 for (unsigned i = 0; i < scopes.size(); ++i)
3842 {
3843 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3844 break; // we don't want file-level variables
3845 if (dwarf_child (&scopes[i], &result) == 0)
3846 do
00cf3709 3847 {
d48bc7eb
JS
3848 switch (dwarf_tag (&result))
3849 {
3850 case DW_TAG_variable:
3851 if (e->name == "$$parms")
3852 continue;
3853 break;
3854 case DW_TAG_formal_parameter:
3855 if (e->name == "$$locals")
3856 continue;
3857 break;
3858
3859 default:
3860 continue;
3861 }
41c262f3 3862
d48bc7eb
JS
3863 const char *diename = dwarf_diename (&result);
3864 if (! diename) continue;
f76427a2 3865
d48bc7eb
JS
3866 if (! first)
3867 pf->raw_components += " ";
3868 pf->raw_components += diename;
fde50242
JS
3869 first = false;
3870
3871 // Write a placeholder for ugly aggregates
3872 Dwarf_Die type;
3873 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3874 {
3875 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3876 switch (dwarf_tag(&type))
3877 {
3878 case DW_TAG_union_type:
3879 case DW_TAG_structure_type:
3880 case DW_TAG_class_type:
3881 pf->raw_components += "={...}";
3882 continue;
3883
3884 case DW_TAG_array_type:
3885 pf->raw_components += "=[...]";
3886 continue;
3887 }
3888 }
345bbb3d 3889
d48bc7eb
JS
3890 tsym->name = "$";
3891 tsym->name += diename;
41c262f3 3892
d48bc7eb
JS
3893 // Ignore any variable that isn't accessible.
3894 tsym->saved_conversion_error = 0;
3895 expression *texp = tsym;
3896 replace (texp); // NB: throws nothing ...
3897 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3898 {
d48bc7eb
JS
3899 if (q.sess.verbose>2)
3900 {
e26c2f83 3901 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb 3902 c != 0;
c081af73 3903 c = c->get_chain()) {
4c5d9906 3904 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3905 }
3906 }
3907
3908 pf->raw_components += "=?";
a43ba433 3909 }
d48bc7eb
JS
3910 else
3911 {
3912 pf->raw_components += format;
3913 pf->args.push_back(texp);
3914 }
a7999c82 3915 }
d48bc7eb
JS
3916 while (dwarf_siblingof (&result, &result) == 0);
3917 }
a7999c82 3918 }
2cb3fe26 3919
a7999c82 3920 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3921 pf->type = pe_string;
a7999c82
JS
3922 provide (pf);
3923}
3924
2cb3fe26 3925
bd1fcbad
YZ
3926void
3927dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3928{
3929 // Fill in our current module context if needed
3930 if (e->module.empty())
3931 e->module = q.dw.module_name;
3932
3933 if (e->module == q.dw.module_name && e->cu_name.empty())
3934 {
3935 // process like any other local
3936 // e->sym_name() will do the right thing
3937 visit_target_symbol(e);
3938 return;
3939 }
3940
3941 var_expanding_visitor::visit_atvar_op(e);
3942}
3943
3944
a7999c82
JS
3945void
3946dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3947{
bd1fcbad 3948 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3949 visited = true;
30263a73
FCE
3950 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3951 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3952
70208613 3953 try
a7999c82 3954 {
c69a87e0
FCE
3955 bool lvalue = is_active_lvalue(e);
3956 if (lvalue && !q.sess.guru_mode)
dc09353a 3957 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3958
100a540e 3959 // XXX: process $context vars should be writable
70208613 3960
c69a87e0
FCE
3961 // See if we need to generate a new probe to save/access function
3962 // parameters from a return probe. PR 1382.
3963 if (q.has_return
3964 && !defined_being_checked
277c21bc
JS
3965 && e->name != "$return" // not the special return-value variable handled below
3966 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3967 {
3968 if (lvalue)
dc09353a 3969 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3970 visit_target_symbol_saved_return(e);
3971 return;
3972 }
e57b735a 3973
277c21bc
JS
3974 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3975 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3976 {
3977 if (lvalue)
dc09353a 3978 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3979
c69a87e0 3980 if (e->addressof)
dc09353a 3981 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3982
5f36109e
JS
3983 e->assert_no_components("dwarf", true);
3984
c69a87e0
FCE
3985 visit_target_symbol_context(e);
3986 return;
3987 }
70208613 3988
04c8e51b
JL
3989 // Everything else (pretty-printed vars, and context vars) require a
3990 // scope_die in which to search for them. If we don't have that, just
3991 // leave it unresolved; we'll produce an error later on.
3992 if (null_die(scope_die))
3993 {
3994 provide(e);
3995 return;
3996 }
3997
5f36109e
JS
3998 if (!e->components.empty() &&
3999 e->components.back().type == target_symbol::comp_pretty_print)
4000 {
4001 if (lvalue)
dc09353a 4002 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 4003
277c21bc 4004 if (q.has_return && (e->name == "$return"))
5f36109e
JS
4005 {
4006 dwarf_pretty_print dpp (q.dw, scope_die, addr,
4007 q.has_process, *e);
4008 dpp.expand()->visit(this);
4009 }
4010 else
4011 {
4012 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 4013 e->sym_name(),
5f36109e
JS
4014 q.has_process, *e);
4015 dpp.expand()->visit(this);
4016 }
4017 return;
4018 }
4019
1c0be8c7 4020 bool userspace_p = q.has_process;
c69a87e0 4021 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 4022 + "_" + e->sym_name()
c69a87e0 4023 + "_" + lex_cast(tick++));
70208613 4024
70208613 4025
1c0be8c7
JS
4026 exp_type type = pe_long;
4027 string code;
277c21bc 4028 if (q.has_return && (e->name == "$return"))
1c0be8c7 4029 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 4030 else
1c0be8c7
JS
4031 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
4032 e, lvalue, type);
70208613 4033
1c0be8c7
JS
4034 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
4035 userspace_p, lvalue, e);
70208613 4036
c69a87e0
FCE
4037 if (lvalue)
4038 {
4039 // Provide the functioncall to our parent, so that it can be
4040 // used to substitute for the assignment node immediately above
4041 // us.
4042 assert(!target_symbol_setter_functioncalls.empty());
4043 *(target_symbol_setter_functioncalls.top()) = n;
4044 }
70208613 4045
1c0be8c7
JS
4046 // Revisit the functioncall so arguments can be expanded.
4047 n->visit (this);
66d284f4
FCE
4048 }
4049 catch (const semantic_error& er)
4050 {
9fab2262
JS
4051 // We suppress this error message, and pass the unresolved
4052 // target_symbol to the next pass. We hope that this value ends
4053 // up not being referenced after all, so it can be optimized out
4054 // quietly.
1af1e62d 4055 e->chain (er);
9fab2262 4056 provide (e);
66d284f4 4057 }
77de5e9e
GH
4058}
4059
4060
c24447be
JS
4061void
4062dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
4063{
4064 // Fill in our current module context if needed
4065 if (e->module.empty())
4066 e->module = q.dw.module_name;
4067
4068 var_expanding_visitor::visit_cast_op(e);
4069}
4070
4071
8cc799a5
JS
4072void
4073dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
4074{
4075 expression *repl = e;
4076 if (q.has_return)
4077 {
4078 // expand the operand as if it weren't a return probe
4079 q.has_return = false;
4080 replace (e->operand);
4081 q.has_return = true;
4082
4083 // XXX it would be nice to use gen_kretprobe_saved_return when available,
4084 // but it requires knowing the types already, which is problematic for
4085 // arbitrary expressons.
cc9001af 4086 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
4087 }
4088 provide (repl);
4089}
4090
3689db05
SC
4091void
4092dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
4093{
ace7c23f 4094 string e_lit_val = e->operand->value;
b78a0fbb 4095
3689db05 4096 add_block = new block;
9eaaceaa 4097 add_block->tok = e->tok;
3689db05
SC
4098
4099 systemtap_session &s = this->q.sess;
4100 map<string, pair<string,derived_probe*> >::iterator it;
4101 // Find the associated perf.counter probe
4102 for (it=s.perf_counters.begin();
4103 it != s.perf_counters.end();
4104 it++)
4105 if ((*it).first == e_lit_val)
4106 {
4107 // if perf .function("name") omitted, then set it to this process name
4108 if ((*it).second.first.length() == 0)
4109 ((*it).second).first = this->q.user_path;
4110 if (((*it).second).first == this->q.user_path)
4111 break;
4112 }
4113
4114 if (it != s.perf_counters.end())
4115 {
698de6cc 4116 perf_counter_refs.insert((*it).second.second);
3689db05
SC
4117 // __perf_read_N is assigned in the probe prologue
4118 symbol* sym = new symbol;
4653caf1 4119 sym->tok = e->tok;
3689db05
SC
4120 sym->name = "__perf_read_" + (*it).first;
4121 provide (sym);
4122 }
4123 else
dc09353a 4124 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
4125}
4126
8cc799a5 4127
729455a7
JS
4128vector<Dwarf_Die>&
4129dwarf_var_expanding_visitor::getscopes(target_symbol *e)
4130{
4131 if (scopes.empty())
4132 {
04c8e51b 4133 if(!null_die(scope_die))
f25a9197 4134 scopes = q.dw.getscopes(scope_die);
729455a7 4135 if (scopes.empty())
b530b5b3
LB
4136 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
4137 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 4138 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7 4139 + lex_cast_hex(addr)
04c8e51b 4140 + (null_die(scope_die) ? ""
729455a7
JS
4141 : (string (" in ")
4142 + (dwarf_diename(scope_die) ?: "<unknown>")
4143 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
4144 + ")"))
4145 + " while searching for local '"
cc9001af 4146 + e->sym_name() + "'",
729455a7
JS
4147 e->tok);
4148 }
4149 return scopes;
4150}
4151
4152
5f36109e
JS
4153struct dwarf_cast_expanding_visitor: public var_expanding_visitor
4154{
4155 systemtap_session& s;
4156 dwarf_builder& db;
4157
4158 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4159 s(s), db(db) {}
4160 void visit_cast_op (cast_op* e);
4161 void filter_special_modules(string& module);
4162};
4163
4164
c4ce66a1
JS
4165struct dwarf_cast_query : public base_query
4166{
946e1a48 4167 cast_op& e;
c4ce66a1 4168 const bool lvalue;
5f36109e
JS
4169 const bool userspace_p;
4170 functioncall*& result;
c4ce66a1 4171
5f36109e
JS
4172 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
4173 const bool userspace_p, functioncall*& result):
abb41d92 4174 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 4175 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
4176
4177 void handle_query_module();
822a6a3d 4178 void query_library (const char *) {}
576eaefe 4179 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
4180};
4181
4182
c4ce66a1
JS
4183void
4184dwarf_cast_query::handle_query_module()
4185{
5f36109e
JS
4186 static unsigned tick = 0;
4187
4188 if (result)
c4ce66a1
JS
4189 return;
4190
ea1e477a 4191 // look for the type in any CU
a44a7cb5
JS
4192 Dwarf_Die* type_die = NULL;
4193 if (startswith(e.type_name, "class "))
4194 {
4195 // normalize to match dwflpp::global_alias_caching_callback
4196 string struct_name = "struct " + e.type_name.substr(6);
4197 type_die = dw.declaration_resolve_other_cus(struct_name);
4198 }
4199 else
4200 type_die = dw.declaration_resolve_other_cus(e.type_name);
4201
4202 // NB: We now index the types as "struct name"/"union name"/etc. instead of
4203 // just "name". But since we didn't require users to be explicit before, and
4204 // actually sort of discouraged it, we must be flexible now. So if a lookup
4205 // fails with a bare name, try augmenting it.
4206 if (!type_die &&
4207 !startswith(e.type_name, "class ") &&
4208 !startswith(e.type_name, "struct ") &&
4209 !startswith(e.type_name, "union ") &&
4210 !startswith(e.type_name, "enum "))
4211 {
4212 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
4213 if (!type_die)
4214 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
4215 if (!type_die)
4216 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
4217 }
4218
ea1e477a
JS
4219 if (!type_die)
4220 return;
c4ce66a1 4221
5f36109e
JS
4222 string code;
4223 exp_type type = pe_long;
4224
ea1e477a 4225 try
c4ce66a1 4226 {
ea1e477a
JS
4227 Dwarf_Die cu_mem;
4228 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4229
4230 if (!e.components.empty() &&
4231 e.components.back().type == target_symbol::comp_pretty_print)
4232 {
4233 if (lvalue)
dc09353a 4234 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4235
d19a9a82 4236 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4237 result = dpp.expand();
4238 return;
4239 }
4240
4241 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4242 }
4243 catch (const semantic_error& er)
4244 {
4245 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4246 // may be attempted using several different modules:
4247 // @cast(ptr, "type", "module1:module2:...")
4248 e.chain (er);
c4ce66a1 4249 }
c4ce66a1 4250
5f36109e
JS
4251 if (code.empty())
4252 return;
c4ce66a1 4253
5f36109e 4254 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4255 + "_" + e.sym_name()
5f36109e 4256 + "_" + lex_cast(tick++));
c4ce66a1 4257
1c0be8c7
JS
4258 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4259 userspace_p, lvalue, &e, e.operand);
5f36109e 4260}
c4ce66a1
JS
4261
4262
fb0274bc
JS
4263void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4264{
d90053e7 4265 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4266 // for those cases, build a module including that header
d90053e7 4267 if (module[module.size() - 1] == '>' &&
60d98537 4268 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4269 {
4270 string cached_module;
4271 if (s.use_cache)
4272 {
4273 // see if the cached module exists
a2639cb7 4274 cached_module = find_typequery_hash(s, module);
d105f664 4275 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4276 {
4277 int fd = open(cached_module.c_str(), O_RDONLY);
4278 if (fd != -1)
4279 {
4280 if (s.verbose > 2)
b530b5b3
LB
4281 //TRANSLATORS: Here we're using a cached module.
4282 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4283 module = cached_module;
4284 close(fd);
4285 return;
4286 }
4287 }
4288 }
4289
4290 // no cached module, time to make it
d90053e7 4291 if (make_typequery(s, module) == 0)
fb0274bc 4292 {
e16dc041 4293 // try to save typequery in the cache
fb0274bc 4294 if (s.use_cache)
e16dc041 4295 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4296 }
4297 }
4298}
4299
4300
c4ce66a1
JS
4301void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4302{
4303 bool lvalue = is_active_lvalue(e);
4304 if (lvalue && !s.guru_mode)
dc09353a 4305 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4306
4307 if (e->module.empty())
4308 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4309
5f36109e 4310 functioncall* result = NULL;
8b31197b
JS
4311
4312 // split the module string by ':' for alternatives
4313 vector<string> modules;
4314 tokenize(e->module, modules, ":");
b5a0dd41 4315 bool userspace_p=false; // PR10601
5f36109e 4316 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4317 {
8b31197b 4318 string& module = modules[i];
fb0274bc 4319 filter_special_modules(module);
abb41d92 4320
c4ce66a1
JS
4321 // NB: This uses '/' to distinguish between kernel modules and userspace,
4322 // which means that userspace modules won't get any PATH searching.
4323 dwflpp* dw;
707bf35e
JS
4324 try
4325 {
b5a0dd41
FCE
4326 userspace_p=is_user_module (module);
4327 if (! userspace_p)
707bf35e
JS
4328 {
4329 // kernel or kernel module target
ae2552da 4330 dw = db.get_kern_dw(s, module);
707bf35e
JS
4331 }
4332 else
4333 {
05fb3e0c 4334 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4335 dw = db.get_user_dw(s, module);
4336 }
4337 }
4338 catch (const semantic_error& er)
4339 {
4340 /* ignore and go to the next module */
4341 continue;
4342 }
c4ce66a1 4343
5f36109e 4344 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
06de3a04 4345 dw->iterate_over_modules<base_query>(&query_module, &q);
c4ce66a1 4346 }
abb41d92 4347
5f36109e 4348 if (!result)
c4ce66a1 4349 {
946e1a48
JS
4350 // We pass the unresolved cast_op to the next pass, and hope
4351 // that this value ends up not being referenced after all, so
4352 // it can be optimized out quietly.
c4ce66a1
JS
4353 provide (e);
4354 return;
4355 }
4356
c4ce66a1
JS
4357 if (lvalue)
4358 {
4359 // Provide the functioncall to our parent, so that it can be
4360 // used to substitute for the assignment node immediately above
4361 // us.
4362 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4363 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4364 }
4365
5f36109e 4366 result->visit (this);
77de5e9e
GH
4367}
4368
4369
bd1fcbad
YZ
4370struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4371{
4372 systemtap_session& s;
4373 dwarf_builder& db;
4374
4375 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4376 s(s), db(db) {}
4377 void visit_atvar_op (atvar_op* e);
4378};
4379
4380
4381struct dwarf_atvar_query: public base_query
4382{
4383 atvar_op& e;
4384 const bool userspace_p, lvalue;
4385 functioncall*& result;
4386 unsigned& tick;
4387 const string cu_name_pattern;
4388
4389 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4390 const bool userspace_p, const bool lvalue,
4391 functioncall*& result,
4392 unsigned& tick):
4393 base_query(dw, module), e(e),
4394 userspace_p(userspace_p), lvalue(lvalue), result(result),
4395 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4396
4397 void handle_query_module ();
4398 void query_library (const char *) {}
4399 void query_plt (const char *entry, size_t addr) {}
5c378838 4400 static int atvar_query_cu (Dwarf_Die *cudie, dwarf_atvar_query *q);
bd1fcbad
YZ
4401};
4402
4403
4404int
5c378838 4405dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, dwarf_atvar_query *q)
bd1fcbad 4406{
bd1fcbad
YZ
4407 if (! q->e.cu_name.empty())
4408 {
c60517ca 4409 const char *die_name = dwarf_diename(cudie) ?: "";
bd1fcbad
YZ
4410 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4411 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4412 {
4413 return DWARF_CB_OK;
4414 }
4415 }
4416
4417 try
4418 {
4419 vector<Dwarf_Die> scopes(1, *cudie);
4420
4421 q->dw.focus_on_cu (cudie);
4422
4423 if (! q->e.components.empty() &&
4424 q->e.components.back().type == target_symbol::comp_pretty_print)
4425 {
4426 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4427 q->userspace_p, q->e);
4428 q->result = dpp.expand();
4429 return DWARF_CB_ABORT;
4430 }
4431
4432 exp_type type = pe_long;
4433 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4434 &q->e, q->lvalue, type);
4435
4436 if (code.empty())
4437 return DWARF_CB_OK;
4438
4439 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4440 : "_dwarf_tvar_get")
4441 + "_" + q->e.sym_name()
4442 + "_" + lex_cast(q->tick++));
4443
4444 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4445 q->userspace_p, q->lvalue,
4446 &q->e);
4447 }
4448 catch (const semantic_error& er)
4449 {
4450 // Here we suppress the error because we often just have too many
4451 // when scanning all the CUs.
4452 return DWARF_CB_OK;
4453 }
4454
4455 if (q->result) {
4456 return DWARF_CB_ABORT;
4457 }
4458
4459 return DWARF_CB_OK;
4460}
4461
4462
4463void
4464dwarf_atvar_query::handle_query_module ()
4465{
4466
4467 dw.iterate_over_cus(atvar_query_cu, this, false);
4468}
4469
4470
4471void
4472dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4473{
4474 const bool lvalue = is_active_lvalue(e);
4475 if (lvalue && !s.guru_mode)
dc09353a 4476 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4477 "need stap -g"), e->tok);
4478
4479 if (e->module.empty())
4480 e->module = "kernel";
4481
4482 functioncall* result = NULL;
4483
4484 // split the module string by ':' for alternatives
4485 vector<string> modules;
4486 tokenize(e->module, modules, ":");
4487 bool userspace_p = false;
4488 for (unsigned i = 0; !result && i < modules.size(); ++i)
4489 {
4490 string& module = modules[i];
4491
4492 dwflpp* dw;
4493 try
4494 {
4495 userspace_p = is_user_module(module);
4496 if (!userspace_p)
4497 {
4498 // kernel or kernel module target
4499 dw = db.get_kern_dw(s, module);
4500 }
4501 else
4502 {
4503 module = find_executable(module, "", s.sysenv);
4504 dw = db.get_user_dw(s, module);
4505 }
4506 }
4507 catch (const semantic_error& er)
4508 {
4509 /* ignore and go to the next module */
4510 continue;
4511 }
4512
4513 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
06de3a04 4514 dw->iterate_over_modules<base_query>(&query_module, &q);
bd1fcbad
YZ
4515
4516 if (result)
4517 {
4518 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4519
4520 if (lvalue)
4521 {
4522 // Provide the functioncall to our parent, so that it can be
4523 // used to substitute for the assignment node immediately above
4524 // us.
4525 assert(!target_symbol_setter_functioncalls.empty());
4526 *(target_symbol_setter_functioncalls.top()) = result;
4527 }
4528
4529 result->visit(this);
4530 return;
4531 }
4532
4533 /* Unable to find the variable in the current module, so we chain
4534 * an error in atvar_op */
dc09353a 4535 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4536 e->sym_name().c_str(), module.c_str(),
4537 e->cu_name.empty() ? "" : _(", in "),
4538 e->cu_name.c_str()));
4539 e->chain (er);
4540 }
4541
4542 provide(e);
4543}
4544
4545
b8da0ad1
FCE
4546void
4547dwarf_derived_probe::printsig (ostream& o) const
4548{
4549 // Instead of just printing the plain locations, we add a PC value
4550 // as a comment as a way of telling e.g. apart multiple inlined
4551 // function instances. This is distinct from the verbose/clog
4552 // output, since this part goes into the cache hash calculations.
4553 sole_location()->print (o);
6d0f3f0c 4554 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4555 printsig_nested (o);
4556}
4557
4558
4559
dc38c0ae 4560void
b20febf3
FCE
4561dwarf_derived_probe::join_group (systemtap_session& s)
4562{
af234c40
JS
4563 // skip probes which are paired entry-handlers
4564 if (!has_return && (saved_longs || saved_strings))
4565 return;
4566
b20febf3
FCE
4567 if (! s.dwarf_derived_probes)
4568 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4569 s.dwarf_derived_probes->enroll (this);
4570}
4571
4572
2b69faaf
JS
4573static bool
4574kernel_supports_inode_uprobes(systemtap_session& s)
4575{
4576 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4577 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4578 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4579 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4580 && s.kernel_config["CONFIG_UPROBES"] == "y");
4581}
4582
4583
3667d615
JS
4584static bool
4585kernel_supports_inode_uretprobes(systemtap_session& s)
4586{
766013af
JS
4587 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4588 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4589 return kernel_supports_inode_uprobes(s) &&
af9e147f 4590 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4591}
4592
4593
5261f7ab
DS
4594void
4595check_process_probe_kernel_support(systemtap_session& s)
4596{
4597 // If we've got utrace, we're good to go.
4598 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4599 return;
4600
8c021542
DS
4601 // We don't have utrace. For process probes that aren't
4602 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4603 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4604 // specific autoconf test for its needs.
8c021542
DS
4605 //
4606 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4607 // approximation.
4608 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4609 return;
4610
d3e959b0
DS
4611 // For uprobes-based process probes, we need the task_finder plus
4612 // the builtin inode-uprobes.
8c021542
DS
4613 if (s.need_uprobes
4614 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4615 && kernel_supports_inode_uprobes(s))
8c021542
DS
4616 return;
4617
dc09353a 4618 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4619}
4620
4621
b20febf3
FCE
4622dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4623 const string& filename,
4624 int line,
91af0778 4625 // module & section specify a relocation
b20febf3
FCE
4626 // base for <addr>, unless section==""
4627 // (equivalently module=="kernel")
4628 const string& module,
4629 const string& section,
4630 // NB: dwfl_addr is the virtualized
4631 // address for this symbol.
4632 Dwarf_Addr dwfl_addr,
4633 // addr is the section-offset for
4634 // actual relocation.
4635 Dwarf_Addr addr,
4636 dwarf_query& q,
37ebca01 4637 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4638 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4639 module (module), section (section), addr (addr),
63b4fd14 4640 path (q.path),
27dc09b1 4641 has_process (q.has_process),
c9bad430
DS
4642 has_return (q.has_return),
4643 has_maxactive (q.has_maxactive),
c57ea854 4644 has_library (q.has_library),
6b66b9f7 4645 maxactive_val (q.maxactive_val),
b642c901
SC
4646 user_path (q.user_path),
4647 user_lib (q.user_lib),
af234c40 4648 access_vars(false),
c57ea854 4649 saved_longs(0), saved_strings(0),
af234c40 4650 entry_handler(0)
bd2b1e68 4651{
b642c901
SC
4652 if (user_lib.size() != 0)
4653 has_library = true;
4654
6b66b9f7
JS
4655 if (q.has_process)
4656 {
4657 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4658 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4659 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4660 // by the incoming section value (".absolute" vs. ".dynamic").
4661 // XXX Assert invariants here too?
2b69faaf
JS
4662
4663 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4664 // ditto for userspace runtimes (dyninst)
ac3af990 4665 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4666 section == ".absolute" && addr == dwfl_addr &&
4667 addr >= q.dw.module_start && addr < q.dw.module_end)
4668 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4669 }
4670 else
4671 {
4672 // Assert kernel relocation invariants
4673 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4674 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4675 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4676 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4677 }
2930abc7 4678
21beacc9
FCE
4679 // XXX: hack for strange g++/gcc's
4680#ifndef USHRT_MAX
4681#define USHRT_MAX 32767
4682#endif
4683
606fd9c8 4684 // Range limit maxactive() value
6b66b9f7 4685 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4686 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4687 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4688
a7696882
JL
4689 // Expand target variables in the probe body. Even if the scope_die is
4690 // invalid, we still want to expand things such as $$vars/$$parms/etc...
4691 // (PR15999, PR16473). Access to specific context vars e.g. $argc will not be
4692 // expanded and will produce an error during the typeresolution_info pass.
8fc05e57 4693 {
6b66b9f7 4694 // XXX: user-space deref's for q.has_process!
5a617dc6
JL
4695
4696 // PR14436: if we're expanding target variables in the probe body of a
4697 // .return probe, we need to make the expansion at the postprologue addr
4698 // instead (if any), which is then also the spot where the entry handler
4699 // probe is placed. (Note that at this point, a nonzero prologue_end
4700 // implies that it should be used, i.e. code is unoptimized).
4701 Dwarf_Addr handler_dwfl_addr = dwfl_addr;
4702 if (q.prologue_end != 0 && q.has_return)
4703 {
4704 handler_dwfl_addr = q.prologue_end;
4705 if (q.sess.verbose > 2)
4706 clog << _F("expanding .return vars at prologue_end (0x%s) "
4707 "rather than entrypc (0x%s)\n",
4708 lex_cast_hex(handler_dwfl_addr).c_str(),
4709 lex_cast_hex(dwfl_addr).c_str());
4710 }
4711 dwarf_var_expanding_visitor v (q, scope_die, handler_dwfl_addr);
8b095b45 4712 v.replace (this->body);
3689db05
SC
4713
4714 // Propagate perf.counters so we can emit later
4715 this->perf_counter_refs = v.perf_counter_refs;
4716 // Emit local var used to save the perf counter read value
698de6cc 4717 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4718 for (pcii = v.perf_counter_refs.begin();
4719 pcii != v.perf_counter_refs.end(); pcii++)
4720 {
4721 map<string, pair<string,derived_probe*> >::iterator it;
4722 // Find the associated perf counter probe
4723 for (it=q.sess.perf_counters.begin() ;
4724 it != q.sess.perf_counters.end();
4725 it++)
4726 if ((*it).second.second == (*pcii))
4727 break;
4728 vardecl* vd = new vardecl;
4729 vd->name = "__perf_read_" + (*it).first;
4730 vd->tok = this->tok;
4731 vd->set_arity(0, this->tok);
4732 vd->type = pe_long;
4733 vd->synthetic = true;
4734 this->locals.push_back (vd);
4735 }
4736
4737
6b66b9f7
JS
4738 if (!q.has_process)
4739 access_vars = v.visited;
37ebca01
FCE
4740
4741 // If during target-variable-expanding the probe, we added a new block
4742 // of code, add it to the start of the probe.
4743 if (v.add_block)
ba6f838d 4744 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4745
4746 // If when target-variable-expanding the probe, we need to synthesize a
4747 // sibling function-entry probe. We don't go through the whole probe derivation
4748 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4749 // dwarf-induced duplication.
4750 if (v.add_call_probe)
37ebca01 4751 {
2260f4e3
FCE
4752 assert (q.has_return && !q.has_call);
4753
4754 // We temporarily replace q.base_probe.
4755 statement* old_body = q.base_probe->body;
4756 q.base_probe->body = v.add_call_probe;
4757 q.has_return = false;
4758 q.has_call = true;
af234c40 4759
da23eceb 4760 if (q.has_process)
5a617dc6
JL
4761 {
4762 // Place handler probe at the same addr as where the vars were
4763 // expanded (which may not be the same addr as the one for the
4764 // main retprobe, PR14436).
4765 Dwarf_Addr handler_addr = addr;
4766 if (handler_dwfl_addr != dwfl_addr)
4767 // adjust section offset by prologue_end-entrypc
4768 handler_addr += handler_dwfl_addr - dwfl_addr;
4769 entry_handler = new uprobe_derived_probe (funcname, filename,
4770 line, module, section,
4771 handler_dwfl_addr,
4772 handler_addr, q,
4773 scope_die);
4774 }
da23eceb 4775 else
af234c40
JS
4776 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4777 module, section, dwfl_addr,
4778 addr, q, scope_die);
4779
4780 saved_longs = entry_handler->saved_longs = v.saved_longs;
4781 saved_strings = entry_handler->saved_strings = v.saved_strings;
4782
4783 q.results.push_back (entry_handler);
2260f4e3
FCE
4784
4785 q.has_return = true;
4786 q.has_call = false;
4787 q.base_probe->body = old_body;
37ebca01 4788 }
a7696882
JL
4789 // Save the local variables for listing mode. If the scope_die is null,
4790 // local vars aren't accessible, so no need to invoke saveargs (PR10820).
bba368c5
JL
4791 if (!null_die(scope_die) &&
4792 q.sess.dump_mode == systemtap_session::dump_matched_probes_vars)
4793 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4794 }
0a98fd42 4795
5d23847d 4796 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4797 // "reverse-engineered" form of the incoming (q.base_loc) probe
4798 // point. This allows a user to see what function / file / line
4799 // number any particular match of the wildcards.
919debfc
JL
4800
4801 vector<probe_point::component*> comps;
4802 if (q.has_kernel)
4803 comps.push_back (new probe_point::component(TOK_KERNEL));
4804 else if(q.has_module)
4805 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4806 else if(q.has_process)
4807 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4808 else
4809 assert (0);
4810
4811 string fn_or_stmt;
4812 if (q.has_function_str || q.has_function_num)
e772a6e7 4813 fn_or_stmt = TOK_FUNCTION;
919debfc 4814 else
e772a6e7 4815 fn_or_stmt = TOK_STATEMENT;
919debfc
JL
4816
4817 if (q.has_function_str || q.has_statement_str)
4818 {
79954c0f 4819 string retro_name = q.final_function_name(funcname, filename.c_str(), line);
919debfc
JL
4820 comps.push_back
4821 (new probe_point::component
4822 (fn_or_stmt, new literal_string (retro_name)));
4823 }
4824 else if (q.has_function_num || q.has_statement_num)
4825 {
4826 Dwarf_Addr retro_addr;
4827 if (q.has_function_num)
4828 retro_addr = q.function_num_val;
4829 else
4830 retro_addr = q.statement_num_val;
4831 comps.push_back (new probe_point::component
4832 (fn_or_stmt,
4833 new literal_number(retro_addr, true)));
4834
4835 if (q.has_absolute)
4836 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
4837 }
4838
4839 if (q.has_call)
4840 comps.push_back (new probe_point::component(TOK_CALL));
4841 if (q.has_exported)
4842 comps.push_back (new probe_point::component(TOK_EXPORTED));
4843 if (q.has_inline)
4844 comps.push_back (new probe_point::component(TOK_INLINE));
4845 if (has_return)
4846 comps.push_back (new probe_point::component(TOK_RETURN));
4847 if (has_maxactive)
4848 comps.push_back (new probe_point::component
4849 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
4850
4851 // Overwrite it.
4852 this->sole_location()->components = comps;
e2941743
JL
4853
4854 // if it's a .callee[s[(N)]] call, add checks to the probe body so that the
4855 // user body is only 'triggered' when called from q.callers[N-1], which
4856 // itself is called from q.callers[N-2], etc... I.E.
4857 // callees(N) --> N elements in q.callers --> N checks against [u]stack(0..N-1)
4858 if ((q.has_callee || q.has_callees_num) && q.callers && !q.callers->empty())
4859 {
4860 if (q.sess.verbose > 2)
7761da8b 4861 clog << _F("adding caller checks for callee %s\n", funcname.c_str());
e2941743
JL
4862
4863 // Copy the stack and empty it out
4864 stack<Dwarf_Addr> callers(*q.callers);
4865 for (unsigned level = 1; !callers.empty(); level++,
4866 callers.pop())
4867 {
4868 Dwarf_Addr caller = callers.top();
4869
4870 // We first need to make the caller addr relocatable
4871 string caller_section;
4872 Dwarf_Addr caller_reloc;
4873 if (module == TOK_KERNEL)
4874 { // allow for relocatable kernel (see also add_probe_point())
4875 caller_reloc = caller - q.sess.sym_stext;
4876 caller_section = "_stext";
4877 }
4878 else
4879 caller_reloc = q.dw.relocate_address(caller,
4880 caller_section);
4881
4882 if (q.sess.verbose > 2)
7761da8b
JL
4883 clog << _F("adding caller check [u]stack(%d) == reloc(0x%s)\n",
4884 level, lex_cast_hex(caller_reloc).c_str());
e2941743
JL
4885
4886 // We want to add a statement like this:
6211aed9 4887 // if (!_caller_match(user, mod, sec, addr)) next;
e2941743
JL
4888 // Something similar is done in semantic_pass_conditions()
4889
4890 functioncall* check = new functioncall();
4891 check->tok = this->tok;
6211aed9 4892 check->function = "_caller_match";
e2941743
JL
4893 check->args.push_back(new literal_number(q.has_process));
4894 check->args[0]->tok = this->tok;
4895 check->args.push_back(new literal_number(level));
4896 check->args[1]->tok = this->tok;
4897 check->args.push_back(new literal_string(module));
4898 check->args[2]->tok = this->tok;
4899 check->args.push_back(new literal_string(caller_section));
4900 check->args[3]->tok = this->tok;
4901 check->args.push_back(new literal_number(caller_reloc, true /* hex */));
4902 check->args[4]->tok = this->tok;
4903
4904 unary_expression* notexp = new unary_expression();
4905 notexp->tok = this->tok;
4906 notexp->op = "!";
4907 notexp->operand = check;
4908
4909 if_statement* ifs = new if_statement();
4910 ifs->tok = this->tok;
4911 ifs->thenblock = new next_statement();
4912 ifs->thenblock->tok = this->tok;
4913 ifs->elseblock = NULL;
4914 ifs->condition = notexp;
4915
4916 this->body = new block(ifs, this->body);
4917 }
4918 }
2930abc7
FCE
4919}
4920
bd2b1e68 4921
0a98fd42 4922void
8c67c337
JS
4923dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4924 Dwarf_Addr dwfl_addr)
0a98fd42 4925{
9aa8ffce 4926 if (null_die(scope_die))
0a98fd42 4927 return;
0a98fd42 4928
8c67c337 4929 bool verbose = q.sess.verbose > 2;
0a98fd42 4930
8c67c337 4931 if (verbose)
b530b5b3 4932 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4933
8c67c337
JS
4934 if (has_return)
4935 {
4936 /* Only save the return value if it has a type. */
4937 string type_name;
4938 Dwarf_Die type_die;
4939 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4940 dwarf_type_name(&type_die, type_name))
4941 args.push_back("$return:"+type_name);
4942
4943 else if (verbose)
b530b5b3
LB
4944 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4945 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4946 }
d87623a1 4947
0a98fd42 4948 Dwarf_Die arg;
4ef35696
JS
4949 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4950 for (unsigned i = 0; i < scopes.size(); ++i)
4951 {
4952 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4953 break; // we don't want file-level variables
4954 if (dwarf_child (&scopes[i], &arg) == 0)
4955 do
0a98fd42 4956 {
4ef35696
JS
4957 switch (dwarf_tag (&arg))
4958 {
4959 case DW_TAG_variable:
4960 case DW_TAG_formal_parameter:
4961 break;
0a98fd42 4962
4ef35696
JS
4963 default:
4964 continue;
4965 }
0a98fd42 4966
4ef35696
JS
4967 /* Ignore this local if it has no name. */
4968 const char *arg_name = dwarf_diename (&arg);
4969 if (!arg_name)
8c67c337
JS
4970 {
4971 if (verbose)
b530b5b3
LB
4972 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4973 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4974 continue;
4975 }
4ef35696
JS
4976
4977 if (verbose)
b530b5b3
LB
4978 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4979 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4980
4981 /* Ignore this local if it has no location (or not at this PC). */
4982 /* NB: It still may not be directly accessible, e.g. if it is an
4983 * aggregate type, implicit_pointer, etc., but the user can later
4984 * figure out how to access the interesting parts. */
45b02a36
FCE
4985
4986 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4987 * several synthetic
4988 * probe foo { $var }
4989 * probes, testing them for overall resolvability.
4990 */
4991
4ef35696
JS
4992 Dwarf_Attribute attr_mem;
4993 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4994 {
4995 Dwarf_Op *expr;
4996 size_t len;
4997 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4998 {
4999 if (verbose)
b530b5b3
LB
5000 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
5001 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
5002 continue;
5003 }
5004 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
5005 &len, 1) == 1 && len > 0))
5006 {
45b02a36
FCE
5007 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
5008 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
5009 &len, 1) == 1 && len > 0))) {
5010 if (verbose)
5011 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
5012 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
5013 continue;
5014 }
4ef35696
JS
5015 }
5016 }
5017
5018 /* Ignore this local if it has no type. */
5019 string type_name;
5020 Dwarf_Die type_die;
5021 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
5022 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
5023 {
5024 if (verbose)
b530b5b3
LB
5025 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
5026 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
5027 continue;
5028 }
8c67c337 5029
4ef35696
JS
5030 /* This local looks good -- save it! */
5031 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 5032 }
4ef35696
JS
5033 while (dwarf_siblingof (&arg, &arg) == 0);
5034 }
0a98fd42
JS
5035}
5036
5037
5038void
d0bfd2ac 5039dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 5040{
d0bfd2ac 5041 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
5042}
5043
5044
27dc09b1 5045void
42e38653 5046dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
5047{
5048 if (has_process)
5049 {
5050 // These probes are allowed for unprivileged users, but only in the
5051 // context of processes which they own.
5052 emit_process_owner_assertion (o);
5053 return;
5054 }
5055
5056 // Other probes must contain the default assertion which aborts
5057 // if executed by an unprivileged user.
42e38653 5058 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
5059}
5060
5061
5062void
5063dwarf_derived_probe::print_dupe_stamp(ostream& o)
5064{
5065 if (has_process)
5066 {
5067 // These probes are allowed for unprivileged users, but only in the
5068 // context of processes which they own.
5069 print_dupe_stamp_unprivileged_process_owner (o);
5070 return;
5071 }
5072
5073 // Other probes must contain the default dupe stamp
5074 derived_probe::print_dupe_stamp (o);
5075}
5076
64211010 5077
7a053d3b 5078void
20c6c071 5079dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 5080 dwarf_builder * dw,
42e38653 5081 privilege_t privilege)
bd2b1e68 5082{
27dc09b1 5083 root
42e38653 5084 ->bind_privilege(privilege)
27dc09b1 5085 ->bind(dw);
54efe513
GH
5086}
5087
7a053d3b 5088void
fd6602a0 5089dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 5090 dwarf_builder * dw,
42e38653 5091 privilege_t privilege)
2865d17a 5092{
27dc09b1 5093 root
42e38653 5094 ->bind_privilege(privilege)
27dc09b1 5095 ->bind(dw);
27dc09b1 5096 root->bind(TOK_CALL)
42e38653 5097 ->bind_privilege(privilege)
27dc09b1 5098 ->bind(dw);
4bda987e
SC
5099 root->bind(TOK_EXPORTED)
5100 ->bind_privilege(privilege)
5101 ->bind(dw);
27dc09b1 5102 root->bind(TOK_RETURN)
42e38653 5103 ->bind_privilege(privilege)
27dc09b1 5104 ->bind(dw);
1e035395 5105
f6be7c06
DB
5106 // For process probes / uprobes, .maxactive() is unused.
5107 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
5108 {
5109 root->bind(TOK_RETURN)
1e035395
FCE
5110 ->bind_num(TOK_MAXACTIVE)->bind(dw);
5111 }
bd2b1e68
GH
5112}
5113
7a053d3b 5114void
27dc09b1 5115dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 5116 systemtap_session& s,
27dc09b1
DB
5117 match_node * root,
5118 dwarf_builder * dw,
42e38653 5119 privilege_t privilege
27dc09b1 5120)
bd2b1e68
GH
5121{
5122 // Here we match 4 forms:
5123 //
5124 // .function("foo")
5125 // .function(0xdeadbeef)
5126 // .statement("foo")
5127 // .statement(0xdeadbeef)
5128
440d9b00 5129 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 5130 register_function_variants(fv_root, dw, privilege);
7f02ca94 5131 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 5132 fv_root->bind(TOK_INLINE)
42e38653 5133 ->bind_privilege(privilege)
440d9b00 5134 ->bind(dw);
7f02ca94
JS
5135 fv_root->bind_str(TOK_LABEL)
5136 ->bind_privilege(privilege)
440d9b00 5137 ->bind(dw);
c31add50
JL
5138 fv_root->bind_str(TOK_CALLEE)
5139 ->bind_privilege(privilege)
5140 ->bind(dw);
5141 fv_root->bind(TOK_CALLEES)
5142 ->bind_privilege(privilege)
5143 ->bind(dw);
5144 fv_root->bind_num(TOK_CALLEES)
5145 ->bind_privilege(privilege)
5146 ->bind(dw);
440d9b00
DB
5147
5148 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 5149 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
5150 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
5151 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
5152 {
5153 fv_root->bind(TOK_INLINE)
42e38653 5154 ->bind_privilege(privilege)
440d9b00
DB
5155 ->bind(dw);
5156 }
5157
42e38653
DB
5158 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
5159 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
5160}
5161
b1615c74
JS
5162void
5163dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
5164 match_node * root,
5165 dwarf_builder * dw)
5166{
5167 root->bind_str(TOK_MARK)
f66bb29a 5168 ->bind_privilege(pr_all)
b1615c74
JS
5169 ->bind(dw);
5170 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 5171 ->bind_privilege(pr_all)
b1615c74
JS
5172 ->bind(dw);
5173}
5174
5175void
5176dwarf_derived_probe::register_plt_variants(systemtap_session& s,
5177 match_node * root,
5178 dwarf_builder * dw)
5179{
5180 root->bind(TOK_PLT)
f66bb29a 5181 ->bind_privilege(pr_all)
b1615c74
JS
5182 ->bind(dw);
5183 root->bind_str(TOK_PLT)
f66bb29a 5184 ->bind_privilege(pr_all)
b1615c74
JS
5185 ->bind(dw);
5186 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5187 ->bind_privilege(pr_all)
b1615c74
JS
5188 ->bind(dw);
5189 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5190 ->bind_privilege(pr_all)
b1615c74 5191 ->bind(dw);
bd2b1e68
GH
5192}
5193
5194void
c4ce66a1 5195dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 5196{
c4ce66a1 5197 match_node* root = s.pattern_root;
bd2b1e68
GH
5198 dwarf_builder *dw = new dwarf_builder();
5199
c4ce66a1
JS
5200 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
5201 s.code_filters.push_back(filter);
5202
bd1fcbad
YZ
5203 filter = new dwarf_atvar_expanding_visitor(s, *dw);
5204 s.code_filters.push_back(filter);
5205
73f52eb4
DB
5206 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
5207 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
5208 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
5209 ->bind(dw);
2cab6244 5210
7f02ca94
JS
5211 match_node* uprobes[] = {
5212 root->bind(TOK_PROCESS),
5213 root->bind_str(TOK_PROCESS),
5214 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5215 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5216 };
5217 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
5218 {
f66bb29a 5219 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
5220 register_sdt_variants(s, uprobes[i], dw);
5221 register_plt_variants(s, uprobes[i], dw);
5222 }
bd2b1e68
GH
5223}
5224
9020300d 5225void
3689db05
SC
5226dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
5227{
698de6cc 5228 std::set<derived_probe*>::iterator pcii;
3689db05
SC
5229 for (pcii = perf_counter_refs.begin();
5230 pcii != perf_counter_refs.end();
5231 pcii++)
5232 {
5233 map<string, pair<string,derived_probe*> >::iterator it;
5234 // Find the associated perf.counter probe
5235 unsigned i = 0;
5236 for (it=s.perf_counters.begin() ;
5237 it != s.perf_counters.end();
5238 it++, i++)
5239 if ((*it).second.second == (*pcii))
5240 break;
5241 // place the perf counter read so it precedes stp_lock_probe
5242 o->newline() << "l->l___perf_read_" + (*it).first
5243 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
5244 + lex_cast(i) + "))));";
5245 }
b78a0fbb 5246
b95e2b79
MH
5247 if (access_vars)
5248 {
5249 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 5250 o->newline() << "#if defined __ia64__";
d9aed31e 5251 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 5252 o->newline() << "#endif";
b95e2b79 5253 }
9020300d 5254}
2930abc7 5255
b20febf3 5256// ------------------------------------------------------------------------
46b84a80
DS
5257
5258void
b20febf3 5259dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 5260{
b20febf3 5261 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
5262
5263 // XXX: probes put at the same address should all share a
5264 // single kprobe/kretprobe, and have their handlers executed
5265 // sequentially.
b55bc428
FCE
5266}
5267
7a053d3b 5268void
775d51e5 5269dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 5270{
b20febf3 5271 if (probes_by_module.empty()) return;
2930abc7 5272
775d51e5
DS
5273 s.op->newline() << "/* ---- dwarf probes ---- */";
5274
5275 // Warn of misconfigured kernels
f41595cc
FCE
5276 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
5277 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
5278 s.op->newline() << "#endif";
775d51e5 5279 s.op->newline();
f41595cc 5280
f07c3b68 5281 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 5282 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
5283 s.op->newline() << "#endif";
5284
14cf7e42 5285 // Forward decls
2ba1736a 5286 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 5287
b20febf3
FCE
5288 // Forward declare the master entry functions
5289 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5290 s.op->line() << " struct pt_regs *regs);";
5291 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5292 s.op->line() << " struct pt_regs *regs);";
5293
42cb22bd
MH
5294 // Emit an array of kprobe/kretprobe pointers
5295 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5296 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
5297 s.op->newline() << "#endif";
5298
b20febf3 5299 // Emit the actual probe list.
606fd9c8
FCE
5300
5301 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
5302 // struct stap_dwarf_probe, but it being initialized data makes it add
5303 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 5304 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
5305 // NB: bss!
5306
4c2732a1 5307 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
5308 s.op->newline(1) << "const unsigned return_p:1;";
5309 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 5310 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 5311 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 5312 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 5313
af234c40
JS
5314 // data saved in the kretprobe_instance packet
5315 s.op->newline() << "const unsigned short saved_longs;";
5316 s.op->newline() << "const unsigned short saved_strings;";
5317
faea5e16 5318 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5319 // are small and uniform enough to justify putting char[MAX]'s into
5320 // the array instead of relocated char*'s.
faea5e16
JS
5321 size_t module_name_max = 0, section_name_max = 0;
5322 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5323 size_t all_name_cnt = probes_by_module.size(); // for average
5324 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5325 {
5326 dwarf_derived_probe* p = it->second;
5327#define DOIT(var,expr) do { \
5328 size_t var##_size = (expr) + 1; \
5329 var##_max = max (var##_max, var##_size); \
5330 var##_tot += var##_size; } while (0)
5331 DOIT(module_name, p->module.size());
5332 DOIT(section_name, p->section.size());
606fd9c8
FCE
5333#undef DOIT
5334 }
5335
5336 // Decide whether it's worthwhile to use char[] or char* by comparing
5337 // the amount of average waste (max - avg) to the relocation data size
5338 // (3 native long words).
5339#define CALCIT(var) \
5340 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5341 { \
5342 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5343 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5344 << "[" << var##_name_max << "]" << endl; \
5345 } \
5346 else \
5347 { \
b0986e7a 5348 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5349 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5350 }
5351
5352 CALCIT(module);
5353 CALCIT(section);
e6fe60e7 5354#undef CALCIT
606fd9c8 5355
b0986e7a 5356 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5357 s.op->newline() << "const struct stap_probe * const probe;";
5358 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5359 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5360 s.op->indent(1);
5361
5362 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5363 {
b20febf3
FCE
5364 dwarf_derived_probe* p = it->second;
5365 s.op->newline() << "{";
5366 if (p->has_return)
5367 s.op->line() << " .return_p=1,";
c9bad430 5368 if (p->has_maxactive)
606fd9c8
FCE
5369 {
5370 s.op->line() << " .maxactive_p=1,";
5371 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5372 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5373 }
af234c40
JS
5374 if (p->saved_longs || p->saved_strings)
5375 {
5376 if (p->saved_longs)
5377 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5378 if (p->saved_strings)
5379 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5380 if (p->entry_handler)
c87ae2c1 5381 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5382 }
b350f56b
JS
5383 if (p->locations[0]->optional)
5384 s.op->line() << " .optional_p=1,";
dc38c256 5385 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5386 s.op->line() << " .module=\"" << p->module << "\",";
5387 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5388 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5389 s.op->line() << " },";
2930abc7 5390 }
2930abc7 5391
b20febf3
FCE
5392 s.op->newline(-1) << "};";
5393
5394 // Emit the kprobes callback function
5395 s.op->newline();
5396 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5397 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5398 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5399 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5400 // Check that the index is plausible
5401 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5402 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5403 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5404 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5405 s.op->line() << "];";
71db462b 5406 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5407 "stp_probe_type_kprobe");
d9aed31e 5408 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5409
5410 // Make it look like the IP is set as it wouldn't have been replaced
5411 // by a breakpoint instruction when calling real probe handler. Reset
5412 // IP regs on return, so we don't confuse kprobes. PR10458
5413 s.op->newline() << "{";
5414 s.op->indent(1);
d9aed31e 5415 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5416 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5417 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5418 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5419 s.op->newline(-1) << "}";
5420
f887a8c9 5421 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5422 s.op->newline() << "return 0;";
5423 s.op->newline(-1) << "}";
5424
5425 // Same for kretprobes
5426 s.op->newline();
af234c40
JS
5427 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5428 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5429 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5430
5431 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5432 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5433 // Check that the index is plausible
5434 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5435 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5436 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5437 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5438 s.op->line() << "];";
5439
7c3e97f4 5440 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5441 s.op->newline() << "if (sp) {";
5442 s.op->indent(1);
71db462b 5443 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5444 "stp_probe_type_kretprobe");
d9aed31e 5445 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5446
5447 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5448 s.op->newline() << "c->ips.krp.pi = inst;";
5449 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5450
5451 // Make it look like the IP is set as it wouldn't have been replaced
5452 // by a breakpoint instruction when calling real probe handler. Reset
5453 // IP regs on return, so we don't confuse kprobes. PR10458
5454 s.op->newline() << "{";
d9aed31e 5455 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5456 s.op->newline() << "if (entry)";
5457 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5458 s.op->newline(-1) << "else";
5459 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5460 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5461 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5462 s.op->newline(-1) << "}";
5463
f887a8c9 5464 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5465 s.op->newline(-1) << "}";
b20febf3
FCE
5466 s.op->newline() << "return 0;";
5467 s.op->newline(-1) << "}";
af234c40
JS
5468
5469 s.op->newline();
5470 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5471 s.op->line() << " struct pt_regs *regs) {";
5472 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5473 s.op->newline(-1) << "}";
5474
5475 s.op->newline();
5476 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5477 s.op->line() << " struct pt_regs *regs) {";
5478 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5479 s.op->newline(-1) << "}";
b642c901 5480
14cf7e42 5481 s.op->newline();
20c6c071 5482}
ec4373ff 5483
20c6c071 5484
dc38c0ae 5485void
b20febf3
FCE
5486dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5487{
5488 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5489 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5490 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5491 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5492 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5493 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5494 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5495 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5496 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5497 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5498 s.op->newline(-1) << "} else {";
f07c3b68 5499 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5500 s.op->newline(-1) << "}";
606fd9c8 5501 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5502 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5503 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5504 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5505 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5506 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5507 s.op->newline(-1) << "}";
5508 s.op->newline() << "#endif";
e4cb375f
MH
5509 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5510 s.op->newline() << "#ifdef __ia64__";
5511 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5512 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5513 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5514 s.op->newline() << "if (rc == 0) {";
5515 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5516 s.op->newline() << "if (rc != 0)";
5517 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5518 s.op->newline(-2) << "}";
5519 s.op->newline() << "#else";
606fd9c8 5520 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5521 s.op->newline() << "#endif";
b20febf3 5522 s.op->newline(-1) << "} else {";
e4cb375f 5523 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5524 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5525 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5526 s.op->newline() << "#ifdef __ia64__";
5527 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5528 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5529 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5530 s.op->newline() << "if (rc == 0) {";
5531 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5532 s.op->newline() << "if (rc != 0)";
5533 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5534 s.op->newline(-2) << "}";
5535 s.op->newline() << "#else";
606fd9c8 5536 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5537 s.op->newline() << "#endif";
b20febf3 5538 s.op->newline(-1) << "}";
9063462a
FCE
5539 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5540 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5541 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5542 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5543 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5544 // XXX: shall we increment numskipped?
5545 s.op->newline(-1) << "}";
5546
5547#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5548 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5549 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5550 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5551 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5552 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5553 s.op->newline() << "#ifdef __ia64__";
5554 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5555 s.op->newline() << "#endif";
c48cb0cc
FCE
5556 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5557 // not run for this early-abort case.
5558 s.op->newline(-1) << "}";
5559 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5560 s.op->newline(-1) << "}";
9063462a
FCE
5561#endif
5562
b20febf3
FCE
5563 s.op->newline() << "else sdp->registered_p = 1;";
5564 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5565}
5566
5567
b4be7cbc
FCE
5568void
5569dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5570{
5571 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5572 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5573 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5574 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5575 s.op->newline() << "int rc;";
5576
5577 // new module arrived?
5578 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5579 s.op->newline(1) << "if (sdp->return_p) {";
5580 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5581 s.op->newline() << "if (sdp->maxactive_p) {";
5582 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5583 s.op->newline(-1) << "} else {";
5584 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5585 s.op->newline(-1) << "}";
5586 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5587 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5588 s.op->newline() << "if (sdp->entry_probe) {";
5589 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5590 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5591 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5592 s.op->newline(-1) << "}";
5593 s.op->newline() << "#endif";
5594 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5595 s.op->newline() << "#ifdef __ia64__";
5596 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5597 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5598 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5599 s.op->newline() << "if (rc == 0) {";
5600 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5601 s.op->newline() << "if (rc != 0)";
5602 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5603 s.op->newline(-2) << "}";
5604 s.op->newline() << "#else";
5605 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5606 s.op->newline() << "#endif";
5607 s.op->newline(-1) << "} else {";
5608 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5609 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5610 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5611 s.op->newline() << "#ifdef __ia64__";
5612 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5613 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5614 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5615 s.op->newline() << "if (rc == 0) {";
5616 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5617 s.op->newline() << "if (rc != 0)";
5618 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5619 s.op->newline(-2) << "}";
5620 s.op->newline() << "#else";
5621 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5622 s.op->newline() << "#endif";
5623 s.op->newline(-1) << "}";
5624 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5625
5626 // old module disappeared?
5627 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5628 s.op->newline(1) << "if (sdp->return_p) {";
5629 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5630 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5631 s.op->newline() << "#ifdef STP_TIMING";
5632 s.op->newline() << "if (kp->u.krp.nmissed)";
5633 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5634 s.op->newline(-1) << "#endif";
065d5567 5635 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5636 s.op->newline() << "#ifdef STP_TIMING";
5637 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5638 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5639 s.op->newline(-1) << "#endif";
5640 s.op->newline(-1) << "} else {";
5641 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5642 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5643 s.op->newline() << "#ifdef STP_TIMING";
5644 s.op->newline() << "if (kp->u.kp.nmissed)";
5645 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5646 s.op->newline(-1) << "#endif";
5647 s.op->newline(-1) << "}";
5648 s.op->newline() << "#if defined(__ia64__)";
5649 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5650 s.op->newline() << "#endif";
5651 s.op->newline() << "sdp->registered_p = 0;";
5652 s.op->newline(-1) << "}";
5653
5654 s.op->newline(-1) << "}"; // for loop
5655}
5656
5657
5658
5659
46b84a80 5660void
b20febf3 5661dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5662{
42cb22bd
MH
5663 //Unregister kprobes by batch interfaces.
5664 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5665 s.op->newline() << "j = 0;";
5666 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5667 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5668 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5669 s.op->newline() << "if (! sdp->registered_p) continue;";
5670 s.op->newline() << "if (!sdp->return_p)";
5671 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5672 s.op->newline(-2) << "}";
5673 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5674 s.op->newline() << "j = 0;";
5675 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5676 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5677 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5678 s.op->newline() << "if (! sdp->registered_p) continue;";
5679 s.op->newline() << "if (sdp->return_p)";
5680 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5681 s.op->newline(-2) << "}";
5682 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5683 s.op->newline() << "#ifdef __ia64__";
5684 s.op->newline() << "j = 0;";
5685 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5686 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5687 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5688 s.op->newline() << "if (! sdp->registered_p) continue;";
5689 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5690 s.op->newline(-1) << "}";
5691 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5692 s.op->newline() << "#endif";
42cb22bd
MH
5693 s.op->newline() << "#endif";
5694
b20febf3
FCE
5695 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5696 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5697 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5698 s.op->newline() << "if (! sdp->registered_p) continue;";
5699 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5700 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5701 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5702 s.op->newline() << "#endif";
065d5567 5703 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5704 s.op->newline() << "#ifdef STP_TIMING";
5705 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5706 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5707 s.op->newline(-1) << "#endif";
065d5567 5708 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5709 s.op->newline() << "#ifdef STP_TIMING";
5710 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5711 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 5712 s.op->newline(-1) << "#endif";
557fb7a8 5713 s.op->newline(-1) << "} else {";
42cb22bd 5714 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5715 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5716 s.op->newline() << "#endif";
065d5567 5717 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5718 s.op->newline() << "#ifdef STP_TIMING";
5719 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5720 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5721 s.op->newline(-1) << "#endif";
b20febf3 5722 s.op->newline(-1) << "}";
e4cb375f
MH
5723 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5724 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5725 s.op->newline() << "#endif";
b20febf3
FCE
5726 s.op->newline() << "sdp->registered_p = 0;";
5727 s.op->newline(-1) << "}";
46b84a80
DS
5728}
5729
272c9036
WF
5730static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5731{
5732 string::size_type pos;
5733 string::size_type lastPos = str.find_first_not_of(" ", 0);
5734 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5735
5736 if (nextAt == string::npos)
5737 {
5738 // PR13934: Assembly probes are not forced to use the N@OP form.
5739 // In this case, N is inferred to be the native word size. Since we
5740 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5741 // then must not put any spaces in arguments, to avoid ambiguity.
5742 tokenize(str, tokens, " ");
5743 return;
5744 }
5745
272c9036
WF
5746 while (lastPos != string::npos)
5747 {
5748 pos = nextAt + 1;
5749 nextAt = str.find("@", pos);
5750 if (nextAt == string::npos)
5751 pos = string::npos;
5752 else
5753 pos = str.rfind(" ", nextAt);
5754
5755 tokens.push_back(str.substr(lastPos, pos - lastPos));
5756 lastPos = str.find_first_not_of(" ", pos);
5757 }
5758}
8aabf152 5759
8aabf152 5760
aff5d390 5761struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5762{
ae1418f0 5763 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5 5764 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
b8688ee6 5765 dwflpp& dw,
f83336a5
FCE
5766 int elf_machine,
5767 const string & process_name,
a794dbeb 5768 const string & provider_name,
aff5d390 5769 const string & probe_name,
71e5e13d 5770 stap_sdt_probe_type probe_type,
aff5d390 5771 const string & arg_string,
8aabf152 5772 int ac):
b8688ee6
JL
5773 session (s), dw (dw), elf_machine (elf_machine),
5774 process_name (process_name), provider_name (provider_name),
5775 probe_name (probe_name), probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5776 {
a57b7534
JL
5777 // sanity check that we're not somehow here for a kernel probe
5778 assert(is_user_module(process_name));
5779
2e6d617a 5780 build_dwarf_registers();
f83336a5 5781
ebbd2b45 5782 need_debug_info = false;
88e39987 5783 if (probe_type == uprobe3_type)
272c9036
WF
5784 {
5785 sdt_v3_tokenize(arg_string, arg_tokens);
5786 assert(arg_count <= 12);
5787 }
88e39987 5788 else
272c9036
WF
5789 {
5790 tokenize(arg_string, arg_tokens, " ");
5791 assert(arg_count <= 10);
5792 }
a8ec7719 5793 }
8aabf152 5794
f83336a5 5795 systemtap_session& session;
b8688ee6 5796 dwflpp& dw;
332ba7e7 5797 int elf_machine;
aff5d390 5798 const string & process_name;
a794dbeb 5799 const string & provider_name;
aff5d390 5800 const string & probe_name;
71e5e13d 5801 stap_sdt_probe_type probe_type;
8aabf152 5802 unsigned arg_count;
aff5d390 5803 vector<string> arg_tokens;
2e6d617a 5804
46a94997 5805 map<string, pair<unsigned,int> > dwarf_regs;
2e6d617a
JL
5806 string regnames;
5807 string percent_regnames;
5808
ebbd2b45 5809 bool need_debug_info;
aff5d390 5810
2e6d617a 5811 void build_dwarf_registers();
aff5d390 5812 void visit_target_symbol (target_symbol* e);
03c45fcb 5813 unsigned get_target_symbol_argno_and_validate (target_symbol* e);
ac074daf 5814 long parse_out_arg_precision(string& asmarg);
0fbf6fb8
JL
5815 expression* try_parse_arg_literal (target_symbol *e,
5816 const string& asmarg,
5817 long precision);
95b78bc9
JL
5818 expression* try_parse_arg_register (target_symbol *e,
5819 const string& asmarg,
5820 long precision);
8da56b62
JL
5821 expression* try_parse_arg_offset_register (target_symbol *e,
5822 const string& asmarg,
5823 long precision);
10fcca15
JL
5824 expression* try_parse_arg_effective_addr (target_symbol *e,
5825 const string& asmarg,
5826 long precision);
451c0c25
JL
5827 expression* try_parse_arg_varname (target_symbol *e,
5828 const string& asmarg,
5829 long precision);
6ef331c8
SC
5830 void visit_target_symbol_arg (target_symbol* e);
5831 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5832 void visit_atvar_op (atvar_op* e);
40a0c64e 5833 void visit_cast_op (cast_op* e);
aff5d390
SC
5834};
5835
2e6d617a
JL
5836void
5837sdt_uprobe_var_expanding_visitor::build_dwarf_registers ()
5838{
5839 /* Register name mapping table depends on the elf machine of this particular
5840 probe target process/file, not upon the host. So we can't just
5841 #ifdef _i686_ etc. */
5842
5843#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
5844 if (elf_machine == EM_X86_64) {
5845 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5846 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5847 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5848 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5849 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5850 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5851 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5852 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5853 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5854 DRI ("%sil", 4, QI);
5855 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5856 DRI ("%dil", 5, QI);
5857 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5858 DRI ("%bpl", 6, QI);
5859 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5860 DRI ("%spl", 7, QI);
5861 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5862 DRI ("%r8b", 8, QI);
5863 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5864 DRI ("%r9b", 9, QI);
5865 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5866 DRI ("%r10b", 10, QI);
5867 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5868 DRI ("%r11b", 11, QI);
5869 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5870 DRI ("%r12b", 12, QI);
5871 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5872 DRI ("%r13b", 13, QI);
5873 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5874 DRI ("%r14b", 14, QI);
5875 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5876 DRI ("%r15b", 15, QI);
5877 DRI ("%rip", 16, DI); DRI ("%eip", 16, SI); DRI ("%ip", 16, HI);
5878 } else if (elf_machine == EM_386) {
5879 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5880 DRI ("%ah", 0, QIh);
5881 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5882 DRI ("%ch", 1, QIh);
5883 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5884 DRI ("%dh", 2, QIh);
5885 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5886 DRI ("%bh", 3, QIh);
5887 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5888 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5889 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5890 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
5891 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
5892 DRI ("%r0", 0, DI);
5893 DRI ("%r1", 1, DI);
5894 DRI ("%r2", 2, DI);
5895 DRI ("%r3", 3, DI);
5896 DRI ("%r4", 4, DI);
5897 DRI ("%r5", 5, DI);
5898 DRI ("%r6", 6, DI);
5899 DRI ("%r7", 7, DI);
5900 DRI ("%r8", 8, DI);
5901 DRI ("%r9", 9, DI);
5902 DRI ("%r10", 10, DI);
5903 DRI ("%r11", 11, DI);
5904 DRI ("%r12", 12, DI);
5905 DRI ("%r13", 13, DI);
5906 DRI ("%r14", 14, DI);
5907 DRI ("%r15", 15, DI);
5908 DRI ("%r16", 16, DI);
5909 DRI ("%r17", 17, DI);
5910 DRI ("%r18", 18, DI);
5911 DRI ("%r19", 19, DI);
5912 DRI ("%r20", 20, DI);
5913 DRI ("%r21", 21, DI);
5914 DRI ("%r22", 22, DI);
5915 DRI ("%r23", 23, DI);
5916 DRI ("%r24", 24, DI);
5917 DRI ("%r25", 25, DI);
5918 DRI ("%r26", 26, DI);
5919 DRI ("%r27", 27, DI);
5920 DRI ("%r28", 28, DI);
5921 DRI ("%r29", 29, DI);
5922 DRI ("%r30", 30, DI);
5923 DRI ("%r31", 31, DI);
5924 // PR11821: unadorned register "names" without -mregnames
5925 DRI ("0", 0, DI);
5926 DRI ("1", 1, DI);
5927 DRI ("2", 2, DI);
5928 DRI ("3", 3, DI);
5929 DRI ("4", 4, DI);
5930 DRI ("5", 5, DI);
5931 DRI ("6", 6, DI);
5932 DRI ("7", 7, DI);
5933 DRI ("8", 8, DI);
5934 DRI ("9", 9, DI);
5935 DRI ("10", 10, DI);
5936 DRI ("11", 11, DI);
5937 DRI ("12", 12, DI);
5938 DRI ("13", 13, DI);
5939 DRI ("14", 14, DI);
5940 DRI ("15", 15, DI);
5941 DRI ("16", 16, DI);
5942 DRI ("17", 17, DI);
5943 DRI ("18", 18, DI);
5944 DRI ("19", 19, DI);
5945 DRI ("20", 20, DI);
5946 DRI ("21", 21, DI);
5947 DRI ("22", 22, DI);
5948 DRI ("23", 23, DI);
5949 DRI ("24", 24, DI);
5950 DRI ("25", 25, DI);
5951 DRI ("26", 26, DI);
5952 DRI ("27", 27, DI);
5953 DRI ("28", 28, DI);
5954 DRI ("29", 29, DI);
5955 DRI ("30", 30, DI);
5956 DRI ("31", 31, DI);
5957 } else if (elf_machine == EM_S390) {
5958 DRI ("%r0", 0, DI);
5959 DRI ("%r1", 1, DI);
5960 DRI ("%r2", 2, DI);
5961 DRI ("%r3", 3, DI);
5962 DRI ("%r4", 4, DI);
5963 DRI ("%r5", 5, DI);
5964 DRI ("%r6", 6, DI);
5965 DRI ("%r7", 7, DI);
5966 DRI ("%r8", 8, DI);
5967 DRI ("%r9", 9, DI);
5968 DRI ("%r10", 10, DI);
5969 DRI ("%r11", 11, DI);
5970 DRI ("%r12", 12, DI);
5971 DRI ("%r13", 13, DI);
5972 DRI ("%r14", 14, DI);
5973 DRI ("%r15", 15, DI);
5974 } else if (elf_machine == EM_ARM) {
5975 DRI ("r0", 0, SI);
5976 DRI ("r1", 1, SI);
5977 DRI ("r2", 2, SI);
5978 DRI ("r3", 3, SI);
5979 DRI ("r4", 4, SI);
5980 DRI ("r5", 5, SI);
5981 DRI ("r6", 6, SI);
5982 DRI ("r7", 7, SI);
5983 DRI ("r8", 8, SI);
5984 DRI ("r9", 9, SI);
5985 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
5986 DRI ("fp", 11, SI);
5987 DRI ("ip", 12, SI);
5988 DRI ("sp", 13, SI);
5989 DRI ("lr", 14, SI);
5990 DRI ("pc", 15, SI);
5991 } else if (elf_machine == EM_AARCH64) {
5992 DRI ("x0", 0, DI); DRI ("w0", 0, SI);
5993 DRI ("x1", 1, DI); DRI ("w1", 1, SI);
5994 DRI ("x2", 2, DI); DRI ("w2", 2, SI);
5995 DRI ("x3", 3, DI); DRI ("w3", 3, SI);
5996 DRI ("x4", 4, DI); DRI ("w4", 4, SI);
5997 DRI ("x5", 5, DI); DRI ("w5", 5, SI);
5998 DRI ("x6", 6, DI); DRI ("w6", 6, SI);
5999 DRI ("x7", 7, DI); DRI ("w7", 7, SI);
6000 DRI ("x8", 8, DI); DRI ("w8", 8, SI);
6001 DRI ("x9", 9, DI); DRI ("w9", 9, SI);
6002 DRI ("x10", 10, DI); DRI ("w10", 10, SI);
6003 DRI ("x11", 11, DI); DRI ("w11", 11, SI);
6004 DRI ("x12", 12, DI); DRI ("w12", 12, SI);
6005 DRI ("x13", 13, DI); DRI ("w13", 13, SI);
6006 DRI ("x14", 14, DI); DRI ("w14", 14, SI);
6007 DRI ("x15", 15, DI); DRI ("w15", 15, SI);
6008 DRI ("x16", 16, DI); DRI ("w16", 16, SI);
6009 DRI ("x17", 17, DI); DRI ("w17", 17, SI);
6010 DRI ("x18", 18, DI); DRI ("w18", 18, SI);
6011 DRI ("x19", 19, DI); DRI ("w19", 19, SI);
6012 DRI ("x20", 20, DI); DRI ("w20", 20, SI);
6013 DRI ("x21", 21, DI); DRI ("w21", 21, SI);
6014 DRI ("x22", 22, DI); DRI ("w22", 22, SI);
6015 DRI ("x23", 23, DI); DRI ("w23", 23, SI);
6016 DRI ("x24", 24, DI); DRI ("w24", 24, SI);
6017 DRI ("x25", 25, DI); DRI ("w25", 25, SI);
6018 DRI ("x26", 26, DI); DRI ("w26", 26, SI);
6019 DRI ("x27", 27, DI); DRI ("w27", 27, SI);
6020 DRI ("x28", 28, DI); DRI ("w28", 28, SI);
6021 DRI ("x29", 29, DI); DRI ("w29", 29, SI);
6022 DRI ("x30", 30, DI); DRI ("w30", 30, SI);
6023 DRI ("sp", 31, DI);
6024 } else if (arg_count) {
6025 /* permit this case; just fall back to dwarf */
6026 }
6027#undef DRI
6028
6029 // Build regex pieces out of the known dwarf_regs. We keep two separate
6030 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
6031 // and ones with no prefix (and thus only usable in unambiguous contexts).
6032 map<string,pair<unsigned,int> >::const_iterator ri;
6033 for (ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
6034 {
6035 string regname = ri->first;
6036 assert (regname != "");
6037 regnames += string("|")+regname;
6038 if (regname[0]=='%')
6039 percent_regnames += string("|")+regname;
6040 }
6041
6042 // clip off leading |
6043 if (regnames != "")
6044 regnames = regnames.substr(1);
6045 if (percent_regnames != "")
6046 percent_regnames = percent_regnames.substr(1);
6047}
7a05f484
SC
6048
6049void
6ef331c8 6050sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 6051{
6ef331c8 6052 if (e->addressof)
dc09353a 6053 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
6054
6055 if (e->name == "$$name")
7a05f484 6056 {
6ef331c8
SC
6057 literal_string *myname = new literal_string (probe_name);
6058 myname->tok = e->tok;
6059 provide(myname);
6060 return;
6061 }
7a05f484 6062
6ef331c8
SC
6063 else if (e->name == "$$provider")
6064 {
6065 literal_string *myname = new literal_string (provider_name);
6066 myname->tok = e->tok;
6067 provide(myname);
6068 return;
6069 }
a794dbeb 6070
6ef331c8
SC
6071 else if (e->name == "$$vars" || e->name == "$$parms")
6072 {
6073 e->assert_no_components("sdt", true);
6ef331c8
SC
6074
6075 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
63ea4244 6076
1c922ad7 6077 print_format* pf = print_format::create(e->tok, "sprintf");
6ef331c8
SC
6078
6079 for (unsigned i = 1; i <= arg_count; ++i)
6080 {
6081 if (i > 1)
6082 pf->raw_components += " ";
6083 target_symbol *tsym = new target_symbol;
6084 tsym->tok = e->tok;
6085 tsym->name = "$arg" + lex_cast(i);
6086 pf->raw_components += tsym->name;
6087 tsym->components = e->components;
6088
8c2f50c0 6089 expression *texp = require<expression> (tsym);
6ef331c8
SC
6090 if (!e->components.empty() &&
6091 e->components[0].type == target_symbol::comp_pretty_print)
6092 pf->raw_components += "=%s";
6093 else
6094 pf->raw_components += "=%#x";
6095 pf->args.push_back(texp);
6096 }
6097
6098 pf->components = print_format::string_to_components(pf->raw_components);
6099 provide (pf);
6100 }
6101 else
6102 assert(0); // shouldn't get here
6103}
6104
03c45fcb
JL
6105unsigned
6106sdt_uprobe_var_expanding_visitor::get_target_symbol_argno_and_validate (target_symbol *e)
6107{
6108 // parsing
6109 unsigned argno = 0;
6110 if (startswith(e->name, "$arg"))
6111 {
6112 try
6113 {
6114 argno = lex_cast<unsigned>(e->name.substr(4));
6115 }
6116 catch (const runtime_error& f)
6117 {
6118 // non-integral $arg suffix: e.g. $argKKKSDF
6119 argno = 0;
6120 }
6121 }
6122
6123 // validation
6124 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
6125 argno < 1 || argno > arg_count) // a $argN with out-of-range N
6126 {
6127 // NB: Either
6128 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
6129 // 2) uprobe2_type $FOO (no probe args)
6130 // both of which get resolved later.
6131 // Throw it now, and it might be resolved by DWARF later.
6132 need_debug_info = true;
6133 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
6134 }
6135 assert (arg_tokens.size() >= argno);
6136 return argno;
6137}
6ef331c8 6138
ac074daf
JL
6139long
6140sdt_uprobe_var_expanding_visitor::parse_out_arg_precision(string& asmarg)
6141{
6142 long precision;
6143 if (asmarg.find('@') != string::npos)
6144 {
6145 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
6146 asmarg = asmarg.substr(asmarg.find('@')+1);
6147 }
6148 else
6149 {
6150 // V1/V2 do not have precision field so default to signed long
6151 // V3 asm does not have precision field so default to unsigned long
6152 if (probe_type == uprobe3_type)
6153 precision = sizeof(long); // this is an asm probe
6154 else
6155 precision = -sizeof(long);
6156 }
6157 return precision;
6158}
6159
0fbf6fb8
JL
6160expression*
6161sdt_uprobe_var_expanding_visitor::try_parse_arg_literal (target_symbol *e,
6162 const string& asmarg,
6163 long precision)
6164{
6165 expression *argexpr = NULL;
6166
6167 // Here, we test for a numeric literal.
6168 // Only accept (signed) decimals throughout. XXX
6169
6170 // PR11821. NB: on powerpc, literals are not prefixed with $,
6171 // so this regex does not match. But that's OK, since without
6172 // -mregnames, we can't tell them apart from register numbers
6173 // anyway. With -mregnames, we could, if gcc somehow
6174 // communicated to us the presence of that option, but alas it
6175 // doesn't. http://gcc.gnu.org/PR44995.
6176 vector<string> matches;
6177 if (!regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches))
6178 {
6179 string sn = matches[0].substr(1);
6180 int64_t n;
6181
6182 // We have to pay attention to the size & sign, as gcc sometimes
6183 // propagates constants that don't quite match, like a negative
6184 // value to fill an unsigned type.
6185 // NB: let it throw if something happens
6186 switch (precision)
6187 {
6188 case -1: n = lex_cast< int8_t>(sn); break;
6189 case 1: n = lex_cast< uint8_t>(sn); break;
6190 case -2: n = lex_cast< int16_t>(sn); break;
6191 case 2: n = lex_cast<uint16_t>(sn); break;
6192 case -4: n = lex_cast< int32_t>(sn); break;
6193 case 4: n = lex_cast<uint32_t>(sn); break;
6194 default:
6195 case -8: n = lex_cast< int64_t>(sn); break;
6196 case 8: n = lex_cast<uint64_t>(sn); break;
6197 }
6198
6199 literal_number* ln = new literal_number(n);
6200 ln->tok = e->tok;
6201 argexpr = ln;
6202 }
6203
6204 return argexpr;
6205}
6206
95b78bc9
JL
6207expression*
6208sdt_uprobe_var_expanding_visitor::try_parse_arg_register (target_symbol *e,
6209 const string& asmarg,
6210 long precision)
6211{
6212 expression *argexpr = NULL;
6213
6214 // test for REGISTER
6215 // NB: Because PR11821, we must use percent_regnames here.
6216 string regexp;
6217 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
6218 regexp = "^(" + regnames + ")$";
6219 else
6220 regexp = "^(" + percent_regnames + ")$";
6221
6222 vector<string> matches;
6223 if (!regexp_match(asmarg, regexp, matches))
6224 {
6225 string regname = matches[1];
6226 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
6227 if (ri != dwarf_regs.end()) // known register
6228 {
6229 embedded_expr *get_arg1 = new embedded_expr;
6230 string width_adjust;
6231 switch (ri->second.second)
6232 {
6233 case QI: width_adjust = ") & 0xff)"; break;
6234 case QIh: width_adjust = ">>8) & 0xff)"; break;
6235 case HI:
6236 // preserve 16 bit register signness
6237 width_adjust = ") & 0xffff)";
6238 if (precision < 0)
6239 width_adjust += " << 48 >> 48";
6240 break;
6241 case SI:
6242 // preserve 32 bit register signness
6243 width_adjust = ") & 0xffffffff)";
6244 if (precision < 0)
6245 width_adjust += " << 32 >> 32";
6246 break;
6247 default: width_adjust = "))";
6248 }
6249 string type = "";
6250 if (probe_type == uprobe3_type)
6251 type = (precision < 0
6252 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
6253 type = type + "((";
6254 get_arg1->tok = e->tok;
6255 get_arg1->code = string("/* unprivileged */ /* pure */")
6256 + string(" ((int64_t)") + type
a57b7534 6257 + string("u_fetch_register(")
95b78bc9
JL
6258 + lex_cast(dwarf_regs[regname].first) + string("))")
6259 + width_adjust;
6260 argexpr = get_arg1;
6261 }
6262 }
6263 return argexpr;
6264}
6265
b15f98b2
JL
6266static string
6267precision_to_function(long precision)
6268{
6269 switch (precision)
6270 {
6271 case 1: case -1:
6272 return "user_int8";
6273 case 2:
6274 return "user_uint16";
6275 case -2:
6276 return "user_int16";
6277 case 4:
6278 return "user_uint32";
6279 case -4:
6280 return "user_int32";
6281 case 8: case -8:
6282 return "user_int64";
6283 default:
6284 return "user_long";
6285 }
6286}
6287
8da56b62
JL
6288expression*
6289sdt_uprobe_var_expanding_visitor::try_parse_arg_offset_register (target_symbol *e,
6290 const string& asmarg,
6291 long precision)
6292{
6293 expression *argexpr = NULL;
6294
6295 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
6296 // NB: Despite PR11821, we can use regnames here, since the parentheses
6297 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6298 // On ARM test for [REGISTER, OFFSET]
6299
6300 string regexp;
6301 int reg, offset1;
6302 if (elf_machine == EM_ARM)
6303 {
6304 regexp = "^\\[(" + regnames + ")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$";
6305 reg = 1;
6306 offset1 = 3;
6307 }
6308 else
6309 {
6310 regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + ")[)]$";
6311 reg = 4;
6312 offset1 = 1;
6313 }
6314
6315 vector<string> matches;
6316 if (!regexp_match(asmarg, regexp, matches))
6317 {
6318 string regname;
6319 int64_t disp = 0;
6320 if (matches[reg].length())
6321 regname = matches[reg];
6322 if (dwarf_regs.find (regname) == dwarf_regs.end())
6323 throw SEMANTIC_ERROR(_F("unrecognized register '%s'", regname.c_str()));
6324
6325 for (int i=offset1; i <= (offset1 + 2); i++)
6326 if (matches[i].length())
6327 // should decode positive/negative hex/decimal
6328 // NB: let it throw if something happens
6329 disp += lex_cast<int64_t>(matches[i]);
6330
6331 // synthesize user_long(%{fetch_register(R)%} + D)
6332 embedded_expr *get_arg1 = new embedded_expr;
6333 get_arg1->tok = e->tok;
6334 get_arg1->code = string("/* unprivileged */ /* pure */")
a57b7534 6335 + string("u_fetch_register(")
8da56b62
JL
6336 + lex_cast(dwarf_regs[regname].first) + string(")");
6337 // XXX: may we ever need to cast that to a narrower type?
6338
6339 literal_number* inc = new literal_number(disp);
6340 inc->tok = e->tok;
6341
6342 binary_expression *be = new binary_expression;
6343 be->tok = e->tok;
6344 be->left = get_arg1;
6345 be->op = "+";
6346 be->right = inc;
6347
6348 functioncall *fc = new functioncall;
b15f98b2 6349 fc->function = precision_to_function(precision);
8da56b62
JL
6350 fc->tok = e->tok;
6351 fc->args.push_back(be);
6352
6353 argexpr = fc;
6354 }
6355
6356 return argexpr;
6357}
6358
10fcca15
JL
6359expression*
6360sdt_uprobe_var_expanding_visitor::try_parse_arg_effective_addr (target_symbol *e,
6361 const string& asmarg,
6362 long precision)
6363{
6364 expression *argexpr = NULL;
6365
6366 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
6367 // NB: Despite PR11821, we can use regnames here, since the parentheses
6368 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
6369 string regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + "),(" +
6370 regnames + ")(,[1248])?[)]$";
6371 vector<string> matches;
6372 if (!regexp_match(asmarg, regexp, matches))
6373 {
6374 string baseregname;
6375 string indexregname;
6376 int64_t disp = 0;
6377 short scale = 1;
6378
6379 if (matches[6].length())
6380 // NB: let it throw if we can't cast
6381 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
6382
6383 if (matches[4].length())
6384 baseregname = matches[4];
6385 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6386 throw SEMANTIC_ERROR(_F("unrecognized base register '%s'", baseregname.c_str()));
6387
6388 if (matches[5].length())
6389 indexregname = matches[5];
6390 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6391 throw SEMANTIC_ERROR(_F("unrecognized index register '%s'", indexregname.c_str()));
6392
6393 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
6394 if (matches[i].length())
6395 // should decode positive/negative hex/decimal
6396 // NB: let it throw if something happens
6397 disp += lex_cast<int64_t>(matches[i]);
6398
6399 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6400
6401 embedded_expr *get_arg1 = new embedded_expr;
a57b7534 6402 string regfn = "u_fetch_register";
10fcca15
JL
6403
6404 get_arg1->tok = e->tok;
6405 get_arg1->code = string("/* unprivileged */ /* pure */")
6406 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6407 + string("+(")
6408 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6409 + string("*")
6410 + lex_cast(scale)
6411 + string(")");
6412
6413 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6414 literal_number* inc = new literal_number(disp);
6415 inc->tok = e->tok;
6416
6417 binary_expression *be = new binary_expression;
6418 be->tok = e->tok;
6419 be->left = get_arg1;
6420 be->op = "+";
6421 be->right = inc;
6422
6423 functioncall *fc = new functioncall;
b15f98b2 6424 fc->function = precision_to_function(precision);
10fcca15
JL
6425 fc->tok = e->tok;
6426 fc->args.push_back(be);
6427
6428 argexpr = fc;
6429 }
6430
6431 return argexpr;
6432}
6433
451c0c25
JL
6434expression*
6435sdt_uprobe_var_expanding_visitor::try_parse_arg_varname (target_symbol *e,
6436 const string& asmarg,
6437 long precision)
6ef331c8 6438{
b8688ee6 6439 static unsigned tick = 0;
451c0c25
JL
6440 expression *argexpr = NULL;
6441
6442 // test for [OFF+]VARNAME[+OFF][(REGISTER)], where VARNAME is a variable
6443 // name. NB: Despite PR11821, we can use regnames here, since the parentheses
6444 // make things unambiguous.
6445 string regex = "^(([0-9]+)[+])?([a-zA-Z_][a-zA-Z0-9_]*)([+][0-9]+)?([(]("
6446 + regnames + ")[)])?$";
6447 vector<string> matches;
6448 if (!regexp_match(asmarg, regex, matches))
6449 {
6450 assert(matches.size() >= 4);
6451 string varname = matches[3];
6452
6453 // OFF can be before VARNAME (put in matches[2]) or after (put in
6454 // matches[4]) (or both?). Seems like in most cases it comes after,
6455 // unless the code was compiled with -fPIC.
6456 int64_t offset = 0;
6457 if (!matches[2].empty())
6458 offset += lex_cast<int64_t>(matches[2]);
6459 if (matches.size() >= 5 && !matches[4].empty())
6460 offset += lex_cast<int64_t>(matches[4]);
6461
6462 string regname;
6463 if (matches.size() >= 7)
6464 regname = matches[6];
6465
6466 // If it's just VARNAME, then proceed. If it's VARNAME(REGISTER), then
6467 // only proceed if it's RIP-relative addressing on x86_64.
6468 if (regname.empty() || (regname == "%rip" && elf_machine == EM_X86_64))
6469 {
6470 dw.mod_info->get_symtab();
6471 if (dw.mod_info->symtab_status != info_present)
6472 throw SEMANTIC_ERROR(_("can't retrieve symbol table"));
6473
6474 assert(dw.mod_info->sym_table);
6475 map<string, Dwarf_Addr>& globals = dw.mod_info->sym_table->globals;
6476 map<string, Dwarf_Addr>& locals = dw.mod_info->sym_table->locals;
6477 Dwarf_Addr addr = 0;
6478
6479 // check symtab locals then globals
6480 if (locals.count(varname))
6481 addr = locals[varname];
6482 if (globals.count(varname))
6483 addr = globals[varname];
6484
6485 if (addr)
6486 {
6487 // add whatever offset is in the operand
6488 addr += offset;
6489
6490 // adjust for dw bias because relocate_address() expects a
6491 // libdw address and this addr is from the symtab
6492 dw.get_module_dwarf(false, false);
6493 addr -= dw.module_bias;
6494
6495 string reloc_section;
6496 Dwarf_Addr reloc_addr = dw.relocate_address(addr, reloc_section);
6497
6498 // OK, we have an address for the variable. Let's create a
6499 // function that will just relocate it at runtime, and then
6500 // call user_[u]int*() on the address it returns.
6501
6502 functioncall *user_int_call = new functioncall;
b15f98b2 6503 user_int_call->function = precision_to_function(precision);
451c0c25
JL
6504 user_int_call->tok = e->tok;
6505
6506 functiondecl *get_addr_decl = new functiondecl;
6507 get_addr_decl->tok = e->tok;
6508 get_addr_decl->synthetic = true;
6509 get_addr_decl->name = "_sdt_arg_get_addr_" + lex_cast(tick++);
6510 get_addr_decl->type = pe_long;
6511
6512 // build _stp_[ku]module_relocate(module, addr, current)
6513 stringstream ss;
6514 ss << " /* unprivileged */ /* pure */ /* pragma:vma */" << endl;
a57b7534
JL
6515 ss << "STAP_RETURN(_stp_umodule_relocate(";
6516 ss << "\"" << path_remove_sysroot(session, process_name) << "\", ";
6517 ss << "0x" << hex << reloc_addr << dec << ", ";
6518 ss << "current";
6519 ss << "));" << endl;
451c0c25
JL
6520
6521 embeddedcode *ec = new embeddedcode;
6522 ec->tok = e->tok;
6523 ec->code = ss.str();
6524 get_addr_decl->body = ec;
6525 get_addr_decl->join(session);
6526
6527 functioncall *get_addr_call = new functioncall;
6528 get_addr_call->tok = e->tok;
6529 get_addr_call->function = get_addr_decl->name;
6530 user_int_call->args.push_back(get_addr_call);
b8688ee6 6531
451c0c25
JL
6532 argexpr = user_int_call;
6533 }
6534 }
6535 }
6536
6537 return argexpr;
6538}
6539
6540void
6541sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
6542{
6ef331c8
SC
6543 try
6544 {
03c45fcb 6545 unsigned argno = get_target_symbol_argno_and_validate(e); // the N in $argN
8aabf152 6546 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 6547
8aabf152
FCE
6548 // Now we try to parse this thing, which is an assembler operand
6549 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 6550 // and hope for the best. Here is the syntax for a few architectures.
9859b766 6551 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157 6552 //
b6aaaf21
JL
6553 // literal reg reg reg+ base+index*size+ VAR VAR+off RIP-relative
6554 // indirect offset offset VAR+off
6555 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6556 // x86_64 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6557 // power iN R (R) N(R)
6558 // ia64 N rR [r16]
6559 // s390 N %rR 0(rR) N(r15)
6560 // arm #N rR [rR] [rR, #N]
b874bd52 6561
8aabf152
FCE
6562 expression* argexpr = 0; // filled in in case of successful parse
6563
ac074daf
JL
6564 // Parse (and remove from asmarg) the leading length
6565 long precision = parse_out_arg_precision(asmarg);
40fe32e0 6566
0fbf6fb8 6567 try
8aabf152 6568 {
0fbf6fb8
JL
6569 if ((argexpr = try_parse_arg_literal(e, asmarg, precision)) != NULL)
6570 goto matched;
2e6d617a
JL
6571
6572 // all other matches require registers
6573 if (regnames == "")
6574 throw SEMANTIC_ERROR("no registers to use for parsing");
95b78bc9
JL
6575
6576 if ((argexpr = try_parse_arg_register(e, asmarg, precision)) != NULL)
6577 goto matched;
8da56b62
JL
6578 if ((argexpr = try_parse_arg_offset_register(e, asmarg, precision)) != NULL)
6579 goto matched;
10fcca15
JL
6580 if ((argexpr = try_parse_arg_effective_addr(e, asmarg, precision)) != NULL)
6581 goto matched;
451c0c25
JL
6582 if ((argexpr = try_parse_arg_varname(e, asmarg, precision)) != NULL)
6583 goto matched;
0fbf6fb8
JL
6584 }
6585 catch (const semantic_error& err)
6586 {
6587 e->chain(err);
b8688ee6 6588 }
8aabf152 6589
8aabf152
FCE
6590 // The asmarg operand was not recognized. Back down to dwarf.
6591 if (! session.suppress_warnings)
84fef8ee
FCE
6592 {
6593 if (probe_type == UPROBE3_TYPE)
451c0c25
JL
6594 session.print_warning (_F("Can't parse SDT_V3 operand '%s' "
6595 "[man error::sdt]", asmarg.c_str()),
6596 e->tok);
84fef8ee 6597 else // must be *PROBE2; others don't get asm operands
451c0c25
JL
6598 session.print_warning (_F("Downgrading SDT_V2 probe argument to "
6599 "dwarf, can't parse '%s' [man error::sdt]",
6600 asmarg.c_str()),
6601 e->tok);
84fef8ee 6602 }
451c0c25 6603
8aabf152 6604 need_debug_info = true;
451c0c25
JL
6605 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo "
6606 "[man error::sdt]"), e->tok);
6607
6608 /* NOTREACHED */
366af4e7 6609
8aabf152
FCE
6610 matched:
6611 assert (argexpr != 0);
366af4e7
RM
6612
6613 if (session.verbose > 2)
1e41115c 6614 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6615 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6616
aff5d390 6617 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6618 {
6619 if (e->addressof)
dc09353a 6620 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152 6621 provide (argexpr);
8aabf152
FCE
6622 }
6623 else // $var->foo
6624 {
6625 cast_op *cast = new cast_op;
6626 cast->name = "@cast";
6627 cast->tok = e->tok;
6628 cast->operand = argexpr;
6629 cast->components = e->components;
6630 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6631 cast->module = process_name;
6632 cast->visit(this);
8aabf152 6633 }
aff5d390
SC
6634 }
6635 catch (const semantic_error &er)
6636 {
6637 e->chain (er);
6638 provide (e);
6639 }
6640}
6641
6642
6ef331c8
SC
6643void
6644sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6645{
6646 try
6647 {
49131a6d 6648 assert(e->name.size() > 0
bd1fcbad 6649 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6650
6651 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6652 visit_target_symbol_context (e);
6653 else
6654 visit_target_symbol_arg (e);
6655 }
6656 catch (const semantic_error &er)
6657 {
6658 e->chain (er);
6659 provide (e);
6660 }
6661}
6662
6663
bd1fcbad
YZ
6664void
6665sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6666{
6667 need_debug_info = true;
6668
6669 // Fill in our current module context if needed
6670 if (e->module.empty())
6671 e->module = process_name;
6672
6673 var_expanding_visitor::visit_atvar_op(e);
6674}
6675
6676
40a0c64e
JS
6677void
6678sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6679{
6680 // Fill in our current module context if needed
6681 if (e->module.empty())
6682 e->module = process_name;
6683
6684 var_expanding_visitor::visit_cast_op(e);
6685}
6686
6687
576eaefe
SC
6688void
6689plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6690{
6691 try
6692 {
6693 if (e->name == "$$name")
6694 {
6695 literal_string *myname = new literal_string (entry);
6696 myname->tok = e->tok;
6697 provide(myname);
6698 return;
6699 }
3d69c03f
JS
6700
6701 // variable not found -> throw a semantic error
6702 // (only to be caught right away, but this may be more complex later...)
6703 string alternatives = "$$name";
dc09353a 6704 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6705 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6706 }
6707 catch (const semantic_error &er)
6708 {
6709 e->chain (er);
6710 provide (e);
6711 }
6712}
6713
6714
edce5b67
JS
6715struct sdt_query : public base_query
6716{
6717 sdt_query(probe * base_probe, probe_point * base_loc,
6718 dwflpp & dw, literal_map_t const & params,
51d6bda3 6719 vector<derived_probe *> & results, const string user_lib);
edce5b67 6720
51d6bda3 6721 void query_library (const char *data);
576eaefe 6722 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6723 void handle_query_module();
6724
6725private:
15284963 6726 stap_sdt_probe_type probe_type;
d61ea602 6727 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6728 probe * base_probe;
6729 probe_point * base_loc;
6846cfc8 6730 literal_map_t const & params;
edce5b67 6731 vector<derived_probe *> & results;
a794dbeb
FCE
6732 string pp_mark;
6733 string pp_provider;
51d6bda3 6734 string user_lib;
edce5b67
JS
6735
6736 set<string> probes_handled;
6737
6738 Elf_Data *pdata;
6739 size_t probe_scn_offset;
6740 size_t probe_scn_addr;
aff5d390 6741 uint64_t arg_count;
40fe32e0 6742 GElf_Addr base;
c57ea854 6743 GElf_Addr pc;
aff5d390 6744 string arg_string;
edce5b67 6745 string probe_name;
a794dbeb 6746 string provider_name;
909ab234 6747 GElf_Addr semaphore_load_offset;
79a0ca08 6748 Dwarf_Addr semaphore;
edce5b67
JS
6749
6750 bool init_probe_scn();
6b51ee12 6751 bool get_next_probe();
c57ea854
SC
6752 void iterate_over_probe_entries();
6753 void handle_probe_entry();
edce5b67 6754
488d3c1b 6755 static void setup_note_probe_entry_callback (sdt_query *me,
dbd24034
JL
6756 const string& scn_name,
6757 const string& note_name,
488d3c1b
JL
6758 int type,
6759 const char *data,
6760 size_t len);
dbd24034
JL
6761 void setup_note_probe_entry (const string& scn_name,
6762 const string& note_name, int type,
6763 const char *data, size_t len);
40fe32e0 6764
edce5b67 6765 void convert_probe(probe *base);
4ddb6dd0 6766 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6767 probe* convert_location();
40fe32e0 6768 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6769 bool have_debuginfo_uprobe(bool need_debug_info)
6770 {return probe_type == uprobe1_type
40fe32e0 6771 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6772 && need_debug_info);}
40fe32e0 6773 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6774};
6775
6776
6777sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6778 dwflpp & dw, literal_map_t const & params,
51d6bda3 6779 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6780 base_query(dw, params), probe_type(unknown_probe_type),
6781 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6782 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6783 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6784 semaphore_load_offset(0), semaphore(0)
edce5b67 6785{
a794dbeb
FCE
6786 assert(get_string_param(params, TOK_MARK, pp_mark));
6787 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6788
ef428667
FCE
6789 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6790 // map it to double-underscores.
6791 size_t pos = 0;
6792 while (1) // there may be more than one
6793 {
a794dbeb 6794 size_t i = pp_mark.find("-", pos);
ef428667 6795 if (i == string::npos) break;
a794dbeb 6796 pp_mark.replace (i, 1, "__");
ef428667
FCE
6797 pos = i+1; // resume searching after the inserted __
6798 }
a794dbeb
FCE
6799
6800 // XXX: same for pp_provider?
edce5b67
JS
6801}
6802
6803
6804void
c57ea854 6805sdt_query::handle_probe_entry()
edce5b67 6806{
c57ea854
SC
6807 if (! have_uprobe()
6808 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6809 return;
6810
6811 if (sess.verbose > 3)
c57ea854 6812 {
b78a0fbb 6813 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
b530b5b3
LB
6814 //TRANSLATORS: is matched to.
6815 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6816 switch (probe_type)
6817 {
6818 case uprobe1_type:
6819 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6820 break;
6821 case uprobe2_type:
6822 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6823 break;
40fe32e0
SC
6824 case uprobe3_type:
6825 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6826 break;
d61ea602
JS
6827 default:
6828 clog << "unknown!" << endl;
6829 break;
c57ea854
SC
6830 }
6831 }
edce5b67 6832
c57ea854
SC
6833 // Extend the derivation chain
6834 probe *new_base = convert_location();
6835 probe_point *new_location = new_base->locations[0];
6836
c57ea854
SC
6837 bool need_debug_info = false;
6838
7d395255
JS
6839 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6840 // or dwfl_module_getelf(...). We only need it for the machine type, which
6841 // should be the same. The bias is used for relocating debuginfoless probes,
6842 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6843 Dwarf_Addr bias;
7d395255 6844 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6845
1cc41cd6
DS
6846 /* Figure out the architecture of this particular ELF file. The
6847 dwarfless register-name mappings depend on it. */
6848 GElf_Ehdr ehdr_mem;
6849 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 6850 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6851 assert(em);
1cc41cd6 6852 int elf_machine = em->e_machine;
b8688ee6
JL
6853 sdt_uprobe_var_expanding_visitor svv (sess, dw, elf_machine, module_val,
6854 provider_name, probe_name, probe_type,
6855 arg_string, arg_count);
1cc41cd6
DS
6856 svv.replace (new_base->body);
6857 need_debug_info = svv.need_debug_info;
c57ea854 6858
1cc41cd6
DS
6859 // XXX: why not derive_probes() in the uprobes case too?
6860 literal_map_t params;
6861 for (unsigned i = 0; i < new_location->components.size(); ++i)
6862 {
6863 probe_point::component *c = new_location->components[i];
6864 params[c->functor] = c->arg;
6865 }
c57ea854 6866
73d53dd2 6867 unsigned prior_results_size = results.size();
1cc41cd6
DS
6868 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6869 q.has_mark = true; // enables mid-statement probing
30263a73 6870
73d53dd2
JS
6871 // V1 probes always need dwarf info
6872 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6 6873 if (have_debuginfo_uprobe(need_debug_info))
06de3a04 6874 dw.iterate_over_modules<base_query>(&query_module, &q);
73d53dd2
JS
6875
6876 // For V2+ probes, if variable references weren't used or failed (PR14369),
6877 // then try with the more direct approach. Unresolved $vars might still
6878 // cause their own error, but this gives them a chance to be optimized out.
6879 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6880 {
6881 string section;
6882 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6883 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6884 {
6885 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6886 section = ".dynamic";
6887 }
6888 else
6889 section = ".absolute";
edce5b67 6890
1cc41cd6
DS
6891 uprobe_derived_probe* p =
6892 new uprobe_derived_probe ("", "", 0,
6893 path_remove_sysroot(sess,q.module_val),
6894 section,
6895 q.statement_num_val, reloc_addr, q, 0);
6896 p->saveargs (arg_count);
6897 results.push_back (p);
c57ea854 6898 }
487bf4e2 6899 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6900 record_semaphore(results, prior_results_size);
c57ea854 6901}
edce5b67 6902
4ddb6dd0 6903
c57ea854
SC
6904void
6905sdt_query::handle_query_module()
6906{
6907 if (!init_probe_scn())
6908 return;
edce5b67 6909
c57ea854
SC
6910 if (sess.verbose > 3)
6911 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6912
40fe32e0
SC
6913 if (probe_loc == note_section)
6914 {
6915 GElf_Shdr shdr_mem;
6916 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6917
909ab234
JS
6918 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6919 // effects. The 'semaphore_load_offset' accounts for the difference in
6920 // load addresses between text and data, so the semaphore can be
6921 // converted to a file offset if needed.
40fe32e0 6922 if (shdr)
909ab234
JS
6923 {
6924 base = shdr->sh_addr;
6925 GElf_Addr base_offset = shdr->sh_offset;
6926 shdr = dw.get_section (".probes", &shdr_mem);
6927 if (shdr)
6928 semaphore_load_offset =
6929 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6930 }
40fe32e0 6931 else
909ab234
JS
6932 base = semaphore_load_offset = 0;
6933
488d3c1b 6934 dw.iterate_over_notes (this, &sdt_query::setup_note_probe_entry_callback);
40fe32e0 6935 }
d61ea602 6936 else if (probe_loc == probe_section)
40fe32e0 6937 iterate_over_probe_entries ();
edce5b67
JS
6938}
6939
6940
6941bool
6942sdt_query::init_probe_scn()
6943{
448a86b7 6944 Elf* elf;
edce5b67 6945 GElf_Shdr shdr_mem;
40fe32e0
SC
6946
6947 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6948 if (shdr)
6949 {
6950 probe_loc = note_section;
6951 return true;
6952 }
edce5b67 6953
448a86b7 6954 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6955 if (shdr)
edce5b67 6956 {
fea74777
SC
6957 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6958 probe_scn_offset = 0;
6959 probe_scn_addr = shdr->sh_addr;
6960 assert (pdata != NULL);
6961 if (sess.verbose > 4)
ce0f6648
LB
6962 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6963 << pdata->d_size << endl;
40fe32e0 6964 probe_loc = probe_section;
fea74777 6965 return true;
edce5b67 6966 }
fea74777 6967 else
edce5b67 6968 return false;
edce5b67
JS
6969}
6970
40fe32e0 6971void
dbd24034
JL
6972sdt_query::setup_note_probe_entry_callback (sdt_query *me,
6973 const string& scn_name,
6974 const string& note_name, int type,
6975 const char *data, size_t len)
40fe32e0 6976{
dbd24034 6977 me->setup_note_probe_entry (scn_name, note_name, type, data, len);
40fe32e0
SC
6978}
6979
6980
6981void
dbd24034
JL
6982sdt_query::setup_note_probe_entry (const string& scn_name,
6983 const string& note_name, int type,
6984 const char *data, size_t len)
40fe32e0 6985{
dbd24034
JL
6986 if (scn_name.compare(".note.stapsdt"))
6987 return;
6988#define _SDT_NOTE_NAME "stapsdt"
6989 if (note_name.compare(_SDT_NOTE_NAME))
6990 return;
40fe32e0
SC
6991#define _SDT_NOTE_TYPE 3
6992 if (type != _SDT_NOTE_TYPE)
6993 return;
6994
dbd24034 6995 // we found a probe entry
40fe32e0
SC
6996 union
6997 {
6998 Elf64_Addr a64[3];
6999 Elf32_Addr a32[3];
7000 } buf;
7001 Dwarf_Addr bias;
7002 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
7003 Elf_Data dst =
7004 {
7005 &buf, ELF_T_ADDR, EV_CURRENT,
7006 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
7007 };
7008 assert (dst.d_size <= sizeof buf);
7009
7010 if (len < dst.d_size + 3)
7011 return;
7012
7013 Elf_Data src =
7014 {
7015 (void *) data, ELF_T_ADDR, EV_CURRENT,
7016 dst.d_size, 0, 0
7017 };
7018
7019 if (gelf_xlatetom (elf, &dst, &src,
7020 elf_getident (elf, NULL)[EI_DATA]) == NULL)
7021 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
7022
7023 probe_type = uprobe3_type;
7024 const char * provider = data + dst.d_size;
3f803f9e 7025
40fe32e0 7026 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
7027 if(name++ == NULL)
7028 return;
7029
7030 const char *args = (const char*)memchr (name, '\0', data + len - name);
7031 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
7032 return;
7033
7034 provider_name = provider;
7035 probe_name = name;
7036 arg_string = args;
40fe32e0 7037
e90006d7
JL
7038 dw.mod_info->marks.insert(make_pair(provider, name));
7039
40fe32e0
SC
7040 // Did we find a matching probe?
7041 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
7042 && ((pp_provider == "")
7043 || dw.function_name_matches_pattern (provider_name, pp_provider))))
7044 return;
7045
e9a90eee
JS
7046 // PR13934: Assembly probes are not forced to use the N@OP form.
7047 // If we have '@' then great, else count based on space-delimiters.
7048 arg_count = count(arg_string.begin(), arg_string.end(), '@');
7049 if (!arg_count && !arg_string.empty())
7050 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
7051
40fe32e0
SC
7052 GElf_Addr base_ref;
7053 if (gelf_getclass (elf) == ELFCLASS32)
7054 {
7055 pc = buf.a32[0];
7056 base_ref = buf.a32[1];
7057 semaphore = buf.a32[2];
7058 }
7059 else
7060 {
7061 pc = buf.a64[0];
7062 base_ref = buf.a64[1];
7063 semaphore = buf.a64[2];
7064 }
7065
7066 semaphore += base - base_ref;
7067 pc += base - base_ref;
7068
7d395255
JS
7069 // The semaphore also needs the ELF bias added now, so
7070 // record_semaphore can properly relocate it later.
7071 semaphore += bias;
7072
40fe32e0 7073 if (sess.verbose > 4)
b530b5b3 7074 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
7075
7076 handle_probe_entry();
7077}
7078
7079
c57ea854
SC
7080void
7081sdt_query::iterate_over_probe_entries()
edce5b67 7082{
c57ea854 7083 // probes are in the .probe section
edce5b67
JS
7084 while (probe_scn_offset < pdata->d_size)
7085 {
aff5d390
SC
7086 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
7087 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 7088 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 7089 if (! have_uprobe())
edce5b67
JS
7090 {
7091 // Unless this is a mangled .probes section, this happens
7092 // because the name of the probe comes first, followed by
7093 // the sentinel.
7094 if (sess.verbose > 5)
b530b5b3 7095 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
7096 probe_scn_offset += sizeof(__uint32_t);
7097 continue;
7098 }
aff5d390
SC
7099 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
7100 {
7101 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 7102 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
7103 continue;
7104 }
7105
1cc41cd6 7106 if (probe_type == uprobe1_type)
aff5d390 7107 {
79a0ca08 7108 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 7109 return;
79a0ca08 7110 semaphore = 0;
aff5d390 7111 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 7112 provider_name = ""; // unknown
1cc41cd6
DS
7113 pc = pbe_v1->arg;
7114 arg_count = 0;
aff5d390
SC
7115 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
7116 }
08b5a50c 7117 else if (probe_type == uprobe2_type)
aff5d390 7118 {
79a0ca08 7119 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 7120 return;
79a0ca08 7121 semaphore = pbe_v2->semaphore;
aff5d390 7122 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 7123 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
7124 arg_count = pbe_v2->arg_count;
7125 pc = pbe_v2->pc;
7126 if (pbe_v2->arg_string)
7127 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
7128 // skip over pbe_v2, probe_name text and provider text
7129 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
7130 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 7131 }
edce5b67 7132 if (sess.verbose > 4)
b530b5b3 7133 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 7134 << "@0x" << hex << pc << dec << endl;
edce5b67 7135
e90006d7
JL
7136 dw.mod_info->marks.insert(make_pair(provider_name, probe_name));
7137
a794dbeb
FCE
7138 if (dw.function_name_matches_pattern (probe_name, pp_mark)
7139 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 7140 handle_probe_entry ();
edce5b67 7141 }
edce5b67
JS
7142}
7143
7144
6846cfc8 7145void
4ddb6dd0 7146sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 7147{
a794dbeb
FCE
7148 for (unsigned i=0; i<2; i++) {
7149 // prefer with-provider symbol; look without provider prefix for backward compatibility only
7150 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
7151 // XXX: multiple addresses?
7152 if (sess.verbose > 2)
b530b5b3 7153 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 7154
79a0ca08
SC
7155 Dwarf_Addr addr;
7156 if (this->semaphore)
7157 addr = this->semaphore;
7158 else
7159 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
7160 if (addr)
7161 {
7d395255 7162 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
7163 dwfl_module_relocate_address (dw.module, &addr);
7164 // XXX: relocation basis?
909ab234
JS
7165
7166 // Dyninst needs the *file*-based offset for semaphores,
7167 // so subtract the difference in load addresses between .text and .probes
7168 if (dw.sess.runtime_usermode_p())
7169 addr -= semaphore_load_offset;
7170
a794dbeb
FCE
7171 for (unsigned i = start; i < results.size(); ++i)
7172 results[i]->sdt_semaphore_addr = addr;
7173 if (sess.verbose > 2)
b530b5b3 7174 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
7175 return;
7176 }
7177 else
7178 if (sess.verbose > 2)
b530b5b3 7179 clog << _(", not found") << endl;
a794dbeb 7180 }
6846cfc8
SC
7181}
7182
7183
edce5b67
JS
7184void
7185sdt_query::convert_probe (probe *base)
7186{
7187 block *b = new block;
7188 b->tok = base->body->tok;
7189
edce5b67
JS
7190 // Generate: if (arg1 != mark("label")) next;
7191 functioncall *fc = new functioncall;
bbafcb1e 7192 fc->function = "ulong_arg";
edce5b67 7193 fc->tok = b->tok;
bbafcb1e 7194 literal_number* num = new literal_number(1);
edce5b67
JS
7195 num->tok = b->tok;
7196 fc->args.push_back(num);
7197
7198 functioncall *fcus = new functioncall;
7199 fcus->function = "user_string";
7200 fcus->type = pe_string;
7201 fcus->tok = b->tok;
7202 fcus->args.push_back(fc);
7203
7204 if_statement *is = new if_statement;
7205 is->thenblock = new next_statement;
7206 is->elseblock = NULL;
7207 is->tok = b->tok;
63ea4244 7208 is->thenblock->tok = b->tok;
edce5b67
JS
7209 comparison *be = new comparison;
7210 be->op = "!=";
7211 be->tok = b->tok;
7212 be->left = fcus;
7213 be->right = new literal_string(probe_name);
63ea4244 7214 be->right->tok = b->tok;
edce5b67
JS
7215 is->condition = be;
7216 b->statements.push_back(is);
7217
7218 // Now replace the body
7219 b->statements.push_back(base->body);
7220 base->body = b;
7221}
7222
7223
c72aa911
JS
7224probe*
7225sdt_query::convert_location ()
edce5b67 7226{
684b8718
JL
7227 string module = dw.module_name;
7228 if (has_process)
7229 module = path_remove_sysroot(sess, module);
7230
c72aa911 7231 probe_point* specific_loc = new probe_point(*base_loc);
684b8718
JL
7232 specific_loc->well_formed = true;
7233
662539d9 7234 vector<probe_point::component*> derived_comps;
edce5b67 7235
662539d9
JS
7236 vector<probe_point::component*>::iterator it;
7237 for (it = specific_loc->components.begin();
7238 it != specific_loc->components.end(); ++it)
7239 if ((*it)->functor == TOK_PROCESS)
7240 {
684b8718
JL
7241 // replace the possibly incomplete path to process
7242 *it = new probe_point::component(TOK_PROCESS,
7243 new literal_string(has_library ? path : module));
7244
1cc41cd6
DS
7245 // copy the process name
7246 derived_comps.push_back(*it);
662539d9
JS
7247 }
7248 else if ((*it)->functor == TOK_LIBRARY)
7249 {
1cc41cd6
DS
7250 // copy the library name for process probes
7251 derived_comps.push_back(*it);
662539d9
JS
7252 }
7253 else if ((*it)->functor == TOK_PROVIDER)
7254 {
7255 // replace the possibly wildcarded arg with the specific provider name
7256 *it = new probe_point::component(TOK_PROVIDER,
7257 new literal_string(provider_name));
7258 }
7259 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
7260 {
7261 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
7262 *it = new probe_point::component(TOK_MARK,
7263 new literal_string(probe_name));
a794dbeb 7264
aff5d390
SC
7265 if (sess.verbose > 3)
7266 switch (probe_type)
7267 {
7268 case uprobe1_type:
b530b5b3 7269 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
7270 << hex << pc << dec << endl;
7271 break;
7272 case uprobe2_type:
b530b5b3 7273 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
7274 << hex << pc << dec << endl;
7275 break;
40fe32e0 7276 case uprobe3_type:
b530b5b3 7277 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
7278 << hex << pc << dec << endl;
7279 break;
aff5d390 7280 default:
b530b5b3
LB
7281 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
7282 pp_mark.c_str()) << endl;
aff5d390
SC
7283 }
7284
c72aa911
JS
7285 switch (probe_type)
7286 {
aff5d390
SC
7287 case uprobe1_type:
7288 case uprobe2_type:
40fe32e0 7289 case uprobe3_type:
c72aa911 7290 // process("executable").statement(probe_arg)
662539d9
JS
7291 derived_comps.push_back
7292 (new probe_point::component(TOK_STATEMENT,
7293 new literal_number(pc, true)));
c72aa911
JS
7294 break;
7295
a794dbeb 7296 default: // deprecated
c72aa911 7297 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
7298 derived_comps.push_back
7299 (new probe_point::component(TOK_FUNCTION,
7300 new literal_string("*")));
7301 derived_comps.push_back
c72aa911 7302 (new probe_point::component(TOK_LABEL,
a794dbeb 7303 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
7304 break;
7305 }
7306 }
edce5b67 7307
662539d9
JS
7308 probe_point* derived_loc = new probe_point(*specific_loc);
7309 derived_loc->components = derived_comps;
8159bf55 7310 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
7311}
7312
7313
51d6bda3
SC
7314void
7315sdt_query::query_library (const char *library)
7316{
7317 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
7318}
7319
e90006d7
JL
7320string
7321suggest_marks(systemtap_session& sess,
7322 const set<string>& modules,
7323 const string& mark,
7324 const string& provider)
7325{
7326 if (mark.empty() || modules.empty() || sess.module_cache == NULL)
7327 return "";
7328
7329 set<string> marks;
7330 const map<string, module_info*> &cache = sess.module_cache->cache;
7331 bool dash_suggestions = (mark.find("-") != string::npos);
7332
7333 for (set<string>::iterator itmod = modules.begin();
7334 itmod != modules.end(); ++itmod)
7335 {
7336 map<string, module_info*>::const_iterator itcache;
7337 if ((itcache = cache.find(*itmod)) != cache.end())
7338 {
7339 set<pair<string,string> >::const_iterator itmarks;
7340 for (itmarks = itcache->second->marks.begin();
7341 itmarks != itcache->second->marks.end(); ++itmarks)
7342 {
7343 if (provider.empty()
7344 // simulating dw.function_name_matches_pattern()
7345 || (fnmatch(provider.c_str(), itmarks->first.c_str(), 0) == 0))
7346 {
7347 string marksug = itmarks->second;
7348 if (dash_suggestions)
7349 {
7350 size_t pos = 0;
7351 while (1) // there may be more than one
7352 {
7353 size_t i = marksug.find("__", pos);
7354 if (i == string::npos) break;
7355 marksug.replace (i, 2, "-");
7356 pos = i+1; // resume searching after the inserted -
7357 }
7358 }
7359 marks.insert(marksug);
7360 }
7361 }
7362 }
7363 }
7364
7365 if (sess.verbose > 2)
7366 {
7367 clog << "suggesting " << marks.size() << " marks "
7368 << "from modules:" << endl;
7369 for (set<string>::iterator itmod = modules.begin();
7370 itmod != modules.end(); ++itmod)
7371 clog << *itmod << endl;
7372 }
7373
7374 if (marks.empty())
7375 return "";
7376
7377 return levenshtein_suggest(mark, marks, 5); // print top 5 marks only
7378}
7379
40a70f52
JL
7380string
7381suggest_plt_functions(systemtap_session& sess,
7382 const set<string>& modules,
7383 const string& func)
7384{
7385 if (func.empty() || modules.empty() || sess.module_cache == NULL)
7386 return "";
7387
7388 set<string> funcs;
7389 const map<string, module_info*> &cache = sess.module_cache->cache;
7390
7391 for (set<string>::iterator itmod = modules.begin();
7392 itmod != modules.end(); ++itmod)
7393 {
7394 map<string, module_info*>::const_iterator itcache;
7395 if ((itcache = cache.find(*itmod)) != cache.end())
7396 funcs.insert(itcache->second->plt_funcs.begin(),
7397 itcache->second->plt_funcs.end());
7398 }
7399
7400 if (sess.verbose > 2)
d82dd71f
JL
7401 {
7402 clog << "suggesting " << funcs.size() << " plt functions "
7403 << "from modules:" << endl;
7404 for (set<string>::iterator itmod = modules.begin();
7405 itmod != modules.end(); ++itmod)
7406 clog << *itmod << endl;
7407 }
40a70f52
JL
7408
7409 if (funcs.empty())
7410 return "";
7411
7412 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
7413}
51d6bda3 7414
0508c45f
JL
7415string
7416suggest_dwarf_functions(systemtap_session& sess,
7417 const set<string>& modules,
7418 string func)
44ffe90c
JL
7419{
7420 // Trim any @ component
7421 size_t pos = func.find('@');
7422 if (pos != string::npos)
7423 func.erase(pos);
7424
0508c45f 7425 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
7426 return "";
7427
7428 // We must first aggregate all the functions from the cache
7429 set<string> funcs;
7430 const map<string, module_info*> &cache = sess.module_cache->cache;
7431
0508c45f
JL
7432 for (set<string>::iterator itmod = modules.begin();
7433 itmod != modules.end(); ++itmod)
44ffe90c 7434 {
6e6d9a3b
JL
7435 module_info *module;
7436
7437 // retrieve module_info from cache
44ffe90c
JL
7438 map<string, module_info*>::const_iterator itcache;
7439 if ((itcache = cache.find(*itmod)) != cache.end())
6e6d9a3b
JL
7440 module = itcache->second;
7441 else // module not found
7442 continue;
7443
7444 // add inlines
7445 funcs.insert(module->inlined_funcs.begin(),
7446 module->inlined_funcs.end());
7447
7448 // add all function symbols in cache
7449 if (module->symtab_status != info_present || module->sym_table == NULL)
7450 continue;
7451 map<string, func_info*>& modfuncs = module->sym_table->map_by_name;
7452 for (map<string, func_info*>::const_iterator itfuncs = modfuncs.begin();
7453 itfuncs != modfuncs.end(); ++itfuncs)
7454 funcs.insert(itfuncs->first);
44ffe90c
JL
7455 }
7456
7457 if (sess.verbose > 2)
d82dd71f
JL
7458 {
7459 clog << "suggesting " << funcs.size() << " dwarf functions "
7460 << "from modules:" << endl;
7461 for (set<string>::iterator itmod = modules.begin();
7462 itmod != modules.end(); ++itmod)
7463 clog << *itmod << endl;
7464 }
44ffe90c
JL
7465
7466 if (funcs.empty())
7467 return "";
7468
593f09eb 7469 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
7470}
7471
20c6c071 7472void
5227f1ea 7473dwarf_builder::build(systemtap_session & sess,
7a053d3b 7474 probe * base,
20c6c071 7475 probe_point * location,
86bf665e 7476 literal_map_t const & parameters,
20c6c071
GH
7477 vector<derived_probe *> & finished_results)
7478{
b20febf3
FCE
7479 // NB: the kernel/user dwlfpp objects are long-lived.
7480 // XXX: but they should be per-session, as this builder object
7481 // may be reused if we try to cross-instrument multiple targets.
84048984 7482
7a24d422 7483 dwflpp* dw = 0;
6d5d594e 7484 literal_map_t filled_parameters = parameters;
7a24d422 7485
7a24d422 7486 string module_name;
ae2552da
FCE
7487 if (has_null_param (parameters, TOK_KERNEL))
7488 {
7489 dw = get_kern_dw(sess, "kernel");
7490 }
7491 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 7492 {
c523a015
LB
7493 size_t dash_pos = 0;
7494 while((dash_pos=module_name.find('-'))!=string::npos)
7495 module_name.replace(int(dash_pos),1,"_");
7496 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
7497 // NB: glob patterns get expanded later, during the offline
7498 // elfutils module listing.
ae2552da 7499 dw = get_kern_dw(sess, module_name);
b8da0ad1 7500 }
6d5d594e 7501 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 7502 {
05fb3e0c 7503 module_name = sess.sysroot + module_name;
6d5d594e
LB
7504 if(has_null_param(filled_parameters, TOK_PROCESS))
7505 {
fc18e6c4
JL
7506 string file;
7507 try
7508 {
7509 file = sess.cmd_file();
7510 }
7511 catch (const semantic_error& e)
7512 {
7513 throw SEMANTIC_ERROR(_("invalid -c command for unspecified process"
7514 " probe [man stapprobes]"), NULL, NULL, &e);
7515 }
48cd804a 7516 if(file.empty())
fc18e6c4
JL
7517 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without"
7518 " a -c COMMAND [man stapprobes]"));
48cd804a 7519 module_name = sess.sysroot + file;
6d5d594e
LB
7520 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
7521 // in the case of TOK_MARK we need to modify locations as well
7522 if(location->components[0]->functor==TOK_PROCESS &&
7523 location->components[0]->arg == 0)
7524 location->components[0]->arg = new literal_string(module_name);
b78a0fbb 7525 }
5750ecc6 7526
37001baa
FCE
7527 // PR6456 process("/bin/*") glob handling
7528 if (contains_glob_chars (module_name))
7529 {
7530 // Expand glob via rewriting the probe-point process("....")
7531 // parameter, asserted to be the first one.
7532
7533 assert (location->components.size() > 0);
7534 assert (location->components[0]->functor == TOK_PROCESS);
7535 assert (location->components[0]->arg);
7536 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7537 assert (lit);
7538
7539 // Evaluate glob here, and call derive_probes recursively with each match.
7540 glob_t the_blob;
88f8e2c0 7541 set<string> dupes;
37001baa 7542 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 7543 if (rc)
dc09353a 7544 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 7545 unsigned results_pre = finished_results.size();
37001baa
FCE
7546 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
7547 {
e19ebcf7 7548 assert_no_interrupts();
37001baa
FCE
7549
7550 const char* globbed = the_blob.gl_pathv[i];
7551 struct stat st;
7552
7553 if (access (globbed, X_OK) == 0
7554 && stat (globbed, &st) == 0
7555 && S_ISREG (st.st_mode)) // see find_executable()
7556 {
7977a734
FCE
7557 // Need to call canonicalize here, in order to path-expand
7558 // patterns like process("stap*"). Otherwise it may go through
7559 // to the next round of expansion as ("stap"), leading to a $PATH
7560 // search that's not consistent with the glob search already done.
5bca76a8
JS
7561 string canononicalized = resolve_path (globbed);
7562 globbed = canononicalized.c_str();
7977a734 7563
88f8e2c0
JS
7564 // The canonical names can result in duplication, for example
7565 // having followed symlinks that are common with shared
7566 // libraries. Filter those out.
7567 if (!dupes.insert(canononicalized).second)
7568 continue;
7569
37001baa
FCE
7570 // synthesize a new probe_point, with the glob-expanded string
7571 probe_point *pp = new probe_point (*location);
ef0943df
JL
7572 pp->from_glob = true;
7573
5750ecc6
FCE
7574 // PR13338: quote results to prevent recursion
7575 string eglobbed = escape_glob_chars (globbed);
7576
7577 if (sess.verbose > 1)
7578 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7579 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 7580 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 7581
37001baa 7582 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7583 new literal_string (eglobbed_tgt));
37001baa
FCE
7584 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7585 pp->components[0] = ppc;
7586
d885563b 7587 probe* new_probe = new probe (base, pp);
7977a734
FCE
7588
7589 // We override "optional = true" here, as if the
7590 // wildcarded probe point was given a "?" suffix.
7591
7592 // This is because wildcard probes will be expected
7593 // by users to apply only to some subset of the
7594 // matching binaries, in the sense of "any", rather
7595 // than "all", sort of similarly how
7596 // module("*").function("...") patterns work.
7597
7598 derive_probes (sess, new_probe, finished_results,
7599 true /* NB: not location->optional */ );
37001baa
FCE
7600 }
7601 }
7602
7603 globfree (& the_blob);
44ffe90c
JL
7604
7605 unsigned results_post = finished_results.size();
7606
e90006d7 7607 // Did we fail to find a function/plt/mark by name? Let's suggest
44ffe90c
JL
7608 // something!
7609 string func;
7610 if (results_pre == results_post
7611 && get_param(filled_parameters, TOK_FUNCTION, func)
7612 && !func.empty())
7613 {
0508c45f 7614 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7615 modules_seen.clear();
7616 if (!sugs.empty())
dc09353a 7617 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7618 "no match (similar functions: %s)",
7619 sugs.find(',') == string::npos,
7620 sugs.c_str()));
7621 }
40a70f52
JL
7622 else if (results_pre == results_post
7623 && get_param(filled_parameters, TOK_PLT, func)
7624 && !func.empty())
7625 {
7626 string sugs = suggest_plt_functions(sess, modules_seen, func);
7627 modules_seen.clear();
7628 if (!sugs.empty())
7629 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7630 "no match (similar functions: %s)",
7631 sugs.find(',') == string::npos,
7632 sugs.c_str()));
7633 }
e90006d7
JL
7634 else if (results_pre == results_post
7635 && get_param(filled_parameters, TOK_MARK, func)
7636 && !func.empty())
7637 {
7638 string provider;
7639 get_param(filled_parameters, TOK_PROVIDER, provider);
7640
7641 string sugs = suggest_marks(sess, modules_seen, func, provider);
7642 modules_seen.clear();
7643 if (!sugs.empty())
7644 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7645 "no match (similar marks: %s)",
7646 sugs.find(',') == string::npos,
7647 sugs.c_str()));
7648 }
44ffe90c 7649
37001baa
FCE
7650 return; // avoid falling through
7651 }
7652
5750ecc6
FCE
7653 // PR13338: unquote glob results
7654 module_name = unescape_glob_chars (module_name);
05fb3e0c 7655 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
5fa0d811
JL
7656 if (!is_fully_resolved(user_path, "", sess.sysenv))
7657 throw SEMANTIC_ERROR(_F("cannot find executable '%s'",
7658 user_path.c_str()));
d1bcbe71
RH
7659
7660 // if the executable starts with "#!", we look for the interpreter of the script
7661 {
7662 ifstream script_file (user_path.c_str () );
7663
7664 if (script_file.good ())
7665 {
7666 string line;
7667
7668 getline (script_file, line);
7669
7670 if (line.compare (0, 2, "#!") == 0)
7671 {
7672 string path_head = line.substr(2);
7673
7674 // remove white spaces at the beginning of the string
7675 size_t p2 = path_head.find_first_not_of(" \t");
7676
7677 if (p2 != string::npos)
7678 {
7679 string path = path_head.substr(p2);
7680
7681 // remove white spaces at the end of the string
7682 p2 = path.find_last_not_of(" \t\n");
7683 if (string::npos != p2)
7684 path.erase(p2+1);
7685
8e13c1a1
RH
7686 // handle "#!/usr/bin/env" redirect
7687 size_t offset = 0;
7688 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7689 {
7690 offset = sizeof("/bin/env")-1;
7691 }
7692 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7693 {
7694 offset = sizeof("/usr/bin/env")-1;
7695 }
7696
7697 if (offset != 0)
7698 {
7699 size_t p3 = path.find_first_not_of(" \t", offset);
7700
7701 if (p3 != string::npos)
7702 {
7703 string env_path = path.substr(p3);
05fb3e0c
WF
7704 user_path = find_executable (env_path, sess.sysroot,
7705 sess.sysenv);
8e13c1a1
RH
7706 }
7707 }
7708 else
7709 {
05fb3e0c 7710 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7711 }
d1bcbe71
RH
7712
7713 struct stat st;
7714
7715 if (access (user_path.c_str(), X_OK) == 0
7716 && stat (user_path.c_str(), &st) == 0
7717 && S_ISREG (st.st_mode)) // see find_executable()
7718 {
7719 if (sess.verbose > 1)
b530b5b3
LB
7720 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7721 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7722
7723 assert (location->components.size() > 0);
7724 assert (location->components[0]->functor == TOK_PROCESS);
7725 assert (location->components[0]->arg);
7726 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7727 assert (lit);
7728
7729 // synthesize a new probe_point, with the expanded string
7730 probe_point *pp = new probe_point (*location);
05fb3e0c 7731 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7732 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7733 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7734 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7735 pp->components[0] = ppc;
7736
d885563b 7737 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7738
7739 derive_probes (sess, new_probe, finished_results);
7740
7741 script_file.close();
7742 return;
7743 }
7744 }
7745 }
7746 }
7747 script_file.close();
7748 }
7749
dbe9d133
JL
7750 // If this is a library probe, then target the library module instead. We
7751 // do this only if the library path is already fully resolved (such as
7752 // what query_one_library() would have done for us). Otherwise, we resort
7753 // to iterate_over_libraries.
7754 if (get_param (parameters, TOK_LIBRARY, user_lib) && !user_lib.empty()
7755 && is_fully_resolved(user_lib, sess.sysroot, sess.sysenv, "LD_LIBRARY_PATH"))
7756 module_name = user_lib;
63b4fd14 7757 else
dbe9d133 7758 module_name = user_path; // canonicalize it
d0a7f5a9 7759
3667d615 7760 // uretprobes aren't available everywhere
536f1261 7761 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7762 {
3667d615
JS
7763 if (kernel_supports_inode_uprobes(sess) &&
7764 !kernel_supports_inode_uretprobes(sess))
dc09353a 7765 throw SEMANTIC_ERROR
3ffeaf3c 7766 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7767 }
3667d615 7768
f4000852
MW
7769 // There is a similar check in pass 4 (buildrun), but it is
7770 // needed here too to make sure alternatives for optional
7771 // (? or !) process probes are disposed and/or alternatives
7772 // are selected.
3667d615
JS
7773 if (!sess.runtime_usermode_p())
7774 check_process_probe_kernel_support(sess);
e34d5d13 7775
7a24d422
FCE
7776 // user-space target; we use one dwflpp instance per module name
7777 // (= program or shared library)
707bf35e 7778 dw = get_user_dw(sess, module_name);
c8959a29 7779 }
20c6c071 7780
1acfc030
JS
7781 assert(dw);
7782
e90006d7
JL
7783 unsigned results_pre = finished_results.size();
7784
5896cd05 7785 if (sess.verbose > 3)
b530b5b3 7786 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7787
a794dbeb
FCE
7788 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7789 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7790 {
51d6bda3 7791 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
06de3a04 7792 dw->iterate_over_modules<base_query>(&query_module, &sdtq);
e90006d7
JL
7793
7794 // We need to update modules_seen with the modules we've visited
7795 modules_seen.insert(sdtq.visited_modules.begin(),
7796 sdtq.visited_modules.end());
7797
7798 // Did we fail to find a mark?
7799 if (results_pre == finished_results.size() && !location->from_glob)
7800 {
7801 string provider;
7802 get_param(filled_parameters, TOK_PROVIDER, provider);
7803
7804 string sugs = suggest_marks(sess, modules_seen, dummy_mark_name, provider);
7805 modules_seen.clear();
7806 if (!sugs.empty())
7807 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7808 "no match (similar marks: %s)",
7809 sugs.find(',') == string::npos,
7810 sugs.c_str()));
7811 }
7812
edce5b67 7813 return;
7a05f484 7814 }
20c6c071 7815
6d5d594e 7816 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7817
7818 // XXX: kernel.statement.absolute is a special case that requires no
7819 // dwfl processing. This code should be in a separate builder.
7a24d422 7820 if (q.has_kernel && q.has_absolute)
37ebca01 7821 {
4baf0e53 7822 // assert guru mode for absolute probes
37ebca01
FCE
7823 if (! q.base_probe->privileged)
7824 {
dc09353a 7825 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7826 q.base_probe->tok);
37ebca01
FCE
7827 }
7828
7829 // For kernel.statement(NUM).absolute probe points, we bypass
7830 // all the debuginfo stuff: We just wire up a
7831 // dwarf_derived_probe right here and now.
4baf0e53 7832 dwarf_derived_probe* p =
b8da0ad1
FCE
7833 new dwarf_derived_probe ("", "", 0, "kernel", "",
7834 q.statement_num_val, q.statement_num_val,
7835 q, 0);
37ebca01 7836 finished_results.push_back (p);
1a0dbc5a 7837 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7838 return;
7839 }
7840
06de3a04 7841 dw->iterate_over_modules<base_query>(&query_module, &q);
8f14e444 7842
44ffe90c
JL
7843 // We need to update modules_seen with the modules we've visited
7844 modules_seen.insert(q.visited_modules.begin(),
7845 q.visited_modules.end());
8f14e444
FCE
7846
7847 // PR11553 special processing: .return probes requested, but
7848 // some inlined function instances matched.
7849 unsigned i_n_r = q.inlined_non_returnable.size();
7850 unsigned results_post = finished_results.size();
7851 if (i_n_r > 0)
7852 {
7853 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7854 {
7855 string quicklist;
7856 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7857 it != q.inlined_non_returnable.end();
7858 it++)
7859 {
7860 quicklist += " " + (*it);
7861 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7862 {
7863 quicklist += " ...";
7864 break;
7865 }
7866 }
c57ea854 7867
52c2652f 7868 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7869 "cannot probe .return of %u inlined functions %s",
52c2652f 7870 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7871 // There will be also a "no matches" semantic error generated.
7872 }
7873 if (sess.verbose > 1)
52c2652f
NMA
7874 clog << _NF("skipped .return probe of %u inlined function",
7875 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7876 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7877 {
7878 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7879 it != q.inlined_non_returnable.end();
7880 it++)
7881 clog << (*it) << " ";
7882 clog << endl;
7883 }
7884 } // i_n_r > 0
44ffe90c 7885
e90006d7 7886 // If we just failed to resolve a function/plt by name, we can suggest
ef0943df
JL
7887 // something. We only suggest things for probe points that were not
7888 // synthesized from a glob, i.e. only for 'real' probes. This is also
7889 // required because modules_seen needs to accumulate across recursive
7890 // calls for process(glob)[.library(glob)] probes.
44ffe90c 7891 string func;
ef0943df 7892 if (results_pre == results_post && !location->from_glob
44ffe90c
JL
7893 && get_param(filled_parameters, TOK_FUNCTION, func)
7894 && !func.empty())
7895 {
0508c45f 7896 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7897 modules_seen.clear();
7898 if (!sugs.empty())
dc09353a 7899 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7900 "no match (similar functions: %s)",
7901 sugs.find(',') == string::npos,
7902 sugs.c_str()));
7903 }
ef0943df 7904 else if (results_pre == results_post && !location->from_glob
40a70f52
JL
7905 && get_param(filled_parameters, TOK_PLT, func)
7906 && !func.empty())
7907 {
7908 string sugs = suggest_plt_functions(sess, modules_seen, func);
7909 modules_seen.clear();
7910 if (!sugs.empty())
7911 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7912 "no match (similar functions: %s)",
7913 sugs.find(',') == string::npos,
7914 sugs.c_str()));
7915 }
44ffe90c
JL
7916 else if (results_pre != results_post)
7917 // Something was derived so we won't need to suggest something
7918 modules_seen.clear();
5f0a03a6
JK
7919}
7920
7921symbol_table::~symbol_table()
7922{
c9efa5c9 7923 delete_map(map_by_addr);
5f0a03a6
JK
7924}
7925
7926void
2867a2a1 7927symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7928 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7929{
ab91b232
JK
7930#ifdef __powerpc__
7931 // Map ".sys_foo" to "sys_foo".
7932 if (name[0] == '.')
7933 name++;
7934#endif
5f0a03a6
JK
7935 func_info *fi = new func_info();
7936 fi->addr = addr;
7937 fi->name = name;
ab91b232 7938 fi->weak = weak;
2867a2a1 7939 fi->descriptor = descriptor;
5f0a03a6
JK
7940 map_by_name[fi->name] = fi;
7941 // TODO: Use a multimap in case there are multiple static
7942 // functions with the same name?
1c6b77e5 7943 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7944}
7945
46f7b6be 7946void
f98c6346 7947symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7948{
7949#ifdef __powerpc__
7950 /*
7951 * The .opd section contains function descriptors that can look
7952 * just like function entry points. For example, there's a function
7953 * descriptor called "do_exit" that links to the entry point ".do_exit".
7954 * Reject all symbols in .opd.
7955 */
7956 opd_section = SHN_UNDEF;
7957 Dwarf_Addr bias;
7958 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7959 ?: dwfl_module_getelf (mod, &bias));
7960 Elf_Scn* scn = 0;
7961 size_t shstrndx;
7962
7963 if (!elf)
7964 return;
fcc30d6d 7965 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7966 return;
7967 while ((scn = elf_nextscn(elf, scn)) != NULL)
7968 {
7969 GElf_Shdr shdr_mem;
7970 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7971 if (!shdr)
7972 continue;
7973 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7974 if (!strcmp(name, ".opd"))
7975 {
7976 opd_section = elf_ndxscn(scn);
7977 return;
7978 }
7979 }
7980#endif
7981}
7982
7983bool
7984symbol_table::reject_section(GElf_Word section)
7985{
7986 if (section == SHN_UNDEF)
7987 return true;
7988#ifdef __powerpc__
7989 if (section == opd_section)
7990 return true;
7991#endif
7992 return false;
7993}
7994
5f0a03a6
JK
7995enum info_status
7996symbol_table::get_from_elf()
7997{
7998 Dwarf_Addr high_addr = 0;
7999 Dwfl_Module *mod = mod_info->mod;
8000 int syments = dwfl_module_getsymtab(mod);
8001 assert(syments);
46f7b6be 8002 prepare_section_rejection(mod);
5f0a03a6
JK
8003 for (int i = 1; i < syments; ++i)
8004 {
8005 GElf_Sym sym;
ab91b232 8006 GElf_Word section;
cba67d8f
MW
8007 const char *name;
8008 GElf_Addr addr;
8009 bool reject;
8010
8011/* Note that dwfl_module_getsym does adjust the sym.st_value but doesn't
8012 try to resolve it to a function address. dwfl_module_getsym_info leaves
8013 the st_value in tact (no adjustment applied) and returns the fully
8014 resolved address separately. In that case we can simply reject the
8015 symbol if it is SHN_UNDEF and don't need to call reject_section which
8016 does extra checks to see whether the address fall in an architecture
8017 specific descriptor table (which will never be the case when using the
8018 new dwfl_module_getsym_info). dwfl_module_getsym will only provide us
8019 with the (adjusted) st_value of the symbol, which might point into a
8020 function descriptor table. So in that case we still have to call
8021 reject_section. */
8022#if _ELFUTILS_PREREQ (0, 158)
8023 name = dwfl_module_getsym_info (mod, i, &sym, &addr, &section,
8024 NULL, NULL);
8025 reject = section == SHN_UNDEF;
8026#else
8027 name = dwfl_module_getsym (mod, i, &sym, &section);
b23098cd 8028 addr = sym.st_value;
cba67d8f
MW
8029 reject = reject_section(section);
8030#endif
8031
2867a2a1 8032 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 8033 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
cba67d8f 8034 reject, addr, &high_addr);
2a4acb09
JL
8035 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
8036 && GELF_ST_BIND(sym.st_info) == STB_GLOBAL)
8037 globals[name] = addr;
8038 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
8039 && GELF_ST_BIND(sym.st_info) == STB_LOCAL)
8040 locals[name] = addr;
5f0a03a6
JK
8041 }
8042 return info_present;
8043}
8044
5f0a03a6
JK
8045func_info *
8046symbol_table::get_func_containing_address(Dwarf_Addr addr)
8047{
1c6b77e5
JS
8048 iterator_t iter = map_by_addr.upper_bound(addr);
8049 if (iter == map_by_addr.begin())
5f0a03a6 8050 return NULL;
2e67a43b 8051 else
1c6b77e5 8052 return (--iter)->second;
5f0a03a6
JK
8053}
8054
3d372d6b
SC
8055func_info *
8056symbol_table::get_first_func()
8057{
8058 iterator_t iter = map_by_addr.begin();
8059 return (iter)->second;
8060}
8061
5f0a03a6
JK
8062func_info *
8063symbol_table::lookup_symbol(const string& name)
8064{
8065 map<string, func_info*>::iterator i = map_by_name.find(name);
8066 if (i == map_by_name.end())
8067 return NULL;
8068 return i->second;
8069}
8070
8071Dwarf_Addr
8072symbol_table::lookup_symbol_address(const string& name)
8073{
8074 func_info *fi = lookup_symbol(name);
8075 if (fi)
8076 return fi->addr;
8077 return 0;
8078}
8079
ab91b232
JK
8080// This is the kernel symbol table. The kernel macro cond_syscall creates
8081// a weak symbol for each system call and maps it to sys_ni_syscall.
8082// For system calls not implemented elsewhere, this weak symbol shows up
8083// in the kernel symbol table. Following the precedent of dwarfful stap,
8084// we refuse to consider such symbols. Here we delete them from our
8085// symbol table.
8086// TODO: Consider generalizing this and/or making it part of blacklist
8087// processing.
8088void
8089symbol_table::purge_syscall_stubs()
8090{
8091 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
8092 if (stub_addr == 0)
8093 return;
1c6b77e5 8094 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
8095 for (iterator_t iter = purge_range.first;
8096 iter != purge_range.second;
1c6b77e5 8097 )
ab91b232 8098 {
1c6b77e5 8099 func_info *fi = iter->second;
2e67a43b 8100 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 8101 {
2e67a43b 8102 map_by_name.erase(fi->name);
1c6b77e5 8103 map_by_addr.erase(iter++);
2e67a43b 8104 delete fi;
2e67a43b 8105 }
1c6b77e5
JS
8106 else
8107 iter++;
ab91b232
JK
8108 }
8109}
8110
5f0a03a6 8111void
5f52fafe 8112module_info::get_symtab()
5f0a03a6 8113{
1c6b77e5
JS
8114 if (symtab_status != info_unknown)
8115 return;
8116
5f0a03a6
JK
8117 sym_table = new symbol_table(this);
8118 if (!elf_path.empty())
8119 {
5f0a03a6
JK
8120 symtab_status = sym_table->get_from_elf();
8121 }
8122 else
8123 {
8124 assert(name == TOK_KERNEL);
ab3ed72d
DS
8125 symtab_status = info_absent;
8126 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
8127 }
8128 if (symtab_status == info_absent)
8129 {
8130 delete sym_table;
8131 sym_table = NULL;
8132 return;
8133 }
8134
ab91b232
JK
8135 if (name == TOK_KERNEL)
8136 sym_table->purge_syscall_stubs();
5f0a03a6
JK
8137}
8138
1c6b77e5
JS
8139// update_symtab reconciles data between the elf symbol table and the dwarf
8140// function enumeration. It updates the symbol table entries with the dwarf
8141// die that describes the function, which also signals to query_module_symtab
8142// that a statement probe isn't needed. In return, it also adds aliases to the
8143// function table for names that share the same addr/die.
8144void
8145module_info::update_symtab(cu_function_cache_t *funcs)
8146{
8147 if (!sym_table)
8148 return;
8149
8150 cu_function_cache_t new_funcs;
8151
8152 for (cu_function_cache_t::iterator func = funcs->begin();
8153 func != funcs->end(); func++)
8154 {
8155 // optimization: inlines will never be in the symbol table
8156 if (dwarf_func_inline(&func->second) != 0)
6e6d9a3b
JL
8157 {
8158 inlined_funcs.insert(func->first);
8159 continue;
8160 }
1c6b77e5 8161
1ffb8bd1
JS
8162 // XXX We may want to make additional efforts to match mangled elf names
8163 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
8164 // missing, so we may also need to try matching by address. See also the
8165 // notes about _Z in dwflpp::iterate_over_functions().
8166
1c6b77e5
JS
8167 func_info *fi = sym_table->lookup_symbol(func->first);
8168 if (!fi)
8169 continue;
8170
8171 // iterate over all functions at the same address
8172 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
8173 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
8174 {
8175 // update this function with the dwarf die
8176 it->second->die = func->second;
8177
8178 // if this function is a new alias, then
8179 // save it to merge into the function cache
8180 if (it->second != fi)
b7478964 8181 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
8182 }
8183 }
8184
8185 // add all discovered aliases back into the function cache
8186 // NB: this won't replace any names that dwarf may have already found
8187 funcs->insert(new_funcs.begin(), new_funcs.end());
8188}
8189
5f0a03a6
JK
8190module_info::~module_info()
8191{
8192 if (sym_table)
8193 delete sym_table;
b55bc428
FCE
8194}
8195
935447c8 8196// ------------------------------------------------------------------------
888af770 8197// user-space probes
935447c8
DS
8198// ------------------------------------------------------------------------
8199
935447c8 8200
888af770 8201struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 8202{
89ba3085
FCE
8203private:
8204 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 8205 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
8206 }
8207
cfcab6c7
JS
8208 void emit_module_maxuprobes (systemtap_session& s);
8209
2b69faaf
JS
8210 // Using our own utrace-based uprobes
8211 void emit_module_utrace_decls (systemtap_session& s);
8212 void emit_module_utrace_init (systemtap_session& s);
8213 void emit_module_utrace_exit (systemtap_session& s);
8214
8215 // Using the upstream inode-based uprobes
8216 void emit_module_inode_decls (systemtap_session& s);
8217 void emit_module_inode_init (systemtap_session& s);
8218 void emit_module_inode_exit (systemtap_session& s);
8219
3a894f7e
JS
8220 // Using the dyninst backend (via stapdyn)
8221 void emit_module_dyninst_decls (systemtap_session& s);
8222 void emit_module_dyninst_init (systemtap_session& s);
8223 void emit_module_dyninst_exit (systemtap_session& s);
8224
935447c8 8225public:
888af770 8226 void emit_module_decls (systemtap_session& s);
935447c8
DS
8227 void emit_module_init (systemtap_session& s);
8228 void emit_module_exit (systemtap_session& s);
8229};
8230
8231
888af770
FCE
8232void
8233uprobe_derived_probe::join_group (systemtap_session& s)
8234{
8235 if (! s.uprobe_derived_probes)
8236 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
8237 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
8238 if (s.runtime_usermode_p())
8239 enable_dynprobes(s);
8240 else
4441e344 8241 enable_task_finder(s);
a96d1db0 8242
8a03658e 8243 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
8244 // signal staprun to load that module. If we're using the builtin
8245 // inode-uprobes, we still need to know that it is required.
8a03658e 8246 s.need_uprobes = true;
a96d1db0
DN
8247}
8248
888af770 8249
c0f84e7b
SC
8250void
8251uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
8252{
8253 dwarf_derived_probe::getargs(arg_set);
8254 arg_set.insert(arg_set.end(), args.begin(), args.end());
8255}
8256
8257
8258void
8259uprobe_derived_probe::saveargs(int nargs)
8260{
8261 for (int i = 1; i <= nargs; i++)
8262 args.push_back("$arg" + lex_cast (i) + ":long");
8263}
8264
8265
2865d17a 8266void
42e38653 8267uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
8268{
8269 // These probes are allowed for unprivileged users, but only in the
8270 // context of processes which they own.
8271 emit_process_owner_assertion (o);
8272}
8273
8274
888af770 8275struct uprobe_builder: public derived_probe_builder
a96d1db0 8276{
888af770 8277 uprobe_builder() {}
2b69faaf 8278 virtual void build(systemtap_session & sess,
a96d1db0
DN
8279 probe * base,
8280 probe_point * location,
86bf665e 8281 literal_map_t const & parameters,
a96d1db0
DN
8282 vector<derived_probe *> & finished_results)
8283 {
888af770 8284 int64_t process, address;
a96d1db0 8285
2b69faaf 8286 if (kernel_supports_inode_uprobes(sess))
dc09353a 8287 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 8288
888af770 8289 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 8290 (void) b1;
888af770 8291 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 8292 (void) b2;
888af770
FCE
8293 bool rr = has_null_param (parameters, TOK_RETURN);
8294 assert (b1 && b2); // by pattern_root construction
a96d1db0 8295
0973d815 8296 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
8297 }
8298};
8299
8300
8301void
cfcab6c7 8302uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 8303{
43241c44
FCE
8304 // We'll probably need at least this many:
8305 unsigned minuprobes = probes.size();
8306 // .. but we don't want so many that .bss is inflated (PR10507):
8307 unsigned uprobesize = 64;
8308 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
8309 unsigned maxuprobes = maxuprobesmem / uprobesize;
8310
aaf7ffe8
FCE
8311 // Let's choose a value on the geometric middle. This should end up
8312 // between minuprobes and maxuprobes. It's OK if this number turns
8313 // out to be < minuprobes or > maxuprobes. At worst, we get a
8314 // run-time error of one kind (too few: missed uprobe registrations)
8315 // or another (too many: vmalloc errors at module load time).
8316 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 8317
6d0f3f0c 8318 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 8319 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 8320 s.op->newline() << "#endif";
cfcab6c7
JS
8321}
8322
8323
8324void
8325uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
8326{
8327 if (probes.empty()) return;
8328 s.op->newline() << "/* ---- utrace uprobes ---- */";
8329 // If uprobes isn't in the kernel, pull it in from the runtime.
8330
8331 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
8332 s.op->newline() << "#include <linux/uprobes.h>";
8333 s.op->newline() << "#else";
2ba1736a 8334 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
8335 s.op->newline() << "#endif";
8336 s.op->newline() << "#ifndef UPROBES_API_VERSION";
8337 s.op->newline() << "#define UPROBES_API_VERSION 1";
8338 s.op->newline() << "#endif";
8339
8340 emit_module_maxuprobes (s);
a96d1db0 8341
cc52276b 8342 // Forward decls
2ba1736a 8343 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 8344
5e112f92
FCE
8345 // In .bss, the shared pool of uprobe/uretprobe structs. These are
8346 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
8347 // XXX: consider a slab cache or somesuch for stap_uprobes
8348 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 8349 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 8350
89ba3085
FCE
8351 s.op->assert_0_indent();
8352
89ba3085
FCE
8353 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
8354 // This means we process probes[] in two passes.
8355 map <string,unsigned> module_index;
8356 unsigned module_index_ctr = 0;
8357
cc52276b
WC
8358 // not const since embedded task_finder_target struct changes
8359 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
8360 s.op->indent(1);
8361 for (unsigned i=0; i<probes.size(); i++)
8362 {
8363 uprobe_derived_probe *p = probes[i];
8364 string pbmkey = make_pbm_key (p);
8365 if (module_index.find (pbmkey) == module_index.end())
8366 {
8367 module_index[pbmkey] = module_index_ctr++;
8368
8369 s.op->newline() << "{";
8370 // NB: it's essential that make_pbm_key() use all of and
8371 // only the same fields as we're about to emit.
8372 s.op->line() << " .finder={";
1af100fc 8373 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 8374 if (p->pid != 0)
68910c97
JK
8375 s.op->line() << " .pid=" << p->pid << ",";
8376
8377 if (p->section == "") // .statement(addr).absolute
8378 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
8379 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8380 {
8381 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8382 s.op->line() << " .callback=&stap_uprobe_process_found,";
8383 }
68910c97 8384 else if (p->section != ".absolute") // ET_DYN
89ba3085 8385 {
4ad95bbc
SC
8386 if (p->has_library)
8387 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
8388 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
8389 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 8390 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 8391 }
89ba3085 8392 s.op->line() << " },";
68910c97
JK
8393 if (p->module != "")
8394 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
8395 s.op->line() << " },";
8396 }
c57ea854 8397 else
822a6a3d 8398 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
8399 }
8400 s.op->newline(-1) << "};";
8401
8402 s.op->assert_0_indent();
8403
3689db05
SC
8404 unsigned pci;
8405 for (pci=0; pci<probes.size(); pci++)
8406 {
8407 // List of perf counters used by each probe
8408 // This list is an index into struct stap_perf_probe,
8409 uprobe_derived_probe *p = probes[pci];
698de6cc 8410 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8411 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8412 for (pcii = p->perf_counter_refs.begin();
8413 pcii != p->perf_counter_refs.end(); pcii++)
8414 {
8415 map<string, pair<string,derived_probe*> >::iterator it;
8416 unsigned i = 0;
8417 // Find the associated perf.counter probe
8418 for (it=s.perf_counters.begin() ;
8419 it != s.perf_counters.end(); it++, i++)
8420 if ((*it).second.second == (*pcii))
8421 break;
8422 s.op->line() << lex_cast(i) << ", ";
8423 }
8424 s.op->newline() << "};";
8425 }
8426
cc52276b
WC
8427 // NB: read-only structure
8428 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 8429 s.op->indent(1);
888af770
FCE
8430 for (unsigned i =0; i<probes.size(); i++)
8431 {
8432 uprobe_derived_probe* p = probes[i];
8433 s.op->newline() << "{";
89ba3085
FCE
8434 string key = make_pbm_key (p);
8435 unsigned value = module_index[key];
759e1d76
FCE
8436 if (value != 0)
8437 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 8438 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 8439 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 8440
038c38c6 8441 if (p->sdt_semaphore_addr != 0)
63b4fd14 8442 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 8443 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 8444
0d049a1d 8445 // XXX: don't bother emit if array is empty
3689db05
SC
8446 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8447 // List of perf counters used by a probe from above
0d049a1d 8448 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 8449
4ddb6dd0
JS
8450 if (p->has_return)
8451 s.op->line() << " .return_p=1,";
888af770
FCE
8452 s.op->line() << " },";
8453 }
8454 s.op->newline(-1) << "};";
a96d1db0 8455
89ba3085
FCE
8456 s.op->assert_0_indent();
8457
48e685da 8458 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 8459 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 8460 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8461 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8462 "stp_probe_type_uprobe");
0e090c74 8463 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
8464 << "sup->spec_index >= " << probes.size() << ") {";
8465 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8466 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
8467 s.op->newline() << "goto probe_epilogue;";
8468 s.op->newline(-1) << "}";
d9aed31e 8469 s.op->newline() << "c->uregs = regs;";
e04b5d74 8470 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8471
8472 // Make it look like the IP is set as it would in the actual user
8473 // task when calling real probe handler. Reset IP regs on return, so
8474 // we don't confuse uprobes. PR10458
8475 s.op->newline() << "{";
8476 s.op->indent(1);
d9aed31e 8477 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 8478 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 8479 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8480 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8481 s.op->newline(-1) << "}";
8482
f887a8c9 8483 common_probe_entryfn_epilogue (s, true);
888af770 8484 s.op->newline(-1) << "}";
a96d1db0 8485
48e685da 8486 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 8487 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 8488 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8489 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8490 "stp_probe_type_uretprobe");
6dceb5c9 8491 s.op->newline() << "c->ips.ri = inst;";
0e090c74 8492 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
8493 << "sup->spec_index >= " << probes.size() << ") {";
8494 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8495 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
8496 s.op->newline() << "goto probe_epilogue;";
8497 s.op->newline(-1) << "}";
8498
d9aed31e 8499 s.op->newline() << "c->uregs = regs;";
e04b5d74 8500 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8501
8502 // Make it look like the IP is set as it would in the actual user
8503 // task when calling real probe handler. Reset IP regs on return, so
8504 // we don't confuse uprobes. PR10458
8505 s.op->newline() << "{";
8506 s.op->indent(1);
d9aed31e 8507 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 8508 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 8509 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8510 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8511 s.op->newline(-1) << "}";
8512
f887a8c9 8513 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
8514 s.op->newline(-1) << "}";
8515
89ba3085 8516 s.op->newline();
2ba1736a 8517 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 8518 s.op->newline();
888af770 8519}
935447c8
DS
8520
8521
888af770 8522void
2b69faaf 8523uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 8524{
888af770 8525 if (probes.empty()) return;
935447c8 8526
2b69faaf 8527 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 8528
01b05e2e 8529 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
8530 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
8531 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
8532 // NB: we assume the rest of the struct (specificaly, sup->up) is
8533 // initialized to zero. This is so that we can use
8534 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
8535 s.op->newline(-1) << "}";
8536 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 8537
89ba3085
FCE
8538 // Set up the task_finders
8539 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
8540 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 8541 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 8542 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 8543
5e112f92
FCE
8544 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
8545 // finders already registered, since mere registration does not
8546 // cause any utrace or memory allocation actions. That happens only
8547 // later, once the task finder engine starts running. So, for a
8548 // partial initialization requiring unwind, we need do nothing.
8549 s.op->newline() << "if (rc) break;";
a7a68293 8550
888af770
FCE
8551 s.op->newline(-1) << "}";
8552}
d0ea46ce 8553
d0a7f5a9 8554
888af770 8555void
2b69faaf 8556uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
8557{
8558 if (probes.empty()) return;
2b69faaf 8559 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 8560
6d0f3f0c
FCE
8561 // NB: there is no stap_unregister_task_finder_target call;
8562 // important stuff like utrace cleanups are done by
d41d451c
FCE
8563 // __stp_task_finder_cleanup() via stap_stop_task_finder().
8564 //
8565 // This function blocks until all callbacks are completed, so there
8566 // is supposed to be no possibility of any registration-related code starting
8567 // to run in parallel with our shutdown here. So we don't need to protect the
8568 // stap_uprobes[] array with the mutex.
d0a7f5a9 8569
01b05e2e 8570 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 8571 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 8572 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 8573 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 8574
8faa1fc5 8575 // PR10655: decrement that ENABLED semaphore
c116c31b 8576 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
8577 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
8578 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
8579 s.op->newline() << "struct task_struct *tsk;";
8580 s.op->newline() << "rcu_read_lock();";
6846cfc8 8581
86229a55
DS
8582 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
8583 // that the pid is always in the global namespace, not in any
8584 // private namespace.
8faa1fc5 8585 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
8586 // We'd like to call find_task_by_pid_ns() here, but it isn't
8587 // exported. So, we call what it calls...
8588 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
8589 s.op->newline() << "#else";
8590 s.op->newline() << " tsk = find_task_by_pid (pid);";
8591 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
8592
8593 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 8594 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 8595 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 8596 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 8597 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 8598 s.op->newline() << "#endif";
3c5b8e2b 8599 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 8600 s.op->newline(-1) << "}";
8faa1fc5
FCE
8601 // XXX: need to analyze possibility of race condition
8602 s.op->newline(-1) << "}";
8603 s.op->newline() << "rcu_read_unlock();";
8604 s.op->newline(-1) << "}";
6846cfc8 8605
3568f1dd
FCE
8606 s.op->newline() << "if (sups->return_p) {";
8607 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 8608 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 8609 s.op->newline() << "#endif";
80b4ad8b
FCE
8610 // NB: PR6829 does not change that we still need to unregister at
8611 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
8612 s.op->newline() << "unregister_uretprobe (& sup->urp);";
8613 s.op->newline(-1) << "} else {";
8614 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 8615 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
8616 s.op->newline() << "#endif";
8617 s.op->newline() << "unregister_uprobe (& sup->up);";
8618 s.op->newline(-1) << "}";
935447c8 8619
6d0f3f0c 8620 s.op->newline() << "sup->spec_index = -1;";
935447c8 8621
3568f1dd
FCE
8622 // XXX: uprobe missed counts?
8623
6d0f3f0c 8624 s.op->newline(-1) << "}";
935447c8 8625
5e112f92 8626 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8627}
8628
2b69faaf
JS
8629
8630void
8631uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8632{
8633 if (probes.empty()) return;
8634 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8635 emit_module_maxuprobes (s);
2ba1736a 8636 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8637
8638 // Write the probe handler.
79af55c3
JS
8639 s.op->newline() << "static int stapiu_probe_handler "
8640 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8641 s.op->newline(1);
2dbbd473
JS
8642
8643 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8644 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8645 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8646 probe_type);
8647
3bff6634 8648 s.op->newline() << "c->uregs = regs;";
e04b5d74 8649 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8650 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8651 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8652
f887a8c9 8653 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8654 s.op->newline() << "return 0;";
8655 s.op->newline(-1) << "}";
8656 s.op->assert_0_indent();
8657
8658 // Index of all the modules for which we need inodes.
8659 map<string, unsigned> module_index;
8660 unsigned module_index_ctr = 0;
8661
8662 // Discover and declare targets for each unique path.
cfcab6c7 8663 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8664 << "stap_inode_uprobe_targets[] = {";
8665 s.op->indent(1);
8666 for (unsigned i=0; i<probes.size(); i++)
8667 {
8668 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8669 const string key = make_pbm_key(p);
8670 if (module_index.find (key) == module_index.end())
2b69faaf 8671 {
cfcab6c7
JS
8672 module_index[key] = module_index_ctr++;
8673 s.op->newline() << "{";
8674 s.op->line() << " .finder={";
b78a0fbb 8675 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8676 if (p->pid != 0)
8677 s.op->line() << " .pid=" << p->pid << ",";
8678
8679 if (p->section == "") // .statement(addr).absolute XXX?
8680 s.op->line() << " .callback=&stapiu_process_found,";
8681 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8682 {
8683 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8684 s.op->line() << " .callback=&stapiu_process_found,";
8685 }
8686 else if (p->section != ".absolute") // ET_DYN
8687 {
8688 if (p->has_library)
8689 s.op->line() << " .procname=\"" << p->path << "\", ";
8690 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8691 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8692 s.op->line() << " .callback=&stapiu_process_munmap,";
8693 }
8694 s.op->line() << " },";
8695 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8696 s.op->line() << " },";
2b69faaf
JS
8697 }
8698 }
8699 s.op->newline(-1) << "};";
8700 s.op->assert_0_indent();
8701
8702 // Declare the actual probes.
3689db05
SC
8703 unsigned pci;
8704 for (pci=0; pci<probes.size(); pci++)
8705 {
8706 // List of perf counters used by each probe
8707 // This list is an index into struct stap_perf_probe,
8708 uprobe_derived_probe *p = probes[pci];
698de6cc 8709 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8710 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8711 for (pcii = p->perf_counter_refs.begin();
8712 pcii != p->perf_counter_refs.end(); pcii++)
8713 {
8714 map<string, pair<string,derived_probe*> >::iterator it;
8715 unsigned i = 0;
8716 // Find the associated perf.counter probe
4fa83377
SC
8717 for (it=s.perf_counters.begin() ;
8718 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8719 if ((*it).second.second == (*pcii))
8720 break;
8721 s.op->line() << lex_cast(i) << ", ";
8722 }
8723 s.op->newline() << "};";
8724 }
8725
cfcab6c7 8726 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8727 << "stap_inode_uprobe_consumers[] = {";
8728 s.op->indent(1);
8729 for (unsigned i=0; i<probes.size(); i++)
8730 {
8731 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8732 unsigned index = module_index[make_pbm_key(p)];
8733 s.op->newline() << "{";
79af55c3
JS
8734 if (p->has_return)
8735 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8736 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8737 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8738 if (p->sdt_semaphore_addr)
8739 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8740 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8741 // XXX: don't bother emit if array is empty
3689db05
SC
8742 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8743 // List of perf counters used by a probe from above
0d049a1d 8744 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8745 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8746 s.op->line() << " },";
2b69faaf
JS
8747 }
8748 s.op->newline(-1) << "};";
8749 s.op->assert_0_indent();
8750}
8751
8752
8753void
8754uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8755{
8756 if (probes.empty()) return;
8757 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8758 // Let stapiu_init() handle reporting errors by setting probe_point
8759 // to NULL.
8760 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8761 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8762 << "stap_inode_uprobe_targets, "
8763 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8764 << "stap_inode_uprobe_consumers, "
8765 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8766}
8767
8768
8769void
8770uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8771{
8772 if (probes.empty()) return;
8773 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8774 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8775 << "stap_inode_uprobe_targets, "
8776 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8777 << "stap_inode_uprobe_consumers, "
8778 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8779}
8780
8781
3a894f7e
JS
8782void
8783uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8784{
8785 if (probes.empty()) return;
8786 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8787 emit_module_maxuprobes (s);
e00f3fb7 8788 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8789
f31a77f5
DS
8790 // Let the dynprobe_derived_probe_group handle outputting targets
8791 // and probes. This allows us to merge different types of probes.
8792 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8793 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8794 {
8795 uprobe_derived_probe *p = probes[i];
e00f3fb7 8796
f31a77f5
DS
8797 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8798 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8799 common_probe_init(p));
3a894f7e 8800 }
874d38bf
JS
8801 // loc2c-generated code assumes pt_regs are available, so use this to make
8802 // sure we always have *something* for it to dereference...
f31a77f5 8803 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8804
3a894f7e
JS
8805 // Write the probe handler.
8806 // NB: not static, so dyninst can find it
8807 s.op->newline() << "int enter_dyninst_uprobe "
8808 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8809 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8810
8811 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8812 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8813 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8814 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8815 probe_type);
8816
874d38bf 8817 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8818 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8819 // XXX: once we have regs, check how dyninst sets the IP
8820 // XXX: the way that dyninst rewrites stuff is probably going to be
8821 // ... very confusing to our backtracer (at least if we stay in process)
8822 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8823 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8824 s.op->newline() << "return 0;";
8825 s.op->newline(-1) << "}";
3debb935 8826 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8827 s.op->assert_0_indent();
8828}
8829
8830
8831void
8832uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8833{
8834 if (probes.empty()) return;
8835
8836 /* stapdyn handles the dirty work via dyninst */
8837 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8838 s.op->newline() << "/* this section left intentionally blank */";
8839}
8840
8841
8842void
8843uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8844{
8845 if (probes.empty()) return;
8846
8847 /* stapdyn handles the dirty work via dyninst */
8848 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8849 s.op->newline() << "/* this section left intentionally blank */";
8850}
8851
8852
2b69faaf
JS
8853void
8854uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8855{
ac3af990 8856 if (s.runtime_usermode_p())
4441e344
JS
8857 emit_module_dyninst_decls (s);
8858 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8859 emit_module_inode_decls (s);
8860 else
8861 emit_module_utrace_decls (s);
8862}
8863
8864
8865void
8866uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8867{
ac3af990 8868 if (s.runtime_usermode_p())
4441e344
JS
8869 emit_module_dyninst_init (s);
8870 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8871 emit_module_inode_init (s);
8872 else
8873 emit_module_utrace_init (s);
8874}
8875
8876
8877void
8878uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8879{
ac3af990 8880 if (s.runtime_usermode_p())
4441e344
JS
8881 emit_module_dyninst_exit (s);
8882 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8883 emit_module_inode_exit (s);
8884 else
8885 emit_module_utrace_exit (s);
8886}
8887
8888
e6fe60e7
AM
8889// ------------------------------------------------------------------------
8890// Kprobe derived probes
8891// ------------------------------------------------------------------------
8892
4627ed58 8893static const string TOK_KPROBE("kprobe");
935447c8 8894
bae55db9 8895struct kprobe_derived_probe: public derived_probe
d0ea46ce 8896{
23dc94f6
DS
8897 kprobe_derived_probe (systemtap_session& sess,
8898 vector<derived_probe *> & results,
8899 probe *base,
bae55db9
JS
8900 probe_point *location,
8901 const string& name,
8902 int64_t stmt_addr,
e6afb07b 8903 bool has_call,
bae55db9
JS
8904 bool has_return,
8905 bool has_statement,
8906 bool has_maxactive,
b642c901
SC
8907 bool has_path,
8908 bool has_library,
8909 long maxactive_val,
8910 const string& path,
8911 const string& library
bae55db9
JS
8912 );
8913 string symbol_name;
8914 Dwarf_Addr addr;
e6afb07b 8915 bool has_call;
bae55db9
JS
8916 bool has_return;
8917 bool has_statement;
8918 bool has_maxactive;
b642c901
SC
8919 bool has_path;
8920 bool has_library;
bae55db9 8921 long maxactive_val;
b642c901
SC
8922 string path;
8923 string library;
bae55db9
JS
8924 bool access_var;
8925 void printsig (std::ostream &o) const;
8926 void join_group (systemtap_session& s);
8927};
d0ea46ce 8928
bae55db9
JS
8929struct kprobe_derived_probe_group: public derived_probe_group
8930{
8931private:
8932 multimap<string,kprobe_derived_probe*> probes_by_module;
8933 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8934
bae55db9
JS
8935public:
8936 void enroll (kprobe_derived_probe* probe);
8937 void emit_module_decls (systemtap_session& s);
8938 void emit_module_init (systemtap_session& s);
8939 void emit_module_exit (systemtap_session& s);
8940};
d0ea46ce 8941
23dc94f6
DS
8942struct kprobe_var_expanding_visitor: public var_expanding_visitor
8943{
8944 systemtap_session& sess;
8945 block *add_block;
8946 block *add_call_probe; // synthesized from .return probes with saved $vars
8947 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8948 bool has_return;
23dc94f6 8949
bd5b25e1 8950 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8951 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8952 add_block_tid(false), add_call_probe_tid(false),
8953 has_return(has_return) {}
23dc94f6
DS
8954
8955 void visit_entry_op (entry_op* e);
8956};
8957
8958
8959kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8960 vector<derived_probe *> & results,
8961 probe *base,
e6fe60e7 8962 probe_point *location,
b6371390 8963 const string& name,
e6fe60e7 8964 int64_t stmt_addr,
e6afb07b 8965 bool has_call,
b6371390
JS
8966 bool has_return,
8967 bool has_statement,
8968 bool has_maxactive,
b642c901
SC
8969 bool has_path,
8970 bool has_library,
8971 long maxactive_val,
8972 const string& path,
8973 const string& library
b6371390 8974 ):
4c5d1300 8975 derived_probe (base, location, true /* .components soon rewritten */ ),
e6afb07b 8976 symbol_name (name), addr (stmt_addr), has_call (has_call),
b6371390 8977 has_return (has_return), has_statement (has_statement),
b642c901
SC
8978 has_maxactive (has_maxactive), has_path (has_path),
8979 has_library (has_library),
8980 maxactive_val (maxactive_val),
8981 path (path), library (library)
e6fe60e7
AM
8982{
8983 this->tok = base->tok;
8984 this->access_var = false;
d0ea46ce 8985
e6fe60e7
AM
8986#ifndef USHRT_MAX
8987#define USHRT_MAX 32767
8988#endif
d0ea46ce 8989
46856d8d
JS
8990 // Expansion of $target variables in the probe body produces an error during
8991 // translate phase, since we're not using debuginfo
d0ea46ce 8992
e6fe60e7 8993 vector<probe_point::component*> comps;
46856d8d 8994 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8995
46856d8d
JS
8996 if (has_statement)
8997 {
9ea68eb9
JS
8998 comps.push_back (new probe_point::component(TOK_STATEMENT,
8999 new literal_number(addr, true)));
46856d8d
JS
9000 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
9001 }
9002 else
9003 {
9004 size_t pos = name.find(':');
9005 if (pos != string::npos)
d0ea46ce 9006 {
46856d8d
JS
9007 string module = name.substr(0, pos);
9008 string function = name.substr(pos + 1);
9009 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
9010 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
9011 }
9012 else
9013 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 9014 }
d0ea46ce 9015
e6afb07b
JL
9016 if (has_call)
9017 comps.push_back (new probe_point::component(TOK_CALL));
b6371390
JS
9018 if (has_return)
9019 comps.push_back (new probe_point::component(TOK_RETURN));
9020 if (has_maxactive)
9021 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 9022
bd5b25e1 9023 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
9024 v.replace (this->body);
9025
9026 // If during target-variable-expanding the probe, we added a new block
9027 // of code, add it to the start of the probe.
9028 if (v.add_block)
9029 this->body = new block(v.add_block, this->body);
9030
9031 // If when target-variable-expanding the probe, we need to
9032 // synthesize a sibling function-entry probe. We don't go through
9033 // the whole probe derivation business (PR10642) that could lead to
9034 // wildcard/alias resolution, or for that dwarf-induced duplication.
9035 if (v.add_call_probe)
9036 {
9037 assert (has_return);
9038
9039 // We temporarily replace base.
9040 statement* old_body = base->body;
9041 base->body = v.add_call_probe;
9042
9043 derived_probe *entry_handler
9044 = new kprobe_derived_probe (sess, results, base, location, name, 0,
e6afb07b
JL
9045 true /* has_call */, false /* has_return */,
9046 has_statement, has_maxactive, has_path,
9047 has_library, maxactive_val, path, library);
23dc94f6
DS
9048 results.push_back (entry_handler);
9049
9050 base->body = old_body;
9051 }
9052
e6fe60e7
AM
9053 this->sole_location()->components = comps;
9054}
d0ea46ce 9055
e6fe60e7
AM
9056void kprobe_derived_probe::printsig (ostream& o) const
9057{
9058 sole_location()->print (o);
9059 o << " /* " << " name = " << symbol_name << "*/";
9060 printsig_nested (o);
9061}
d0ea46ce 9062
e6fe60e7
AM
9063void kprobe_derived_probe::join_group (systemtap_session& s)
9064{
d0ea46ce 9065
e6fe60e7
AM
9066 if (! s.kprobe_derived_probes)
9067 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
9068 s.kprobe_derived_probes->enroll (this);
d0ea46ce 9069
e6fe60e7 9070}
d0ea46ce 9071
e6fe60e7
AM
9072void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
9073{
9074 probes_by_module.insert (make_pair (p->symbol_name, p));
9075 // probes of same symbol should share single kprobe/kretprobe
9076}
d0ea46ce 9077
e6fe60e7
AM
9078void
9079kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
9080{
9081 if (probes_by_module.empty()) return;
d0ea46ce 9082
e6fe60e7 9083 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 9084
e6fe60e7
AM
9085 // Warn of misconfigured kernels
9086 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
9087 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
9088 s.op->newline() << "#endif";
9089 s.op->newline();
d0ea46ce 9090
f07c3b68 9091 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 9092 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
9093 s.op->newline() << "#endif";
9094
e6fe60e7 9095 // Forward declare the master entry functions
88747011 9096 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 9097 s.op->line() << " struct pt_regs *regs);";
88747011 9098 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 9099 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 9100
e6fe60e7
AM
9101 // Emit an array of kprobe/kretprobe pointers
9102 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 9103 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 9104 s.op->newline() << "#endif";
d0ea46ce 9105
e6fe60e7 9106 // Emit the actual probe list.
d0ea46ce 9107
e6fe60e7
AM
9108 s.op->newline() << "static struct stap_dwarfless_kprobe {";
9109 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
9110 s.op->newline() << "#ifdef __ia64__";
9111 s.op->newline() << "struct kprobe dummy;";
9112 s.op->newline() << "#endif";
9113 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
9114 // NB: bss!
d0ea46ce 9115
e6fe60e7
AM
9116 s.op->newline() << "static struct stap_dwarfless_probe {";
9117 s.op->newline(1) << "const unsigned return_p:1;";
9118 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 9119 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
9120 s.op->newline() << "unsigned registered_p:1;";
9121 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 9122
e6fe60e7
AM
9123 // Function Names are mostly small and uniform enough to justify putting
9124 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 9125
faea5e16
JS
9126 size_t symbol_string_name_max = 0;
9127 size_t symbol_string_name_tot = 0;
e6fe60e7 9128 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 9129 {
e6fe60e7
AM
9130 kprobe_derived_probe* p = it->second;
9131#define DOIT(var,expr) do { \
9132 size_t var##_size = (expr) + 1; \
9133 var##_max = max (var##_max, var##_size); \
9134 var##_tot += var##_size; } while (0)
e6fe60e7
AM
9135 DOIT(symbol_string_name, p->symbol_name.size());
9136#undef DOIT
6270adc1
MH
9137 }
9138
e6fe60e7
AM
9139#define CALCIT(var) \
9140 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 9141
e6fe60e7
AM
9142 CALCIT(symbol_string);
9143#undef CALCIT
6270adc1 9144
bd659351 9145 s.op->newline() << "unsigned long address;";
7c3e97f4 9146 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
9147 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
9148 s.op->indent(1);
6270adc1 9149
e6fe60e7
AM
9150 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
9151 {
9152 kprobe_derived_probe* p = it->second;
9153 s.op->newline() << "{";
9154 if (p->has_return)
9155 s.op->line() << " .return_p=1,";
6270adc1 9156
e6fe60e7
AM
9157 if (p->has_maxactive)
9158 {
9159 s.op->line() << " .maxactive_p=1,";
9160 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
9161 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
9162 }
6270adc1 9163
b350f56b
JS
9164 if (p->locations[0]->optional)
9165 s.op->line() << " .optional_p=1,";
9166
e6fe60e7 9167 if (p->has_statement)
c8d9d15e 9168 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 9169 else
c8d9d15e 9170 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 9171
faea5e16 9172 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 9173 s.op->line() << " },";
935447c8
DS
9174 }
9175
e6fe60e7 9176 s.op->newline(-1) << "};";
5d67b47c 9177
e6fe60e7
AM
9178 // Emit the kprobes callback function
9179 s.op->newline();
88747011 9180 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
9181 s.op->line() << " struct pt_regs *regs) {";
9182 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9183 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9184 // Check that the index is plausible
9185 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9186 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9187 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9188 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9189 s.op->line() << "];";
71db462b 9190 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9191 "stp_probe_type_kprobe");
d9aed31e 9192 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
9193
9194 // Make it look like the IP is set as it wouldn't have been replaced
9195 // by a breakpoint instruction when calling real probe handler. Reset
9196 // IP regs on return, so we don't confuse kprobes. PR10458
9197 s.op->newline() << "{";
9198 s.op->indent(1);
d9aed31e 9199 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9200 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 9201 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9202 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9203 s.op->newline(-1) << "}";
9204
f887a8c9 9205 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9206 s.op->newline() << "return 0;";
9207 s.op->newline(-1) << "}";
935447c8 9208
e6fe60e7
AM
9209 // Same for kretprobes
9210 s.op->newline();
88747011 9211 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
9212 s.op->line() << " struct pt_regs *regs) {";
9213 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 9214
e6fe60e7
AM
9215 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9216 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9217 // Check that the index is plausible
9218 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9219 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9220 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9221 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9222 s.op->line() << "];";
935447c8 9223
71db462b 9224 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9225 "stp_probe_type_kretprobe");
d9aed31e 9226 s.op->newline() << "c->kregs = regs;";
6dceb5c9 9227 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
9228
9229 // Make it look like the IP is set as it wouldn't have been replaced
9230 // by a breakpoint instruction when calling real probe handler. Reset
9231 // IP regs on return, so we don't confuse kprobes. PR10458
9232 s.op->newline() << "{";
9233 s.op->indent(1);
d9aed31e 9234 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9235 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 9236 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9237 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9238 s.op->newline(-1) << "}";
9239
f887a8c9 9240 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9241 s.op->newline() << "return 0;";
9242 s.op->newline(-1) << "}";
bd659351 9243
03a4ec63 9244 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9245 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
9246 s.op->newline() << " struct module *owner,";
9247 s.op->newline() << " unsigned long val) {";
9248 s.op->newline(1) << "int i;";
fc1d2aa2
MW
9249 s.op->newline() << "int *p = (int *) data;";
9250 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
9251 << " && *p > 0; i++) {";
bd659351 9252 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
9253 s.op->newline() << "if (! sdp->address) {";
9254 s.op->indent(1);
9255 s.op->newline() << "const char *colon;";
9256 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
9257 s.op->indent(1);
9258 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
9259 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
9260 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
9261 s.op->newline(1) << "sdp->address = val;";
9262 s.op->newline() << "(*p)--;";
9263 s.op->newline(-1) << "}";
9264 s.op->newline(-1) << "}";
9265 s.op->newline() << "else {";
fc1d2aa2 9266 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 9267 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
9268 s.op->newline() << "(*p)--;";
9269 s.op->newline(-1) << "}";
8c272819
YW
9270 s.op->newline(-1) << "}";
9271 s.op->newline(-1) << "}";
9272 s.op->newline(-1) << "}";
fc1d2aa2 9273 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 9274 s.op->newline(-1) << "}";
03a4ec63 9275 s.op->newline() << "#endif";
935447c8
DS
9276}
9277
e6fe60e7 9278
6270adc1 9279void
e6fe60e7 9280kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 9281{
03a4ec63 9282 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
9283 s.op->newline() << "{";
9284 s.op->newline(1) << "int p = 0;";
9285 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
9286 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9287 s.op->newline() << "if (! sdp->address)";
9288 s.op->newline(1) << "p++;";
9289 s.op->newline(-2) << "}";
9290 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
9291 s.op->newline(-1) << "}";
03a4ec63 9292 s.op->newline() << "#endif";
bd659351 9293
e6fe60e7 9294 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 9295 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 9296 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 9297 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
9298 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
9299
9300 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9301 s.op->newline() << "if (! addr) {";
9302 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
9303 s.op->newline() << "if (!sdp->optional_p)";
9304 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
9305 s.op->newline(-1) << "continue;";
bd659351 9306 s.op->newline(-1) << "}";
03a4ec63
MW
9307 s.op->newline() << "#endif";
9308
26e63673 9309 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 9310 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 9311 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 9312 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9313 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 9314 s.op->newline() << "#endif";
e6fe60e7
AM
9315 s.op->newline() << "if (sdp->maxactive_p) {";
9316 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
9317 s.op->newline(-1) << "} else {";
f07c3b68 9318 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 9319 s.op->newline(-1) << "}";
88747011 9320 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
9321 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
9322 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9323 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 9324 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9325 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 9326 s.op->newline() << "#endif";
c8d9d15e 9327 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
9328 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9329 s.op->newline() << "if (rc == 0) {";
9330 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
9331 s.op->newline() << "if (rc != 0)";
9332 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9333 s.op->newline(-2) << "}";
9334 s.op->newline() << "#else";
9335 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
9336 s.op->newline() << "#endif";
9337 s.op->newline(-1) << "} else {";
9338 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 9339 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 9340 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9341 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 9342 s.op->newline() << "#endif";
88747011 9343 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 9344 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9345 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 9346 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 9347 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9348 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 9349 s.op->newline() << "#endif";
e6fe60e7
AM
9350 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9351 s.op->newline() << "if (rc == 0) {";
9352 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
9353 s.op->newline() << "if (rc != 0)";
9354 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9355 s.op->newline(-2) << "}";
9356 s.op->newline() << "#else";
9357 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
9358 s.op->newline() << "#endif";
9359 s.op->newline(-1) << "}";
9360 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
9361 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 9362 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 9363 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 9364 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
9365 // XXX: shall we increment numskipped?
9366 s.op->newline(-1) << "}";
6270adc1 9367
e6fe60e7
AM
9368 s.op->newline() << "else sdp->registered_p = 1;";
9369 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
9370}
9371
b4be7cbc 9372
e6fe60e7
AM
9373void
9374kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 9375{
e6fe60e7
AM
9376 //Unregister kprobes by batch interfaces.
9377 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
9378 s.op->newline() << "j = 0;";
9379 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9380 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9381 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9382 s.op->newline() << "if (! sdp->registered_p) continue;";
9383 s.op->newline() << "if (!sdp->return_p)";
c9116e99 9384 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 9385 s.op->newline(-2) << "}";
c9116e99 9386 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9387 s.op->newline() << "j = 0;";
9388 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9389 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9390 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9391 s.op->newline() << "if (! sdp->registered_p) continue;";
9392 s.op->newline() << "if (sdp->return_p)";
c9116e99 9393 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 9394 s.op->newline(-2) << "}";
c9116e99 9395 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9396 s.op->newline() << "#ifdef __ia64__";
9397 s.op->newline() << "j = 0;";
9398 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9399 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9400 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9401 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 9402 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 9403 s.op->newline(-1) << "}";
c9116e99 9404 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9405 s.op->newline() << "#endif";
9406 s.op->newline() << "#endif";
3e3bd7b6 9407
e6fe60e7
AM
9408 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9409 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9410 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9411 s.op->newline() << "if (! sdp->registered_p) continue;";
9412 s.op->newline() << "if (sdp->return_p) {";
9413 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9414 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
9415 s.op->newline() << "#endif";
065d5567 9416 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
9417 s.op->newline() << "#ifdef STP_TIMING";
9418 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 9419 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 9420 s.op->newline(-1) << "#endif";
065d5567 9421 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
9422 s.op->newline() << "#ifdef STP_TIMING";
9423 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 9424 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
9425 s.op->newline(-1) << "#endif";
9426 s.op->newline(-1) << "} else {";
9427 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9428 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
9429 s.op->newline() << "#endif";
065d5567 9430 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
9431 s.op->newline() << "#ifdef STP_TIMING";
9432 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 9433 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
9434 s.op->newline(-1) << "#endif";
9435 s.op->newline(-1) << "}";
9436 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
9437 s.op->newline() << "unregister_kprobe (&kp->dummy);";
9438 s.op->newline() << "#endif";
9439 s.op->newline() << "sdp->registered_p = 0;";
9440 s.op->newline(-1) << "}";
f8a968bc
JS
9441}
9442
e6fe60e7 9443struct kprobe_builder: public derived_probe_builder
3c1b3d06 9444{
9fdf787d 9445public:
2a639817 9446 kprobe_builder() {}
9fdf787d 9447
2a639817 9448 void build_no_more (systemtap_session &s) {}
9fdf787d 9449
e6fe60e7
AM
9450 virtual void build(systemtap_session & sess,
9451 probe * base,
9452 probe_point * location,
9453 literal_map_t const & parameters,
9454 vector<derived_probe *> & finished_results);
9455};
3c1b3d06
FCE
9456
9457
79189b84 9458void
05fb3e0c 9459kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
9460 probe * base,
9461 probe_point * location,
9462 literal_map_t const & parameters,
9463 vector<derived_probe *> & finished_results)
79189b84 9464{
e6fe60e7 9465 string function_string_val, module_string_val;
05fb3e0c 9466 string path, library, path_tgt, library_tgt;
b6371390
JS
9467 int64_t statement_num_val = 0, maxactive_val = 0;
9468 bool has_function_str, has_module_str, has_statement_num;
e6afb07b 9469 bool has_absolute, has_call, has_return, has_maxactive;
b642c901 9470 bool has_path, has_library;
79189b84 9471
b6371390
JS
9472 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
9473 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
e6afb07b 9474 has_call = has_null_param (parameters, TOK_CALL);
b6371390
JS
9475 has_return = has_null_param (parameters, TOK_RETURN);
9476 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
9477 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
9478 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
9479 has_path = get_param (parameters, TOK_PROCESS, path);
9480 has_library = get_param (parameters, TOK_LIBRARY, library);
9481
9482 if (has_path)
05fb3e0c
WF
9483 {
9484 path = find_executable (path, sess.sysroot, sess.sysenv);
9485 path_tgt = path_remove_sysroot(sess, path);
9486 }
b642c901 9487 if (has_library)
05fb3e0c
WF
9488 {
9489 library = find_executable (library, sess.sysroot, sess.sysenv,
9490 "LD_LIBRARY_PATH");
9491 library_tgt = path_remove_sysroot(sess, library);
9492 }
c57ea854 9493
b6371390 9494 if (has_function_str)
6fb70fb7 9495 {
2a639817 9496 if (has_module_str)
9fdf787d
DS
9497 {
9498 function_string_val = module_string_val + ":" + function_string_val;
9499 derived_probe *dp
23dc94f6
DS
9500 = new kprobe_derived_probe (sess, finished_results, base,
9501 location, function_string_val,
e6afb07b
JL
9502 0, has_call, has_return,
9503 has_statement_num, has_maxactive,
9504 has_path, has_library, maxactive_val,
9505 path_tgt, library_tgt);
9fdf787d
DS
9506 finished_results.push_back (dp);
9507 }
9508 else
9509 {
2a639817
JS
9510 vector<string> matches;
9511
9512 // Simple names can be found directly
9513 if (function_string_val.find_first_of("*?[") == string::npos)
9514 {
9515 if (sess.kernel_functions.count(function_string_val))
9516 matches.push_back(function_string_val);
9517 }
9518 else // Search function name list for matching names
9519 {
9520 for (set<string>::const_iterator it = sess.kernel_functions.begin();
9521 it != sess.kernel_functions.end(); it++)
9522 // fnmatch returns zero for matching.
9523 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
9524 matches.push_back(*it);
9525 }
86758d5f 9526
2a639817
JS
9527 for (vector<string>::const_iterator it = matches.begin();
9528 it != matches.end(); it++)
9fdf787d 9529 {
2a639817
JS
9530 derived_probe *dp
9531 = new kprobe_derived_probe (sess, finished_results, base,
e6afb07b
JL
9532 location, *it, 0, has_call,
9533 has_return, has_statement_num,
2a639817
JS
9534 has_maxactive, has_path,
9535 has_library, maxactive_val,
9536 path_tgt, library_tgt);
9537 finished_results.push_back (dp);
9fdf787d
DS
9538 }
9539 }
6fb70fb7 9540 }
e6fe60e7 9541 else
b6371390
JS
9542 {
9543 // assert guru mode for absolute probes
9544 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 9545 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 9546
23dc94f6
DS
9547 finished_results.push_back (new kprobe_derived_probe (sess,
9548 finished_results,
9549 base,
b6371390
JS
9550 location, "",
9551 statement_num_val,
e6afb07b 9552 has_call,
b6371390
JS
9553 has_return,
9554 has_statement_num,
9555 has_maxactive,
b642c901
SC
9556 has_path,
9557 has_library,
9558 maxactive_val,
05fb3e0c
WF
9559 path_tgt,
9560 library_tgt));
96b030fe 9561 }
79189b84
JS
9562}
9563
23dc94f6
DS
9564
9565void
9566kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
9567{
9568 expression *repl = e;
9569
bd5b25e1
JS
9570 if (has_return)
9571 {
9572 // expand the operand as if it weren't a return probe
9573 has_return = false;
9574 replace (e->operand);
9575 has_return = true;
23dc94f6 9576
bd5b25e1
JS
9577 // XXX it would be nice to use gen_kretprobe_saved_return when
9578 // available, but it requires knowing the types already, which is
9579 // problematic for arbitrary expressons.
9580 repl = gen_mapped_saved_return (sess, e->operand, "entry",
9581 add_block, add_block_tid,
9582 add_call_probe, add_call_probe_tid);
9583 }
23dc94f6
DS
9584 provide (repl);
9585}
9586
9587
dd225250
PS
9588// ------------------------------------------------------------------------
9589// Hardware breakpoint based probes.
9590// ------------------------------------------------------------------------
9591
9592static const string TOK_HWBKPT("data");
9593static const string TOK_HWBKPT_WRITE("write");
9594static const string TOK_HWBKPT_RW("rw");
9595static const string TOK_LENGTH("length");
9596
9597#define HWBKPT_READ 0
9598#define HWBKPT_WRITE 1
9599#define HWBKPT_RW 2
9600struct hwbkpt_derived_probe: public derived_probe
9601{
9602 hwbkpt_derived_probe (probe *base,
9603 probe_point *location,
9604 uint64_t addr,
9605 string symname,
9606 unsigned int len,
9607 bool has_only_read_access,
9608 bool has_only_write_access,
9609 bool has_rw_access
9610 );
9611 Dwarf_Addr hwbkpt_addr;
9612 string symbol_name;
9613 unsigned int hwbkpt_access,hwbkpt_len;
9614
9615 void printsig (std::ostream &o) const;
9616 void join_group (systemtap_session& s);
9617};
9618
9619struct hwbkpt_derived_probe_group: public derived_probe_group
9620{
dd225250 9621private:
dac77b80 9622 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
9623
9624public:
9625 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
9626 void emit_module_decls (systemtap_session& s);
9627 void emit_module_init (systemtap_session& s);
9628 void emit_module_exit (systemtap_session& s);
9629};
9630
9631hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
9632 probe_point *location,
9633 uint64_t addr,
9634 string symname,
9635 unsigned int len,
9636 bool has_only_read_access,
9637 bool has_only_write_access,
822a6a3d 9638 bool):
4c5d1300 9639 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9640 hwbkpt_addr (addr),
9641 symbol_name (symname),
9642 hwbkpt_len (len)
9643{
9644 this->tok = base->tok;
9645
9646 vector<probe_point::component*> comps;
9647 comps.push_back (new probe_point::component(TOK_KERNEL));
9648
9649 if (hwbkpt_addr)
9ea68eb9
JS
9650 comps.push_back (new probe_point::component (TOK_HWBKPT,
9651 new literal_number(hwbkpt_addr, true)));
9652 else if (symbol_name.size())
9653 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9654
9655 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9656
9657 if (has_only_read_access)
9ea68eb9 9658 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9659//TODO add code for comps.push_back for read, since this flag is not for x86
9660
9661 else
9ea68eb9
JS
9662 {
9663 if (has_only_write_access)
9664 {
9665 this->hwbkpt_access = HWBKPT_WRITE ;
9666 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9667 }
9668 else
9669 {
9670 this->hwbkpt_access = HWBKPT_RW ;
9671 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9672 }
9673 }
dd225250
PS
9674
9675 this->sole_location()->components = comps;
9676}
9677
9678void hwbkpt_derived_probe::printsig (ostream& o) const
9679{
9680 sole_location()->print (o);
9681 printsig_nested (o);
9682}
9683
9684void hwbkpt_derived_probe::join_group (systemtap_session& s)
9685{
dac77b80
FCE
9686 if (! s.hwbkpt_derived_probes)
9687 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9688 s.hwbkpt_derived_probes->enroll (this, s);
9689}
9690
9691void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9692{
dac77b80
FCE
9693 hwbkpt_probes.push_back (p);
9694
9695 unsigned max_hwbkpt_probes_by_arch = 0;
9696 if (s.architecture == "i386" || s.architecture == "x86_64")
9697 max_hwbkpt_probes_by_arch = 4;
9698 else if (s.architecture == "s390")
9699 max_hwbkpt_probes_by_arch = 1;
9700
c57ea854 9701 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9702 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9703 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9704}
9705
9706void
9707hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9708{
dac77b80 9709 if (hwbkpt_probes.empty()) return;
dd225250
PS
9710
9711 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9712
9713 s.op->newline() << "#include <linux/perf_event.h>";
9714 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9715 s.op->newline();
9716
9717 // Forward declare the master entry functions
23063de1 9718 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9719 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9720 s.op->line() << " int nmi,";
9721 s.op->line() << " struct perf_sample_data *data,";
9722 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9723 s.op->newline() << "#else";
9724 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9725 s.op->line() << " struct perf_sample_data *data,";
9726 s.op->line() << " struct pt_regs *regs);";
9727 s.op->newline() << "#endif";
79189b84 9728
dd225250
PS
9729 // Emit the actual probe list.
9730
9731 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9732 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9733
9734 s.op->newline() << "static struct perf_event **";
dac77b80 9735 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9736 s.op->newline() << "static struct stap_hwbkpt_probe {";
9737 s.op->newline() << "int registered_p:1;";
43650b10 9738// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9739// registered_p = 1 signifies a probe that got registered successfully
9740
faea5e16 9741 // Symbol Names are mostly small and uniform enough
dd225250 9742 // to justify putting const char*.
dac77b80 9743 s.op->newline() << "const char * const symbol;";
dd225250
PS
9744
9745 s.op->newline() << "const unsigned long address;";
9746 s.op->newline() << "uint8_t atype;";
bb0a4e12 9747 s.op->newline() << "unsigned int len;";
7c3e97f4 9748 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9749 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9750 s.op->indent(1);
9751
dac77b80 9752 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9753 {
dac77b80 9754 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9755 s.op->newline() << "{";
dd225250
PS
9756 if (p->symbol_name.size())
9757 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9758 else
9759 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9760 switch(p->hwbkpt_access){
9761 case HWBKPT_READ:
9762 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9763 break;
dd225250
PS
9764 case HWBKPT_WRITE:
9765 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9766 break;
dd225250
PS
9767 case HWBKPT_RW:
9768 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9769 break;
dd225250
PS
9770 };
9771 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9772 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9773 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9774 s.op->line() << " },";
9775 }
dac77b80 9776 s.op->newline(-1) << "};";
dd225250
PS
9777
9778 // Emit the hwbkpt callback function
9779 s.op->newline() ;
23063de1 9780 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9781 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9782 s.op->line() << " int nmi,";
9783 s.op->line() << " struct perf_sample_data *data,";
9784 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9785 s.op->newline() << "#else";
9786 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9787 s.op->line() << " struct perf_sample_data *data,";
9788 s.op->line() << " struct pt_regs *regs) {";
9789 s.op->newline() << "#endif";
dac77b80
FCE
9790 s.op->newline(1) << "unsigned int i;";
9791 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9792 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9793 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9794 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9795 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) {";
9796 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9797 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9798 "stp_probe_type_hwbkpt");
d9aed31e 9799 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9800 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9801 s.op->newline() << "c->uregs = regs;";
9802 s.op->newline(-1) << "} else {";
9803 s.op->newline(1) << "c->kregs = regs;";
9804 s.op->newline(-1) << "}";
26e63673 9805 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9806 common_probe_entryfn_epilogue (s, true);
dac77b80 9807 s.op->newline(-1) << "}";
dd225250
PS
9808 s.op->newline(-1) << "}";
9809 s.op->newline() << "return 0;";
dac77b80 9810 s.op->newline(-1) << "}";
dd225250
PS
9811}
9812
9813void
9814hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9815{
dac77b80 9816 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9817 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9818 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9819 s.op->newline() << "void *addr = (void *) sdp->address;";
9820 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9821 s.op->newline() << "hw_breakpoint_init(hp);";
9822 s.op->newline() << "if (addr)";
9823 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9824 s.op->newline(-1) << "else { ";
9825 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9826 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9827 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9828 s.op->newline() << "continue;";
9829 s.op->newline(-1) << "}";
9830 s.op->newline(-1) << "}";
9831 s.op->newline() << "hp->bp_type = sdp->atype;";
9832
9833 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9834 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9835 {
9836 s.op->newline() << "switch(sdp->len) {";
9837 s.op->newline() << "case 1:";
9838 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9839 s.op->newline() << "break;";
9840 s.op->newline(-1) << "case 2:";
9841 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9842 s.op->newline() << "break;";
9843 s.op->newline(-1) << "case 3:";
9844 s.op->newline() << "case 4:";
9845 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9846 s.op->newline() << "break;";
9847 s.op->newline(-1) << "case 5:";
9848 s.op->newline() << "case 6:";
9849 s.op->newline() << "case 7:";
9850 s.op->newline() << "case 8:";
9851 s.op->newline() << "default:"; // XXX: could instead reject
9852 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9853 s.op->newline() << "break;";
9854 s.op->newline(-1) << "}";
9855 }
9856 else // other architectures presumed straightforward
9857 s.op->newline() << "hp->bp_len = sdp->len;";
9858
26e63673 9859 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9860 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9861 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9862 s.op->newline() << "#else";
dac77b80 9863 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9864 s.op->newline() << "#endif";
43650b10 9865 s.op->newline() << "rc = 0;";
dac77b80 9866 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9867 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9868 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9869 s.op->newline(-1) << "}";
217ef1f4
WC
9870 s.op->newline() << "if (rc) {";
9871 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9872 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9873 s.op->newline(-1) << "}";
dd225250 9874 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9875 s.op->newline(-1) << "}"; // for loop
9876}
9877
9878void
9879hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9880{
9881 //Unregister hwbkpt probes.
dac77b80 9882 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9883 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9884 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9885 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9886 s.op->newline() << "sdp->registered_p = 0;";
9887 s.op->newline(-1) << "}";
9888}
9889
9890struct hwbkpt_builder: public derived_probe_builder
9891{
9892 hwbkpt_builder() {}
9893 virtual void build(systemtap_session & sess,
9894 probe * base,
9895 probe_point * location,
9896 literal_map_t const & parameters,
9897 vector<derived_probe *> & finished_results);
9898};
9899
9900void
9901hwbkpt_builder::build(systemtap_session & sess,
9902 probe * base,
9903 probe_point * location,
9904 literal_map_t const & parameters,
9905 vector<derived_probe *> & finished_results)
9906{
9907 string symbol_str_val;
9908 int64_t hwbkpt_address, len;
9909 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9910
b47f3a55 9911 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9912 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9913 location->components[0]->tok);
9914 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9915 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9916 location->components[0]->tok);
9917
dd225250
PS
9918 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9919 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9920 has_len = get_param (parameters, TOK_LENGTH, len);
9921 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9922 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9923
b31695eb
JL
9924 // Make an intermediate pp that is well-formed. It's pretty much the same as
9925 // the user-provided one, except that the addr literal is well-typed.
9926 probe_point* well_formed_loc = new probe_point(*location);
9927 well_formed_loc->well_formed = true;
9928
9929 vector<probe_point::component*> well_formed_comps;
9930 vector<probe_point::component*>::iterator it;
9931 for (it = location->components.begin();
9932 it != location->components.end(); ++it)
9933 if ((*it)->functor == TOK_HWBKPT && has_addr)
9934 well_formed_comps.push_back(new probe_point::component(TOK_HWBKPT,
9935 new literal_number(hwbkpt_address, true /* hex */ )));
9936 else
9937 well_formed_comps.push_back(*it);
9938 well_formed_loc->components = well_formed_comps;
9939 probe *new_base = new probe (base, well_formed_loc);
9940
dd225250
PS
9941 if (!has_len)
9942 len = 1;
9943
9944 if (has_addr)
b31695eb 9945 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9946 location,
9947 hwbkpt_address,
9948 "",len,0,
9949 has_write,
9950 has_rw));
5d8a0aea 9951 else if (has_symbol_str)
b31695eb 9952 finished_results.push_back (new hwbkpt_derived_probe (new_base,
dd225250
PS
9953 location,
9954 0,
9955 symbol_str_val,len,0,
9956 has_write,
9957 has_rw));
5d8a0aea
FCE
9958 else
9959 assert (0);
dd225250 9960}
342d3f96 9961
0a6f5a3f
JS
9962// ------------------------------------------------------------------------
9963// statically inserted kernel-tracepoint derived probes
9964// ------------------------------------------------------------------------
9965
6fb70fb7 9966struct tracepoint_arg
79189b84 9967{
ad370dcc 9968 string name, c_type, typecast;
dcaa1a65 9969 bool usable, used, isptr;
f8a968bc 9970 Dwarf_Die type_die;
dcaa1a65 9971 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9972};
79189b84 9973
0a6f5a3f
JS
9974struct tracepoint_derived_probe: public derived_probe
9975{
79189b84
JS
9976 tracepoint_derived_probe (systemtap_session& s,
9977 dwflpp& dw, Dwarf_Die& func_die,
9978 const string& tracepoint_name,
9979 probe* base_probe, probe_point* location);
bc9a523d 9980
79189b84 9981 systemtap_session& sess;
6fb70fb7
JS
9982 string tracepoint_name, header;
9983 vector <struct tracepoint_arg> args;
bc9a523d 9984
6fb70fb7 9985 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9986 void getargs (std::list<std::string> &arg_set) const;
79189b84 9987 void join_group (systemtap_session& s);
3e3bd7b6 9988 void print_dupe_stamp(ostream& o);
0a6f5a3f 9989};
79189b84
JS
9990
9991
0a6f5a3f 9992struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9993{
79189b84
JS
9994 void emit_module_decls (systemtap_session& s);
9995 void emit_module_init (systemtap_session& s);
9996 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9997};
79189b84 9998
bc9a523d 9999
f8a968bc
JS
10000struct tracepoint_var_expanding_visitor: public var_expanding_visitor
10001{
10002 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
10003 vector <struct tracepoint_arg>& args):
10004 dw (dw), probe_name (probe_name), args (args) {}
10005 dwflpp& dw;
10006 const string& probe_name;
10007 vector <struct tracepoint_arg>& args;
bc9a523d 10008
f8a968bc
JS
10009 void visit_target_symbol (target_symbol* e);
10010 void visit_target_symbol_arg (target_symbol* e);
10011 void visit_target_symbol_context (target_symbol* e);
10012};
79189b84
JS
10013
10014
f8a968bc
JS
10015void
10016tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 10017{
cc9001af 10018 string argname = e->sym_name();
75ead1f7 10019
f8a968bc
JS
10020 // search for a tracepoint parameter matching this name
10021 tracepoint_arg *arg = NULL;
10022 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 10023 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
10024 {
10025 arg = &args[i];
10026 arg->used = true;
10027 break;
10028 }
75ead1f7 10029
f8a968bc
JS
10030 if (arg == NULL)
10031 {
1d0499c2 10032 set<string> vars;
f8a968bc 10033 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
10034 vars.insert("$" + args[i].name);
10035 vars.insert("$$name");
10036 vars.insert("$$parms");
10037 vars.insert("$$vars");
10038 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 10039
f8a968bc
JS
10040 // We hope that this value ends up not being referenced after all, so it
10041 // can be optimized out quietly.
1d0499c2
JL
10042 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
10043 e->name.c_str(), sugs.empty() ? "" :
10044 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
10045 // NB: we use 'alternatives' because we list all
f8a968bc
JS
10046 // NB: we can have multiple errors, since a target variable
10047 // may be expanded in several different contexts:
10048 // trace ("*") { $foo->bar }
f8a968bc 10049 }
75ead1f7 10050
f8a968bc 10051 // make sure we're not dereferencing base types
dc5a09fc 10052 if (!arg->isptr)
d19a9a82 10053 e->assert_no_components("tracepoint", true);
75ead1f7 10054
f8a968bc
JS
10055 // we can only write to dereferenced fields, and only if guru mode is on
10056 bool lvalue = is_active_lvalue(e);
10057 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 10058 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 10059
ad370dcc
JS
10060 // XXX: if a struct/union arg is passed by value, then writing to its fields
10061 // is also meaningless until you dereference past a pointer member. It's
10062 // harder to detect and prevent that though...
75ead1f7 10063
f8a968bc
JS
10064 if (e->components.empty())
10065 {
03c75a4a 10066 if (e->addressof)
dc09353a 10067 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 10068
3e3bd7b6 10069 // Just grab the value from the probe locals
a45664f4
JS
10070 symbol* sym = new symbol;
10071 sym->tok = e->tok;
10072 sym->name = "__tracepoint_arg_" + arg->name;
10073 provide (sym);
f8a968bc
JS
10074 }
10075 else
10076 {
5f36109e
JS
10077 // make a copy of the original as a bare target symbol for the tracepoint
10078 // value, which will be passed into the dwarf dereferencing code
10079 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
10080 e2->components.clear();
10081
10082 if (e->components.back().type == target_symbol::comp_pretty_print)
10083 {
10084 if (lvalue)
dc09353a 10085 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 10086
d19a9a82 10087 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
10088 dpp.expand()->visit (this);
10089 return;
10090 }
10091
1c0be8c7 10092 bool userspace_p = false;
f8a968bc 10093 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 10094 + "_" + e->sym_name()
aca66a36 10095 + "_" + lex_cast(tick++));
75ead1f7 10096
1c0be8c7
JS
10097 exp_type type = pe_long;
10098 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 10099
1c0be8c7
JS
10100 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
10101 userspace_p, lvalue, e, e2);
75ead1f7 10102
f8a968bc
JS
10103 if (lvalue)
10104 {
10105 // Provide the functioncall to our parent, so that it can be
10106 // used to substitute for the assignment node immediately above
10107 // us.
10108 assert(!target_symbol_setter_functioncalls.empty());
10109 *(target_symbol_setter_functioncalls.top()) = n;
10110 }
75ead1f7 10111
1c0be8c7
JS
10112 // Revisit the functioncall so arguments can be expanded.
10113 n->visit (this);
f8a968bc 10114 }
75ead1f7
JS
10115}
10116
10117
f8a968bc
JS
10118void
10119tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 10120{
03c75a4a 10121 if (e->addressof)
dc09353a 10122 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 10123
f8a968bc 10124 if (is_active_lvalue (e))
dc09353a 10125 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 10126
277c21bc 10127 if (e->name == "$$name")
f8a968bc 10128 {
5f36109e
JS
10129 e->assert_no_components("tracepoint");
10130
bfdaad1e
DS
10131 // Synthesize an embedded expression.
10132 embedded_expr *expr = new embedded_expr;
10133 expr->tok = e->tok;
10134 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 10135 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 10136 provide (expr);
f8a968bc 10137 }
277c21bc 10138 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 10139 {
5f36109e
JS
10140 e->assert_no_components("tracepoint", true);
10141
1c922ad7 10142 print_format* pf = print_format::create(e->tok, "sprintf");
0a6f5a3f 10143
f8a968bc 10144 for (unsigned i = 0; i < args.size(); ++i)
b278033a 10145 {
dcaa1a65
JS
10146 if (!args[i].usable)
10147 continue;
f8a968bc
JS
10148 if (i > 0)
10149 pf->raw_components += " ";
10150 pf->raw_components += args[i].name;
3e3bd7b6 10151 target_symbol *tsym = new target_symbol;
f8a968bc 10152 tsym->tok = e->tok;
277c21bc 10153 tsym->name = "$" + args[i].name;
5f36109e 10154 tsym->components = e->components;
b278033a 10155
f8a968bc
JS
10156 // every variable should always be accessible!
10157 tsym->saved_conversion_error = 0;
8c2f50c0 10158 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
10159 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
10160 {
10161 if (dw.sess.verbose>2)
e26c2f83 10162 for (const semantic_error *c = tsym->saved_conversion_error;
c081af73 10163 c != 0; c = c->get_chain())
4c5d9906 10164 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
10165 pf->raw_components += "=?";
10166 continue;
10167 }
b278033a 10168
5f36109e
JS
10169 if (!e->components.empty() &&
10170 e->components[0].type == target_symbol::comp_pretty_print)
10171 pf->raw_components += "=%s";
10172 else
10173 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
10174 pf->args.push_back(texp);
10175 }
0a6f5a3f 10176
f8a968bc
JS
10177 pf->components = print_format::string_to_components(pf->raw_components);
10178 provide (pf);
b278033a 10179 }
f8a968bc
JS
10180 else
10181 assert(0); // shouldn't get here
0a6f5a3f
JS
10182}
10183
0a6f5a3f 10184void
f8a968bc 10185tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 10186{
aff5d390 10187 try
c69a87e0 10188 {
bd1fcbad 10189 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 10190
277c21bc 10191 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 10192 visit_target_symbol_context (e);
bd1fcbad 10193
c69a87e0
FCE
10194 else
10195 visit_target_symbol_arg (e);
10196 }
10197 catch (const semantic_error &er)
10198 {
1af1e62d 10199 e->chain (er);
c69a87e0
FCE
10200 provide (e);
10201 }
0a6f5a3f
JS
10202}
10203
10204
79189b84
JS
10205tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
10206 dwflpp& dw, Dwarf_Die& func_die,
10207 const string& tracepoint_name,
10208 probe* base, probe_point* loc):
4c5d1300 10209 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 10210 sess (s), tracepoint_name (tracepoint_name)
56894e91 10211{
79189b84
JS
10212 // create synthetic probe point name; preserve condition
10213 vector<probe_point::component*> comps;
10214 comps.push_back (new probe_point::component (TOK_KERNEL));
10215 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
10216 this->sole_location()->components = comps;
10217
6fb70fb7
JS
10218 // fill out the available arguments in this tracepoint
10219 build_args(dw, func_die);
56894e91 10220
6fb70fb7
JS
10221 // determine which header defined this tracepoint
10222 string decl_file = dwarf_decl_file(&func_die);
b78a0fbb 10223 header = decl_file;
d4393459
FCE
10224
10225#if 0 /* This convention is not enforced. */
6fb70fb7
JS
10226 size_t header_pos = decl_file.rfind("trace/");
10227 if (header_pos == string::npos)
dc09353a 10228 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
10229 + tracepoint_name + "' in '"
10230 + decl_file + "'");
10231 header = decl_file.substr(header_pos);
d4393459 10232#endif
56894e91 10233
6fb70fb7
JS
10234 // tracepoints from FOO_event_types.h should really be included from FOO.h
10235 // XXX can dwarf tell us the include hierarchy? it would be better to
10236 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 10237 // XXX: see also PR9993.
d4393459 10238 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
10239 if (header_pos != string::npos)
10240 header.erase(header_pos, 12);
56894e91 10241
f8a968bc
JS
10242 // Now expand the local variables in the probe body
10243 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 10244 v.replace (this->body);
a45664f4
JS
10245 for (unsigned i = 0; i < args.size(); i++)
10246 if (args[i].used)
10247 {
10248 vardecl* v = new vardecl;
10249 v->name = "__tracepoint_arg_" + args[i].name;
10250 v->tok = this->tok;
58701b78 10251 v->set_arity(0, this->tok);
a45664f4 10252 v->type = pe_long;
69aa668e 10253 v->synthetic = true;
a45664f4
JS
10254 this->locals.push_back (v);
10255 }
56894e91 10256
79189b84 10257 if (sess.verbose > 2)
ce0f6648 10258 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 10259}
dc38c0ae 10260
56894e91 10261
f8a968bc 10262static bool
dcaa1a65 10263resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 10264{
d19a9a82 10265 Dwarf_Die type;
dcaa1a65 10266 switch (dwarf_tag(&arg.type_die))
b20febf3 10267 {
f8a968bc
JS
10268 case DW_TAG_typedef:
10269 case DW_TAG_const_type:
10270 case DW_TAG_volatile_type:
10271 // iterate on the referent type
3d1ad340 10272 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 10273 && resolve_tracepoint_arg_type(arg));
f8a968bc 10274 case DW_TAG_base_type:
a52d2ac0 10275 case DW_TAG_enumeration_type:
f8a968bc 10276 // base types will simply be treated as script longs
dcaa1a65 10277 arg.isptr = false;
f8a968bc
JS
10278 return true;
10279 case DW_TAG_pointer_type:
dcaa1a65
JS
10280 // pointers can be treated as script longs,
10281 // and if we know their type, they can also be dereferenced
d19a9a82
JS
10282 type = arg.type_die;
10283 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
10284 {
10285 // It still might be a non-type, e.g. const void,
10286 // so we need to strip away all qualifiers.
10287 int tag = dwarf_tag(&arg.type_die);
10288 if (tag != DW_TAG_typedef &&
10289 tag != DW_TAG_const_type &&
10290 tag != DW_TAG_volatile_type)
10291 {
10292 arg.isptr = true;
10293 break;
10294 }
10295 }
10296 if (!arg.isptr)
10297 arg.type_die = type;
ad370dcc
JS
10298 arg.typecast = "(intptr_t)";
10299 return true;
10300 case DW_TAG_structure_type:
10301 case DW_TAG_union_type:
10302 // for structs/unions which are passed by value, we turn it into
10303 // a pointer that can be dereferenced.
10304 arg.isptr = true;
10305 arg.typecast = "(intptr_t)&";
dcaa1a65 10306 return true;
f8a968bc
JS
10307 default:
10308 // should we consider other types too?
10309 return false;
b20febf3 10310 }
56894e91
JS
10311}
10312
10313
10314void
822a6a3d 10315tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 10316{
6fb70fb7
JS
10317 Dwarf_Die arg;
10318 if (dwarf_child(&func_die, &arg) == 0)
10319 do
10320 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
10321 {
10322 // build a tracepoint_arg for this parameter
10323 tracepoint_arg tparg;
c60517ca 10324 tparg.name = dwarf_diename(&arg) ?: "";
56894e91 10325
6fb70fb7 10326 // read the type of this parameter
3d1ad340 10327 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 10328 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 10329 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 10330 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 10331
dcaa1a65 10332 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
10333 args.push_back(tparg);
10334 if (sess.verbose > 4)
a52d2ac0
JS
10335 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
10336 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
10337 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
10338 }
10339 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
10340}
10341
dc38c0ae 10342void
d0bfd2ac 10343tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 10344{
dcaa1a65
JS
10345 for (unsigned i = 0; i < args.size(); ++i)
10346 if (args[i].usable)
d0bfd2ac 10347 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
10348}
10349
79189b84
JS
10350void
10351tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 10352{
79189b84
JS
10353 if (! s.tracepoint_derived_probes)
10354 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
10355 s.tracepoint_derived_probes->enroll (this);
10356}
e38d6504 10357
56894e91 10358
197a4d62 10359void
3e3bd7b6 10360tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 10361{
3e3bd7b6
JS
10362 for (unsigned i = 0; i < args.size(); i++)
10363 if (args[i].used)
10364 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 10365}
56894e91 10366
3e3bd7b6 10367
c9ccb642 10368static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 10369{
3c1b3d06
FCE
10370 vector<string> they_live;
10371 // PR 9993
10372 // XXX: may need this to be configurable
d4393459 10373 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
10374
10375 // PR11649: conditional extra header
10376 // for kvm tracepoints in 2.6.33ish
10377 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
10378 they_live.push_back ("#include <linux/kvm_host.h>");
10379 }
10380
50b72692 10381 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 10382 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
10383 if (s.kernel_source_tree != "")
10384 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
10385 they_live.push_back ("struct xfs_mount;");
10386 they_live.push_back ("struct xfs_inode;");
10387 they_live.push_back ("struct xfs_buf;");
10388 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 10389 they_live.push_back ("struct xfs_trans;");
9e0cd21a 10390 }
d4393459 10391
50b72692 10392 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
10393 they_live.push_back ("struct rpc_task;");
10394 }
b64d65e2
FCE
10395 // RHEL6.3
10396 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
10397 they_live.push_back ("struct rpc_clnt;");
10398 they_live.push_back ("struct rpc_wait_queue;");
10399 }
d4393459
FCE
10400
10401 they_live.push_back ("#include <asm/cputime.h>");
10402
c2cf1b87
FCE
10403 // linux 3.0
10404 they_live.push_back ("struct cpu_workqueue_struct;");
10405
50b72692 10406 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
10407 if (s.kernel_source_tree != "")
10408 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
10409
d97d428e 10410 if (header.find("ext3") != string::npos)
50b72692
HP
10411 they_live.push_back ("struct ext3_reserve_window_node;");
10412
d97d428e
FCE
10413 if (header.find("workqueue") != string::npos)
10414 {
10415 they_live.push_back ("struct pool_workqueue;");
10416 they_live.push_back ("struct work_struct;");
10417 }
10418
10419 if (header.find("asoc") != string::npos)
10420 they_live.push_back ("struct snd_soc_dapm_path;");
10421
10422 if (header.find("9p") != string::npos)
10423 {
10424 they_live.push_back ("struct p9_client;");
10425 they_live.push_back ("struct p9_fcall;");
10426 }
10427
10428 if (header.find("bcache") != string::npos)
10429 {
10430 they_live.push_back ("struct bkey;");
10431 they_live.push_back ("struct btree;");
10432 they_live.push_back ("struct cache_set;");
10433 they_live.push_back ("struct cache;");
10434 }
10435
10436 if (header.find("f2fs") != string::npos)
10437 {
10438 // cannot get fs/f2fs/f2fs.h #included
10439 they_live.push_back ("typedef u32 block_t;");
10440 they_live.push_back ("typedef u32 nid_t;");
10441 }
10442
10443 if (header.find("radeon") != string::npos)
10444 they_live.push_back ("struct radeon_bo;");
10445
10446 // argh, 3.11, i915_trace.h -> i915_drv.h -> i915_reg.h without -I
10447 // also brcms_trace_events.h -> ... -> "types.h"
10448 // XXX: need a way to add a temporary -I flag
10449
10450 if (header.find("/ath/") != string::npos)
10451 they_live.push_back ("struct ath5k_hw;");
10452
10453
3c1b3d06
FCE
10454 return they_live;
10455}
47dd066d
WC
10456
10457
10458void
79189b84 10459tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 10460{
79189b84
JS
10461 if (probes.empty())
10462 return;
47dd066d 10463
96b030fe 10464 s.op->newline() << "/* ---- tracepoint probes ---- */";
3ef9830a 10465 s.op->newline() << "#include <linux/stp_tracepoint.h>" << endl;
96b030fe 10466 s.op->newline();
79189b84 10467
47dd066d 10468
a4b9c3b3
FCE
10469 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
10470 // to be separately compiled. That's because kernel tracepoint headers sometimes
10471 // conflict. PR13155.
10472
10473 map<string,translator_output*> per_header_aux;
10474 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 10475
6fb70fb7
JS
10476 for (unsigned i = 0; i < probes.size(); ++i)
10477 {
10478 tracepoint_derived_probe *p = probes[i];
75ae2ec9 10479 string header = p->header;
5f73a260 10480
a4b9c3b3
FCE
10481 // We cache the auxiliary output files on a per-header basis. We don't
10482 // need one aux file per tracepoint, only one per tracepoint-header.
10483 translator_output *tpop = per_header_aux[header];
10484 if (tpop == 0)
10485 {
10486 tpop = s.op_create_auxiliary();
10487 per_header_aux[header] = tpop;
10488
10489 // PR9993: Add extra headers to work around undeclared types in individual
10490 // include/trace/foo.h files
10491 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
10492 for (unsigned z=0; z<extra_decls.size(); z++)
10493 tpop->newline() << extra_decls[z] << "\n";
720c435f 10494
a4b9c3b3
FCE
10495 // strip include/ substring, the same way as done in get_tracequery_module()
10496 size_t root_pos = header.rfind("include/");
10497 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443 10498
3ef9830a 10499 tpop->newline() << "#include <linux/stp_tracepoint.h>" << endl;
a4b9c3b3 10500 tpop->newline() << "#include <" << header << ">";
a4b9c3b3
FCE
10501 }
10502
720c435f
JS
10503 // collect the args that are actually in use
10504 vector<const tracepoint_arg*> used_args;
6fb70fb7 10505 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
10506 if (p->args[j].used)
10507 used_args.push_back(&p->args[j]);
10508
3ef9830a
JS
10509 // forward-declare the generated-side tracepoint callback, and define the
10510 // generated-side tracepoint callback in the main translator-output
10511 string enter_real_fn = "enter_real_tracepoint_probe_" + lex_cast(i);
720c435f 10512 if (used_args.empty())
6fb70fb7 10513 {
3ef9830a
JS
10514 tpop->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
10515 s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ")";
6fb70fb7 10516 }
3ef9830a 10517 else
a4b9c3b3 10518 {
3ef9830a
JS
10519 tpop->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10520 s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10521 s.op->indent(2);
10522 for (unsigned j = 0; j < used_args.size(); ++j)
10523 {
10524 tpop->line() << ", int64_t";
10525 s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
10526 }
10527 tpop->line() << ");";
10528 s.op->newline() << ")";
10529 s.op->indent(-2);
6fb70fb7 10530 }
3ef9830a 10531 s.op->newline() << "{";
7c3e97f4 10532 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 10533 << common_probe_init (p) << ";";
71db462b 10534 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 10535 "stp_probe_type_tracepoint");
6dceb5c9 10536 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
10537 << lex_cast_qstring (p->tracepoint_name)
10538 << ";";
720c435f
JS
10539 for (unsigned j = 0; j < used_args.size(); ++j)
10540 {
10541 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 10542 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
10543 << " = __tracepoint_arg_" << used_args[j]->name << ";";
10544 }
26e63673 10545 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 10546 common_probe_entryfn_epilogue (s, true);
6fb70fb7 10547 s.op->newline(-1) << "}";
47dd066d 10548
a4b9c3b3 10549 // define the real tracepoint callback function
3ef9830a
JS
10550 string enter_fn = "enter_tracepoint_probe_" + lex_cast(i);
10551 if (p->args.empty())
10552 tpop->newline() << "static STP_TRACE_ENTER_NOARGS(" << enter_fn << ")";
10553 else
a4b9c3b3 10554 {
3ef9830a
JS
10555 tpop->newline() << "static STP_TRACE_ENTER(" << enter_fn;
10556 s.op->indent(2);
10557 for (unsigned j = 0; j < p->args.size(); ++j)
10558 {
10559 tpop->newline() << ", " << p->args[j].c_type
10560 << " __tracepoint_arg_" << p->args[j].name;
10561 }
10562 tpop->newline() << ")";
10563 s.op->indent(-2);
a4b9c3b3 10564 }
3ef9830a
JS
10565 tpop->newline() << "{";
10566 tpop->newline(1) << enter_real_fn << "(";
720c435f
JS
10567 tpop->indent(2);
10568 for (unsigned j = 0; j < used_args.size(); ++j)
10569 {
10570 if (j > 0)
10571 tpop->line() << ", ";
10572 tpop->newline() << "(int64_t)" << used_args[j]->typecast
10573 << "__tracepoint_arg_" << used_args[j]->name;
10574 }
10575 tpop->newline() << ");";
10576 tpop->newline(-3) << "}";
a4b9c3b3
FCE
10577
10578
96b030fe 10579 // emit normalized registration functions
720c435f 10580 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10581 tpop->newline(1) << "return STP_TRACE_REGISTER(" << p->tracepoint_name
10582 << ", " << enter_fn << ");";
a4b9c3b3 10583 tpop->newline(-1) << "}";
47dd066d 10584
86758d5f
JS
10585 // NB: we're not prepared to deal with unreg failures. However, failures
10586 // can only occur if the tracepoint doesn't exist (yet?), or if we
10587 // weren't even registered. The former should be OKed by the initial
10588 // registration call, and the latter is safe to ignore.
720c435f 10589 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10590 tpop->newline(1) << "(void) STP_TRACE_UNREGISTER(" << p->tracepoint_name
10591 << ", " << enter_fn << ");";
a4b9c3b3
FCE
10592 tpop->newline(-1) << "}";
10593 tpop->newline();
5f73a260 10594
720c435f
JS
10595 // declare normalized registration functions
10596 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
10597 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 10598
a4b9c3b3 10599 tpop->assert_0_indent();
af304783
DS
10600 }
10601
96b030fe
JS
10602 // emit an array of registration functions for easy init/shutdown
10603 s.op->newline() << "static struct stap_tracepoint_probe {";
10604 s.op->newline(1) << "int (*reg)(void);";
86758d5f 10605 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
10606 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
10607 s.op->indent(1);
10608 for (unsigned i = 0; i < probes.size(); ++i)
10609 {
10610 s.op->newline () << "{";
10611 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
10612 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
10613 s.op->line() << " },";
10614 }
10615 s.op->newline(-1) << "};";
10616 s.op->newline();
47dd066d
WC
10617}
10618
10619
79189b84
JS
10620void
10621tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 10622{
79189b84
JS
10623 if (probes.size () == 0)
10624 return;
47dd066d 10625
79189b84 10626 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
10627 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
10628 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
10629 s.op->newline() << "if (rc) {";
10630 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
10631 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
10632 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
10633 s.op->newline(-1) << "}";
10634 s.op->newline(-1) << "}";
47dd066d 10635
bc9a523d
FCE
10636 // This would be technically proper (on those autoconf-detectable
10637 // kernels that include this function in tracepoint.h), however we
10638 // already make several calls to synchronze_sched() during our
10639 // shutdown processes.
47dd066d 10640
bc9a523d
FCE
10641 // s.op->newline() << "if (rc)";
10642 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
10643 // s.op->indent(-1);
79189b84 10644}
47dd066d
WC
10645
10646
79189b84
JS
10647void
10648tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 10649{
79189b84
JS
10650 if (probes.empty())
10651 return;
47dd066d 10652
96b030fe
JS
10653 s.op->newline() << "/* deregister tracepoint probes */";
10654 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
10655 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
10656 s.op->indent(-1);
47dd066d 10657
bc9a523d 10658 // Not necessary: see above.
47dd066d 10659
bc9a523d 10660 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 10661}
b20febf3 10662
47dd066d 10663
75ead1f7 10664struct tracepoint_query : public base_query
47dd066d 10665{
75ead1f7
JS
10666 tracepoint_query(dwflpp & dw, const string & tracepoint,
10667 probe * base_probe, probe_point * base_loc,
10668 vector<derived_probe *> & results):
10669 base_query(dw, "*"), tracepoint(tracepoint),
10670 base_probe(base_probe), base_loc(base_loc),
10671 results(results) {}
47dd066d 10672
75ead1f7 10673 const string& tracepoint;
47dd066d 10674
75ead1f7
JS
10675 probe * base_probe;
10676 probe_point * base_loc;
10677 vector<derived_probe *> & results;
f982c59b 10678 set<string> probed_names;
47dd066d 10679
75ead1f7
JS
10680 void handle_query_module();
10681 int handle_query_cu(Dwarf_Die * cudie);
10682 int handle_query_func(Dwarf_Die * func);
822a6a3d 10683 void query_library (const char *) {}
576eaefe 10684 void query_plt (const char *entry, size_t addr) {}
b20febf3 10685
5c378838 10686 static int tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q);
7d007451 10687 static int tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q);
75ead1f7 10688};
47dd066d
WC
10689
10690
10691void
75ead1f7 10692tracepoint_query::handle_query_module()
47dd066d 10693{
75ead1f7 10694 // look for the tracepoints in each CU
337b7c44 10695 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10696}
10697
10698
75ead1f7
JS
10699int
10700tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10701{
75ead1f7 10702 dw.focus_on_cu (cudie);
5f52fafe 10703 dw.mod_info->get_symtab();
47dd066d 10704
75ead1f7
JS
10705 // look at each function to see if it's a tracepoint
10706 string function = "stapprobe_" + tracepoint;
10707 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10708}
10709
10710
75ead1f7
JS
10711int
10712tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10713{
75ead1f7 10714 dw.focus_on_function (func);
47dd066d 10715
60d98537 10716 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10717 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10718
10719 // check for duplicates -- sometimes tracepoint headers may be indirectly
10720 // included in more than one of our tracequery modules.
10721 if (!probed_names.insert(tracepoint_instance).second)
10722 return DWARF_CB_OK;
10723
79189b84
JS
10724 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10725 tracepoint_instance,
10726 base_probe, base_loc);
10727 results.push_back (dp);
75ead1f7 10728 return DWARF_CB_OK;
47dd066d
WC
10729}
10730
10731
75ead1f7 10732int
5c378838 10733tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q)
47dd066d 10734{
85007c04 10735 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10736 return q->handle_query_cu(cudie);
47dd066d
WC
10737}
10738
10739
75ead1f7 10740int
7d007451 10741tracepoint_query::tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q)
47dd066d 10742{
85007c04 10743 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10744 return q->handle_query_func(func);
47dd066d
WC
10745}
10746
10747
0a6f5a3f 10748struct tracepoint_builder: public derived_probe_builder
47dd066d 10749{
0a6f5a3f
JS
10750private:
10751 dwflpp *dw;
10752 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10753 void get_tracequery_modules(systemtap_session& s,
10754 const vector<string>& headers,
10755 vector<string>& modules);
47dd066d 10756
0a6f5a3f 10757public:
47dd066d 10758
0a6f5a3f
JS
10759 tracepoint_builder(): dw(0) {}
10760 ~tracepoint_builder() { delete dw; }
47dd066d 10761
0a6f5a3f
JS
10762 void build_no_more (systemtap_session& s)
10763 {
10764 if (dw && s.verbose > 3)
b530b5b3 10765 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10766 delete dw;
10767 dw = NULL;
435f53a7
FCE
10768
10769 delete_session_module_cache (s);
0a6f5a3f 10770 }
47dd066d 10771
0a6f5a3f
JS
10772 void build(systemtap_session& s,
10773 probe *base, probe_point *location,
10774 literal_map_t const& parameters,
10775 vector<derived_probe*>& finished_results);
10776};
47dd066d 10777
47dd066d 10778
c9ccb642 10779
2a0e62a8 10780// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10781// tracepoint-related header files given. Return the generated or cached
10782// modules[].
10783
10784void
10785tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10786 const vector<string>& headers,
10787 vector<string>& modules)
0a6f5a3f 10788{
c95eddf7 10789 if (s.verbose > 2)
55e50c24 10790 {
ce0f6648 10791 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10792 for (size_t i = 0; i < headers.size(); ++i)
10793 clog << " " << headers[i] << endl;
10794 }
c95eddf7 10795
2a0e62a8
JS
10796 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10797 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10798 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10799 // so we prefer not to repeat this.
10800 vector<string> uncached_headers;
10801 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10802 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10803
10804 // They may be in the cache already.
10805 if (s.use_cache && !s.poison_cache)
10806 for (size_t i=0; i<headers.size(); i++)
10807 {
10808 // see if the cached module exists
2a0e62a8 10809 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10810 if (!tracequery_path.empty() && file_exists(tracequery_path))
10811 {
10812 if (s.verbose > 2)
10813 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10814
c252fca2
JS
10815 // an empty file is a cached failure
10816 if (get_file_size(tracequery_path) > 0)
10817 modules.push_back (tracequery_path);
c9ccb642
FCE
10818 }
10819 else
10820 uncached_headers.push_back(headers[i]);
10821 }
10822 else
10823 uncached_headers = headers;
f982c59b 10824
c9ccb642
FCE
10825 // If we have nothing left to search for, quit
10826 if (uncached_headers.empty()) return;
55e50c24 10827
c9ccb642 10828 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10829
c9ccb642
FCE
10830 // We could query several subsets of headers[] to make this go
10831 // faster, but let's KISS and do one at a time.
10832 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10833 {
c9ccb642
FCE
10834 const string& header = uncached_headers[i];
10835
10836 // create a tracequery source file
10837 ostringstream osrc;
10838
10839 // PR9993: Add extra headers to work around undeclared types in individual
10840 // include/trace/foo.h files
10841 vector<string> short_decls = tracepoint_extra_decls(s, header);
10842
10843 // add each requested tracepoint header
75ae2ec9 10844 size_t root_pos = header.rfind("include/");
832f100d 10845 short_decls.push_back(string("#include <") +
75ae2ec9 10846 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10847 string(">"));
f982c59b 10848
c9ccb642
FCE
10849 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10850 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10851
10852 // the kernel has changed this naming a few times, previously TPPROTO,
10853 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10854 osrc << "#ifndef PARAMS" << endl;
10855 osrc << "#define PARAMS(args...) args" << endl;
10856 osrc << "#endif" << endl;
10857
c9ccb642
FCE
10858 // override DECLARE_TRACE to synthesize probe functions for us
10859 osrc << "#undef DECLARE_TRACE" << endl;
10860 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10861 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10862
c9ccb642
FCE
10863 // 2.6.35 added the NOARGS variant, but it's the same for us
10864 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10865 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10866 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10867
10868 // 2.6.38 added the CONDITION variant, which can also just redirect
10869 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10870 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10871 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10872
c9ccb642
FCE
10873 // older tracepoints used DEFINE_TRACE, so redirect that too
10874 osrc << "#undef DEFINE_TRACE" << endl;
10875 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10876 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10877
c9ccb642
FCE
10878 // add the specified decls/#includes
10879 for (unsigned z=0; z<short_decls.size(); z++)
10880 osrc << "#undef TRACE_INCLUDE_FILE\n"
10881 << "#undef TRACE_INCLUDE_PATH\n"
10882 << short_decls[z] << "\n";
10883
10884 // finish up the module source
10885 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10886
c9ccb642
FCE
10887 // save the source file away
10888 headers_tracequery_src[header] = osrc.str();
55e50c24 10889 }
f982c59b 10890
c9ccb642 10891 // now build them all together
2a0e62a8 10892 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10893
c9ccb642 10894 // now plop them into the cache
b278033a 10895 if (s.use_cache)
c9ccb642
FCE
10896 for (size_t i=0; i<uncached_headers.size(); i++)
10897 {
10898 const string& header = uncached_headers[i];
2a0e62a8
JS
10899 const string& tracequery_obj = tracequery_objs[header];
10900 const string& tracequery_path = headers_cache_obj[header];
10901 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10902 {
2a0e62a8 10903 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10904 modules.push_back (tracequery_path);
10905 }
c252fca2
JS
10906 else
10907 // cache an empty file for failures
10908 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10909 }
f982c59b
JS
10910}
10911
10912
d4393459 10913
f982c59b
JS
10914bool
10915tracepoint_builder::init_dw(systemtap_session& s)
10916{
10917 if (dw != NULL)
10918 return true;
10919
10920 vector<string> tracequery_modules;
55e50c24 10921 vector<string> system_headers;
f982c59b
JS
10922
10923 glob_t trace_glob;
d4393459
FCE
10924
10925 // find kernel_source_tree
10926 if (s.kernel_source_tree == "")
f982c59b 10927 {
d4393459 10928 unsigned found;
ccf2c922 10929 Dwfl *dwfl = setup_dwfl_kernel ("kernel", &found, s);
d4393459
FCE
10930 if (found)
10931 {
10932 Dwarf_Die *cudie = 0;
10933 Dwarf_Addr bias;
10934 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10935 {
e19ebcf7 10936 assert_no_interrupts();
d4393459
FCE
10937 Dwarf_Attribute attr;
10938 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10939 if (name)
d4393459 10940 {
36d65b45
JS
10941 // check that the path actually exists locally before we try to use it
10942 if (file_exists(name))
10943 {
10944 if (s.verbose > 2)
10945 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10946 s.kernel_source_tree = name;
10947 }
10948 else
10949 {
10950 if (s.verbose > 2)
10951 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10952 }
61f1a63b 10953
d4393459
FCE
10954 break; // skip others; modern Kbuild uses same comp_dir for them all
10955 }
10956 }
10957 }
44392d73 10958 dwfl_end (dwfl);
d4393459
FCE
10959 }
10960
10961 // prefixes
10962 vector<string> glob_prefixes;
10963 glob_prefixes.push_back (s.kernel_build_tree);
10964 if (s.kernel_source_tree != "")
10965 glob_prefixes.push_back (s.kernel_source_tree);
10966
10967 // suffixes
10968 vector<string> glob_suffixes;
10969 glob_suffixes.push_back("include/trace/events/*.h");
10970 glob_suffixes.push_back("include/trace/*.h");
d97d428e 10971 glob_suffixes.push_back("include/ras/*_event.h");
d4393459 10972 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
d97d428e
FCE
10973 glob_suffixes.push_back("arch/x86/kernel/*trace.h");
10974 glob_suffixes.push_back("arch/*/include/asm/trace*.h");
10975 glob_suffixes.push_back("arch/*/include/asm/trace/*.h");
f89ff3e2 10976 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d97d428e
FCE
10977 glob_suffixes.push_back("fs/*/*trace*.h");
10978 glob_suffixes.push_back("net/*/*trace*.h");
10979 glob_suffixes.push_back("sound/pci/hda/*_trace.h");
10980 glob_suffixes.push_back("drivers/gpu/drm/*_trace.h");
10981 glob_suffixes.push_back("drivers/gpu/drm/*/*_trace.h");
10982 glob_suffixes.push_back("drivers/net/wireless/*/*/*trace*.h");
10983 glob_suffixes.push_back("drivers/usb/host/*trace*.h");
10984
10985 // see also tracepoint_extra_decls above
d4393459
FCE
10986
10987 // compute cartesian product
10988 vector<string> globs;
10989 for (unsigned i=0; i<glob_prefixes.size(); i++)
10990 for (unsigned j=0; j<glob_suffixes.size(); j++)
10991 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10992
8aa43b8d 10993 set<string> duped_headers;
d4393459
FCE
10994 for (unsigned z = 0; z < globs.size(); z++)
10995 {
10996 string glob_str = globs[z];
10997 if (s.verbose > 3)
b530b5b3 10998 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10999
067cc66f
CM
11000 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
11001 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
11002 throw runtime_error("Error globbing tracepoint");
11003
f982c59b
JS
11004 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
11005 {
11006 string header(trace_glob.gl_pathv[i]);
11007
11008 // filter out a few known "internal-only" headers
60d98537
JS
11009 if (endswith(header, "/define_trace.h") ||
11010 endswith(header, "/ftrace.h") ||
11011 endswith(header, "/trace_events.h") ||
11012 endswith(header, "_event_types.h"))
f982c59b
JS
11013 continue;
11014
b1966849
FCE
11015 // With headers now plopped under arch/FOO/include/asm/*,
11016 // the following logic miss some tracepoints.
11017#if 0
8aa43b8d
JS
11018 // skip identical headers from the build and source trees.
11019 size_t root_pos = header.rfind("include/");
11020 if (root_pos != string::npos &&
11021 !duped_headers.insert(header.substr(root_pos + 8)).second)
11022 continue;
b1966849 11023#endif
8aa43b8d 11024
55e50c24 11025 system_headers.push_back(header);
f982c59b
JS
11026 }
11027 globfree(&trace_glob);
11028 }
11029
c9ccb642
FCE
11030 // Build tracequery modules
11031 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 11032
f982c59b
JS
11033 // TODO: consider other sources of tracepoint headers too, like from
11034 // a command-line parameter or some environment or .systemtaprc
47dd066d 11035
59c11f91 11036 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
11037 return true;
11038}
47dd066d 11039
0a6f5a3f
JS
11040void
11041tracepoint_builder::build(systemtap_session& s,
11042 probe *base, probe_point *location,
11043 literal_map_t const& parameters,
11044 vector<derived_probe*>& finished_results)
11045{
11046 if (!init_dw(s))
11047 return;
47dd066d 11048
75ead1f7
JS
11049 string tracepoint;
11050 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 11051
75ead1f7 11052 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
d906ab9d 11053 unsigned results_pre = finished_results.size();
06de3a04 11054 dw->iterate_over_modules<base_query>(&query_module, &q);
d906ab9d
JL
11055 unsigned results_post = finished_results.size();
11056
11057 // Did we fail to find a match? Let's suggest something!
11058 if (results_pre == results_post)
11059 {
11060 size_t pos;
11061 string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
11062 while ((pos = sugs.find("stapprobe_")) != string::npos)
11063 sugs.erase(pos, string("stapprobe_").size());
11064 if (!sugs.empty())
ece93f53
JL
11065 throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
11066 "no match (similar tracepoints: %s)",
d906ab9d
JL
11067 sugs.find(',') == string::npos,
11068 sugs.c_str()));
11069 }
47dd066d 11070}
47dd066d 11071
e6fe60e7 11072
b55bc428 11073// ------------------------------------------------------------------------
bd2b1e68 11074// Standard tapset registry.
b55bc428
FCE
11075// ------------------------------------------------------------------------
11076
7a053d3b 11077void
f8220a7b 11078register_standard_tapsets(systemtap_session & s)
b55bc428 11079{
47e0478e 11080 register_tapset_been(s);
93646f4d 11081 register_tapset_itrace(s);
dd0e4fa7 11082 register_tapset_mark(s);
7a212aa8 11083 register_tapset_procfs(s);
912e8c59 11084 register_tapset_timers(s);
8d9609f5 11085 register_tapset_netfilter(s);
b84779a5 11086 register_tapset_utrace(s);
b98a8d73 11087
7a24d422 11088 // dwarf-based kprobe/uprobe parts
c4ce66a1 11089 dwarf_derived_probe::register_patterns(s);
30a279be 11090
888af770
FCE
11091 // XXX: user-space starter set
11092 s.pattern_root->bind_num(TOK_PROCESS)
11093 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 11094 ->bind_privilege(pr_all)
888af770
FCE
11095 ->bind(new uprobe_builder ());
11096 s.pattern_root->bind_num(TOK_PROCESS)
11097 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 11098 ->bind_privilege(pr_all)
888af770
FCE
11099 ->bind(new uprobe_builder ());
11100
0a6f5a3f
JS
11101 // kernel tracepoint probes
11102 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
11103 ->bind(new tracepoint_builder());
11104
e6fe60e7
AM
11105 // Kprobe based probe
11106 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
11107 ->bind(new kprobe_builder());
3c57fe1f
JS
11108 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
11109 ->bind(new kprobe_builder());
e6fe60e7
AM
11110 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11111 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
11112 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11113 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
11114 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11115 ->bind(new kprobe_builder());
b6371390
JS
11116 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11117 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
11118 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11119 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
11120 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
11121 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
11122 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
11123 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
11124 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
11125
11126 //Hwbkpt based probe
b47f3a55
FCE
11127 // NB: we formerly registered the probe point types only if the kernel configuration
11128 // allowed it. However, we get better error messages if we allow probes to resolve.
11129 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11130 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11131 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11132 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11133 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11134 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11135 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
11136 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11137 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11138 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
11139 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
11140 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
11141 // length supported with address only, not symbol names
83ea76b1
WC
11142
11143 //perf event based probe
4763f713 11144 register_tapset_perf(s);
a29858ef 11145 register_tapset_java(s);
b55bc428 11146}
dc38c0ae
DS
11147
11148
b20febf3
FCE
11149vector<derived_probe_group*>
11150all_session_groups(systemtap_session& s)
dc38c0ae 11151{
b20febf3 11152 vector<derived_probe_group*> g;
912e8c59
JS
11153
11154#define DOONE(x) \
11155 if (s. x##_derived_probes) \
11156 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
11157
11158 // Note that order *is* important here. We want to make sure we
11159 // register (actually run) begin probes before any other probe type
11160 // is run. Similarly, when unregistering probes, we want to
11161 // unregister (actually run) end probes after every other probe type
11162 // has be unregistered. To do the latter,
11163 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
11164 DOONE(be);
11165 DOONE(dwarf);
888af770 11166 DOONE(uprobe);
b20febf3
FCE
11167 DOONE(timer);
11168 DOONE(profile);
11169 DOONE(mark);
0a6f5a3f 11170 DOONE(tracepoint);
e6fe60e7 11171 DOONE(kprobe);
dd225250 11172 DOONE(hwbkpt);
83ea76b1 11173 DOONE(perf);
b20febf3 11174 DOONE(hrtimer);
ce82316f 11175 DOONE(procfs);
8d9609f5 11176 DOONE(netfilter);
935447c8
DS
11177
11178 // Another "order is important" item. We want to make sure we
11179 // "register" the dummy task_finder probe group after all probe
11180 // groups that use the task_finder.
11181 DOONE(utrace);
a96d1db0 11182 DOONE(itrace);
f31a77f5 11183 DOONE(dynprobe);
e7d4410d 11184 DOONE(java);
935447c8 11185 DOONE(task_finder);
b20febf3
FCE
11186#undef DOONE
11187 return g;
46b84a80 11188}
73267b89
JS
11189
11190/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 3.251667 seconds and 5 git commands to generate.