]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
remove suggest_functions from dwarf_builder class
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
1af100fc 2// Copyright (C) 2005-2013 Red Hat Inc.
aa30ccd3 3// Copyright (C) 2005-2007 Intel Corporation.
0b8f6579 4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
56e12059
FCE
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "config.h"
12#include "staptree.h"
13#include "elaborate.h"
b55bc428 14#include "tapsets.h"
93646f4d 15#include "task_finder.h"
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>
e36387d7 40#include <cstdarg>
29e64872 41#include <cassert>
1969b5bc 42#include <iomanip>
f781f849 43#include <cerrno>
bd2b1e68
GH
44
45extern "C" {
df8fadee 46#include <fcntl.h>
bd2b1e68 47#include <elfutils/libdwfl.h>
7a053d3b 48#include <elfutils/libdw.h>
77de5e9e
GH
49#include <dwarf.h>
50#include <elf.h>
51#include <obstack.h>
b20febf3 52#include <glob.h>
30a279be 53#include <fnmatch.h>
5f0a03a6 54#include <stdio.h>
349dc70e 55#include <sys/types.h>
37001baa 56#include <sys/stat.h>
aaf7ffe8 57#include <math.h>
aff5d390 58#include <regex.h>
37001baa 59#include <unistd.h>
6d5d594e 60#include <wordexp.h>
4b1ad75e
RM
61
62#define __STDC_FORMAT_MACROS
63#include <inttypes.h>
bd2b1e68 64}
77de5e9e 65
56e12059
FCE
66
67using namespace std;
2171f774 68using namespace __gnu_cxx;
56e12059 69
47dd066d 70
b20febf3
FCE
71
72// ------------------------------------------------------------------------
faea5e16
JS
73
74string
75common_probe_init (derived_probe* p)
76{
26e63673
JS
77 assert(p->session_index != (unsigned)-1);
78 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
79}
80
81
b20febf3 82void
71db462b
DS
83common_probe_entryfn_prologue (systemtap_session& s,
84 string statestr, string probe,
85 string probe_type, bool overload_processing)
b20febf3 86{
944c9a7a 87 if (s.runtime_usermode_p())
ac34f2aa
JS
88 {
89 // If session_state() is NULL, then we haven't even initialized shm yet,
90 // and there's *nothing* for the probe to do. (even alibi is in shm)
91 // So failure skips this whole block through the end of the epilogue.
92 s.op->newline() << "if (likely(session_state())) {";
e481ab2e 93 s.op->indent(1);
ac34f2aa
JS
94 }
95
71db462b 96 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 97 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 98 s.op->newline() << "#else";
653e6a9a 99
e481ab2e
JS
100 if (s.runtime_usermode_p())
101 s.op->newline() << "int _stp_saved_errno = errno;";
102
fee09ad5 103 s.op->newline() << "struct context* __restrict__ c = NULL;";
71db462b
DS
104 s.op->newline() << "#if !INTERRUPTIBLE";
105 s.op->newline() << "unsigned long flags;";
106 s.op->newline() << "#endif";
b20febf3 107
f887a8c9 108 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 109 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
110 s.op->newline() << "#endif";
111 if (overload_processing && !s.runtime_usermode_p())
71db462b 112 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 113 else
71db462b 114 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 115
f887a8c9
DS
116 if (! s.runtime_usermode_p())
117 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
118 else
119 {
120 s.op->newline() << "struct timespec timespec_atstart;";
121 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atstart);";
122 }
71db462b 123 s.op->newline() << "#endif";
994aac0e 124
71db462b
DS
125 s.op->newline() << "#if INTERRUPTIBLE";
126 s.op->newline() << "preempt_disable ();";
127 s.op->newline() << "#else";
128 s.op->newline() << "local_irq_save (flags);";
129 s.op->newline() << "#endif";
b20febf3 130
ac3af990 131 if (! s.runtime_usermode_p())
71db462b
DS
132 {
133 // Check for enough free enough stack space
134 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
135 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
136 // XXX: may need porting to platforms where task_struct is not
137 // at bottom of kernel stack NB: see also
138 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 139 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 140 s.op->newline() << "#ifdef STP_TIMING";
065d5567 141 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
142 s.op->newline() << "#endif";
143 s.op->newline() << "goto probe_epilogue;";
144 s.op->newline(-1) << "}";
145 }
c931ec8a 146
065d5567 147 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
148 s.op->newline(1) << "goto probe_epilogue;";
149 s.op->indent(-1);
9a604fac 150
1d0e697d
DS
151 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
152 if (s.runtime_usermode_p())
153 {
154 s.op->newline() << "if (!c) {";
155 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 156 s.op->newline() << "atomic_inc (skipped_count());";
1d0e697d
DS
157 s.op->newline() << "#endif";
158 s.op->newline() << "#ifdef STP_TIMING";
065d5567 159 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
1d0e697d
DS
160 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
161 s.op->newline() << "_stp_warn (\"Skipped %s\\n\", " << probe << "->pp);";
162 s.op->newline() << "#endif";
163 s.op->newline() << "#endif";
164 s.op->newline() << "goto probe_epilogue;";
165 s.op->newline(-1) << "}";
166 }
167
71db462b
DS
168 s.op->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
169 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 170 s.op->newline() << "atomic_inc (skipped_count());";
71db462b
DS
171 s.op->newline() << "#endif";
172 s.op->newline() << "#ifdef STP_TIMING";
065d5567 173 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
71db462b
DS
174 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
175 s.op->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 176 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
177 // NB: There is a conceivable race condition here with reading
178 // c->probe_point, knowing that this other probe is sort of running.
179 // However, in reality, it's interrupted. Plus even if it were able
180 // to somehow start again, and stop before we read c->probe_point,
181 // at least we have that ?: "?" bit in there to avoid a NULL deref.
71db462b
DS
182 s.op->newline() << "#endif";
183 s.op->newline() << "#endif";
184 s.op->newline() << "atomic_dec (& c->busy);";
185 s.op->newline() << "goto probe_epilogue;";
186 s.op->newline(-1) << "}";
187 s.op->newline();
188 s.op->newline() << "c->last_stmt = 0;";
189 s.op->newline() << "c->last_error = 0;";
190 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
191 s.op->newline() << "c->uregs = 0;";
192 s.op->newline() << "c->kregs = 0;";
193 s.op->newline() << "#if defined __ia64__";
194 s.op->newline() << "c->unwaddr = 0;";
195 s.op->newline() << "#endif";
f4d70a33
JS
196 if (s.runtime_usermode_p())
197 s.op->newline() << "c->probe_index = " << probe << "->index;";
71db462b
DS
198 s.op->newline() << "c->probe_point = " << probe << "->pp;";
199 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
200 s.op->newline() << "c->probe_name = " << probe << "->pn;";
201 s.op->newline() << "#endif";
202 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 203 // reset Individual Probe State union
71db462b 204 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 205 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
206 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
207 s.op->newline() << "c->regparm = 0;";
208 s.op->newline() << "#endif";
e0a17418 209
152fa051
LB
210 if(!s.suppress_time_limits){
211 s.op->newline() << "#if INTERRUPTIBLE";
212 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
213 s.op->newline() << "#else";
214 s.op->newline() << "c->actionremaining = MAXACTION;";
215 s.op->newline() << "#endif";
216 }
9915575b
FCE
217 // NB: The following would actually be incorrect.
218 // That's because cycles_sum/cycles_base values are supposed to survive
219 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
220 // cycles), the values will be reset.
221 /*
71db462b
DS
222 s.op->newline() << "#ifdef STP_OVERLOAD";
223 s.op->newline() << "c->cycles_sum = 0;";
224 s.op->newline() << "c->cycles_base = 0;";
225 s.op->newline() << "#endif";
9915575b 226 */
44cfbe25
SM
227
228 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
229 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
230 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
231 s.op->newline() << "#endif";
b20febf3 232}
9a604fac 233
a44a0785 234
b20febf3 235void
f887a8c9
DS
236common_probe_entryfn_epilogue (systemtap_session& s,
237 bool overload_processing)
b20febf3 238{
f887a8c9
DS
239 if (overload_processing && !s.runtime_usermode_p())
240 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 241 else
f887a8c9
DS
242 s.op->newline() << "#ifdef STP_TIMING";
243 s.op->newline() << "{";
244 s.op->indent(1);
245 if (! s.runtime_usermode_p())
246 {
247 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
248 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
249 // fewer, if the hardware counter rolls over really quickly. We
250 // handle 32-bit wraparound here.
251 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
252 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
253 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
254 s.op->indent(-1);
255 }
256 else
257 {
258 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
259 s.op->newline() << "long cycles_elapsed;";
260 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atend);";
261 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
262 // 'cycles_elapsed' is really elapsed nanoseconds
263 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
264 }
265
266 s.op->newline() << "#ifdef STP_TIMING";
267 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
268 s.op->newline() << "#endif";
269
270 if (overload_processing && !s.runtime_usermode_p())
271 {
272 s.op->newline() << "#ifdef STP_OVERLOAD";
273 s.op->newline() << "{";
a58d79d0
DS
274 // If the cycle count has wrapped (cycles_atend > cycles_base),
275 // let's go ahead and pretend the interval has been reached.
276 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
277 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
278 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
279 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
280 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
281
282 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
283 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
284 // has overloaded the system and we need to quit.
7baf48e9
FCE
285 // NB: this is not suppressible via --suppress-runtime-errors,
286 // because this is a system safety metric that we cannot trust
287 // unprivileged users to override.
f887a8c9
DS
288 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
289 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
290 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
291 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
292 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
293 s.op->newline(-1) << "}";
294
295 s.op->newline() << "c->cycles_base = cycles_atend;";
296 s.op->newline() << "c->cycles_sum = 0;";
297 s.op->newline(-1) << "}";
298 s.op->newline(-1) << "}";
299 s.op->newline() << "#endif";
a58d79d0 300 }
e57b735a 301
f887a8c9
DS
302 s.op->newline(-1) << "}";
303 s.op->newline() << "#endif";
e57b735a 304
f887a8c9
DS
305 s.op->newline() << "c->probe_point = 0;"; // vacated
306 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
307 s.op->newline() << "c->probe_name = 0;";
308 s.op->newline() << "#endif";
309 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
310
311
f887a8c9
DS
312 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
313 s.op->indent(1);
314 if (s.suppress_handler_errors) // PR 13306
7baf48e9 315 {
065d5567 316 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
317 }
318 else
319 {
f887a8c9
DS
320 s.op->newline() << "if (c->last_stmt != NULL)";
321 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
322 s.op->newline(-1) << "else";
323 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
324 s.op->indent(-1);
065d5567
JS
325 s.op->newline() << "atomic_inc (error_count());";
326 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
327 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
328 s.op->newline() << "_stp_exit ();";
329 s.op->newline(-1) << "}";
7baf48e9
FCE
330 }
331
f887a8c9 332 s.op->newline(-1) << "}";
7baf48e9
FCE
333
334
f887a8c9 335 s.op->newline() << "atomic_dec (&c->busy);";
e57b735a 336
f887a8c9
DS
337 s.op->newline(-1) << "probe_epilogue:"; // context is free
338 s.op->indent(1);
e57b735a 339
8ca891c4
DS
340 // In dyninst mode, we're not done with the context yet, since
341 // _stp_error() still needs a context structure (since the log
342 // buffers are stored there).
343 if (!s.runtime_usermode_p())
344 {
e481ab2e 345 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
8ca891c4 346 }
f887a8c9 347 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
348 {
349 // Check for excessive skip counts.
065d5567
JS
350 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
351 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
352 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
353 s.op->newline(-1) << "}";
7baf48e9 354 }
e57b735a 355
f887a8c9
DS
356 s.op->newline() << "#if INTERRUPTIBLE";
357 s.op->newline() << "preempt_enable_no_resched ();";
358 s.op->newline() << "#else";
359 s.op->newline() << "local_irq_restore (flags);";
360 s.op->newline() << "#endif";
653e6a9a 361
944c9a7a 362 if (s.runtime_usermode_p())
ac34f2aa 363 {
e481ab2e 364 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
ac34f2aa 365 s.op->newline() << "errno = _stp_saved_errno;";
ac34f2aa 366 }
e481ab2e
JS
367
368 s.op->newline() << "#endif // STP_ALIBI";
369
370 if (s.runtime_usermode_p())
371 s.op->newline(-1) << "}";
440f755a 372}
e57b735a 373
e57b735a 374
440f755a 375// ------------------------------------------------------------------------
e57b735a 376
440f755a
JS
377// ------------------------------------------------------------------------
378// Dwarf derived probes. "We apologize for the inconvience."
379// ------------------------------------------------------------------------
e57b735a 380
4627ed58
JS
381static const string TOK_KERNEL("kernel");
382static const string TOK_MODULE("module");
383static const string TOK_FUNCTION("function");
384static const string TOK_INLINE("inline");
385static const string TOK_CALL("call");
4bda987e 386static const string TOK_EXPORTED("exported");
4627ed58
JS
387static const string TOK_RETURN("return");
388static const string TOK_MAXACTIVE("maxactive");
389static const string TOK_STATEMENT("statement");
390static const string TOK_ABSOLUTE("absolute");
391static const string TOK_PROCESS("process");
a794dbeb 392static const string TOK_PROVIDER("provider");
4627ed58
JS
393static const string TOK_MARK("mark");
394static const string TOK_TRACE("trace");
395static const string TOK_LABEL("label");
63b4fd14 396static const string TOK_LIBRARY("library");
576eaefe 397static const string TOK_PLT("plt");
e7d4410d
LB
398static const string TOK_METHOD("method");
399static const string TOK_CLASS("class");;
e57b735a 400
1adf8ef1 401static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 402static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 403
440f755a
JS
404// Can we handle this query with just symbol-table info?
405enum dbinfo_reqt
406{
407 dbr_unknown,
408 dbr_none, // kernel.statement(NUM).absolute
409 dbr_need_symtab, // can get by with symbol table if there's no dwarf
410 dbr_need_dwarf
411};
e57b735a 412
20e4a32c 413
440f755a
JS
414struct base_query; // forward decls
415struct dwarf_query;
416struct dwflpp;
417struct symbol_table;
20e4a32c 418
a781f401 419
440f755a
JS
420struct
421symbol_table
422{
423 module_info *mod_info; // associated module
424 map<string, func_info*> map_by_name;
1c6b77e5
JS
425 multimap<Dwarf_Addr, func_info*> map_by_addr;
426 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
427 typedef pair<iterator_t, iterator_t> range_t;
428#ifdef __powerpc__
429 GElf_Word opd_section;
430#endif
2867a2a1
JS
431 void add_symbol(const char *name, bool weak, bool descriptor,
432 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 433 enum info_status read_symbols(FILE *f, const string& path);
83ca3872 434 enum info_status read_from_elf_file(const string& path,
2713ea24 435 systemtap_session &sess);
83ca3872 436 enum info_status read_from_text_file(const string& path,
2713ea24 437 systemtap_session &sess);
440f755a
JS
438 enum info_status get_from_elf();
439 void prepare_section_rejection(Dwfl_Module *mod);
440 bool reject_section(GElf_Word section);
440f755a
JS
441 void purge_syscall_stubs();
442 func_info *lookup_symbol(const string& name);
443 Dwarf_Addr lookup_symbol_address(const string& name);
444 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 445 func_info *get_first_func();
7a053d3b 446
440f755a
JS
447 symbol_table(module_info *mi) : mod_info(mi) {}
448 ~symbol_table();
449};
77de5e9e 450
440f755a
JS
451static bool null_die(Dwarf_Die *die)
452{
822a6a3d 453 static Dwarf_Die null;
440f755a
JS
454 return (!die || !memcmp(die, &null, sizeof(null)));
455}
c4ce66a1
JS
456
457
7a053d3b 458enum
bd2b1e68 459function_spec_type
7a053d3b 460 {
bd2b1e68
GH
461 function_alone,
462 function_and_file,
7a053d3b 463 function_file_and_line
bd2b1e68
GH
464 };
465
ec4373ff 466
bd2b1e68 467struct dwarf_builder;
f10534c6 468struct dwarf_var_expanding_visitor;
77de5e9e 469
2930abc7 470
b20febf3
FCE
471// XXX: This class is a candidate for subclassing to separate
472// the relocation vs non-relocation variants. Likewise for
473// kprobe vs kretprobe variants.
474
475struct dwarf_derived_probe: public derived_probe
b55bc428 476{
b20febf3
FCE
477 dwarf_derived_probe (const string& function,
478 const string& filename,
479 int line,
480 const string& module,
481 const string& section,
482 Dwarf_Addr dwfl_addr,
2930abc7 483 Dwarf_Addr addr,
b20febf3
FCE
484 dwarf_query & q,
485 Dwarf_Die* scope_die);
20e4a32c 486
b20febf3
FCE
487 string module;
488 string section;
489 Dwarf_Addr addr;
63b4fd14 490 string path;
27dc09b1 491 bool has_process;
2930abc7 492 bool has_return;
c9bad430 493 bool has_maxactive;
63b4fd14 494 bool has_library;
c9bad430 495 long maxactive_val;
4ad95bbc 496 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
497 string user_path;
498 string user_lib;
b95e2b79 499 bool access_vars;
2930abc7 500
af234c40
JS
501 unsigned saved_longs, saved_strings;
502 dwarf_derived_probe* entry_handler;
503
b8da0ad1 504 void printsig (std::ostream &o) const;
6b66b9f7 505 virtual void join_group (systemtap_session& s);
3689db05 506 void emit_probe_local_init(systemtap_session& s, translator_output * o);
d0bfd2ac 507 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 508
42e38653 509 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
510 void print_dupe_stamp(ostream& o);
511
bd2b1e68 512 // Pattern registration helpers.
7a053d3b 513 static void register_statement_variants(match_node * root,
27dc09b1 514 dwarf_builder * dw,
42e38653 515 privilege_t privilege);
fd6602a0 516 static void register_function_variants(match_node * root,
27dc09b1 517 dwarf_builder * dw,
42e38653 518 privilege_t privilege);
440d9b00
DB
519 static void register_function_and_statement_variants(systemtap_session& s,
520 match_node * root,
27dc09b1 521 dwarf_builder * dw,
42e38653 522 privilege_t privilege);
b1615c74
JS
523 static void register_sdt_variants(systemtap_session& s,
524 match_node * root,
525 dwarf_builder * dw);
526 static void register_plt_variants(systemtap_session& s,
527 match_node * root,
528 dwarf_builder * dw);
c4ce66a1 529 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
530
531protected:
532 dwarf_derived_probe(probe *base,
533 probe_point *location,
534 Dwarf_Addr addr,
535 bool has_return):
74fe61bc
LB
536 derived_probe(base, location), addr(addr), has_process(0),
537 has_return(has_return), has_maxactive(0), has_library(0),
538 maxactive_val(0), access_vars(false), saved_longs(0),
539 saved_strings(0), entry_handler(0)
6b66b9f7
JS
540 {}
541
542private:
d0bfd2ac 543 list<string> args;
8c67c337 544 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
545};
546
dc38c0ae 547
6b66b9f7 548struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 549{
6d0f3f0c 550 int pid; // 0 => unrestricted
0973d815 551
6d0f3f0c
FCE
552 uprobe_derived_probe (const string& function,
553 const string& filename,
554 int line,
555 const string& module,
6d0f3f0c
FCE
556 const string& section,
557 Dwarf_Addr dwfl_addr,
558 Dwarf_Addr addr,
559 dwarf_query & q,
6b66b9f7
JS
560 Dwarf_Die* scope_die):
561 dwarf_derived_probe(function, filename, line, module, section,
562 dwfl_addr, addr, q, scope_die), pid(0)
563 {}
6d0f3f0c 564
0973d815
FCE
565 // alternate constructor for process(PID).statement(ADDR).absolute
566 uprobe_derived_probe (probe *base,
567 probe_point *location,
568 int pid,
569 Dwarf_Addr addr,
6b66b9f7
JS
570 bool has_return):
571 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
572 {}
9ace370f 573
6d0f3f0c 574 void join_group (systemtap_session& s);
2865d17a 575
42e38653 576 void emit_privilege_assertion (translator_output*);
8f6d8c2b 577 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
578 void getargs(std::list<std::string> &arg_set) const;
579 void saveargs(int nargs);
580private:
581 list<string> args;
6d0f3f0c
FCE
582};
583
dc38c0ae
DS
584struct dwarf_derived_probe_group: public derived_probe_group
585{
586private:
b20febf3
FCE
587 multimap<string,dwarf_derived_probe*> probes_by_module;
588 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
589
590public:
08b5a50c 591 dwarf_derived_probe_group() {}
b20febf3
FCE
592 void enroll (dwarf_derived_probe* probe);
593 void emit_module_decls (systemtap_session& s);
594 void emit_module_init (systemtap_session& s);
b4be7cbc 595 void emit_module_refresh (systemtap_session& s);
b20febf3 596 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
597};
598
599
20c6c071 600// Helper struct to thread through the dwfl callbacks.
2c384610 601struct base_query
20c6c071 602{
c4ce66a1
JS
603 base_query(dwflpp & dw, literal_map_t const & params);
604 base_query(dwflpp & dw, const string & module_val);
2c384610 605 virtual ~base_query() {}
bd2b1e68 606
5227f1ea 607 systemtap_session & sess;
2c384610 608 dwflpp & dw;
5227f1ea 609
070764c0
JL
610 // Used to keep track of which modules were visited during
611 // iterate_over_modules()
612 set<string> visited_modules;
613
bd2b1e68 614 // Parameter extractors.
86bf665e 615 static bool has_null_param(literal_map_t const & params,
888af770 616 string const & k);
86bf665e 617 static bool get_string_param(literal_map_t const & params,
bd2b1e68 618 string const & k, string & v);
86bf665e 619 static bool get_number_param(literal_map_t const & params,
bd2b1e68 620 string const & k, long & v);
86bf665e 621 static bool get_number_param(literal_map_t const & params,
c239d28c 622 string const & k, Dwarf_Addr & v);
f301a9ff 623 static void query_library_callback (void *object, const char *data);
576eaefe 624 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 625 virtual void query_library (const char *data) = 0;
576eaefe 626 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 627
b55bc428 628
2c384610
DS
629 // Extracted parameters.
630 bool has_kernel;
91af0778
FCE
631 bool has_module;
632 bool has_process;
63b4fd14 633 bool has_library;
576eaefe
SC
634 bool has_plt;
635 bool has_statement;
2c384610 636 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 637 string path; // executable path if module is a .so
576eaefe 638 string plt_val; // has_plt => plt wildcard
2c384610
DS
639
640 virtual void handle_query_module() = 0;
641};
642
643
c4ce66a1 644base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 645 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 646{
91af0778 647 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
648 if (has_kernel)
649 module_val = "kernel";
91af0778
FCE
650
651 has_module = get_string_param (params, TOK_MODULE, module_val);
652 if (has_module)
653 has_process = false;
4baf0e53 654 else
d0a7f5a9 655 {
63b4fd14 656 string library_name;
576eaefe 657 long statement_num_val;
d0a7f5a9 658 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 659 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
660 if ((has_plt = has_null_param (params, TOK_PLT)))
661 plt_val = "*";
662 else has_plt = get_string_param (params, TOK_PLT, plt_val);
18418d34
SC
663 if (has_plt)
664 sess.consult_symtab = true;
576eaefe
SC
665 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
666
84c84ac4 667 if (has_process)
05fb3e0c 668 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
669 if (has_library)
670 {
671 if (! contains_glob_chars (library_name))
672 {
05fb3e0c
WF
673 path = path_remove_sysroot(sess, module_val);
674 module_val = find_executable (library_name, sess.sysroot,
675 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
676 if (module_val.find('/') == string::npos)
677 {
678 // We didn't find library_name so use iterate_over_libraries
679 module_val = path;
680 path = library_name;
681 }
84c84ac4
SC
682 }
683 else
684 path = library_name;
685 }
d0a7f5a9 686 }
91af0778
FCE
687
688 assert (has_kernel || has_process || has_module);
2c384610
DS
689}
690
c4ce66a1 691base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
692 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
693 module_val(module_val)
c4ce66a1
JS
694{
695 // NB: This uses '/' to distinguish between kernel modules and userspace,
696 // which means that userspace modules won't get any PATH searching.
697 if (module_val.find('/') == string::npos)
698 {
699 has_kernel = (module_val == TOK_KERNEL);
700 has_module = !has_kernel;
701 has_process = false;
702 }
703 else
704 {
705 has_kernel = has_module = false;
706 has_process = true;
707 }
708}
709
2c384610 710bool
86bf665e 711base_query::has_null_param(literal_map_t const & params,
2c384610
DS
712 string const & k)
713{
888af770 714 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
715}
716
717
718bool
86bf665e 719base_query::get_string_param(literal_map_t const & params,
2c384610
DS
720 string const & k, string & v)
721{
722 return derived_probe_builder::get_param (params, k, v);
723}
724
725
726bool
86bf665e 727base_query::get_number_param(literal_map_t const & params,
2c384610
DS
728 string const & k, long & v)
729{
730 int64_t value;
731 bool present = derived_probe_builder::get_param (params, k, value);
732 v = (long) value;
733 return present;
734}
735
736
737bool
86bf665e 738base_query::get_number_param(literal_map_t const & params,
2c384610
DS
739 string const & k, Dwarf_Addr & v)
740{
741 int64_t value;
742 bool present = derived_probe_builder::get_param (params, k, value);
743 v = (Dwarf_Addr) value;
744 return present;
745}
746
2c384610
DS
747struct dwarf_query : public base_query
748{
e1278bd4 749 dwarf_query(probe * base_probe,
2c384610
DS
750 probe_point * base_loc,
751 dwflpp & dw,
86bf665e 752 literal_map_t const & params,
b642c901
SC
753 vector<derived_probe *> & results,
754 const string user_path,
755 const string user_lib);
2c384610 756
c4ce66a1 757 vector<derived_probe *> & results;
8f14e444 758 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
759 probe * base_probe;
760 probe_point * base_loc;
b642c901
SC
761 string user_path;
762 string user_lib;
c4ce66a1 763
2c384610 764 virtual void handle_query_module();
5f0a03a6
JK
765 void query_module_dwarf();
766 void query_module_symtab();
5d5bd369 767 void query_library (const char *data);
576eaefe 768 void query_plt (const char *entry, size_t addr);
2c384610 769
2930abc7
FCE
770 void add_probe_point(string const & funcname,
771 char const * filename,
772 int line,
773 Dwarf_Die *scope_die,
774 Dwarf_Addr addr);
36f9dd1d 775
857bdfd1
JS
776 // Track addresses we've already seen in a given module
777 set<Dwarf_Addr> alias_dupes;
778
7fdd3e2c
JS
779 // Track inlines we've already seen as well
780 // NB: this can't be compared just by entrypc, as inlines can overlap
781 set<inline_instance_info> inline_dupes;
782
2930abc7 783 // Extracted parameters.
7a053d3b 784 string function_val;
20c6c071
GH
785
786 bool has_function_str;
787 bool has_statement_str;
788 bool has_function_num;
789 bool has_statement_num;
7a053d3b
RM
790 string statement_str_val;
791 string function_str_val;
c239d28c
GH
792 Dwarf_Addr statement_num_val;
793 Dwarf_Addr function_num_val;
20c6c071 794
b8da0ad1 795 bool has_call;
4bda987e 796 bool has_exported;
b8da0ad1 797 bool has_inline;
20c6c071
GH
798 bool has_return;
799
c9bad430
DS
800 bool has_maxactive;
801 long maxactive_val;
802
20c6c071
GH
803 bool has_label;
804 string label_val;
805
806 bool has_relative;
807 long relative_val;
808
37ebca01
FCE
809 bool has_absolute;
810
467bea43
SC
811 bool has_mark;
812
5f0a03a6
JK
813 enum dbinfo_reqt dbinfo_reqt;
814 enum dbinfo_reqt assess_dbinfo_reqt();
815
7d6d0afc 816 void parse_function_spec(const string & spec);
20c6c071 817 function_spec_type spec_type;
7d6d0afc 818 vector<string> scopes;
20c6c071
GH
819 string function;
820 string file;
0c8b7d37 821 line_t line_type;
879eb9e9 822 int line[2];
5f0a03a6 823 bool query_done; // Found exact match
20c6c071 824
bd25380d 825 set<string> filtered_srcfiles;
7e1279ea
FCE
826
827 // Map official entrypc -> func_info object
86bf665e
TM
828 inline_instance_map_t filtered_inlines;
829 func_info_map_t filtered_functions;
7e1279ea
FCE
830 bool choose_next_line;
831 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
832
833 void query_module_functions ();
b55bc428
FCE
834};
835
98afd80e 836
435f53a7
FCE
837static void delete_session_module_cache (systemtap_session& s); // forward decl
838
839
98afd80e 840struct dwarf_builder: public derived_probe_builder
b55bc428 841{
665e1256 842 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 843 map <string,dwflpp*> user_dw;
b642c901
SC
844 string user_path;
845 string user_lib;
44ffe90c
JL
846
847 // Holds modules to suggest functions from. NB: aggregates over
848 // recursive calls to build() when deriving globby probes.
849 set <string> modules_seen;
850
ae2552da 851 dwarf_builder() {}
aa30ccd3 852
ae2552da 853 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 854 {
ea14cf67
FCE
855 if (kern_dw[module] == 0)
856 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 857 return kern_dw[module];
707bf35e
JS
858 }
859
860 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
861 {
ea14cf67
FCE
862 if (user_dw[module] == 0)
863 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
864 return user_dw[module];
865 }
7a24d422
FCE
866
867 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 868 void dwarf_build_no_more (bool)
aa30ccd3 869 {
435f53a7
FCE
870 delete_map(kern_dw);
871 delete_map(user_dw);
7a24d422
FCE
872 }
873
874 void build_no_more (systemtap_session &s)
875 {
876 dwarf_build_no_more (s.verbose > 3);
435f53a7 877 delete_session_module_cache (s);
aa30ccd3
FCE
878 }
879
e38d6504
RM
880 ~dwarf_builder()
881 {
7a24d422 882 dwarf_build_no_more (false);
c8959a29 883 }
aa30ccd3 884
5227f1ea 885 virtual void build(systemtap_session & sess,
7a053d3b 886 probe * base,
20c6c071 887 probe_point * location,
86bf665e 888 literal_map_t const & parameters,
20c6c071 889 vector<derived_probe *> & finished_results);
b55bc428
FCE
890};
891
5111fc3e 892
e1278bd4 893dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
894 probe_point * base_loc,
895 dwflpp & dw,
86bf665e 896 literal_map_t const & params,
b642c901
SC
897 vector<derived_probe *> & results,
898 const string user_path,
899 const string user_lib)
c4ce66a1 900 : base_query(dw, params), results(results),
b642c901 901 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
902 user_path(user_path), user_lib(user_lib), has_relative(false),
903 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
904{
905 // Reduce the query to more reasonable semantic values (booleans,
906 // extracted strings, numbers, etc).
bd2b1e68
GH
907 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
908 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
909
910 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
911 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
912
0f336e95
SC
913 has_label = get_string_param(params, TOK_LABEL, label_val);
914
b8da0ad1 915 has_call = has_null_param(params, TOK_CALL);
4bda987e 916 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 917 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 918 has_return = has_null_param(params, TOK_RETURN);
c9bad430 919 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 920 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 921 has_mark = false;
37ebca01 922
bd2b1e68 923 if (has_function_str)
7d6d0afc 924 parse_function_spec(function_str_val);
bd2b1e68 925 else if (has_statement_str)
7d6d0afc 926 parse_function_spec(statement_str_val);
0daad364 927
5f0a03a6
JK
928 dbinfo_reqt = assess_dbinfo_reqt();
929 query_done = false;
0daad364
JS
930}
931
932
440f755a
JS
933func_info_map_t *
934get_filtered_functions(dwarf_query *q)
935{
936 return &q->filtered_functions;
937}
938
939
940inline_instance_map_t *
941get_filtered_inlines(dwarf_query *q)
942{
943 return &q->filtered_inlines;
944}
945
946
2c384610 947void
5f0a03a6 948dwarf_query::query_module_dwarf()
2c384610
DS
949{
950 if (has_function_num || has_statement_num)
951 {
952 // If we have module("foo").function(0xbeef) or
953 // module("foo").statement(0xbeef), the address is relative
954 // to the start of the module, so we seek the function
955 // number plus the module's bias.
6b517475
JS
956 Dwarf_Addr addr = has_function_num ?
957 function_num_val : statement_num_val;
08d1d520
MW
958
959 // These are raw addresses, we need to know what the elf_bias
960 // is to feed it to libdwfl based functions.
961 Dwarf_Addr elf_bias;
962 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
963 assert(elf);
964 addr += elf_bias;
6b517475 965 query_addr(addr, this);
2c384610
DS
966 }
967 else
968 {
969 // Otherwise if we have a function("foo") or statement("foo")
970 // specifier, we have to scan over all the CUs looking for
971 // the function(s) in question
972 assert(has_function_str || has_statement_str);
4df79aaf
JS
973
974 // For simple cases, no wildcard and no source:line, we can do a very
975 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
976 if (spec_type == function_alone &&
977 !dw.name_has_wildcard(function) &&
978 !startswith(function, "_Z"))
4df79aaf
JS
979 query_module_functions();
980 else
337b7c44 981 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
982 }
983}
984
5f0a03a6
JK
985static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
986 dwarf_query * q);
987
988void
989dwarf_query::query_module_symtab()
990{
991 // Get the symbol table if it's necessary, sufficient, and not already got.
992 if (dbinfo_reqt == dbr_need_dwarf)
993 return;
994
995 module_info *mi = dw.mod_info;
996 if (dbinfo_reqt == dbr_need_symtab)
997 {
998 if (mi->symtab_status == info_unknown)
999 mi->get_symtab(this);
1000 if (mi->symtab_status == info_absent)
1001 return;
1002 }
1003
1004 func_info *fi = NULL;
1005 symbol_table *sym_table = mi->sym_table;
1006
1007 if (has_function_str)
1008 {
1009 // Per dwarf_query::assess_dbinfo_reqt()...
1010 assert(spec_type == function_alone);
1011 if (dw.name_has_wildcard(function_str_val))
1012 {
1013 // Until we augment the blacklist sufficently...
c5810d31 1014 if ((function_str_val.find_first_not_of("*?") == string::npos) && !dw.has_gnu_debugdata())
5f0a03a6
JK
1015 {
1016 // e.g., kernel.function("*")
b530b5b3
LB
1017 cerr << _F("Error: Pattern '%s' matches every single "
1018 "instruction address in the symbol table,\n"
1019 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
1020 return;
1021 }
2e67a43b 1022 symbol_table::iterator_t iter;
1c6b77e5
JS
1023 for (iter = sym_table->map_by_addr.begin();
1024 iter != sym_table->map_by_addr.end();
2e67a43b 1025 ++iter)
5f0a03a6 1026 {
1c6b77e5 1027 fi = iter->second;
5f0a03a6
JK
1028 if (!null_die(&fi->die))
1029 continue; // already handled in query_module_dwarf()
1030 if (dw.function_name_matches_pattern(fi->name, function_str_val))
1031 query_func_info(fi->addr, *fi, this);
1032 }
1033 }
1034 else
1035 {
1036 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1037 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
1038 query_func_info(fi->addr, *fi, this);
1039 }
1040 }
1041 else
1042 {
1043 assert(has_function_num || has_statement_num);
1044 // Find the "function" in which the indicated address resides.
1045 Dwarf_Addr addr =
1046 (has_function_num ? function_num_val : statement_num_val);
576eaefe 1047 if (has_plt)
3d372d6b
SC
1048 {
1049 // Use the raw address from the .plt
1050 fi = sym_table->get_first_func();
1051 fi->addr = addr;
1052 }
1053 else
1054 fi = sym_table->get_func_containing_address(addr);
1055
5f0a03a6
JK
1056 if (!fi)
1057 {
2713ea24
CM
1058 sess.print_warning(_F("address %#" PRIx64 " out of range for module %s",
1059 addr, dw.module_name.c_str()));
1060 return;
5f0a03a6
JK
1061 }
1062 if (!null_die(&fi->die))
1063 {
1064 // addr looks like it's in the compilation unit containing
1065 // the indicated function, but query_module_dwarf() didn't
1066 // match addr to any compilation unit, so addr must be
1067 // above that cu's address range.
2713ea24
CM
1068 sess.print_warning(_F("address %#" PRIx64 " maps to no known compilation unit in module %s",
1069 addr, dw.module_name.c_str()));
5f0a03a6
JK
1070 return;
1071 }
1072 query_func_info(fi->addr, *fi, this);
1073 }
1074}
1075
1076void
1077dwarf_query::handle_query_module()
1078{
1c6b77e5
JS
1079 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
1080 dw.get_module_dwarf(false, report);
1081
1082 // prebuild the symbol table to resolve aliases
1083 dw.mod_info->get_symtab(this);
1084
857bdfd1
JS
1085 // reset the dupe-checking for each new module
1086 alias_dupes.clear();
7fdd3e2c 1087 inline_dupes.clear();
857bdfd1 1088
5f0a03a6
JK
1089 if (dw.mod_info->dwarf_status == info_present)
1090 query_module_dwarf();
1c6b77e5 1091
5f0a03a6 1092 // Consult the symbol table if we haven't found all we're looking for.
c5810d31
LB
1093 // asm functions can show up in the symbol table but not in dwarf,
1094 // or if we want to check the .gnu_debugdata section
1095 if ((sess.consult_symtab || dw.has_gnu_debugdata()) && !query_done)
5f0a03a6
JK
1096 query_module_symtab();
1097}
1098
2c384610 1099
7d6d0afc
JS
1100void
1101dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1102{
1d12a9b2
JS
1103 line_type = ABSOLUTE;
1104 line[0] = line[1] = 0;
1105
91699a70 1106 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1107
7d6d0afc 1108 // look for named scopes
91699a70
JS
1109 scope_pos = spec.rfind("::");
1110 if (scope_pos != string::npos)
bd2b1e68 1111 {
91699a70
JS
1112 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1113 scope_pos += 2;
bd2b1e68 1114 }
91699a70
JS
1115 else
1116 scope_pos = 0;
bd2b1e68 1117
7d6d0afc
JS
1118 // look for a source separator
1119 src_pos = spec.find('@', scope_pos);
1120 if (src_pos == string::npos)
bd2b1e68 1121 {
7d6d0afc
JS
1122 function = spec.substr(scope_pos);
1123 spec_type = function_alone;
bd2b1e68 1124 }
7d6d0afc 1125 else
879eb9e9 1126 {
7d6d0afc 1127 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1128
7d6d0afc
JS
1129 // look for a line-number separator
1130 line_pos = spec.find_first_of(":+", src_pos);
1131 if (line_pos == string::npos)
1132 {
1133 file = spec.substr(src_pos + 1);
1134 spec_type = function_and_file;
1135 }
1136 else
1137 {
1138 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1139
1140 // classify the line spec
1141 spec_type = function_file_and_line;
1142 if (spec[line_pos] == '+')
1143 line_type = RELATIVE;
1144 else if (spec[line_pos + 1] == '*' &&
1145 spec.length() == line_pos + 2)
1146 line_type = WILDCARD;
1147 else
1148 line_type = ABSOLUTE;
1149
1150 if (line_type != WILDCARD)
1151 try
1152 {
1153 // try to parse either N or N-M
1154 dash_pos = spec.find('-', line_pos + 1);
1155 if (dash_pos == string::npos)
1156 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1157 else
1158 {
1159 line_type = RANGE;
1160 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1161 dash_pos - line_pos - 1));
1162 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1163 }
1164 }
1165 catch (runtime_error & exn)
1166 {
1167 goto bad;
1168 }
1169 }
bd2b1e68
GH
1170 }
1171
7d6d0afc
JS
1172 if (function.empty() ||
1173 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1174 goto bad;
1175
7d6d0afc 1176 if (sess.verbose > 2)
bd2b1e68 1177 {
b530b5b3
LB
1178 //clog << "parsed '" << spec << "'";
1179 clog << _F("parse '%s'", spec.c_str());
41c262f3 1180
7d6d0afc
JS
1181 if (!scopes.empty())
1182 clog << ", scope '" << scopes[0] << "'";
1183 for (unsigned i = 1; i < scopes.size(); ++i)
1184 clog << "::'" << scopes[i] << "'";
41c262f3 1185
7d6d0afc
JS
1186 clog << ", func '" << function << "'";
1187
1188 if (spec_type != function_alone)
1189 clog << ", file '" << file << "'";
1190
1191 if (spec_type == function_file_and_line)
1192 {
1193 clog << ", line ";
1194 switch (line_type)
1195 {
1196 case ABSOLUTE:
1197 clog << line[0];
1198 break;
1199
1200 case RELATIVE:
1201 clog << "+" << line[0];
1202 break;
1203
1204 case RANGE:
1205 clog << line[0] << " - " << line[1];
1206 break;
1207
1208 case WILDCARD:
1209 clog << "*";
1210 break;
1211 }
1212 }
1213
1214 clog << endl;
bd2b1e68
GH
1215 }
1216
7d6d0afc
JS
1217 return;
1218
1219bad:
dc09353a 1220 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1221 base_probe->tok);
bd2b1e68
GH
1222}
1223
05fb3e0c
WF
1224string path_remove_sysroot(const systemtap_session& sess, const string& path)
1225{
1226 size_t pos;
1227 string retval = path;
1228 if (!sess.sysroot.empty() &&
1229 (pos = retval.find(sess.sysroot)) != string::npos)
1230 retval.replace(pos, sess.sysroot.length(), "/");
1231 return retval;
1232}
bd2b1e68 1233
36f9dd1d 1234void
1ffb8bd1 1235dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1236 const char* filename,
36f9dd1d 1237 int line,
b20febf3 1238 Dwarf_Die* scope_die,
36f9dd1d
FCE
1239 Dwarf_Addr addr)
1240{
b20febf3 1241 string reloc_section; // base section for relocation purposes
27646582 1242 Dwarf_Addr reloc_addr; // relocated
b20febf3 1243 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1244 string funcname = dw_funcname;
36f9dd1d 1245
37ebca01
FCE
1246 assert (! has_absolute); // already handled in dwarf_builder::build()
1247
576eaefe
SC
1248 if (!has_plt)
1249 reloc_addr = dw.relocate_address(addr, reloc_section);
1250 else
1251 {
3d372d6b 1252 // Set the reloc_section but use the plt entry for reloc_addr
576eaefe
SC
1253 dw.relocate_address(addr, reloc_section);
1254 reloc_addr = addr;
1255 }
2930abc7 1256
1ffb8bd1 1257 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1258 const char* linkage_name;
1259 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1260 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1261 funcname = linkage_name;
1262
7f9f3386
FCE
1263 if (sess.verbose > 1)
1264 {
b530b5b3 1265 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1266 if (string(module) == TOK_KERNEL)
b530b5b3 1267 clog << _(" kernel");
91af0778 1268 else if (has_module)
b530b5b3 1269 clog << _(" module=") << module;
91af0778 1270 else if (has_process)
b530b5b3 1271 clog << _(" process=") << module;
b20febf3 1272 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1273 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1274 }
4baf0e53 1275
27646582 1276 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1277 addr, has_return);
b20febf3
FCE
1278 if (sess.verbose > 1)
1279 clog << endl;
7f9f3386 1280
84048984
FCE
1281 if (module == TOK_KERNEL)
1282 {
1283 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1284 reloc_addr = addr - sess.sym_stext;
37ebca01 1285 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1286 }
1287
b20febf3
FCE
1288 if (! bad)
1289 {
1a0dbc5a 1290 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1291
1292 if (has_process)
1293 {
05fb3e0c 1294 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1295 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1296 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1297 *this, scope_die));
1298 }
1299 else
1300 {
1301 assert (has_kernel || has_module);
1302 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1303 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1304 *this, scope_die));
1305 }
b20febf3 1306 }
2930abc7
FCE
1307}
1308
5f0a03a6
JK
1309enum dbinfo_reqt
1310dwarf_query::assess_dbinfo_reqt()
1311{
1312 if (has_absolute)
1313 {
1314 // kernel.statement(NUM).absolute
1315 return dbr_none;
1316 }
1317 if (has_inline)
1318 {
1319 // kernel.function("f").inline or module("m").function("f").inline
1320 return dbr_need_dwarf;
1321 }
1322 if (has_function_str && spec_type == function_alone)
1323 {
1324 // kernel.function("f") or module("m").function("f")
1325 return dbr_need_symtab;
1326 }
1327 if (has_statement_num)
1328 {
1329 // kernel.statement(NUM) or module("m").statement(NUM)
1330 // Technically, all we need is the module offset (or _stext, for
1331 // the kernel). But for that we need either the ELF file or (for
1332 // _stext) the symbol table. In either case, the symbol table
1333 // is available, and that allows us to map the NUM (address)
1334 // to a function, which is goodness.
1335 return dbr_need_symtab;
1336 }
1337 if (has_function_num)
1338 {
1339 // kernel.function(NUM) or module("m").function(NUM)
1340 // Need the symbol table so we can back up from NUM to the
1341 // start of the function.
1342 return dbr_need_symtab;
1343 }
1344 // Symbol table tells us nothing about source files or line numbers.
1345 return dbr_need_dwarf;
1346}
2930abc7
FCE
1347
1348
b8da0ad1
FCE
1349// The critical determining factor when interpreting a pattern
1350// string is, perhaps surprisingly: "presence of a lineno". The
1351// presence of a lineno changes the search strategy completely.
1352//
1353// Compare the two cases:
1354//
1355// 1. {statement,function}(foo@file.c:lineno)
1356// - find the files matching file.c
1357// - in each file, find the functions matching foo
1358// - query the file for line records matching lineno
1359// - iterate over the line records,
1360// - and iterate over the functions,
1361// - if(haspc(function.DIE, line.addr))
1362// - if looking for statements: probe(lineno.addr)
1363// - if looking for functions: probe(function.{entrypc,return,etc.})
1364//
1365// 2. {statement,function}(foo@file.c)
1366// - find the files matching file.c
1367// - in each file, find the functions matching foo
1368// - probe(function.{entrypc,return,etc.})
1369//
1370// Thus the first decision we make is based on the presence of a
1371// lineno, and we enter entirely different sets of callbacks
1372// depending on that decision.
1373//
1374// Note that the first case is a generalization fo the second, in that
1375// we could theoretically search through line records for matching
1376// file names (a "table scan" in rdbms lingo). Luckily, file names
1377// are already cached elsewhere, so we can do an "index scan" as an
1378// optimization.
7e1279ea 1379
bd2b1e68 1380static void
4cd232e4 1381query_statement (string const & func,
20e4a32c 1382 char const * file,
4cd232e4 1383 int line,
bcc12710 1384 Dwarf_Die *scope_die,
20e4a32c 1385 Dwarf_Addr stmt_addr,
4cd232e4 1386 dwarf_query * q)
bd2b1e68 1387{
39bcd429
FCE
1388 try
1389 {
cee35f73 1390 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1391 line, scope_die, stmt_addr);
39bcd429
FCE
1392 }
1393 catch (const semantic_error& e)
1394 {
1395 q->sess.print_error (e);
1396 }
bd2b1e68
GH
1397}
1398
6b517475
JS
1399static void
1400query_addr(Dwarf_Addr addr, dwarf_query *q)
1401{
1402 dwflpp &dw = q->dw;
1403
08d1d520
MW
1404 if (q->sess.verbose > 2)
1405 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1406
1407 // First pick which CU contains this address
1408 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1409 if (!cudie) // address could be wildly out of range
1410 return;
1411 dw.focus_on_cu(cudie);
1412
1413 // Now compensate for the dw bias
1414 addr -= dw.module_bias;
1415
1416 // Per PR5787, we look up the scope die even for
1417 // statement_num's, for blacklist sensitivity and $var
1418 // resolution purposes.
1419
1420 // Find the scopes containing this address
1421 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1422 if (scopes.empty())
1423 return;
1424
1425 // Look for the innermost containing function
1426 Dwarf_Die *fnscope = NULL;
1427 for (size_t i = 0; i < scopes.size(); ++i)
1428 {
1429 int tag = dwarf_tag(&scopes[i]);
1430 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1431 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1432 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1433 {
1434 fnscope = &scopes[i];
1435 break;
1436 }
1437 }
1438 if (!fnscope)
1439 return;
1440 dw.focus_on_function(fnscope);
1441
1442 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1443
1444 const char *file = dwarf_decl_file(fnscope);
1445 int line;
1446 dwarf_decl_line(fnscope, &line);
1447
1448 // Function probes should reset the addr to the function entry
1449 // and possibly perform prologue searching
1450 if (q->has_function_num)
1451 {
1452 dw.die_entrypc(fnscope, &addr);
1453 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1454 (q->sess.prologue_searching || q->has_process)) // PR 6871
1455 {
1456 func_info func;
1457 func.die = *fnscope;
1458 func.name = dw.function_name;
1459 func.decl_file = file;
1460 func.decl_line = line;
1461 func.entrypc = addr;
1462
1463 func_info_map_t funcs(1, func);
1464 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1465 if (q->has_return) // PR13200
1466 {
1467 if (q->sess.verbose > 2)
1468 clog << "ignoring prologue for .return probes" << endl;
1469 }
1470 else
1471 {
1472 if (funcs[0].prologue_end)
1473 addr = funcs[0].prologue_end;
1474 }
6b517475
JS
1475 }
1476 }
1477 else
1478 {
1479 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1480 if (address_line)
1481 {
1482 file = address_line.linesrc();
1483 line = address_line.lineno();
1484 }
1485
1486 // Verify that a raw address matches the beginning of a
1487 // statement. This is a somewhat lame check that the address
1488 // is at the start of an assembly instruction. Mark probes are in the
1489 // middle of a macro and thus not strictly at a statement beginning.
1490 // Guru mode may override this check.
1491 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1492 {
1493 stringstream msg;
2a97f50b 1494 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1495 addr);
6b517475 1496 if (address_line)
2a97f50b 1497 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1498 else
b530b5b3
LB
1499 msg << _F(" (no line info found for '%s', in module '%s')",
1500 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475 1501 if (! q->sess.guru_mode)
dc09353a 1502 throw SEMANTIC_ERROR(msg.str());
2713ea24 1503 else
6b517475
JS
1504 q->sess.print_warning(msg.str());
1505 }
1506 }
1507
1508 // Build a probe at this point
1509 query_statement(dw.function_name, file, line, scope, addr, q);
1510}
1511
8096dd7d
JS
1512static void
1513query_label (string const & func,
1514 char const * label,
1515 char const * file,
1516 int line,
1517 Dwarf_Die *scope_die,
1518 Dwarf_Addr stmt_addr,
1519 dwarf_query * q)
1520{
6b517475
JS
1521 assert (q->has_statement_str || q->has_function_str);
1522
8096dd7d
JS
1523 size_t i = q->results.size();
1524
1525 // weed out functions whose decl_file isn't one of
1526 // the source files that we actually care about
6b517475 1527 if (q->spec_type != function_alone &&
8096dd7d
JS
1528 q->filtered_srcfiles.count(file) == 0)
1529 return;
1530
1531 query_statement(func, file, line, scope_die, stmt_addr, q);
1532
c72aa911
JS
1533 // after the fact, insert the label back into the derivation chain
1534 probe_point::component* ppc =
1535 new probe_point::component(TOK_LABEL, new literal_string (label));
1536 for (; i < q->results.size(); ++i)
1537 {
1538 derived_probe* p = q->results[i];
1539 probe_point* pp = new probe_point(*p->locations[0]);
1540 pp->components.push_back (ppc);
1541 p->base = p->base->create_alias(p->locations[0], pp);
1542 }
8096dd7d
JS
1543}
1544
7e1279ea 1545static void
3e961ba6 1546query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1547 dwarf_query * q)
1548{
b6581717 1549 try
7e1279ea 1550 {
8f14e444
FCE
1551 assert (! q->has_return); // checked by caller already
1552 if (q->sess.verbose>2)
b530b5b3
LB
1553 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1554 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1555 query_statement (ii.name, ii.decl_file, ii.decl_line,
1556 &ii.die, ii.entrypc, q);
7e1279ea 1557 }
b6581717 1558 catch (semantic_error &e)
7e1279ea 1559 {
b6581717 1560 q->sess.print_error (e);
7e1279ea
FCE
1561 }
1562}
1563
1564static void
1565query_func_info (Dwarf_Addr entrypc,
bcc12710 1566 func_info & fi,
7e1279ea
FCE
1567 dwarf_query * q)
1568{
b6581717 1569 try
7e1279ea 1570 {
b6581717
GH
1571 if (q->has_return)
1572 {
1573 // NB. dwarf_derived_probe::emit_registrations will emit a
1574 // kretprobe based on the entrypc in this case.
464379bb
FCE
1575 if (fi.prologue_end != 0 && q->has_return) // PR13200
1576 {
1577 if (q->sess.verbose > 2)
1578 clog << "ignoring prologue for .return probes" << endl;
1579 }
20e4a32c 1580 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1581 &fi.die, entrypc, q);
1582 }
1583 else
1584 {
35dc8b04 1585 if (fi.prologue_end != 0)
44f75386 1586 {
44f75386
FCE
1587 query_statement (fi.name, fi.decl_file, fi.decl_line,
1588 &fi.die, fi.prologue_end, q);
1589 }
1590 else
1591 {
1592 query_statement (fi.name, fi.decl_file, fi.decl_line,
1593 &fi.die, entrypc, q);
1594 }
b6581717 1595 }
7e1279ea 1596 }
b6581717 1597 catch (semantic_error &e)
7e1279ea 1598 {
b6581717 1599 q->sess.print_error (e);
7e1279ea
FCE
1600 }
1601}
1602
1603
bd4b874d
SC
1604static void
1605query_srcfile_label (const dwarf_line_t& line, void * arg)
1606{
1607 dwarf_query * q = static_cast<dwarf_query *>(arg);
1608
1609 Dwarf_Addr addr = line.addr();
1610
1611 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1612 i != q->filtered_functions.end(); ++i)
1613 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1614 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1615 q, query_label);
1616
1617 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1618 i != q->filtered_inlines.end(); ++i)
1619 if (q->dw.die_has_pc (i->die, addr))
1620 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1621 q, query_label);
bd4b874d
SC
1622}
1623
7e1279ea 1624static void
86bf665e 1625query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1626{
1627 dwarf_query * q = static_cast<dwarf_query *>(arg);
1628
86bf665e 1629 Dwarf_Addr addr = line.addr();
4cd232e4 1630
86bf665e 1631 int lineno = line.lineno();
847bf07f 1632
86bf665e 1633 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1634 i != q->filtered_functions.end(); ++i)
1635 {
3e961ba6 1636 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1637 {
b0ee93c4 1638 if (q->sess.verbose>3)
b530b5b3 1639 clog << _("function DIE lands on srcfile\n");
4cd232e4 1640 if (q->has_statement_str)
f5958c8f
JS
1641 {
1642 Dwarf_Die scope;
1643 q->dw.inner_die_containing_pc(i->die, addr, scope);
1644 query_statement (i->name, i->decl_file,
1645 lineno, // NB: not q->line !
1646 &scope, addr, q);
1647 }
4cd232e4 1648 else
3e961ba6 1649 query_func_info (i->entrypc, *i, q);
7e1279ea 1650 }
20e4a32c
RM
1651 }
1652
86bf665e 1653 for (inline_instance_map_t::iterator i
897820ca
GH
1654 = q->filtered_inlines.begin();
1655 i != q->filtered_inlines.end(); ++i)
1656 {
3e961ba6 1657 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1658 {
b0ee93c4 1659 if (q->sess.verbose>3)
b530b5b3 1660 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1661 if (q->has_statement_str)
f5958c8f
JS
1662 {
1663 Dwarf_Die scope;
1664 q->dw.inner_die_containing_pc(i->die, addr, scope);
1665 query_statement (i->name, i->decl_file,
d807e0ab
JS
1666 lineno, // NB: not q->line !
1667 &scope, addr, q);
f5958c8f 1668 }
897820ca 1669 else
3e961ba6 1670 query_inline_instance_info (*i, q);
897820ca 1671 }
20e4a32c 1672 }
7e1279ea
FCE
1673}
1674
1675
7fdd3e2c
JS
1676bool
1677inline_instance_info::operator<(const inline_instance_info& other) const
1678{
1679 if (entrypc != other.entrypc)
1680 return entrypc < other.entrypc;
1681
1682 if (decl_line != other.decl_line)
1683 return decl_line < other.decl_line;
1684
1685 int cmp = name.compare(other.name);
1686 if (!cmp)
1687 cmp = strcmp(decl_file, other.decl_file);
1688 return cmp < 0;
1689}
1690
1691
4fa7b22b 1692static int
7e1279ea 1693query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1694{
1695 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475 1696 assert (q->has_statement_str || q->has_function_str);
4bda987e 1697 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1698
39bcd429 1699 try
7a053d3b 1700 {
b0ee93c4 1701 if (q->sess.verbose>2)
b530b5b3 1702 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1703
6b517475
JS
1704 Dwarf_Addr entrypc;
1705 if (q->dw.die_entrypc (die, &entrypc))
1706 {
1707 inline_instance_info inl;
1708 inl.die = *die;
1709 inl.name = q->dw.function_name;
1710 inl.entrypc = entrypc;
1711 q->dw.function_file (&inl.decl_file);
1712 q->dw.function_line (&inl.decl_line);
1713
1714 // make sure that this inline hasn't already
1715 // been matched from a different CU
1716 if (q->inline_dupes.insert(inl).second)
1717 q->filtered_inlines.push_back(inl);
1718 }
7e1279ea
FCE
1719 return DWARF_CB_OK;
1720 }
1721 catch (const semantic_error& e)
1722 {
1723 q->sess.print_error (e);
1724 return DWARF_CB_ABORT;
1725 }
1726}
bb788f9f 1727
7e1279ea 1728static int
2da9cedb 1729query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1730{
2da9cedb 1731 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1732 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1733
bd25380d
JS
1734 // weed out functions whose decl_file isn't one of
1735 // the source files that we actually care about
6b517475 1736 if (q->spec_type != function_alone &&
bd25380d 1737 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1738 return DWARF_CB_OK;
bd25380d 1739
7e1279ea
FCE
1740 try
1741 {
7e1279ea
FCE
1742 q->dw.focus_on_function (func);
1743
7d6d0afc
JS
1744 if (!q->dw.function_scope_matches(q->scopes))
1745 return DWARF_CB_OK;
1746
857bdfd1
JS
1747 // make sure that this function address hasn't
1748 // already been matched under an aliased name
1749 Dwarf_Addr addr;
1750 if (!q->dw.func_is_inline() &&
1751 dwarf_entrypc(func, &addr) == 0 &&
1752 !q->alias_dupes.insert(addr).second)
1753 return DWARF_CB_OK;
1754
4bda987e 1755 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1756 {
4bda987e 1757 if (q->sess.verbose>3)
b530b5b3 1758 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1759 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1760 }
8f14e444
FCE
1761 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1762 {
1763 q->inlined_non_returnable.insert (q->dw.function_name);
1764 }
396afcee 1765 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1766 {
4bda987e
SC
1767 if (q->has_exported && !q->dw.func_is_exported ())
1768 return DWARF_CB_OK;
6b517475 1769 if (q->sess.verbose>2)
b530b5b3 1770 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1771
1772 func_info func;
1773 q->dw.function_die (&func.die);
1774 func.name = q->dw.function_name;
1775 q->dw.function_file (&func.decl_file);
1776 q->dw.function_line (&func.decl_line);
1777
1778 Dwarf_Addr entrypc;
1779 if (q->dw.function_entrypc (&entrypc))
1780 {
1781 func.entrypc = entrypc;
1782 q->filtered_functions.push_back (func);
1783 }
1784 /* else this function is fully inlined, just ignore it */
7e1279ea 1785 }
39bcd429 1786 return DWARF_CB_OK;
bd2b1e68 1787 }
39bcd429 1788 catch (const semantic_error& e)
bd2b1e68 1789 {
39bcd429
FCE
1790 q->sess.print_error (e);
1791 return DWARF_CB_ABORT;
bd2b1e68 1792 }
bd2b1e68
GH
1793}
1794
1795static int
1796query_cu (Dwarf_Die * cudie, void * arg)
1797{
20c6c071 1798 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1799 assert (q->has_statement_str || q->has_function_str);
1800
85007c04 1801 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1802
39bcd429 1803 try
bd2b1e68 1804 {
7e1279ea 1805 q->dw.focus_on_cu (cudie);
b5d77020 1806
b0ee93c4 1807 if (false && q->sess.verbose>2)
b530b5b3
LB
1808 clog << _F("focused on CU '%s', in module '%s'\n",
1809 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1810
6b517475
JS
1811 q->filtered_srcfiles.clear();
1812 q->filtered_functions.clear();
1813 q->filtered_inlines.clear();
1814
1815 // In this path, we find "abstract functions", record
1816 // information about them, and then (depending on lineno
1817 // matching) possibly emit one or more of the function's
1818 // associated addresses. Unfortunately the control of this
1819 // cannot easily be turned inside out.
1820
1821 if (q->spec_type != function_alone)
39bcd429 1822 {
6b517475
JS
1823 // If we have a pattern string with a filename, we need
1824 // to elaborate the srcfile mask in question first.
1825 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1826
1827 // If we have a file pattern and *no* srcfile matches, there's
1828 // no need to look further into this CU, so skip.
1829 if (q->filtered_srcfiles.empty())
1830 return DWARF_CB_OK;
1831 }
e4c58386 1832
6b517475
JS
1833 // Pick up [entrypc, name, DIE] tuples for all the functions
1834 // matching the query, and fill in the prologue endings of them
1835 // all in a single pass.
5898b6e1 1836 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1837 if (rc != DWARF_CB_OK)
1838 q->query_done = true;
1839
1840 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1841 && !q->has_statement_str) // PR 2608
1842 if (! q->filtered_functions.empty())
1843 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1844 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1845 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1846
1847 if (q->spec_type == function_file_and_line)
1848 {
58b070fb 1849 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1850 if (q->has_function_str)
b530b5b3
LB
1851 q->sess.print_warning (_("For probing a particular line, use a "
1852 ".statement() probe, not .function()"),
af2e341f 1853 q->base_probe->tok);
58b070fb 1854
6b517475
JS
1855 // If we have a pattern string with target *line*, we
1856 // have to look at lines in all the matched srcfiles.
1857 void (* callback) (const dwarf_line_t&, void*) =
1858 q->has_label ? query_srcfile_label : query_srcfile_line;
1859 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1860 i != q->filtered_srcfiles.end(); ++i)
1861 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1862 q->line_type, callback, q->function, q);
1863 }
1864 else if (q->has_label)
1865 {
1866 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1867 i != q->filtered_functions.end(); ++i)
1868 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1869 q, query_label);
1870
1871 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1872 i != q->filtered_inlines.end(); ++i)
1873 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1874 q, query_label);
39bcd429 1875 }
6b517475
JS
1876 else
1877 {
1878 // Otherwise, simply probe all resolved functions.
1879 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1880 i != q->filtered_functions.end(); ++i)
1881 query_func_info (i->entrypc, *i, q);
1882
1883 // And all inline instances (if we're not excluding inlines with ".call")
1884 if (! q->has_call)
1885 for (inline_instance_map_t::iterator i
1886 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1887 query_inline_instance_info (*i, q);
1888 }
39bcd429 1889 return DWARF_CB_OK;
bd2b1e68 1890 }
39bcd429 1891 catch (const semantic_error& e)
bd2b1e68 1892 {
39bcd429
FCE
1893 q->sess.print_error (e);
1894 return DWARF_CB_ABORT;
bd2b1e68 1895 }
bd2b1e68
GH
1896}
1897
0ce64fb8 1898
4df79aaf
JS
1899void
1900dwarf_query::query_module_functions ()
1901{
1902 try
1903 {
1904 filtered_srcfiles.clear();
1905 filtered_functions.clear();
1906 filtered_inlines.clear();
1907
1908 // Collect all module functions so we know which CUs are interesting
1909 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1910 if (rc != DWARF_CB_OK)
1911 {
1912 query_done = true;
1913 return;
1914 }
1915
1916 set<void*> used_cus; // by cu->addr
1917 vector<Dwarf_Die> cus;
1918 Dwarf_Die cu_mem;
1919
1920 for (func_info_map_t::iterator i = filtered_functions.begin();
1921 i != filtered_functions.end(); ++i)
1922 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1923 used_cus.insert(cu_mem.addr).second)
1924 cus.push_back(cu_mem);
1925
1926 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1927 i != filtered_inlines.end(); ++i)
1928 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1929 used_cus.insert(cu_mem.addr).second)
1930 cus.push_back(cu_mem);
1931
1932 // Reset the dupes since we didn't actually collect them the first time
1933 alias_dupes.clear();
1934 inline_dupes.clear();
1935
1936 // Run the query again on the individual CUs
1937 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1938 query_cu(&*i, this);
1939 }
1940 catch (const semantic_error& e)
1941 {
1942 sess.print_error (e);
1943 }
1944}
1945
1946
5f0a03a6
JK
1947static void
1948validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1949{
1950 // Validate the machine code in this elf file against the
1951 // session machine. This is important, in case the wrong kind
1952 // of debuginfo is being automagically processed by elfutils.
1953 // While we can tell i686 apart from x86-64, unfortunately
1954 // we can't help confusing i586 vs i686 (both EM_386).
1955
1956 Dwarf_Addr bias;
1957 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1958 // because dwfl_module_getelf can force costly section relocations
1959 // we don't really need, while either will do for this purpose.
1960 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1961 ?: dwfl_module_getelf (mod, &bias));
1962
1963 GElf_Ehdr ehdr_mem;
1964 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1965 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 1966 assert(em);
5f0a03a6
JK
1967 int elf_machine = em->e_machine;
1968 const char* debug_filename = "";
1969 const char* main_filename = "";
1970 (void) dwfl_module_info (mod, NULL, NULL,
1971 NULL, NULL, NULL,
1972 & main_filename,
1973 & debug_filename);
1974 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1975
1976 string expect_machine; // to match sess.machine (i.e., kernel machine)
1977 string expect_machine2;
5f0a03a6 1978
d27e6fd5 1979 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1980 switch (elf_machine)
1981 {
756c9462
FCE
1982 // x86 and ppc are bi-architecture; a 64-bit kernel
1983 // can normally run either 32-bit or 64-bit *userspace*.
1984 case EM_386:
1985 expect_machine = "i?86";
1986 if (! q->has_process) break; // 32-bit kernel/module
1987 /* FALLSTHROUGH */
1988 case EM_X86_64:
1989 expect_machine2 = "x86_64";
1990 break;
1991 case EM_PPC:
756c9462 1992 case EM_PPC64:
5a1c472e 1993 expect_machine = "powerpc";
756c9462 1994 break;
3fe7d888 1995 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 1996 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 1997 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
1998 // XXX: fill in some more of these
1999 default: expect_machine = "?"; break;
2000 }
2001
2002 if (! debug_filename) debug_filename = main_filename;
2003 if (! debug_filename) debug_filename = name;
2004
756c9462
FCE
2005 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2006 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2007 {
2008 stringstream msg;
b530b5b3
LB
2009 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2010 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2011 sess_machine.c_str(), debug_filename);
dc09353a 2012 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2013 }
2014
b57082de 2015 if (q->sess.verbose>1)
2a97f50b 2016 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2017 " file %s ELF machine %s|%s (code %d)\n",
2018 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2019 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2020 expect_machine2.c_str(), elf_machine);
5f0a03a6 2021}
1d3a40b6 2022
91af0778
FCE
2023
2024
2025static Dwarf_Addr
2026lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2027{
2028 int syments = dwfl_module_getsymtab(m);
2029 assert(syments);
2030 for (int i = 1; i < syments; ++i)
2031 {
2032 GElf_Sym sym;
2033 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2034 if (name != NULL && strcmp(name, wanted) == 0)
2035 return sym.st_value;
2036 }
2037
2038 return 0;
2039}
2040
2041
2042
bd2b1e68 2043static int
b8da0ad1 2044query_module (Dwfl_Module *mod,
91af0778 2045 void **,
b8da0ad1 2046 const char *name,
6f4c1275 2047 Dwarf_Addr addr,
b8da0ad1 2048 void *arg)
bd2b1e68 2049{
91af0778 2050 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 2051
39bcd429 2052 try
e38d6504 2053 {
91af0778
FCE
2054 module_info* mi = q->sess.module_cache->cache[name];
2055 if (mi == 0)
2056 {
2057 mi = q->sess.module_cache->cache[name] = new module_info(name);
2058
6f4c1275
FCE
2059 mi->mod = mod;
2060 mi->addr = addr;
91af0778 2061
6f4c1275
FCE
2062 const char* debug_filename = "";
2063 const char* main_filename = "";
2064 (void) dwfl_module_info (mod, NULL, NULL,
2065 NULL, NULL, NULL,
2066 & main_filename,
2067 & debug_filename);
2068
ab3ed72d 2069 if (debug_filename || main_filename)
91af0778 2070 {
6f4c1275
FCE
2071 mi->elf_path = debug_filename ?: main_filename;
2072 }
2073 else if (name == TOK_KERNEL)
2074 {
2075 mi->dwarf_status = info_absent;
91af0778 2076 }
91af0778
FCE
2077 }
2078 // OK, enough of that module_info caching business.
2079
5f0a03a6 2080 q->dw.focus_on_module(mod, mi);
d9b516ca 2081
39bcd429
FCE
2082 // If we have enough information in the pattern to skip a module and
2083 // the module does not match that information, return early.
b8da0ad1 2084 if (!q->dw.module_name_matches(q->module_val))
85007c04 2085 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2086
2087 // Don't allow module("*kernel*") type expressions to match the
2088 // elfutils module "kernel", which we refer to in the probe
2089 // point syntax exclusively as "kernel.*".
2090 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2091 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2092
5f0a03a6
JK
2093 if (mod)
2094 validate_module_elf(mod, name, q);
2095 else
91af0778
FCE
2096 assert(q->has_kernel); // and no vmlinux to examine
2097
2098 if (q->sess.verbose>2)
b530b5b3 2099 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2100
2101
2102 // Collect a few kernel addresses. XXX: these belong better
2103 // to the sess.module_info["kernel"] struct.
2104 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2105 {
91af0778
FCE
2106 if (! q->sess.sym_kprobes_text_start)
2107 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2108 if (! q->sess.sym_kprobes_text_end)
2109 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2110 if (! q->sess.sym_stext)
2111 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2112 }
2113
47e226ed
SC
2114 // We either have a wildcard or an unresolved library
2115 if (q->has_library && (contains_glob_chars (q->path)
2116 || q->path.find('/') == string::npos))
84c84ac4
SC
2117 // handle .library(GLOB)
2118 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2119 // .plt is translated to .plt.statement(N). We only want to iterate for the
2120 // .plt case
2121 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2122 {
2123 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2124 q->visited_modules.insert(name);
2125 }
84c84ac4 2126 else
070764c0
JL
2127 {
2128 // search the module for matches of the probe point.
2129 q->handle_query_module();
2130 q->visited_modules.insert(name);
2131 }
bb788f9f 2132
b8da0ad1 2133 // If we know that there will be no more matches, abort early.
85007c04 2134 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2135 return DWARF_CB_ABORT;
2136 else
2137 return DWARF_CB_OK;
7a053d3b 2138 }
39bcd429 2139 catch (const semantic_error& e)
bd2b1e68 2140 {
39bcd429
FCE
2141 q->sess.print_error (e);
2142 return DWARF_CB_ABORT;
bd2b1e68 2143 }
bd2b1e68
GH
2144}
2145
35d4ab18 2146
84c84ac4 2147void
5d5bd369 2148base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2149{
2150 base_query *me = (base_query*)q;
5d5bd369 2151 me->query_library (data);
84c84ac4
SC
2152}
2153
2154
2cbcfa9c 2155string
51d6bda3
SC
2156query_one_library (const char *library, dwflpp & dw,
2157 const string user_lib, probe * base_probe, probe_point *base_loc,
2158 vector<derived_probe *> & results)
84c84ac4 2159{
47e226ed 2160 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2161 {
05fb3e0c
WF
2162 string library_path = find_executable (library, "", dw.sess.sysenv,
2163 "LD_LIBRARY_PATH");
84c84ac4
SC
2164 probe_point* specific_loc = new probe_point(*base_loc);
2165 specific_loc->optional = true;
2166 vector<probe_point::component*> derived_comps;
2167
2168 vector<probe_point::component*>::iterator it;
2169 for (it = specific_loc->components.begin();
2170 it != specific_loc->components.end(); ++it)
2171 if ((*it)->functor == TOK_LIBRARY)
2172 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2173 new literal_string(library_path)));
2174 else
2175 derived_comps.push_back(*it);
2176 probe_point* derived_loc = new probe_point(*specific_loc);
2177 derived_loc->components = derived_comps;
8159bf55 2178 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2179 derive_probes(dw.sess, new_base, results);
2180 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2181 clog << _("module=") << library_path << endl;
2182 return library_path;
84c84ac4 2183 }
2cbcfa9c 2184 return "";
84c84ac4
SC
2185}
2186
2187
51d6bda3
SC
2188void
2189dwarf_query::query_library (const char *library)
2190{
2cbcfa9c
JL
2191 string library_path =
2192 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2193 if (!library_path.empty())
2194 visited_modules.insert(library_path);
51d6bda3
SC
2195}
2196
576eaefe
SC
2197struct plt_expanding_visitor: public var_expanding_visitor
2198{
2199 plt_expanding_visitor(const string & entry):
2200 entry (entry)
2201 {
2202 }
2203 const string & entry;
2204
2205 void visit_target_symbol (target_symbol* e);
2206};
2207
2208
2209void
2210base_query::query_plt_callback (void *q, const char *entry, size_t address)
2211{
2212 base_query *me = (base_query*)q;
2213 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2214 me->query_plt (entry, address);
7f4964f1 2215 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2216}
2217
2218
2219void
2220query_one_plt (const char *entry, long addr, dwflpp & dw,
2221 probe * base_probe, probe_point *base_loc,
2222 vector<derived_probe *> & results)
2223{
2224 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2225 vector<probe_point::component*> derived_comps;
2226
2227 if (dw.sess.verbose > 2)
2228 clog << _F("plt entry=%s\n", entry);
2229
2230 // query_module_symtab requires .plt to recognize that it can set the probe at
2231 // a plt entry so we convert process.plt to process.plt.statement
2232 vector<probe_point::component*>::iterator it;
2233 for (it = specific_loc->components.begin();
2234 it != specific_loc->components.end(); ++it)
2235 if ((*it)->functor == TOK_PLT)
3d372d6b 2236 {
8159bf55
FCE
2237 *it = new probe_point::component(TOK_PLT,
2238 new literal_string(entry));
3d372d6b
SC
2239 derived_comps.push_back(*it);
2240 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2241 new literal_number(addr, true)));
3d372d6b 2242 }
576eaefe
SC
2243 else
2244 derived_comps.push_back(*it);
2245 probe_point* derived_loc = new probe_point(*specific_loc);
2246 derived_loc->components = derived_comps;
02c34e38
FCE
2247 probe *new_base = new probe (new probe (base_probe, specific_loc),
2248 derived_loc);
576eaefe
SC
2249 string e = string(entry);
2250 plt_expanding_visitor pltv (e);
2251 pltv.replace (new_base->body);
2252 derive_probes(dw.sess, new_base, results);
2253}
2254
2255
2256void
2257dwarf_query::query_plt (const char *entry, size_t address)
2258{
2259 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2260}
51d6bda3 2261
435f53a7
FCE
2262// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2263// but the needed declaration for module_cache is not available there.
2264// Nor for that matter in session.cxx. Only in this CU is that field ever
2265// set (in query_module() above), so we clean it up here too.
2266static void
2267delete_session_module_cache (systemtap_session& s)
2268{
2269 if (s.module_cache) {
2270 if (s.verbose > 3)
b530b5b3 2271 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2272 delete s.module_cache;
2273 s.module_cache = 0;
2274 }
2275}
2276
2277
de688825 2278struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2279{
77de5e9e 2280 dwarf_query & q;
bcc12710 2281 Dwarf_Die *scope_die;
77de5e9e 2282 Dwarf_Addr addr;
8c819921 2283 block *add_block;
2260f4e3 2284 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2285 // NB: tids are not always collected in add_block & add_call_probe, because
2286 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2287 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2288 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2289 unsigned saved_longs, saved_strings; // data saved within kretprobes
2290 map<std::string, expression *> return_ts_map;
729455a7 2291 vector<Dwarf_Die> scopes;
3689db05 2292 // probe counter name -> pointer of associated probe
698de6cc 2293 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2294 bool visited;
77de5e9e 2295
de688825 2296 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2297 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2298 add_block_tid(false), add_call_probe_tid(false),
af234c40 2299 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2300 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2301 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2302 void visit_target_symbol_saved_return (target_symbol* e);
2303 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2304 void visit_target_symbol (target_symbol* e);
bd1fcbad 2305 void visit_atvar_op (atvar_op* e);
c24447be 2306 void visit_cast_op (cast_op* e);
8cc799a5 2307 void visit_entry_op (entry_op* e);
3689db05 2308 void visit_perf_op (perf_op* e);
729455a7
JS
2309private:
2310 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2311};
2312
2313
de688825 2314unsigned var_expanding_visitor::tick = 0;
77de5e9e 2315
a50de939 2316
74fe61bc 2317var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2318{
2319 // FIXME: for the time being, by default we only support plain '$foo
2320 // = bar', not '+=' or any other op= variant. This is fixable, but a
2321 // bit ugly.
2322 //
2323 // If derived classes desire to add additional operator support, add
2324 // new operators to this list in the derived class constructor.
2325 valid_ops.insert ("=");
2326}
2327
2328
87214add
JS
2329bool
2330var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2331 expression*& lvalue, expression*& rvalue)
77de5e9e 2332{
e57b735a
GH
2333 // Our job would normally be to require() the left and right sides
2334 // into a new assignment. What we're doing is slightly trickier:
2335 // we're pushing a functioncall** onto a stack, and if our left
2336 // child sets the functioncall* for that value, we're going to
2337 // assume our left child was a target symbol -- transformed into a
2338 // set_target_foo(value) call, and it wants to take our right child
2339 // as the argument "value".
2340 //
2341 // This is why some people claim that languages with
2342 // constructor-decomposing case expressions have a leg up on
2343 // visitors.
2344
2345 functioncall *fcall = NULL;
d9b516ca 2346
a50de939 2347 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2348 const string* old_op = op;
2349 op = &eop;
a50de939 2350
e57b735a 2351 target_symbol_setter_functioncalls.push (&fcall);
87214add 2352 replace (lvalue);
e57b735a 2353 target_symbol_setter_functioncalls.pop ();
87214add
JS
2354 replace (rvalue);
2355
2356 op = old_op;
e57b735a
GH
2357
2358 if (fcall != NULL)
77de5e9e 2359 {
e57b735a
GH
2360 // Our left child is informing us that it was a target variable
2361 // and it has been replaced with a set_target_foo() function
2362 // call; we are going to provide that function call -- with the
2363 // right child spliced in as sole argument -- in place of
de688825 2364 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2365
87214add 2366 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2367 {
2368 // Build up a list of supported operators.
2369 string ops;
2370 std::set<string>::iterator i;
b530b5b3 2371 int valid_ops_size = 0;
a50de939 2372 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2373 {
a50de939 2374 ops += " " + *i + ",";
b530b5b3
LB
2375 valid_ops_size++;
2376 }
a50de939
DS
2377 ops.resize(ops.size() - 1); // chop off the last ','
2378
2379 // Throw the error.
dc09353a 2380 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2381 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2382 valid_ops_size, ops.c_str()), tok);
b530b5b3 2383
a50de939 2384 }
e57b735a 2385
87214add
JS
2386 assert (lvalue == fcall);
2387 if (rvalue)
2388 fcall->args.push_back (rvalue);
4ed05b15 2389 provide (fcall);
87214add 2390 return true;
77de5e9e 2391 }
e57b735a 2392 else
87214add
JS
2393 return false;
2394}
2395
2396
2397void
2398var_expanding_visitor::visit_assignment (assignment* e)
2399{
2400 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2401 provide (e);
2402}
2403
2404
2405void
2406var_expanding_visitor::visit_pre_crement (pre_crement* e)
2407{
2408 expression *dummy = NULL;
2409 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2410 provide (e);
2411}
2412
2413
2414void
2415var_expanding_visitor::visit_post_crement (post_crement* e)
2416{
2417 expression *dummy = NULL;
2418 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2419 provide (e);
2420}
2421
2422
2423void
2424var_expanding_visitor::visit_delete_statement (delete_statement* s)
2425{
2426 string fakeop = "delete";
2427 expression *dummy = NULL;
2428 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2429 provide (s);
e57b735a 2430}
d9b516ca 2431
d7f3e0c5 2432
30263a73
FCE
2433void
2434var_expanding_visitor::visit_defined_op (defined_op* e)
2435{
2436 bool resolved = true;
2437
2438 defined_ops.push (e);
2439 try {
2440 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2441 // defined with a target_symbol* operand, a subsidiary call may attempt to
2442 // rewrite it to a general expression* instead, and require<> happily
2443 // casts to/from void*, causing possible memory corruption. We use
2444 // expression* here, being the general case of rewritten $variable.
2445 expression *foo1 = e->operand;
2446 foo1 = require (foo1);
2447
c69a87e0 2448 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2449 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2450 // erroneous resolutions. Some would signal a visit_target_symbol failure
2451 // with an exception, with a set flag within the target_symbol, or nothing
2452 // at all.
30263a73 2453 //
c69a87e0
FCE
2454 // Now, failures always have to be signalled with a
2455 // saved_conversion_error being chained to the target_symbol.
2456 // Successes have to result in an attempted rewrite of the
850bfddd 2457 // target_symbol (via provide()).
780f11ff 2458 //
c69a87e0
FCE
2459 // Edna Mode: "no capes". fche: "no exceptions".
2460
30263a73
FCE
2461 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2462 //
2463 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2464 //
2465 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2466 // dwarf probe to take care of it.
2467 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2468 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2469 //
30263a73
FCE
2470 // utrace: success: rewrites to function; failure: semantic_error
2471 //
850bfddd 2472 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2473
2474 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2475 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2476 resolved = false;
a45664f4 2477 else if (foo2) // unresolved but not marked failing
b7aedf26 2478 {
780f11ff
JS
2479 // There are some visitors that won't touch certain target_symbols,
2480 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2481 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2482 e->operand = foo2;
2483 provide (e);
2484 return;
2485 }
30263a73
FCE
2486 else // resolved, rewritten to some other expression type
2487 resolved = true;
780f11ff 2488 } catch (const semantic_error& e) {
c69a87e0 2489 assert (0); // should not happen
30263a73
FCE
2490 }
2491 defined_ops.pop ();
2492
2493 literal_number* ln = new literal_number (resolved ? 1 : 0);
2494 ln->tok = e->tok;
2495 provide (ln);
2496}
2497
2498
5f36109e
JS
2499struct dwarf_pretty_print
2500{
2501 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2502 const string& local, bool userspace_p,
2503 const target_symbol& e):
d19a9a82
JS
2504 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2505 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2506 {
2507 init_ts (e);
2508 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2509 }
2510
2511 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2512 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2513 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2514 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2515 {
2516 init_ts (e);
2517 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2518 }
2519
2520 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2521 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2522 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2523 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2524 {
2525 init_ts (e);
2526 dw.type_die_for_pointer (type_die, ts, &base_type);
2527 }
2528
2529 functioncall* expand ();
ce83ff57 2530 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2531
2532private:
2533 dwflpp& dw;
2534 target_symbol* ts;
7d11d8c9 2535 bool print_full;
5f36109e
JS
2536 Dwarf_Die base_type;
2537
2538 string local;
2539 vector<Dwarf_Die> scopes;
2540 Dwarf_Addr pc;
2541
2542 expression* pointer;
2543 Dwarf_Die pointer_type;
2544
d19a9a82 2545 const bool userspace_p, deref_p;
5f36109e
JS
2546
2547 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2548 print_format* pf, bool top=false);
600551ca
JS
2549 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2550 print_format* pf);
5f36109e 2551 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2552 print_format* pf);
5f36109e 2553 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2554 print_format* pf, bool top);
5f36109e 2555 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2556 print_format* pf, bool top);
5f36109e 2557 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2558 print_format* pf, bool top);
5f36109e 2559 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2560 print_format* pf, int& count);
bbee5bb8 2561 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2562
2563 void init_ts (const target_symbol& e);
2564 expression* deref (target_symbol* e);
c55ea10d 2565 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2566};
2567
2568
2569void
2570dwarf_pretty_print::init_ts (const target_symbol& e)
2571{
2572 // Work with a new target_symbol so we can modify arguments
2573 ts = new target_symbol (e);
2574
2575 if (ts->addressof)
dc09353a 2576 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2577
2578 if (ts->components.empty() ||
2579 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2580 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2581 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2582 ts->components.pop_back();
2583}
2584
2585
2586functioncall*
2587dwarf_pretty_print::expand ()
2588{
2589 static unsigned tick = 0;
2590
2591 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2592 // try {
2593 // return sprintf("{.foo=...}", (ts)->foo, ...)
2594 // } catch {
2595 // return "ERROR"
2596 // }
5f36109e
JS
2597 // }
2598
2599 // Create the function decl and call.
2600
2601 functiondecl *fdecl = new functiondecl;
2602 fdecl->tok = ts->tok;
2603 fdecl->synthetic = true;
2604 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2605 fdecl->type = pe_string;
2606
2607 functioncall* fcall = new functioncall;
2608 fcall->tok = ts->tok;
2609 fcall->function = fdecl->name;
140be17a 2610 fcall->type = pe_string;
5f36109e
JS
2611
2612 // If there's a <pointer>, replace it with a new var and make that
2613 // the first function argument.
2614 if (pointer)
2615 {
2616 vardecl *v = new vardecl;
2617 v->type = pe_long;
2618 v->name = "pointer";
2619 v->tok = ts->tok;
2620 fdecl->formal_args.push_back (v);
2621 fcall->args.push_back (pointer);
2622
2623 symbol* sym = new symbol;
2624 sym->tok = ts->tok;
2625 sym->name = v->name;
5f36109e
JS
2626 pointer = sym;
2627 }
2628
2629 // For each expression argument, replace it with a function argument.
2630 for (unsigned i = 0; i < ts->components.size(); ++i)
2631 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2632 {
2633 vardecl *v = new vardecl;
2634 v->type = pe_long;
2635 v->name = "index" + lex_cast(i);
2636 v->tok = ts->tok;
2637 fdecl->formal_args.push_back (v);
2638 fcall->args.push_back (ts->components[i].expr_index);
2639
2640 symbol* sym = new symbol;
2641 sym->tok = ts->tok;
2642 sym->name = v->name;
5f36109e
JS
2643 ts->components[i].expr_index = sym;
2644 }
2645
2646 // Create the return sprintf.
2647 token* pf_tok = new token(*ts->tok);
2648 pf_tok->content = "sprintf";
2649 print_format* pf = print_format::create(pf_tok);
2650 return_statement* rs = new return_statement;
2651 rs->tok = ts->tok;
2652 rs->value = pf;
5f36109e
JS
2653
2654 // Recurse into the actual values.
7d11d8c9 2655 recurse (&base_type, ts, pf, true);
5f36109e
JS
2656 pf->components = print_format::string_to_components(pf->raw_components);
2657
7d11d8c9
JS
2658 // Create the try-catch net
2659 try_block* tb = new try_block;
2660 tb->tok = ts->tok;
2661 tb->try_block = rs;
2662 tb->catch_error_var = 0;
2663 return_statement* rs2 = new return_statement;
2664 rs2->tok = ts->tok;
2665 rs2->value = new literal_string ("ERROR");
2666 rs2->value->tok = ts->tok;
2667 tb->catch_block = rs2;
2668 fdecl->body = tb;
2669
f8809d54 2670 fdecl->join (dw.sess);
5f36109e
JS
2671 return fcall;
2672}
2673
2674
2675void
2676dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2677 print_format* pf, bool top)
5f36109e
JS
2678{
2679 Dwarf_Die type;
2680 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2681
2682 switch (dwarf_tag(&type))
2683 {
2684 default:
2685 // XXX need a warning?
2686 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2687 // + ") for " + dwarf_type_name(&type), e->tok);
2688 pf->raw_components.append("?");
2689 break;
2690
2691 case DW_TAG_enumeration_type:
2692 case DW_TAG_base_type:
7d11d8c9 2693 recurse_base (&type, e, pf);
5f36109e
JS
2694 break;
2695
2696 case DW_TAG_array_type:
7d11d8c9 2697 recurse_array (&type, e, pf, top);
5f36109e
JS
2698 break;
2699
2700 case DW_TAG_pointer_type:
2701 case DW_TAG_reference_type:
2702 case DW_TAG_rvalue_reference_type:
7d11d8c9 2703 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2704 break;
2705
2706 case DW_TAG_subroutine_type:
c55ea10d 2707 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2708 break;
2709
2710 case DW_TAG_union_type:
5f36109e
JS
2711 case DW_TAG_structure_type:
2712 case DW_TAG_class_type:
7d11d8c9 2713 recurse_struct (&type, e, pf, top);
5f36109e
JS
2714 break;
2715 }
2716}
2717
2718
600551ca
JS
2719// Bit fields are handled as a special-case combination of recurse() and
2720// recurse_base(), only called from recurse_struct_members(). The main
2721// difference is that the value is always printed numerically, even if the
2722// underlying type is a char.
2723void
2724dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2725 print_format* pf)
2726{
2727 Dwarf_Die type;
2728 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2729
2730 int tag = dwarf_tag(&type);
2731 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2732 {
2733 // XXX need a warning?
2734 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2735 // + ") for " + dwarf_type_name(&type), e->tok);
2736 pf->raw_components.append("?");
2737 return;
2738 }
2739
2740 Dwarf_Attribute attr;
2741 Dwarf_Word encoding = (Dwarf_Word) -1;
2742 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2743 &encoding);
2744 switch (encoding)
2745 {
2746 case DW_ATE_float:
2747 case DW_ATE_complex_float:
2748 // XXX need a warning?
2749 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2750 // + ") for " + dwarf_type_name(&type), e->tok);
2751 pf->raw_components.append("?");
2752 break;
2753
2754 case DW_ATE_unsigned:
2755 case DW_ATE_unsigned_char:
2756 push_deref (pf, "%u", e);
2757 break;
2758
2759 case DW_ATE_signed:
2760 case DW_ATE_signed_char:
2761 default:
2762 push_deref (pf, "%i", e);
2763 break;
2764 }
2765}
2766
2767
5f36109e
JS
2768void
2769dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2770 print_format* pf)
5f36109e
JS
2771{
2772 Dwarf_Attribute attr;
2773 Dwarf_Word encoding = (Dwarf_Word) -1;
2774 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2775 &encoding);
5f36109e
JS
2776 switch (encoding)
2777 {
2778 case DW_ATE_float:
2779 case DW_ATE_complex_float:
2780 // XXX need a warning?
2781 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2782 // + ") for " + dwarf_type_name(type), e->tok);
2783 pf->raw_components.append("?");
5f36109e
JS
2784 break;
2785
6561d8d1 2786 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2787 case DW_ATE_signed_char:
2788 case DW_ATE_unsigned_char:
941101c1
JS
2789 // Use escapes to make sure that non-printable characters
2790 // don't interrupt our stream (especially '\0' values).
2791 push_deref (pf, "'%#c'", e);
5f36109e
JS
2792 break;
2793
2794 case DW_ATE_unsigned:
c55ea10d 2795 push_deref (pf, "%u", e);
5f36109e
JS
2796 break;
2797
600551ca 2798 case DW_ATE_signed:
5f36109e 2799 default:
c55ea10d 2800 push_deref (pf, "%i", e);
5f36109e
JS
2801 break;
2802 }
5f36109e
JS
2803}
2804
2805
2806void
2807dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2808 print_format* pf, bool top)
5f36109e 2809{
7d11d8c9
JS
2810 if (!top && !print_full)
2811 {
2812 pf->raw_components.append("[...]");
2813 return;
2814 }
2815
5f36109e
JS
2816 Dwarf_Die childtype;
2817 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2818
2819 if (print_chars (&childtype, e, pf))
2820 return;
2821
5f36109e
JS
2822 pf->raw_components.append("[");
2823
2824 // We print the array up to the first 5 elements.
2825 // XXX how can we determine the array size?
2826 // ... for now, just print the first element
64cddf39 2827 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2828 unsigned i, size = 1;
64cddf39 2829 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2830 {
2831 if (i > 0)
2832 pf->raw_components.append(", ");
2833 target_symbol* e2 = new target_symbol(*e);
2834 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2835 recurse (&childtype, e2, pf);
5f36109e
JS
2836 }
2837 if (i < size || 1/*XXX until real size is known */)
2838 pf->raw_components.append(", ...");
2839 pf->raw_components.append("]");
2840}
2841
2842
2843void
2844dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2845 print_format* pf, bool top)
5f36109e 2846{
7d11d8c9 2847 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2848 bool void_p = true;
7d11d8c9 2849 Dwarf_Die pointee;
bbee5bb8 2850 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2851 {
2852 try
2853 {
2854 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2855 void_p = false;
2856 }
2857 catch (const semantic_error&) {}
2858 }
2859
2860 if (!void_p)
5f36109e 2861 {
bbee5bb8
JS
2862 if (print_chars (&pointee, e, pf))
2863 return;
2864
2865 if (top)
2866 {
2867 recurse (&pointee, e, pf, top);
2868 return;
2869 }
5f36109e 2870 }
bbee5bb8 2871
c55ea10d 2872 push_deref (pf, "%p", e);
5f36109e
JS
2873}
2874
2875
2876void
2877dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2878 print_format* pf, bool top)
5f36109e 2879{
bdec0e18
JS
2880 if (dwarf_hasattr(type, DW_AT_declaration))
2881 {
a44a7cb5 2882 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2883 if (!resolved)
2884 {
2885 // could be an error, but for now just stub it
2886 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2887 pf->raw_components.append("{...}");
2888 return;
2889 }
2890 type = resolved;
2891 }
2892
5f36109e
JS
2893 int count = 0;
2894 pf->raw_components.append("{");
7d11d8c9
JS
2895 if (top || print_full)
2896 recurse_struct_members (type, e, pf, count);
2897 else
2898 pf->raw_components.append("...");
5f36109e
JS
2899 pf->raw_components.append("}");
2900}
2901
2902
2903void
2904dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2905 print_format* pf, int& count)
5f36109e 2906{
a80f28d8
JS
2907 /* With inheritance, a subclass may mask member names of parent classes, so
2908 * our search among the inheritance tree must be breadth-first rather than
2909 * depth-first (recursive). The type die is still our starting point. When
2910 * we encounter a masked name, just skip it. */
2911 set<string> dupes;
2912 deque<Dwarf_Die> inheritees(1, *type);
2913 for (; !inheritees.empty(); inheritees.pop_front())
2914 {
dee830d9 2915 Dwarf_Die child, childtype, import;
a80f28d8
JS
2916 if (dwarf_child (&inheritees.front(), &child) == 0)
2917 do
2918 {
2919 target_symbol* e2 = e;
5f36109e 2920
a80f28d8
JS
2921 // skip static members
2922 if (dwarf_hasattr(&child, DW_AT_declaration))
2923 continue;
5f36109e 2924
a80f28d8 2925 int tag = dwarf_tag (&child);
5f36109e 2926
dee830d9
MW
2927 /* Pretend imported units contain members by recursing into
2928 struct_member printing with the same count. */
2929 if (tag == DW_TAG_imported_unit
2930 && dwarf_attr_die (&child, DW_AT_import, &import))
2931 recurse_struct_members (&import, e2, pf, count);
2932
a80f28d8
JS
2933 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2934 continue;
5f36109e 2935
a80f28d8 2936 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2937
a80f28d8
JS
2938 if (tag == DW_TAG_inheritance)
2939 {
2940 inheritees.push_back(childtype);
2941 continue;
2942 }
5f36109e 2943
a80f28d8
JS
2944 int childtag = dwarf_tag (&childtype);
2945 const char *member = dwarf_diename (&child);
3a147004 2946
a80f28d8
JS
2947 // "_vptr.foo" members are C++ virtual function tables,
2948 // which (generally?) aren't interesting for users.
2949 if (member && startswith(member, "_vptr."))
2950 continue;
3a147004 2951
a80f28d8
JS
2952 // skip inheritance-masked duplicates
2953 if (member && !dupes.insert(member).second)
2954 continue;
64cddf39 2955
a80f28d8
JS
2956 if (++count > 1)
2957 pf->raw_components.append(", ");
64cddf39 2958
a80f28d8
JS
2959 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2960 if (pf->args.size() >= 32)
2961 {
2962 pf->raw_components.append("...");
2963 break;
2964 }
2965
2966 if (member)
2967 {
2968 pf->raw_components.append(".");
2969 pf->raw_components.append(member);
5f36109e 2970
a80f28d8
JS
2971 e2 = new target_symbol(*e);
2972 e2->components.push_back (target_symbol::component(e->tok, member));
2973 }
2974 else if (childtag == DW_TAG_union_type)
2975 pf->raw_components.append("<union>");
2976 else if (childtag == DW_TAG_structure_type)
2977 pf->raw_components.append("<class>");
2978 else if (childtag == DW_TAG_class_type)
2979 pf->raw_components.append("<struct>");
2980 pf->raw_components.append("=");
600551ca
JS
2981
2982 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
2983 recurse_bitfield (&childtype, e2, pf);
2984 else
2985 recurse (&childtype, e2, pf);
5f36109e 2986 }
a80f28d8
JS
2987 while (dwarf_siblingof (&child, &child) == 0);
2988 }
5f36109e
JS
2989}
2990
2991
bbee5bb8
JS
2992bool
2993dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2994 print_format* pf)
2995{
2996 Dwarf_Die type;
2997 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
2998
2999 Dwarf_Attribute attr;
3000 Dwarf_Word encoding = (Dwarf_Word) -1;
3001 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3002 &encoding);
3003 switch (encoding)
bbee5bb8 3004 {
6561d8d1
JS
3005 case DW_ATE_UTF:
3006 case DW_ATE_signed_char:
3007 case DW_ATE_unsigned_char:
3008 break;
3009 default:
3010 return false;
3011 }
3012
3013 string function = userspace_p ? "user_string2" : "kernel_string2";
3014 Dwarf_Word size = (Dwarf_Word) -1;
3015 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3016 switch (size)
3017 {
3018 case 1:
3019 break;
3020 case 2:
3021 function += "_utf16";
3022 break;
3023 case 4:
3024 function += "_utf32";
3025 break;
3026 default:
3027 return false;
3028 }
3029
3030 if (push_deref (pf, "\"%s\"", e))
3031 {
3032 // steal the last arg for a string access
3033 assert (!pf->args.empty());
3034 functioncall* fcall = new functioncall;
3035 fcall->tok = e->tok;
3036 fcall->function = function;
3037 fcall->args.push_back (pf->args.back());
3038 expression *err_msg = new literal_string ("<unknown>");
3039 err_msg->tok = e->tok;
3040 fcall->args.push_back (err_msg);
3041 pf->args.back() = fcall;
bbee5bb8 3042 }
6561d8d1 3043 return true;
bbee5bb8
JS
3044}
3045
a5ce5211
MW
3046// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3047static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3048 + "#define fetch_register k_fetch_register\n"
3049 + "#define store_register k_store_register\n"
3050 + "#define deref kderef\n"
3051 + "#define store_deref store_kderef\n";
a5ce5211
MW
3052
3053static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3054 + "#define fetch_register u_fetch_register\n"
3055 + "#define store_register u_store_register\n"
3056 + "#define deref uderef\n"
3057 + "#define store_deref store_uderef\n";
a5ce5211
MW
3058
3059#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3060 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3061
3062static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3063 + "#undef fetch_register\n"
3064 + "#undef store_register\n"
3065 + "#undef deref\n"
3066 + "#undef store_deref\n";
bbee5bb8 3067
1c0be8c7
JS
3068static functioncall*
3069synthetic_embedded_deref_call(systemtap_session& session,
3070 const string& function_name,
3071 const string& function_code,
3072 exp_type function_type,
3073 bool userspace_p,
3074 bool lvalue_p,
3075 target_symbol* e,
3076 expression* pointer=NULL)
3077{
3078 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3079 functiondecl *fdecl = new functiondecl;
3080 fdecl->synthetic = true;
3081 fdecl->tok = e->tok;
1c0be8c7
JS
3082 fdecl->name = function_name;
3083 fdecl->type = function_type;
3084
5f36109e
JS
3085 embeddedcode *ec = new embeddedcode;
3086 ec->tok = e->tok;
1c0be8c7
JS
3087 ec->code += "/* unprivileged */";
3088 if (! lvalue_p)
3089 ec->code += "/* pure */";
3090 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3091 ec->code += function_code;
3092 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3093 fdecl->body = ec;
3094
3095 // Synthesize a functioncall.
3096 functioncall* fcall = new functioncall;
3097 fcall->tok = e->tok;
3098 fcall->function = fdecl->name;
1c0be8c7 3099 fcall->type = fdecl->type;
5f36109e 3100
1c0be8c7
JS
3101 // If this code snippet uses a precomputed pointer,
3102 // pass that as the first argument.
5f36109e
JS
3103 if (pointer)
3104 {
5f36109e
JS
3105 vardecl *v = new vardecl;
3106 v->type = pe_long;
3107 v->name = "pointer";
3108 v->tok = e->tok;
3109 fdecl->formal_args.push_back(v);
3110 fcall->args.push_back(pointer);
3111 }
5f36109e 3112
1c0be8c7 3113 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3114 for (unsigned i = 0; i < e->components.size(); ++i)
3115 if (e->components[i].type == target_symbol::comp_expression_array_index)
3116 {
3117 vardecl *v = new vardecl;
3118 v->type = pe_long;
3119 v->name = "index" + lex_cast(i);
3120 v->tok = e->tok;
3121 fdecl->formal_args.push_back(v);
3122 fcall->args.push_back(e->components[i].expr_index);
3123 }
3124
1c0be8c7
JS
3125 // If this code snippet is assigning to an lvalue,
3126 // add a final argument for the rvalue.
3127 if (lvalue_p)
3128 {
3129 // Modify the fdecl so it carries a single pe_long formal
3130 // argument called "value".
5f36109e 3131
1c0be8c7
JS
3132 // FIXME: For the time being we only support setting target
3133 // variables which have base types; these are 'pe_long' in
3134 // stap's type vocabulary. Strings and pointers might be
3135 // reasonable, some day, but not today.
5f36109e 3136
1c0be8c7
JS
3137 vardecl *v = new vardecl;
3138 v->type = pe_long;
3139 v->name = "value";
3140 v->tok = e->tok;
3141 fdecl->formal_args.push_back(v);
3142 // NB: We don't know the value for fcall argument yet.
3143 // (see target_symbol_setter_functioncalls)
3144 }
3145
3146 // Add the synthesized decl to the session, and return the call.
3147 fdecl->join (session);
5f36109e
JS
3148 return fcall;
3149}
3150
1c0be8c7
JS
3151expression*
3152dwarf_pretty_print::deref (target_symbol* e)
3153{
3154 static unsigned tick = 0;
3155
3156 if (!deref_p)
3157 {
3158 assert (pointer && e->components.empty());
3159 return pointer;
3160 }
3161
3162 bool lvalue_p = false;
3163 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3164
3165 string code;
3166 exp_type type = pe_long;
3167 if (pointer)
3168 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3169 else if (!local.empty())
3170 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3171 else
3172 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3173
3174 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3175 userspace_p, lvalue_p, e, pointer);
3176}
3177
5f36109e 3178
c55ea10d
JS
3179bool
3180dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3181 target_symbol* e)
3182{
3183 expression* e2 = NULL;
3184 try
3185 {
3186 e2 = deref (e);
3187 }
3188 catch (const semantic_error&)
3189 {
3190 pf->raw_components.append ("?");
3191 return false;
3192 }
3193 pf->raw_components.append (fmt);
3194 pf->args.push_back (e2);
3195 return true;
3196}
3197
3198
e57b735a 3199void
a7999c82 3200dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3201{
a7999c82
JS
3202 // Get the full name of the target symbol.
3203 stringstream ts_name_stream;
3204 e->print(ts_name_stream);
3205 string ts_name = ts_name_stream.str();
3206
3207 // Check and make sure we haven't already seen this target
3208 // variable in this return probe. If we have, just return our
3209 // last replacement.
af234c40 3210 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3211 if (i != return_ts_map.end())
85ecf79a 3212 {
a7999c82
JS
3213 provide (i->second);
3214 return;
3215 }
85ecf79a 3216
70208613
JS
3217 // Attempt the expansion directly first, so if there's a problem with the
3218 // variable we won't have a bogus entry probe lying around. Like in
3219 // saveargs(), we pretend for a moment that we're not in a .return.
3220 bool saved_has_return = q.has_return;
3221 q.has_return = false;
3222 expression *repl = e;
3223 replace (repl);
3224 q.has_return = saved_has_return;
3225 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3226 if (n && n->saved_conversion_error)
3227 {
3228 provide (repl);
3229 return;
3230 }
3231
af234c40
JS
3232 expression *exp;
3233 if (!q.has_process &&
3234 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3235 exp = gen_kretprobe_saved_return(repl);
af234c40 3236 else
cc9001af 3237 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3238
3239 // Provide the variable to our parent so it can be used as a
3240 // substitute for the target symbol.
3241 provide (exp);
3242
3243 // Remember this replacement since we might be able to reuse
3244 // it later if the same return probe references this target
3245 // symbol again.
3246 return_ts_map[ts_name] = exp;
3247}
3248
4a2970a3 3249static expression*
23dc94f6
DS
3250gen_mapped_saved_return(systemtap_session &sess, expression* e,
3251 const string& name,
3252 block *& add_block, bool& add_block_tid,
3253 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3254{
23dc94f6
DS
3255 static unsigned tick = 0;
3256
a7999c82
JS
3257 // We've got to do several things here to handle target
3258 // variables in return probes.
85ecf79a 3259
a7999c82
JS
3260 // (1) Synthesize two global arrays. One is the cache of the
3261 // target variable and the other contains a thread specific
3262 // nesting level counter. The arrays will look like
3263 // this:
3264 //
23dc94f6
DS
3265 // _entry_tvar_{name}_{num}
3266 // _entry_tvar_{name}_{num}_ctr
a7999c82 3267
23dc94f6 3268 string aname = (string("_entry_tvar_")
cc9001af 3269 + name
aca66a36 3270 + "_" + lex_cast(tick++));
a7999c82
JS
3271 vardecl* vd = new vardecl;
3272 vd->name = aname;
3273 vd->tok = e->tok;
23dc94f6 3274 sess.globals.push_back (vd);
a7999c82
JS
3275
3276 string ctrname = aname + "_ctr";
3277 vd = new vardecl;
3278 vd->name = ctrname;
3279 vd->tok = e->tok;
23dc94f6 3280 sess.globals.push_back (vd);
a7999c82
JS
3281
3282 // (2) Create a new code block we're going to insert at the
3283 // beginning of this probe to get the cached value into a
3284 // temporary variable. We'll replace the target variable
3285 // reference with the temporary variable reference. The code
3286 // will look like this:
3287 //
23dc94f6
DS
3288 // _entry_tvar_tid = tid()
3289 // _entry_tvar_{name}_{num}_tmp
3290 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3291 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3292 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3293 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3294 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3295 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3296
3297 // (2a) Synthesize the tid temporary expression, which will look
3298 // like this:
3299 //
23dc94f6 3300 // _entry_tvar_tid = tid()
a7999c82 3301 symbol* tidsym = new symbol;
23dc94f6 3302 tidsym->name = string("_entry_tvar_tid");
a7999c82 3303 tidsym->tok = e->tok;
85ecf79a 3304
a7999c82
JS
3305 if (add_block == NULL)
3306 {
3307 add_block = new block;
3308 add_block->tok = e->tok;
8cc799a5 3309 }
8c819921 3310
8cc799a5
JS
3311 if (!add_block_tid)
3312 {
a7999c82
JS
3313 // Synthesize a functioncall to grab the thread id.
3314 functioncall* fc = new functioncall;
3315 fc->tok = e->tok;
3316 fc->function = string("tid");
8c819921 3317
23dc94f6 3318 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3319 assignment* a = new assignment;
3320 a->tok = e->tok;
3321 a->op = "=";
a7999c82
JS
3322 a->left = tidsym;
3323 a->right = fc;
8c819921
DS
3324
3325 expr_statement* es = new expr_statement;
3326 es->tok = e->tok;
3327 es->value = a;
8c819921 3328 add_block->statements.push_back (es);
8cc799a5 3329 add_block_tid = true;
a7999c82 3330 }
8c819921 3331
a7999c82
JS
3332 // (2b) Synthesize an array reference and assign it to a
3333 // temporary variable (that we'll use as replacement for the
3334 // target variable reference). It will look like this:
3335 //
23dc94f6
DS
3336 // _entry_tvar_{name}_{num}_tmp
3337 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3338 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3339
3340 arrayindex* ai_tvar_base = new arrayindex;
3341 ai_tvar_base->tok = e->tok;
3342
3343 symbol* sym = new symbol;
3344 sym->name = aname;
3345 sym->tok = e->tok;
3346 ai_tvar_base->base = sym;
3347
3348 ai_tvar_base->indexes.push_back(tidsym);
3349
3350 // We need to create a copy of the array index in its current
3351 // state so we can have 2 variants of it (the original and one
3352 // that post-decrements the second index).
3353 arrayindex* ai_tvar = new arrayindex;
3354 arrayindex* ai_tvar_postdec = new arrayindex;
3355 *ai_tvar = *ai_tvar_base;
3356 *ai_tvar_postdec = *ai_tvar_base;
3357
3358 // Synthesize the
23dc94f6 3359 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3360 // second index into the array.
3361 arrayindex* ai_ctr = new arrayindex;
3362 ai_ctr->tok = e->tok;
3363
3364 sym = new symbol;
3365 sym->name = ctrname;
3366 sym->tok = e->tok;
3367 ai_ctr->base = sym;
3368 ai_ctr->indexes.push_back(tidsym);
3369 ai_tvar->indexes.push_back(ai_ctr);
3370
3371 symbol* tmpsym = new symbol;
3372 tmpsym->name = aname + "_tmp";
3373 tmpsym->tok = e->tok;
3374
3375 assignment* a = new assignment;
3376 a->tok = e->tok;
3377 a->op = "=";
3378 a->left = tmpsym;
3379 a->right = ai_tvar;
3380
3381 expr_statement* es = new expr_statement;
3382 es->tok = e->tok;
3383 es->value = a;
3384
3385 add_block->statements.push_back (es);
3386
3387 // (2c) Add a post-decrement to the second array index and
3388 // delete the array value. It will look like this:
3389 //
23dc94f6
DS
3390 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3391 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3392
3393 post_crement* pc = new post_crement;
3394 pc->tok = e->tok;
3395 pc->op = "--";
3396 pc->operand = ai_ctr;
3397 ai_tvar_postdec->indexes.push_back(pc);
3398
3399 delete_statement* ds = new delete_statement;
3400 ds->tok = e->tok;
3401 ds->value = ai_tvar_postdec;
3402
3403 add_block->statements.push_back (ds);
3404
3405 // (2d) Delete the counter value if it is 0. It will look like
3406 // this:
23dc94f6
DS
3407 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3408 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3409
3410 ds = new delete_statement;
3411 ds->tok = e->tok;
3412 ds->value = ai_ctr;
3413
3414 unary_expression *ue = new unary_expression;
3415 ue->tok = e->tok;
3416 ue->op = "!";
3417 ue->operand = ai_ctr;
3418
3419 if_statement *ifs = new if_statement;
3420 ifs->tok = e->tok;
3421 ifs->condition = ue;
3422 ifs->thenblock = ds;
3423 ifs->elseblock = NULL;
3424
3425 add_block->statements.push_back (ifs);
3426
3427 // (3) We need an entry probe that saves the value for us in the
3428 // global array we created. Create the entry probe, which will
3429 // look like this:
3430 //
2260f4e3 3431 // probe kernel.function("{function}").call {
23dc94f6
DS
3432 // _entry_tvar_tid = tid()
3433 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3434 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3435 // = ${param}
3436 // }
3437
2260f4e3 3438 if (add_call_probe == NULL)
a7999c82 3439 {
2260f4e3
FCE
3440 add_call_probe = new block;
3441 add_call_probe->tok = e->tok;
8cc799a5 3442 }
4baf0e53 3443
8cc799a5
JS
3444 if (!add_call_probe_tid)
3445 {
a7999c82
JS
3446 // Synthesize a functioncall to grab the thread id.
3447 functioncall* fc = new functioncall;
3448 fc->tok = e->tok;
3449 fc->function = string("tid");
4baf0e53 3450
23dc94f6 3451 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3452 assignment* a = new assignment;
8fc05e57
DS
3453 a->tok = e->tok;
3454 a->op = "=";
a7999c82
JS
3455 a->left = tidsym;
3456 a->right = fc;
8fc05e57 3457
a7999c82 3458 expr_statement* es = new expr_statement;
8fc05e57
DS
3459 es->tok = e->tok;
3460 es->value = a;
2260f4e3 3461 add_call_probe = new block(add_call_probe, es);
8cc799a5 3462 add_call_probe_tid = true;
85ecf79a 3463 }
cf2a1f85 3464
a7999c82 3465 // Save the value, like this:
23dc94f6
DS
3466 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3467 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3468 // = ${param}
3469 arrayindex* ai_tvar_preinc = new arrayindex;
3470 *ai_tvar_preinc = *ai_tvar_base;
3471
3472 pre_crement* preinc = new pre_crement;
3473 preinc->tok = e->tok;
3474 preinc->op = "++";
3475 preinc->operand = ai_ctr;
3476 ai_tvar_preinc->indexes.push_back(preinc);
3477
3478 a = new assignment;
3479 a->tok = e->tok;
3480 a->op = "=";
3481 a->left = ai_tvar_preinc;
3482 a->right = e;
3483
3484 es = new expr_statement;
3485 es->tok = e->tok;
3486 es->value = a;
3487
2260f4e3 3488 add_call_probe = new block(add_call_probe, es);
a7999c82 3489
23dc94f6 3490 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3491 // our parent so it can be used as a substitute for the target
3492 // symbol.
3f803f9e 3493 delete ai_tvar_base;
af234c40
JS
3494 return tmpsym;
3495}
a7999c82 3496
af234c40 3497
23dc94f6
DS
3498expression*
3499dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3500 const string& name)
3501{
3502 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3503 add_block_tid, add_call_probe,
3504 add_call_probe_tid);
3505}
3506
3507
af234c40 3508expression*
140be17a 3509dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3510{
3511 // The code for this is simple.
3512 //
3513 // .call:
3514 // _set_kretprobe_long(index, $value)
3515 //
3516 // .return:
3517 // _get_kretprobe_long(index)
3518 //
3519 // (or s/long/string/ for things like $$parms)
3520
3521 unsigned index;
3522 string setfn, getfn;
3523
140be17a
JS
3524 // We need the caller to predetermine the type of the expression!
3525 switch (e->type)
af234c40 3526 {
140be17a 3527 case pe_string:
af234c40
JS
3528 index = saved_strings++;
3529 setfn = "_set_kretprobe_string";
3530 getfn = "_get_kretprobe_string";
140be17a
JS
3531 break;
3532 case pe_long:
af234c40
JS
3533 index = saved_longs++;
3534 setfn = "_set_kretprobe_long";
3535 getfn = "_get_kretprobe_long";
140be17a
JS
3536 break;
3537 default:
dc09353a 3538 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3539 }
3540
3541 // Create the entry code
3542 // _set_kretprobe_{long|string}(index, $value)
3543
3544 if (add_call_probe == NULL)
3545 {
3546 add_call_probe = new block;
3547 add_call_probe->tok = e->tok;
3548 }
3549
3550 functioncall* set_fc = new functioncall;
3551 set_fc->tok = e->tok;
3552 set_fc->function = setfn;
3553 set_fc->args.push_back(new literal_number(index));
3554 set_fc->args.back()->tok = e->tok;
3555 set_fc->args.push_back(e);
3556
3557 expr_statement* set_es = new expr_statement;
3558 set_es->tok = e->tok;
3559 set_es->value = set_fc;
3560
3561 add_call_probe->statements.push_back(set_es);
3562
3563 // Create the return code
3564 // _get_kretprobe_{long|string}(index)
3565
3566 functioncall* get_fc = new functioncall;
3567 get_fc->tok = e->tok;
3568 get_fc->function = getfn;
3569 get_fc->args.push_back(new literal_number(index));
3570 get_fc->args.back()->tok = e->tok;
3571
3572 return get_fc;
a7999c82 3573}
a43ba433 3574
2cb3fe26 3575
a7999c82
JS
3576void
3577dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3578{
9aa8ffce 3579 if (null_die(scope_die))
a7999c82 3580 return;
2cb3fe26 3581
5f36109e
JS
3582 target_symbol *tsym = new target_symbol(*e);
3583
fde50242
JS
3584 bool pretty = (!e->components.empty() &&
3585 e->components[0].type == target_symbol::comp_pretty_print);
3586 string format = pretty ? "=%s" : "=%#x";
a43ba433 3587
a7999c82
JS
3588 // Convert $$parms to sprintf of a list of parms and active local vars
3589 // which we recursively evaluate
a43ba433 3590
a7999c82
JS
3591 // NB: we synthesize a new token here rather than reusing
3592 // e->tok, because print_format::print likes to use
3593 // its tok->content.
5f36109e 3594 token* pf_tok = new token(*e->tok);
a7999c82 3595 pf_tok->type = tok_identifier;
b393f6f2 3596 pf_tok->content = "sprintf";
2cb3fe26 3597
d5e178c1 3598 print_format* pf = print_format::create(pf_tok);
a7999c82 3599
277c21bc 3600 if (q.has_return && (e->name == "$$return"))
a7999c82 3601 {
277c21bc 3602 tsym->name = "$return";
a7999c82
JS
3603
3604 // Ignore any variable that isn't accessible.
3605 tsym->saved_conversion_error = 0;
3606 expression *texp = tsym;
8b095b45 3607 replace (texp); // NB: throws nothing ...
a7999c82 3608 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3609 {
2cb3fe26 3610
a43ba433
FCE
3611 }
3612 else
3613 {
a7999c82 3614 pf->raw_components += "return";
5f36109e 3615 pf->raw_components += format;
a7999c82
JS
3616 pf->args.push_back(texp);
3617 }
3618 }
3619 else
3620 {
3621 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3622 bool first = true;
a7999c82 3623 Dwarf_Die result;
d48bc7eb
JS
3624 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3625 for (unsigned i = 0; i < scopes.size(); ++i)
3626 {
3627 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3628 break; // we don't want file-level variables
3629 if (dwarf_child (&scopes[i], &result) == 0)
3630 do
00cf3709 3631 {
d48bc7eb
JS
3632 switch (dwarf_tag (&result))
3633 {
3634 case DW_TAG_variable:
3635 if (e->name == "$$parms")
3636 continue;
3637 break;
3638 case DW_TAG_formal_parameter:
3639 if (e->name == "$$locals")
3640 continue;
3641 break;
3642
3643 default:
3644 continue;
3645 }
41c262f3 3646
d48bc7eb
JS
3647 const char *diename = dwarf_diename (&result);
3648 if (! diename) continue;
f76427a2 3649
d48bc7eb
JS
3650 if (! first)
3651 pf->raw_components += " ";
3652 pf->raw_components += diename;
fde50242
JS
3653 first = false;
3654
3655 // Write a placeholder for ugly aggregates
3656 Dwarf_Die type;
3657 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3658 {
3659 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3660 switch (dwarf_tag(&type))
3661 {
3662 case DW_TAG_union_type:
3663 case DW_TAG_structure_type:
3664 case DW_TAG_class_type:
3665 pf->raw_components += "={...}";
3666 continue;
3667
3668 case DW_TAG_array_type:
3669 pf->raw_components += "=[...]";
3670 continue;
3671 }
3672 }
345bbb3d 3673
d48bc7eb
JS
3674 tsym->name = "$";
3675 tsym->name += diename;
41c262f3 3676
d48bc7eb
JS
3677 // Ignore any variable that isn't accessible.
3678 tsym->saved_conversion_error = 0;
3679 expression *texp = tsym;
3680 replace (texp); // NB: throws nothing ...
3681 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3682 {
d48bc7eb
JS
3683 if (q.sess.verbose>2)
3684 {
e26c2f83 3685 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb
JS
3686 c != 0;
3687 c = c->chain) {
4c5d9906 3688 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3689 }
3690 }
3691
3692 pf->raw_components += "=?";
a43ba433 3693 }
d48bc7eb
JS
3694 else
3695 {
3696 pf->raw_components += format;
3697 pf->args.push_back(texp);
3698 }
a7999c82 3699 }
d48bc7eb
JS
3700 while (dwarf_siblingof (&result, &result) == 0);
3701 }
a7999c82 3702 }
2cb3fe26 3703
a7999c82 3704 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3705 pf->type = pe_string;
a7999c82
JS
3706 provide (pf);
3707}
3708
2cb3fe26 3709
bd1fcbad
YZ
3710void
3711dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3712{
3713 // Fill in our current module context if needed
3714 if (e->module.empty())
3715 e->module = q.dw.module_name;
3716
3717 if (e->module == q.dw.module_name && e->cu_name.empty())
3718 {
3719 // process like any other local
3720 // e->sym_name() will do the right thing
3721 visit_target_symbol(e);
3722 return;
3723 }
3724
3725 var_expanding_visitor::visit_atvar_op(e);
3726}
3727
3728
a7999c82
JS
3729void
3730dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3731{
bd1fcbad 3732 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3733 visited = true;
30263a73
FCE
3734 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3735 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3736
70208613 3737 try
a7999c82 3738 {
c69a87e0
FCE
3739 bool lvalue = is_active_lvalue(e);
3740 if (lvalue && !q.sess.guru_mode)
dc09353a 3741 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3742
100a540e 3743 // XXX: process $context vars should be writable
70208613 3744
c69a87e0
FCE
3745 // See if we need to generate a new probe to save/access function
3746 // parameters from a return probe. PR 1382.
3747 if (q.has_return
3748 && !defined_being_checked
277c21bc
JS
3749 && e->name != "$return" // not the special return-value variable handled below
3750 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3751 {
3752 if (lvalue)
dc09353a 3753 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3754 visit_target_symbol_saved_return(e);
3755 return;
3756 }
e57b735a 3757
277c21bc
JS
3758 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3759 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3760 {
3761 if (lvalue)
dc09353a 3762 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3763
c69a87e0 3764 if (e->addressof)
dc09353a 3765 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3766
5f36109e
JS
3767 e->assert_no_components("dwarf", true);
3768
c69a87e0
FCE
3769 visit_target_symbol_context(e);
3770 return;
3771 }
70208613 3772
5f36109e
JS
3773 if (!e->components.empty() &&
3774 e->components.back().type == target_symbol::comp_pretty_print)
3775 {
3776 if (lvalue)
dc09353a 3777 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3778
277c21bc 3779 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3780 {
3781 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3782 q.has_process, *e);
3783 dpp.expand()->visit(this);
3784 }
3785 else
3786 {
3787 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3788 e->sym_name(),
5f36109e
JS
3789 q.has_process, *e);
3790 dpp.expand()->visit(this);
3791 }
3792 return;
3793 }
3794
1c0be8c7 3795 bool userspace_p = q.has_process;
c69a87e0 3796 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3797 + "_" + e->sym_name()
c69a87e0 3798 + "_" + lex_cast(tick++));
70208613 3799
70208613 3800
1c0be8c7
JS
3801 exp_type type = pe_long;
3802 string code;
277c21bc 3803 if (q.has_return && (e->name == "$return"))
1c0be8c7 3804 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 3805 else
1c0be8c7
JS
3806 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
3807 e, lvalue, type);
70208613 3808
1c0be8c7
JS
3809 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
3810 userspace_p, lvalue, e);
70208613 3811
c69a87e0
FCE
3812 if (lvalue)
3813 {
3814 // Provide the functioncall to our parent, so that it can be
3815 // used to substitute for the assignment node immediately above
3816 // us.
3817 assert(!target_symbol_setter_functioncalls.empty());
3818 *(target_symbol_setter_functioncalls.top()) = n;
3819 }
70208613 3820
1c0be8c7
JS
3821 // Revisit the functioncall so arguments can be expanded.
3822 n->visit (this);
66d284f4
FCE
3823 }
3824 catch (const semantic_error& er)
3825 {
9fab2262
JS
3826 // We suppress this error message, and pass the unresolved
3827 // target_symbol to the next pass. We hope that this value ends
3828 // up not being referenced after all, so it can be optimized out
3829 // quietly.
1af1e62d 3830 e->chain (er);
9fab2262 3831 provide (e);
66d284f4 3832 }
77de5e9e
GH
3833}
3834
3835
c24447be
JS
3836void
3837dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3838{
3839 // Fill in our current module context if needed
3840 if (e->module.empty())
3841 e->module = q.dw.module_name;
3842
3843 var_expanding_visitor::visit_cast_op(e);
3844}
3845
3846
8cc799a5
JS
3847void
3848dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3849{
3850 expression *repl = e;
3851 if (q.has_return)
3852 {
3853 // expand the operand as if it weren't a return probe
3854 q.has_return = false;
3855 replace (e->operand);
3856 q.has_return = true;
3857
3858 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3859 // but it requires knowing the types already, which is problematic for
3860 // arbitrary expressons.
cc9001af 3861 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3862 }
3863 provide (repl);
3864}
3865
3689db05
SC
3866void
3867dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
3868{
3869 token* t = new token;
ace7c23f 3870 string e_lit_val = e->operand->value;
3689db05
SC
3871
3872 t->location = e->tok->location;
3873 t->type = tok_identifier;
3874 t->content = e_lit_val;
3875
3876 add_block = new block;
3877
3878 systemtap_session &s = this->q.sess;
3879 map<string, pair<string,derived_probe*> >::iterator it;
3880 // Find the associated perf.counter probe
3881 for (it=s.perf_counters.begin();
3882 it != s.perf_counters.end();
3883 it++)
3884 if ((*it).first == e_lit_val)
3885 {
3886 // if perf .function("name") omitted, then set it to this process name
3887 if ((*it).second.first.length() == 0)
3888 ((*it).second).first = this->q.user_path;
3889 if (((*it).second).first == this->q.user_path)
3890 break;
3891 }
3892
3893 if (it != s.perf_counters.end())
3894 {
698de6cc 3895 perf_counter_refs.insert((*it).second.second);
3689db05
SC
3896 // __perf_read_N is assigned in the probe prologue
3897 symbol* sym = new symbol;
3898 sym->tok = t;
3899 sym->name = "__perf_read_" + (*it).first;
3900 provide (sym);
3901 }
3902 else
dc09353a 3903 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
3904}
3905
8cc799a5 3906
729455a7
JS
3907vector<Dwarf_Die>&
3908dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3909{
3910 if (scopes.empty())
3911 {
f25a9197
CM
3912 if(scope_die != NULL)
3913 scopes = q.dw.getscopes(scope_die);
729455a7 3914 if (scopes.empty())
b530b5b3
LB
3915 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3916 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 3917 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7
JS
3918 + lex_cast_hex(addr)
3919 + ((scope_die == NULL) ? ""
3920 : (string (" in ")
3921 + (dwarf_diename(scope_die) ?: "<unknown>")
3922 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3923 + ")"))
3924 + " while searching for local '"
cc9001af 3925 + e->sym_name() + "'",
729455a7
JS
3926 e->tok);
3927 }
3928 return scopes;
3929}
3930
3931
5f36109e
JS
3932struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3933{
3934 systemtap_session& s;
3935 dwarf_builder& db;
3936
3937 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3938 s(s), db(db) {}
3939 void visit_cast_op (cast_op* e);
3940 void filter_special_modules(string& module);
3941};
3942
3943
c4ce66a1
JS
3944struct dwarf_cast_query : public base_query
3945{
946e1a48 3946 cast_op& e;
c4ce66a1 3947 const bool lvalue;
5f36109e
JS
3948 const bool userspace_p;
3949 functioncall*& result;
c4ce66a1 3950
5f36109e
JS
3951 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3952 const bool userspace_p, functioncall*& result):
abb41d92 3953 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3954 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3955
3956 void handle_query_module();
822a6a3d 3957 void query_library (const char *) {}
576eaefe 3958 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3959};
3960
3961
c4ce66a1
JS
3962void
3963dwarf_cast_query::handle_query_module()
3964{
5f36109e
JS
3965 static unsigned tick = 0;
3966
3967 if (result)
c4ce66a1
JS
3968 return;
3969
ea1e477a 3970 // look for the type in any CU
a44a7cb5
JS
3971 Dwarf_Die* type_die = NULL;
3972 if (startswith(e.type_name, "class "))
3973 {
3974 // normalize to match dwflpp::global_alias_caching_callback
3975 string struct_name = "struct " + e.type_name.substr(6);
3976 type_die = dw.declaration_resolve_other_cus(struct_name);
3977 }
3978 else
3979 type_die = dw.declaration_resolve_other_cus(e.type_name);
3980
3981 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3982 // just "name". But since we didn't require users to be explicit before, and
3983 // actually sort of discouraged it, we must be flexible now. So if a lookup
3984 // fails with a bare name, try augmenting it.
3985 if (!type_die &&
3986 !startswith(e.type_name, "class ") &&
3987 !startswith(e.type_name, "struct ") &&
3988 !startswith(e.type_name, "union ") &&
3989 !startswith(e.type_name, "enum "))
3990 {
3991 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3992 if (!type_die)
3993 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3994 if (!type_die)
3995 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3996 }
3997
ea1e477a
JS
3998 if (!type_die)
3999 return;
c4ce66a1 4000
5f36109e
JS
4001 string code;
4002 exp_type type = pe_long;
4003
ea1e477a 4004 try
c4ce66a1 4005 {
ea1e477a
JS
4006 Dwarf_Die cu_mem;
4007 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4008
4009 if (!e.components.empty() &&
4010 e.components.back().type == target_symbol::comp_pretty_print)
4011 {
4012 if (lvalue)
dc09353a 4013 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4014
d19a9a82 4015 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4016 result = dpp.expand();
4017 return;
4018 }
4019
4020 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4021 }
4022 catch (const semantic_error& er)
4023 {
4024 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4025 // may be attempted using several different modules:
4026 // @cast(ptr, "type", "module1:module2:...")
4027 e.chain (er);
c4ce66a1 4028 }
c4ce66a1 4029
5f36109e
JS
4030 if (code.empty())
4031 return;
c4ce66a1 4032
5f36109e 4033 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4034 + "_" + e.sym_name()
5f36109e 4035 + "_" + lex_cast(tick++));
c4ce66a1 4036
1c0be8c7
JS
4037 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4038 userspace_p, lvalue, &e, e.operand);
5f36109e 4039}
c4ce66a1
JS
4040
4041
fb0274bc
JS
4042void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4043{
d90053e7 4044 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4045 // for those cases, build a module including that header
d90053e7 4046 if (module[module.size() - 1] == '>' &&
60d98537 4047 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4048 {
4049 string cached_module;
4050 if (s.use_cache)
4051 {
4052 // see if the cached module exists
a2639cb7 4053 cached_module = find_typequery_hash(s, module);
d105f664 4054 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4055 {
4056 int fd = open(cached_module.c_str(), O_RDONLY);
4057 if (fd != -1)
4058 {
4059 if (s.verbose > 2)
b530b5b3
LB
4060 //TRANSLATORS: Here we're using a cached module.
4061 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4062 module = cached_module;
4063 close(fd);
4064 return;
4065 }
4066 }
4067 }
4068
4069 // no cached module, time to make it
d90053e7 4070 if (make_typequery(s, module) == 0)
fb0274bc 4071 {
e16dc041 4072 // try to save typequery in the cache
fb0274bc 4073 if (s.use_cache)
e16dc041 4074 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4075 }
4076 }
4077}
4078
4079
c4ce66a1
JS
4080void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4081{
4082 bool lvalue = is_active_lvalue(e);
4083 if (lvalue && !s.guru_mode)
dc09353a 4084 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4085
4086 if (e->module.empty())
4087 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4088
5f36109e 4089 functioncall* result = NULL;
8b31197b
JS
4090
4091 // split the module string by ':' for alternatives
4092 vector<string> modules;
4093 tokenize(e->module, modules, ":");
b5a0dd41 4094 bool userspace_p=false; // PR10601
5f36109e 4095 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4096 {
8b31197b 4097 string& module = modules[i];
fb0274bc 4098 filter_special_modules(module);
abb41d92 4099
c4ce66a1
JS
4100 // NB: This uses '/' to distinguish between kernel modules and userspace,
4101 // which means that userspace modules won't get any PATH searching.
4102 dwflpp* dw;
707bf35e
JS
4103 try
4104 {
b5a0dd41
FCE
4105 userspace_p=is_user_module (module);
4106 if (! userspace_p)
707bf35e
JS
4107 {
4108 // kernel or kernel module target
ae2552da 4109 dw = db.get_kern_dw(s, module);
707bf35e
JS
4110 }
4111 else
4112 {
05fb3e0c 4113 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4114 dw = db.get_user_dw(s, module);
4115 }
4116 }
4117 catch (const semantic_error& er)
4118 {
4119 /* ignore and go to the next module */
4120 continue;
4121 }
c4ce66a1 4122
5f36109e 4123 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 4124 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 4125 }
abb41d92 4126
5f36109e 4127 if (!result)
c4ce66a1 4128 {
946e1a48
JS
4129 // We pass the unresolved cast_op to the next pass, and hope
4130 // that this value ends up not being referenced after all, so
4131 // it can be optimized out quietly.
c4ce66a1
JS
4132 provide (e);
4133 return;
4134 }
4135
c4ce66a1
JS
4136 if (lvalue)
4137 {
4138 // Provide the functioncall to our parent, so that it can be
4139 // used to substitute for the assignment node immediately above
4140 // us.
4141 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4142 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4143 }
4144
5f36109e 4145 result->visit (this);
77de5e9e
GH
4146}
4147
4148
bd1fcbad
YZ
4149struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4150{
4151 systemtap_session& s;
4152 dwarf_builder& db;
4153
4154 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4155 s(s), db(db) {}
4156 void visit_atvar_op (atvar_op* e);
4157};
4158
4159
4160struct dwarf_atvar_query: public base_query
4161{
4162 atvar_op& e;
4163 const bool userspace_p, lvalue;
4164 functioncall*& result;
4165 unsigned& tick;
4166 const string cu_name_pattern;
4167
4168 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4169 const bool userspace_p, const bool lvalue,
4170 functioncall*& result,
4171 unsigned& tick):
4172 base_query(dw, module), e(e),
4173 userspace_p(userspace_p), lvalue(lvalue), result(result),
4174 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4175
4176 void handle_query_module ();
4177 void query_library (const char *) {}
4178 void query_plt (const char *entry, size_t addr) {}
4179 static int atvar_query_cu (Dwarf_Die *cudie, void *data);
4180};
4181
4182
4183int
4184dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, void * data)
4185{
4186 dwarf_atvar_query * q = static_cast<dwarf_atvar_query *>(data);
4187
4188 if (! q->e.cu_name.empty())
4189 {
4190 const char *die_name = dwarf_diename(cudie);
4191
4192 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4193 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4194 {
4195 return DWARF_CB_OK;
4196 }
4197 }
4198
4199 try
4200 {
4201 vector<Dwarf_Die> scopes(1, *cudie);
4202
4203 q->dw.focus_on_cu (cudie);
4204
4205 if (! q->e.components.empty() &&
4206 q->e.components.back().type == target_symbol::comp_pretty_print)
4207 {
4208 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4209 q->userspace_p, q->e);
4210 q->result = dpp.expand();
4211 return DWARF_CB_ABORT;
4212 }
4213
4214 exp_type type = pe_long;
4215 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4216 &q->e, q->lvalue, type);
4217
4218 if (code.empty())
4219 return DWARF_CB_OK;
4220
4221 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4222 : "_dwarf_tvar_get")
4223 + "_" + q->e.sym_name()
4224 + "_" + lex_cast(q->tick++));
4225
4226 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4227 q->userspace_p, q->lvalue,
4228 &q->e);
4229 }
4230 catch (const semantic_error& er)
4231 {
4232 // Here we suppress the error because we often just have too many
4233 // when scanning all the CUs.
4234 return DWARF_CB_OK;
4235 }
4236
4237 if (q->result) {
4238 return DWARF_CB_ABORT;
4239 }
4240
4241 return DWARF_CB_OK;
4242}
4243
4244
4245void
4246dwarf_atvar_query::handle_query_module ()
4247{
4248
4249 dw.iterate_over_cus(atvar_query_cu, this, false);
4250}
4251
4252
4253void
4254dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4255{
4256 const bool lvalue = is_active_lvalue(e);
4257 if (lvalue && !s.guru_mode)
dc09353a 4258 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4259 "need stap -g"), e->tok);
4260
4261 if (e->module.empty())
4262 e->module = "kernel";
4263
4264 functioncall* result = NULL;
4265
4266 // split the module string by ':' for alternatives
4267 vector<string> modules;
4268 tokenize(e->module, modules, ":");
4269 bool userspace_p = false;
4270 for (unsigned i = 0; !result && i < modules.size(); ++i)
4271 {
4272 string& module = modules[i];
4273
4274 dwflpp* dw;
4275 try
4276 {
4277 userspace_p = is_user_module(module);
4278 if (!userspace_p)
4279 {
4280 // kernel or kernel module target
4281 dw = db.get_kern_dw(s, module);
4282 }
4283 else
4284 {
4285 module = find_executable(module, "", s.sysenv);
4286 dw = db.get_user_dw(s, module);
4287 }
4288 }
4289 catch (const semantic_error& er)
4290 {
4291 /* ignore and go to the next module */
4292 continue;
4293 }
4294
4295 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
4296 dw->iterate_over_modules(&query_module, &q);
4297
4298 if (result)
4299 {
4300 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4301
4302 if (lvalue)
4303 {
4304 // Provide the functioncall to our parent, so that it can be
4305 // used to substitute for the assignment node immediately above
4306 // us.
4307 assert(!target_symbol_setter_functioncalls.empty());
4308 *(target_symbol_setter_functioncalls.top()) = result;
4309 }
4310
4311 result->visit(this);
4312 return;
4313 }
4314
4315 /* Unable to find the variable in the current module, so we chain
4316 * an error in atvar_op */
dc09353a 4317 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4318 e->sym_name().c_str(), module.c_str(),
4319 e->cu_name.empty() ? "" : _(", in "),
4320 e->cu_name.c_str()));
4321 e->chain (er);
4322 }
4323
4324 provide(e);
4325}
4326
4327
b8da0ad1
FCE
4328void
4329dwarf_derived_probe::printsig (ostream& o) const
4330{
4331 // Instead of just printing the plain locations, we add a PC value
4332 // as a comment as a way of telling e.g. apart multiple inlined
4333 // function instances. This is distinct from the verbose/clog
4334 // output, since this part goes into the cache hash calculations.
4335 sole_location()->print (o);
6d0f3f0c 4336 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4337 printsig_nested (o);
4338}
4339
4340
4341
dc38c0ae 4342void
b20febf3
FCE
4343dwarf_derived_probe::join_group (systemtap_session& s)
4344{
af234c40
JS
4345 // skip probes which are paired entry-handlers
4346 if (!has_return && (saved_longs || saved_strings))
4347 return;
4348
b20febf3
FCE
4349 if (! s.dwarf_derived_probes)
4350 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4351 s.dwarf_derived_probes->enroll (this);
4352}
4353
4354
2b69faaf
JS
4355static bool
4356kernel_supports_inode_uprobes(systemtap_session& s)
4357{
4358 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4359 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4360 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4361 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4362 && s.kernel_config["CONFIG_UPROBES"] == "y");
4363}
4364
4365
3667d615
JS
4366static bool
4367kernel_supports_inode_uretprobes(systemtap_session& s)
4368{
766013af
JS
4369 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4370 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4371 return kernel_supports_inode_uprobes(s) &&
af9e147f 4372 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4373}
4374
4375
5261f7ab
DS
4376void
4377check_process_probe_kernel_support(systemtap_session& s)
4378{
4379 // If we've got utrace, we're good to go.
4380 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4381 return;
4382
8c021542
DS
4383 // We don't have utrace. For process probes that aren't
4384 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4385 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4386 // specific autoconf test for its needs.
8c021542
DS
4387 //
4388 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4389 // approximation.
4390 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4391 return;
4392
d3e959b0
DS
4393 // For uprobes-based process probes, we need the task_finder plus
4394 // the builtin inode-uprobes.
8c021542
DS
4395 if (s.need_uprobes
4396 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4397 && kernel_supports_inode_uprobes(s))
8c021542
DS
4398 return;
4399
dc09353a 4400 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4401}
4402
4403
b20febf3
FCE
4404dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4405 const string& filename,
4406 int line,
91af0778 4407 // module & section specify a relocation
b20febf3
FCE
4408 // base for <addr>, unless section==""
4409 // (equivalently module=="kernel")
4410 const string& module,
4411 const string& section,
4412 // NB: dwfl_addr is the virtualized
4413 // address for this symbol.
4414 Dwarf_Addr dwfl_addr,
4415 // addr is the section-offset for
4416 // actual relocation.
4417 Dwarf_Addr addr,
4418 dwarf_query& q,
37ebca01 4419 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4420 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4421 module (module), section (section), addr (addr),
63b4fd14 4422 path (q.path),
27dc09b1 4423 has_process (q.has_process),
c9bad430
DS
4424 has_return (q.has_return),
4425 has_maxactive (q.has_maxactive),
c57ea854 4426 has_library (q.has_library),
6b66b9f7 4427 maxactive_val (q.maxactive_val),
b642c901
SC
4428 user_path (q.user_path),
4429 user_lib (q.user_lib),
af234c40 4430 access_vars(false),
c57ea854 4431 saved_longs(0), saved_strings(0),
af234c40 4432 entry_handler(0)
bd2b1e68 4433{
b642c901
SC
4434 if (user_lib.size() != 0)
4435 has_library = true;
4436
6b66b9f7
JS
4437 if (q.has_process)
4438 {
4439 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4440 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4441 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4442 // by the incoming section value (".absolute" vs. ".dynamic").
4443 // XXX Assert invariants here too?
2b69faaf
JS
4444
4445 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4446 // ditto for userspace runtimes (dyninst)
ac3af990 4447 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4448 section == ".absolute" && addr == dwfl_addr &&
4449 addr >= q.dw.module_start && addr < q.dw.module_end)
4450 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4451 }
4452 else
4453 {
4454 // Assert kernel relocation invariants
4455 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4456 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4457 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4458 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4459 }
2930abc7 4460
21beacc9
FCE
4461 // XXX: hack for strange g++/gcc's
4462#ifndef USHRT_MAX
4463#define USHRT_MAX 32767
4464#endif
4465
606fd9c8 4466 // Range limit maxactive() value
6b66b9f7 4467 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4468 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4469 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4470
de688825 4471 // Expand target variables in the probe body
5f0a03a6 4472 if (!null_die(scope_die))
8fc05e57 4473 {
6b66b9f7 4474 // XXX: user-space deref's for q.has_process!
de688825 4475 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4476 v.replace (this->body);
3689db05
SC
4477
4478 // Propagate perf.counters so we can emit later
4479 this->perf_counter_refs = v.perf_counter_refs;
4480 // Emit local var used to save the perf counter read value
698de6cc 4481 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4482 for (pcii = v.perf_counter_refs.begin();
4483 pcii != v.perf_counter_refs.end(); pcii++)
4484 {
4485 map<string, pair<string,derived_probe*> >::iterator it;
4486 // Find the associated perf counter probe
4487 for (it=q.sess.perf_counters.begin() ;
4488 it != q.sess.perf_counters.end();
4489 it++)
4490 if ((*it).second.second == (*pcii))
4491 break;
4492 vardecl* vd = new vardecl;
4493 vd->name = "__perf_read_" + (*it).first;
4494 vd->tok = this->tok;
4495 vd->set_arity(0, this->tok);
4496 vd->type = pe_long;
4497 vd->synthetic = true;
4498 this->locals.push_back (vd);
4499 }
4500
4501
6b66b9f7
JS
4502 if (!q.has_process)
4503 access_vars = v.visited;
37ebca01
FCE
4504
4505 // If during target-variable-expanding the probe, we added a new block
4506 // of code, add it to the start of the probe.
4507 if (v.add_block)
ba6f838d 4508 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4509
4510 // If when target-variable-expanding the probe, we need to synthesize a
4511 // sibling function-entry probe. We don't go through the whole probe derivation
4512 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4513 // dwarf-induced duplication.
4514 if (v.add_call_probe)
37ebca01 4515 {
2260f4e3
FCE
4516 assert (q.has_return && !q.has_call);
4517
4518 // We temporarily replace q.base_probe.
4519 statement* old_body = q.base_probe->body;
4520 q.base_probe->body = v.add_call_probe;
4521 q.has_return = false;
4522 q.has_call = true;
af234c40 4523
da23eceb 4524 if (q.has_process)
af234c40
JS
4525 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4526 module, section, dwfl_addr,
4527 addr, q, scope_die);
da23eceb 4528 else
af234c40
JS
4529 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4530 module, section, dwfl_addr,
4531 addr, q, scope_die);
4532
4533 saved_longs = entry_handler->saved_longs = v.saved_longs;
4534 saved_strings = entry_handler->saved_strings = v.saved_strings;
4535
4536 q.results.push_back (entry_handler);
2260f4e3
FCE
4537
4538 q.has_return = true;
4539 q.has_call = false;
4540 q.base_probe->body = old_body;
37ebca01 4541 }
f10534c6
WH
4542 // Save the local variables for listing mode
4543 if (q.sess.listing_mode_vars)
8c67c337 4544 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4545 }
37ebca01 4546 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4547
f10534c6 4548 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4549
5d23847d 4550 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4551 // "reverse-engineered" form of the incoming (q.base_loc) probe
4552 // point. This allows a user to see what function / file / line
4553 // number any particular match of the wildcards.
2930abc7 4554
a229fcd7 4555 vector<probe_point::component*> comps;
91af0778
FCE
4556 if (q.has_kernel)
4557 comps.push_back (new probe_point::component(TOK_KERNEL));
4558 else if(q.has_module)
4559 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4560 else if(q.has_process)
4561 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4562 else
4563 assert (0);
b5d77020 4564
db520b00
FCE
4565 string fn_or_stmt;
4566 if (q.has_function_str || q.has_function_num)
4567 fn_or_stmt = "function";
4568 else
4569 fn_or_stmt = "statement";
a229fcd7 4570
b8da0ad1 4571 if (q.has_function_str || q.has_statement_str)
db520b00 4572 {
4cd232e4 4573 string retro_name = funcname;
b20febf3 4574 if (filename != "")
cee35f73 4575 {
fb84c077 4576 retro_name += ("@" + string (filename));
cee35f73 4577 if (line > 0)
aca66a36 4578 retro_name += (":" + lex_cast (line));
cee35f73 4579 }
db520b00
FCE
4580 comps.push_back
4581 (new probe_point::component
4582 (fn_or_stmt, new literal_string (retro_name)));
4583 }
b8da0ad1 4584 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4585 {
4586 Dwarf_Addr retro_addr;
4587 if (q.has_function_num)
4588 retro_addr = q.function_num_val;
4589 else
4590 retro_addr = q.statement_num_val;
db520b00
FCE
4591 comps.push_back (new probe_point::component
4592 (fn_or_stmt,
9ea68eb9 4593 new literal_number(retro_addr, true)));
37ebca01
FCE
4594
4595 if (q.has_absolute)
4596 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4597 }
4598
b8da0ad1
FCE
4599 if (q.has_call)
4600 comps.push_back (new probe_point::component(TOK_CALL));
4bda987e
SC
4601 if (q.has_exported)
4602 comps.push_back (new probe_point::component(TOK_EXPORTED));
b8da0ad1
FCE
4603 if (q.has_inline)
4604 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4605 if (has_return)
b8da0ad1
FCE
4606 comps.push_back (new probe_point::component(TOK_RETURN));
4607 if (has_maxactive)
4608 comps.push_back (new probe_point::component
4609 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4610
5d23847d
FCE
4611 // Overwrite it.
4612 this->sole_location()->components = comps;
2930abc7
FCE
4613}
4614
bd2b1e68 4615
0a98fd42 4616void
8c67c337
JS
4617dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4618 Dwarf_Addr dwfl_addr)
0a98fd42 4619{
9aa8ffce 4620 if (null_die(scope_die))
0a98fd42 4621 return;
0a98fd42 4622
8c67c337 4623 bool verbose = q.sess.verbose > 2;
0a98fd42 4624
8c67c337 4625 if (verbose)
b530b5b3 4626 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4627
8c67c337
JS
4628 if (has_return)
4629 {
4630 /* Only save the return value if it has a type. */
4631 string type_name;
4632 Dwarf_Die type_die;
4633 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4634 dwarf_type_name(&type_die, type_name))
4635 args.push_back("$return:"+type_name);
4636
4637 else if (verbose)
b530b5b3
LB
4638 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4639 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4640 }
d87623a1 4641
0a98fd42 4642 Dwarf_Die arg;
4ef35696
JS
4643 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4644 for (unsigned i = 0; i < scopes.size(); ++i)
4645 {
4646 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4647 break; // we don't want file-level variables
4648 if (dwarf_child (&scopes[i], &arg) == 0)
4649 do
0a98fd42 4650 {
4ef35696
JS
4651 switch (dwarf_tag (&arg))
4652 {
4653 case DW_TAG_variable:
4654 case DW_TAG_formal_parameter:
4655 break;
0a98fd42 4656
4ef35696
JS
4657 default:
4658 continue;
4659 }
0a98fd42 4660
4ef35696
JS
4661 /* Ignore this local if it has no name. */
4662 const char *arg_name = dwarf_diename (&arg);
4663 if (!arg_name)
8c67c337
JS
4664 {
4665 if (verbose)
b530b5b3
LB
4666 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4667 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4668 continue;
4669 }
4ef35696
JS
4670
4671 if (verbose)
b530b5b3
LB
4672 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4673 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4674
4675 /* Ignore this local if it has no location (or not at this PC). */
4676 /* NB: It still may not be directly accessible, e.g. if it is an
4677 * aggregate type, implicit_pointer, etc., but the user can later
4678 * figure out how to access the interesting parts. */
45b02a36
FCE
4679
4680 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4681 * several synthetic
4682 * probe foo { $var }
4683 * probes, testing them for overall resolvability.
4684 */
4685
4ef35696
JS
4686 Dwarf_Attribute attr_mem;
4687 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4688 {
4689 Dwarf_Op *expr;
4690 size_t len;
4691 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4692 {
4693 if (verbose)
b530b5b3
LB
4694 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4695 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4696 continue;
4697 }
4698 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4699 &len, 1) == 1 && len > 0))
4700 {
45b02a36
FCE
4701 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4702 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4703 &len, 1) == 1 && len > 0))) {
4704 if (verbose)
4705 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4706 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4707 continue;
4708 }
4ef35696
JS
4709 }
4710 }
4711
4712 /* Ignore this local if it has no type. */
4713 string type_name;
4714 Dwarf_Die type_die;
4715 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4716 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4717 {
4718 if (verbose)
b530b5b3
LB
4719 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4720 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4721 continue;
4722 }
8c67c337 4723
4ef35696
JS
4724 /* This local looks good -- save it! */
4725 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4726 }
4ef35696
JS
4727 while (dwarf_siblingof (&arg, &arg) == 0);
4728 }
0a98fd42
JS
4729}
4730
4731
4732void
d0bfd2ac 4733dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4734{
d0bfd2ac 4735 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4736}
4737
4738
27dc09b1 4739void
42e38653 4740dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4741{
4742 if (has_process)
4743 {
4744 // These probes are allowed for unprivileged users, but only in the
4745 // context of processes which they own.
4746 emit_process_owner_assertion (o);
4747 return;
4748 }
4749
4750 // Other probes must contain the default assertion which aborts
4751 // if executed by an unprivileged user.
42e38653 4752 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4753}
4754
4755
4756void
4757dwarf_derived_probe::print_dupe_stamp(ostream& o)
4758{
4759 if (has_process)
4760 {
4761 // These probes are allowed for unprivileged users, but only in the
4762 // context of processes which they own.
4763 print_dupe_stamp_unprivileged_process_owner (o);
4764 return;
4765 }
4766
4767 // Other probes must contain the default dupe stamp
4768 derived_probe::print_dupe_stamp (o);
4769}
4770
64211010 4771
7a053d3b 4772void
20c6c071 4773dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4774 dwarf_builder * dw,
42e38653 4775 privilege_t privilege)
bd2b1e68 4776{
27dc09b1 4777 root
42e38653 4778 ->bind_privilege(privilege)
27dc09b1 4779 ->bind(dw);
54efe513
GH
4780}
4781
7a053d3b 4782void
fd6602a0 4783dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4784 dwarf_builder * dw,
42e38653 4785 privilege_t privilege)
2865d17a 4786{
27dc09b1 4787 root
42e38653 4788 ->bind_privilege(privilege)
27dc09b1 4789 ->bind(dw);
27dc09b1 4790 root->bind(TOK_CALL)
42e38653 4791 ->bind_privilege(privilege)
27dc09b1 4792 ->bind(dw);
4bda987e
SC
4793 root->bind(TOK_EXPORTED)
4794 ->bind_privilege(privilege)
4795 ->bind(dw);
27dc09b1 4796 root->bind(TOK_RETURN)
42e38653 4797 ->bind_privilege(privilege)
27dc09b1 4798 ->bind(dw);
1e035395 4799
f6be7c06
DB
4800 // For process probes / uprobes, .maxactive() is unused.
4801 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4802 {
4803 root->bind(TOK_RETURN)
1e035395
FCE
4804 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4805 }
bd2b1e68
GH
4806}
4807
7a053d3b 4808void
27dc09b1 4809dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4810 systemtap_session& s,
27dc09b1
DB
4811 match_node * root,
4812 dwarf_builder * dw,
42e38653 4813 privilege_t privilege
27dc09b1 4814)
bd2b1e68
GH
4815{
4816 // Here we match 4 forms:
4817 //
4818 // .function("foo")
4819 // .function(0xdeadbeef)
4820 // .statement("foo")
4821 // .statement(0xdeadbeef)
4822
440d9b00 4823 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4824 register_function_variants(fv_root, dw, privilege);
7f02ca94 4825 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4826 fv_root->bind(TOK_INLINE)
42e38653 4827 ->bind_privilege(privilege)
440d9b00 4828 ->bind(dw);
7f02ca94
JS
4829 fv_root->bind_str(TOK_LABEL)
4830 ->bind_privilege(privilege)
440d9b00
DB
4831 ->bind(dw);
4832
4833 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 4834 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
4835 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4836 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4837 {
4838 fv_root->bind(TOK_INLINE)
42e38653 4839 ->bind_privilege(privilege)
440d9b00
DB
4840 ->bind(dw);
4841 }
4842
42e38653
DB
4843 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
4844 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
4845}
4846
b1615c74
JS
4847void
4848dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
4849 match_node * root,
4850 dwarf_builder * dw)
4851{
4852 root->bind_str(TOK_MARK)
f66bb29a 4853 ->bind_privilege(pr_all)
b1615c74
JS
4854 ->bind(dw);
4855 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 4856 ->bind_privilege(pr_all)
b1615c74
JS
4857 ->bind(dw);
4858}
4859
4860void
4861dwarf_derived_probe::register_plt_variants(systemtap_session& s,
4862 match_node * root,
4863 dwarf_builder * dw)
4864{
4865 root->bind(TOK_PLT)
f66bb29a 4866 ->bind_privilege(pr_all)
b1615c74
JS
4867 ->bind(dw);
4868 root->bind_str(TOK_PLT)
f66bb29a 4869 ->bind_privilege(pr_all)
b1615c74
JS
4870 ->bind(dw);
4871 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4872 ->bind_privilege(pr_all)
b1615c74
JS
4873 ->bind(dw);
4874 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4875 ->bind_privilege(pr_all)
b1615c74 4876 ->bind(dw);
bd2b1e68
GH
4877}
4878
4879void
c4ce66a1 4880dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4881{
c4ce66a1 4882 match_node* root = s.pattern_root;
bd2b1e68
GH
4883 dwarf_builder *dw = new dwarf_builder();
4884
c4ce66a1
JS
4885 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4886 s.code_filters.push_back(filter);
4887
bd1fcbad
YZ
4888 filter = new dwarf_atvar_expanding_visitor(s, *dw);
4889 s.code_filters.push_back(filter);
4890
73f52eb4
DB
4891 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
4892 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
4893 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4894 ->bind(dw);
2cab6244 4895
7f02ca94
JS
4896 match_node* uprobes[] = {
4897 root->bind(TOK_PROCESS),
4898 root->bind_str(TOK_PROCESS),
4899 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4900 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4901 };
4902 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
4903 {
f66bb29a 4904 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
4905 register_sdt_variants(s, uprobes[i], dw);
4906 register_plt_variants(s, uprobes[i], dw);
4907 }
bd2b1e68
GH
4908}
4909
9020300d 4910void
3689db05
SC
4911dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
4912{
698de6cc 4913 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4914 for (pcii = perf_counter_refs.begin();
4915 pcii != perf_counter_refs.end();
4916 pcii++)
4917 {
4918 map<string, pair<string,derived_probe*> >::iterator it;
4919 // Find the associated perf.counter probe
4920 unsigned i = 0;
4921 for (it=s.perf_counters.begin() ;
4922 it != s.perf_counters.end();
4923 it++, i++)
4924 if ((*it).second.second == (*pcii))
4925 break;
4926 // place the perf counter read so it precedes stp_lock_probe
4927 o->newline() << "l->l___perf_read_" + (*it).first
4928 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
4929 + lex_cast(i) + "))));";
4930 }
4931
b95e2b79
MH
4932 if (access_vars)
4933 {
4934 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4935 o->newline() << "#if defined __ia64__";
d9aed31e 4936 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4937 o->newline() << "#endif";
b95e2b79 4938 }
9020300d 4939}
2930abc7 4940
b20febf3 4941// ------------------------------------------------------------------------
46b84a80
DS
4942
4943void
b20febf3 4944dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4945{
b20febf3 4946 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4947
4948 // XXX: probes put at the same address should all share a
4949 // single kprobe/kretprobe, and have their handlers executed
4950 // sequentially.
b55bc428
FCE
4951}
4952
7a053d3b 4953void
775d51e5 4954dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4955{
b20febf3 4956 if (probes_by_module.empty()) return;
2930abc7 4957
775d51e5
DS
4958 s.op->newline() << "/* ---- dwarf probes ---- */";
4959
4960 // Warn of misconfigured kernels
f41595cc
FCE
4961 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4962 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4963 s.op->newline() << "#endif";
775d51e5 4964 s.op->newline();
f41595cc 4965
f07c3b68 4966 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4967 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4968 s.op->newline() << "#endif";
4969
14cf7e42 4970 // Forward decls
2ba1736a 4971 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 4972
b20febf3
FCE
4973 // Forward declare the master entry functions
4974 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4975 s.op->line() << " struct pt_regs *regs);";
4976 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4977 s.op->line() << " struct pt_regs *regs);";
4978
42cb22bd
MH
4979 // Emit an array of kprobe/kretprobe pointers
4980 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4981 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4982 s.op->newline() << "#endif";
4983
b20febf3 4984 // Emit the actual probe list.
606fd9c8
FCE
4985
4986 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4987 // struct stap_dwarf_probe, but it being initialized data makes it add
4988 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4989 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4990 // NB: bss!
4991
4c2732a1 4992 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4993 s.op->newline(1) << "const unsigned return_p:1;";
4994 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4995 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4996 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4997 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4998
af234c40
JS
4999 // data saved in the kretprobe_instance packet
5000 s.op->newline() << "const unsigned short saved_longs;";
5001 s.op->newline() << "const unsigned short saved_strings;";
5002
faea5e16 5003 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5004 // are small and uniform enough to justify putting char[MAX]'s into
5005 // the array instead of relocated char*'s.
faea5e16
JS
5006 size_t module_name_max = 0, section_name_max = 0;
5007 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5008 size_t all_name_cnt = probes_by_module.size(); // for average
5009 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5010 {
5011 dwarf_derived_probe* p = it->second;
5012#define DOIT(var,expr) do { \
5013 size_t var##_size = (expr) + 1; \
5014 var##_max = max (var##_max, var##_size); \
5015 var##_tot += var##_size; } while (0)
5016 DOIT(module_name, p->module.size());
5017 DOIT(section_name, p->section.size());
606fd9c8
FCE
5018#undef DOIT
5019 }
5020
5021 // Decide whether it's worthwhile to use char[] or char* by comparing
5022 // the amount of average waste (max - avg) to the relocation data size
5023 // (3 native long words).
5024#define CALCIT(var) \
5025 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5026 { \
5027 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5028 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5029 << "[" << var##_name_max << "]" << endl; \
5030 } \
5031 else \
5032 { \
b0986e7a 5033 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5034 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5035 }
5036
5037 CALCIT(module);
5038 CALCIT(section);
e6fe60e7 5039#undef CALCIT
606fd9c8 5040
b0986e7a 5041 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5042 s.op->newline() << "const struct stap_probe * const probe;";
5043 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5044 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5045 s.op->indent(1);
5046
5047 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5048 {
b20febf3
FCE
5049 dwarf_derived_probe* p = it->second;
5050 s.op->newline() << "{";
5051 if (p->has_return)
5052 s.op->line() << " .return_p=1,";
c9bad430 5053 if (p->has_maxactive)
606fd9c8
FCE
5054 {
5055 s.op->line() << " .maxactive_p=1,";
5056 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5057 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5058 }
af234c40
JS
5059 if (p->saved_longs || p->saved_strings)
5060 {
5061 if (p->saved_longs)
5062 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5063 if (p->saved_strings)
5064 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5065 if (p->entry_handler)
c87ae2c1 5066 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5067 }
b350f56b
JS
5068 if (p->locations[0]->optional)
5069 s.op->line() << " .optional_p=1,";
dc38c256 5070 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5071 s.op->line() << " .module=\"" << p->module << "\",";
5072 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5073 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5074 s.op->line() << " },";
2930abc7 5075 }
2930abc7 5076
b20febf3
FCE
5077 s.op->newline(-1) << "};";
5078
5079 // Emit the kprobes callback function
5080 s.op->newline();
5081 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5082 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5083 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5084 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5085 // Check that the index is plausible
5086 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5087 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5088 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5089 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5090 s.op->line() << "];";
71db462b 5091 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5092 "stp_probe_type_kprobe");
d9aed31e 5093 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5094
5095 // Make it look like the IP is set as it wouldn't have been replaced
5096 // by a breakpoint instruction when calling real probe handler. Reset
5097 // IP regs on return, so we don't confuse kprobes. PR10458
5098 s.op->newline() << "{";
5099 s.op->indent(1);
d9aed31e 5100 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5101 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5102 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5103 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5104 s.op->newline(-1) << "}";
5105
f887a8c9 5106 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5107 s.op->newline() << "return 0;";
5108 s.op->newline(-1) << "}";
5109
5110 // Same for kretprobes
5111 s.op->newline();
af234c40
JS
5112 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5113 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5114 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5115
5116 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5117 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5118 // Check that the index is plausible
5119 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5120 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5121 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5122 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5123 s.op->line() << "];";
5124
7c3e97f4 5125 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5126 s.op->newline() << "if (sp) {";
5127 s.op->indent(1);
71db462b 5128 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5129 "stp_probe_type_kretprobe");
d9aed31e 5130 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5131
5132 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5133 s.op->newline() << "c->ips.krp.pi = inst;";
5134 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5135
5136 // Make it look like the IP is set as it wouldn't have been replaced
5137 // by a breakpoint instruction when calling real probe handler. Reset
5138 // IP regs on return, so we don't confuse kprobes. PR10458
5139 s.op->newline() << "{";
d9aed31e 5140 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5141 s.op->newline() << "if (entry)";
5142 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5143 s.op->newline(-1) << "else";
5144 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5145 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5146 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5147 s.op->newline(-1) << "}";
5148
f887a8c9 5149 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5150 s.op->newline(-1) << "}";
b20febf3
FCE
5151 s.op->newline() << "return 0;";
5152 s.op->newline(-1) << "}";
af234c40
JS
5153
5154 s.op->newline();
5155 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5156 s.op->line() << " struct pt_regs *regs) {";
5157 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5158 s.op->newline(-1) << "}";
5159
5160 s.op->newline();
5161 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5162 s.op->line() << " struct pt_regs *regs) {";
5163 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5164 s.op->newline(-1) << "}";
b642c901 5165
14cf7e42 5166 s.op->newline();
20c6c071 5167}
ec4373ff 5168
20c6c071 5169
dc38c0ae 5170void
b20febf3
FCE
5171dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5172{
5173 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5174 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5175 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5176 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5177 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5178 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5179 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5180 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5181 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5182 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5183 s.op->newline(-1) << "} else {";
f07c3b68 5184 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5185 s.op->newline(-1) << "}";
606fd9c8 5186 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5187 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5188 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5189 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5190 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5191 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5192 s.op->newline(-1) << "}";
5193 s.op->newline() << "#endif";
e4cb375f
MH
5194 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5195 s.op->newline() << "#ifdef __ia64__";
5196 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5197 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5198 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5199 s.op->newline() << "if (rc == 0) {";
5200 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5201 s.op->newline() << "if (rc != 0)";
5202 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5203 s.op->newline(-2) << "}";
5204 s.op->newline() << "#else";
606fd9c8 5205 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5206 s.op->newline() << "#endif";
b20febf3 5207 s.op->newline(-1) << "} else {";
e4cb375f 5208 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5209 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5210 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5211 s.op->newline() << "#ifdef __ia64__";
5212 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5213 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5214 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5215 s.op->newline() << "if (rc == 0) {";
5216 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5217 s.op->newline() << "if (rc != 0)";
5218 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5219 s.op->newline(-2) << "}";
5220 s.op->newline() << "#else";
606fd9c8 5221 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5222 s.op->newline() << "#endif";
b20febf3 5223 s.op->newline(-1) << "}";
9063462a
FCE
5224 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5225 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5226 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5227 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5228 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5229 // XXX: shall we increment numskipped?
5230 s.op->newline(-1) << "}";
5231
5232#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5233 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5234 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5235 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5236 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5237 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5238 s.op->newline() << "#ifdef __ia64__";
5239 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5240 s.op->newline() << "#endif";
c48cb0cc
FCE
5241 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5242 // not run for this early-abort case.
5243 s.op->newline(-1) << "}";
5244 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5245 s.op->newline(-1) << "}";
9063462a
FCE
5246#endif
5247
b20febf3
FCE
5248 s.op->newline() << "else sdp->registered_p = 1;";
5249 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5250}
5251
5252
b4be7cbc
FCE
5253void
5254dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5255{
5256 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5257 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5258 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5259 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5260 s.op->newline() << "int rc;";
5261
5262 // new module arrived?
5263 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5264 s.op->newline(1) << "if (sdp->return_p) {";
5265 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5266 s.op->newline() << "if (sdp->maxactive_p) {";
5267 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5268 s.op->newline(-1) << "} else {";
5269 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5270 s.op->newline(-1) << "}";
5271 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5272 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5273 s.op->newline() << "if (sdp->entry_probe) {";
5274 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5275 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5276 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5277 s.op->newline(-1) << "}";
5278 s.op->newline() << "#endif";
5279 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5280 s.op->newline() << "#ifdef __ia64__";
5281 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5282 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5283 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5284 s.op->newline() << "if (rc == 0) {";
5285 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5286 s.op->newline() << "if (rc != 0)";
5287 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5288 s.op->newline(-2) << "}";
5289 s.op->newline() << "#else";
5290 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5291 s.op->newline() << "#endif";
5292 s.op->newline(-1) << "} else {";
5293 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5294 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5295 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5296 s.op->newline() << "#ifdef __ia64__";
5297 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5298 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5299 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5300 s.op->newline() << "if (rc == 0) {";
5301 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5302 s.op->newline() << "if (rc != 0)";
5303 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5304 s.op->newline(-2) << "}";
5305 s.op->newline() << "#else";
5306 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5307 s.op->newline() << "#endif";
5308 s.op->newline(-1) << "}";
5309 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5310
5311 // old module disappeared?
5312 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5313 s.op->newline(1) << "if (sdp->return_p) {";
5314 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5315 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5316 s.op->newline() << "#ifdef STP_TIMING";
5317 s.op->newline() << "if (kp->u.krp.nmissed)";
5318 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5319 s.op->newline(-1) << "#endif";
065d5567 5320 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5321 s.op->newline() << "#ifdef STP_TIMING";
5322 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5323 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5324 s.op->newline(-1) << "#endif";
5325 s.op->newline(-1) << "} else {";
5326 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5327 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5328 s.op->newline() << "#ifdef STP_TIMING";
5329 s.op->newline() << "if (kp->u.kp.nmissed)";
5330 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5331 s.op->newline(-1) << "#endif";
5332 s.op->newline(-1) << "}";
5333 s.op->newline() << "#if defined(__ia64__)";
5334 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5335 s.op->newline() << "#endif";
5336 s.op->newline() << "sdp->registered_p = 0;";
5337 s.op->newline(-1) << "}";
5338
5339 s.op->newline(-1) << "}"; // for loop
5340}
5341
5342
5343
5344
46b84a80 5345void
b20febf3 5346dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5347{
42cb22bd
MH
5348 //Unregister kprobes by batch interfaces.
5349 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5350 s.op->newline() << "j = 0;";
5351 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5352 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5353 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5354 s.op->newline() << "if (! sdp->registered_p) continue;";
5355 s.op->newline() << "if (!sdp->return_p)";
5356 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5357 s.op->newline(-2) << "}";
5358 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5359 s.op->newline() << "j = 0;";
5360 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5361 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5362 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5363 s.op->newline() << "if (! sdp->registered_p) continue;";
5364 s.op->newline() << "if (sdp->return_p)";
5365 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5366 s.op->newline(-2) << "}";
5367 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5368 s.op->newline() << "#ifdef __ia64__";
5369 s.op->newline() << "j = 0;";
5370 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5371 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5372 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5373 s.op->newline() << "if (! sdp->registered_p) continue;";
5374 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5375 s.op->newline(-1) << "}";
5376 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5377 s.op->newline() << "#endif";
42cb22bd
MH
5378 s.op->newline() << "#endif";
5379
b20febf3
FCE
5380 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5381 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5382 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5383 s.op->newline() << "if (! sdp->registered_p) continue;";
5384 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5385 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5386 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5387 s.op->newline() << "#endif";
065d5567 5388 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5389 s.op->newline() << "#ifdef STP_TIMING";
5390 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5391 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5392 s.op->newline(-1) << "#endif";
065d5567 5393 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5394 s.op->newline() << "#ifdef STP_TIMING";
5395 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5396 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 5397 s.op->newline(-1) << "#endif";
557fb7a8 5398 s.op->newline(-1) << "} else {";
42cb22bd 5399 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5400 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5401 s.op->newline() << "#endif";
065d5567 5402 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5403 s.op->newline() << "#ifdef STP_TIMING";
5404 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5405 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5406 s.op->newline(-1) << "#endif";
b20febf3 5407 s.op->newline(-1) << "}";
e4cb375f
MH
5408 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5409 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5410 s.op->newline() << "#endif";
b20febf3
FCE
5411 s.op->newline() << "sdp->registered_p = 0;";
5412 s.op->newline(-1) << "}";
46b84a80
DS
5413}
5414
272c9036
WF
5415static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5416{
5417 string::size_type pos;
5418 string::size_type lastPos = str.find_first_not_of(" ", 0);
5419 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5420
5421 if (nextAt == string::npos)
5422 {
5423 // PR13934: Assembly probes are not forced to use the N@OP form.
5424 // In this case, N is inferred to be the native word size. Since we
5425 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5426 // then must not put any spaces in arguments, to avoid ambiguity.
5427 tokenize(str, tokens, " ");
5428 return;
5429 }
5430
272c9036
WF
5431 while (lastPos != string::npos)
5432 {
5433 pos = nextAt + 1;
5434 nextAt = str.find("@", pos);
5435 if (nextAt == string::npos)
5436 pos = string::npos;
5437 else
5438 pos = str.rfind(" ", nextAt);
5439
5440 tokens.push_back(str.substr(lastPos, pos - lastPos));
5441 lastPos = str.find_first_not_of(" ", pos);
5442 }
5443}
8aabf152 5444
8aabf152 5445
aff5d390 5446struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5447{
ae1418f0 5448 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
5449 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
5450 int elf_machine,
5451 const string & process_name,
a794dbeb 5452 const string & provider_name,
aff5d390 5453 const string & probe_name,
71e5e13d 5454 stap_sdt_probe_type probe_type,
aff5d390 5455 const string & arg_string,
8aabf152 5456 int ac):
332ba7e7 5457 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
5458 provider_name (provider_name), probe_name (probe_name),
5459 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5460 {
f83336a5
FCE
5461 /* Register name mapping table depends on the elf machine of this particular
5462 probe target process/file, not upon the host. So we can't just
5463 #ifdef _i686_ etc. */
ae1418f0
FCE
5464
5465#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5466 if (elf_machine == EM_X86_64) {
46a94997
SC
5467 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5468 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5469 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5470 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5471 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5472 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5473 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5474 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5475 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5476 DRI ("%sil", 4, QI);
5477 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5478 DRI ("%dil", 5, QI);
5479 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
2c7281e7 5480 DRI ("%bpl", 6, QI);
46a94997 5481 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
2c7281e7 5482 DRI ("%spl", 7, QI);
46a94997
SC
5483 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5484 DRI ("%r8b", 8, QI);
5485 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5486 DRI ("%r9b", 9, QI);
5487 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5488 DRI ("%r10b", 10, QI);
5489 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5490 DRI ("%r11b", 11, QI);
5491 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5492 DRI ("%r12b", 12, QI);
5493 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5494 DRI ("%r13b", 13, QI);
5495 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5496 DRI ("%r14b", 14, QI);
5497 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5498 DRI ("%r15b", 15, QI);
f83336a5 5499 } else if (elf_machine == EM_386) {
46a94997
SC
5500 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5501 DRI ("%ah", 0, QIh);
5502 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5503 DRI ("%ch", 1, QIh);
5504 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5505 DRI ("%dh", 2, QIh);
5506 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5507 DRI ("%bh", 3, QIh);
5508 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5509 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5510 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5511 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5512 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5513 DRI ("%r0", 0, DI);
5514 DRI ("%r1", 1, DI);
5515 DRI ("%r2", 2, DI);
5516 DRI ("%r3", 3, DI);
5517 DRI ("%r4", 4, DI);
5518 DRI ("%r5", 5, DI);
5519 DRI ("%r6", 6, DI);
5520 DRI ("%r7", 7, DI);
5521 DRI ("%r8", 8, DI);
5522 DRI ("%r9", 9, DI);
5523 DRI ("%r10", 10, DI);
5524 DRI ("%r11", 11, DI);
5525 DRI ("%r12", 12, DI);
5526 DRI ("%r13", 13, DI);
5527 DRI ("%r14", 14, DI);
5528 DRI ("%r15", 15, DI);
5529 DRI ("%r16", 16, DI);
5530 DRI ("%r17", 17, DI);
5531 DRI ("%r18", 18, DI);
5532 DRI ("%r19", 19, DI);
5533 DRI ("%r20", 20, DI);
5534 DRI ("%r21", 21, DI);
5535 DRI ("%r22", 22, DI);
5536 DRI ("%r23", 23, DI);
5537 DRI ("%r24", 24, DI);
5538 DRI ("%r25", 25, DI);
5539 DRI ("%r26", 26, DI);
5540 DRI ("%r27", 27, DI);
5541 DRI ("%r28", 28, DI);
5542 DRI ("%r29", 29, DI);
5543 DRI ("%r30", 30, DI);
5544 DRI ("%r31", 31, DI);
8aabf152 5545 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5546 DRI ("0", 0, DI);
5547 DRI ("1", 1, DI);
5548 DRI ("2", 2, DI);
5549 DRI ("3", 3, DI);
5550 DRI ("4", 4, DI);
5551 DRI ("5", 5, DI);
5552 DRI ("6", 6, DI);
5553 DRI ("7", 7, DI);
5554 DRI ("8", 8, DI);
5555 DRI ("9", 9, DI);
5556 DRI ("10", 10, DI);
5557 DRI ("11", 11, DI);
5558 DRI ("12", 12, DI);
5559 DRI ("13", 13, DI);
5560 DRI ("14", 14, DI);
5561 DRI ("15", 15, DI);
5562 DRI ("16", 16, DI);
5563 DRI ("17", 17, DI);
5564 DRI ("18", 18, DI);
5565 DRI ("19", 19, DI);
5566 DRI ("20", 20, DI);
5567 DRI ("21", 21, DI);
5568 DRI ("22", 22, DI);
5569 DRI ("23", 23, DI);
5570 DRI ("24", 24, DI);
5571 DRI ("25", 25, DI);
5572 DRI ("26", 26, DI);
5573 DRI ("27", 27, DI);
5574 DRI ("28", 28, DI);
5575 DRI ("29", 29, DI);
5576 DRI ("30", 30, DI);
5577 DRI ("31", 31, DI);
14900130 5578 } else if (elf_machine == EM_S390) {
46a94997
SC
5579 DRI ("%r0", 0, DI);
5580 DRI ("%r1", 1, DI);
5581 DRI ("%r2", 2, DI);
5582 DRI ("%r3", 3, DI);
5583 DRI ("%r4", 4, DI);
5584 DRI ("%r5", 5, DI);
5585 DRI ("%r6", 6, DI);
5586 DRI ("%r7", 7, DI);
5587 DRI ("%r8", 8, DI);
5588 DRI ("%r9", 9, DI);
5589 DRI ("%r10", 10, DI);
5590 DRI ("%r11", 11, DI);
5591 DRI ("%r12", 12, DI);
5592 DRI ("%r13", 13, DI);
5593 DRI ("%r14", 14, DI);
5594 DRI ("%r15", 15, DI);
272c9036
WF
5595 } else if (elf_machine == EM_ARM) {
5596 DRI ("r0", 0, SI);
5597 DRI ("r1", 1, SI);
5598 DRI ("r2", 2, SI);
5599 DRI ("r3", 3, SI);
5600 DRI ("r4", 4, SI);
5601 DRI ("r5", 5, SI);
5602 DRI ("r6", 6, SI);
5603 DRI ("r7", 7, SI);
5604 DRI ("r8", 8, SI);
5605 DRI ("r9", 9, SI);
669a2feb 5606 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
272c9036
WF
5607 DRI ("fp", 11, SI);
5608 DRI ("ip", 12, SI);
5609 DRI ("sp", 13, SI);
5610 DRI ("lr", 14, SI);
5611 DRI ("pc", 15, SI);
14900130 5612 } else if (arg_count) {
8aabf152 5613 /* permit this case; just fall back to dwarf */
f83336a5 5614 }
ae1418f0 5615#undef DRI
f83336a5 5616
ebbd2b45 5617 need_debug_info = false;
88e39987 5618 if (probe_type == uprobe3_type)
272c9036
WF
5619 {
5620 sdt_v3_tokenize(arg_string, arg_tokens);
5621 assert(arg_count <= 12);
5622 }
88e39987 5623 else
272c9036
WF
5624 {
5625 tokenize(arg_string, arg_tokens, " ");
5626 assert(arg_count <= 10);
5627 }
a8ec7719 5628 }
8aabf152 5629
f83336a5 5630 systemtap_session& session;
332ba7e7 5631 int elf_machine;
aff5d390 5632 const string & process_name;
a794dbeb 5633 const string & provider_name;
aff5d390 5634 const string & probe_name;
71e5e13d 5635 stap_sdt_probe_type probe_type;
8aabf152 5636 unsigned arg_count;
aff5d390 5637 vector<string> arg_tokens;
46a94997 5638 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5639 bool need_debug_info;
aff5d390
SC
5640
5641 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5642 void visit_target_symbol_arg (target_symbol* e);
5643 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5644 void visit_atvar_op (atvar_op* e);
40a0c64e 5645 void visit_cast_op (cast_op* e);
aff5d390
SC
5646};
5647
7a05f484
SC
5648
5649void
6ef331c8 5650sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5651{
6ef331c8 5652 if (e->addressof)
dc09353a 5653 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5654
5655 if (e->name == "$$name")
7a05f484 5656 {
6ef331c8
SC
5657 literal_string *myname = new literal_string (probe_name);
5658 myname->tok = e->tok;
5659 provide(myname);
5660 return;
5661 }
7a05f484 5662
6ef331c8
SC
5663 else if (e->name == "$$provider")
5664 {
5665 literal_string *myname = new literal_string (provider_name);
5666 myname->tok = e->tok;
5667 provide(myname);
5668 return;
5669 }
a794dbeb 5670
6ef331c8
SC
5671 else if (e->name == "$$vars" || e->name == "$$parms")
5672 {
5673 e->assert_no_components("sdt", true);
6ef331c8
SC
5674
5675 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
5676 // NB: we synthesize a new token here rather than reusing
5677 // e->tok, because print_format::print likes to use
5678 // its tok->content.
5679 token* pf_tok = new token(*e->tok);
5680 pf_tok->content = "sprintf";
63ea4244 5681
6ef331c8
SC
5682 print_format* pf = print_format::create(pf_tok);
5683
5684 for (unsigned i = 1; i <= arg_count; ++i)
5685 {
5686 if (i > 1)
5687 pf->raw_components += " ";
5688 target_symbol *tsym = new target_symbol;
5689 tsym->tok = e->tok;
5690 tsym->name = "$arg" + lex_cast(i);
5691 pf->raw_components += tsym->name;
5692 tsym->components = e->components;
5693
8c2f50c0 5694 expression *texp = require<expression> (tsym);
6ef331c8
SC
5695 if (!e->components.empty() &&
5696 e->components[0].type == target_symbol::comp_pretty_print)
5697 pf->raw_components += "=%s";
5698 else
5699 pf->raw_components += "=%#x";
5700 pf->args.push_back(texp);
5701 }
5702
5703 pf->components = print_format::string_to_components(pf->raw_components);
5704 provide (pf);
5705 }
5706 else
5707 assert(0); // shouldn't get here
5708}
5709
5710
5711void
5712sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5713{
5714 try
5715 {
8aabf152 5716 unsigned argno = 0; // the N in $argN
c69a87e0 5717 try
aff5d390 5718 {
5ecaa5a7 5719 if (startswith(e->name, "$arg"))
8aabf152 5720 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5721 }
c69a87e0 5722 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5723 {
8aabf152 5724 argno = 0;
aff5d390 5725 }
5ecaa5a7 5726
8aabf152
FCE
5727 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5728 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5729 {
8aabf152
FCE
5730 // NB: Either
5731 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5732 // 2) uprobe2_type $FOO (no probe args)
5733 // both of which get resolved later.
73d53dd2 5734 // Throw it now, and it might be resolved by DWARF later.
8aabf152 5735 need_debug_info = true;
dc09353a 5736 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
aff5d390 5737 }
277c21bc 5738
8aabf152
FCE
5739 assert (arg_tokens.size() >= argno);
5740 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5741
8aabf152
FCE
5742 // Now we try to parse this thing, which is an assembler operand
5743 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5744 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5745 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157
FCE
5746 //
5747 // literal reg reg reg + base+index*size+offset
b874bd52 5748 // indirect offset
8095a157 5749 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S)
b874bd52
SC
5750 // power iN R (R) N(R)
5751 // ia64 N rR [r16]
5752 // s390 N %rR 0(rR) N(r15)
5753 // arm #N rR [rR] [rR, #N]
5754
8aabf152
FCE
5755 expression* argexpr = 0; // filled in in case of successful parse
5756
5757 string percent_regnames;
5758 string regnames;
5759 vector<string> matches;
71e5e13d 5760 long precision;
8aabf152
FCE
5761 int rc;
5762
40fe32e0
SC
5763 // Parse the leading length
5764
5765 if (asmarg.find('@') != string::npos)
5766 {
5767 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5768 asmarg = asmarg.substr(asmarg.find('@')+1);
5769 }
71e5e13d
SC
5770 else
5771 {
5772 // V1/V2 do not have precision field so default to signed long
5773 // V3 asm does not have precision field so default to unsigned long
5774 if (probe_type == uprobe3_type)
5775 precision = sizeof(long); // this is an asm probe
5776 else
5777 precision = -sizeof(long);
5778 }
40fe32e0 5779
8aabf152
FCE
5780 // test for a numeric literal.
5781 // Only accept (signed) decimals throughout. XXX
5782
5783 // PR11821. NB: on powerpc, literals are not prefixed with $,
5784 // so this regex does not match. But that's OK, since without
5785 // -mregnames, we can't tell them apart from register numbers
5786 // anyway. With -mregnames, we could, if gcc somehow
5787 // communicated to us the presence of that option, but alas it
5788 // doesn't. http://gcc.gnu.org/PR44995.
272c9036 5789 rc = regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5790 if (! rc)
5791 {
75a371ce
JS
5792 string sn = matches[0].substr(1);
5793 int64_t n;
5794 try
5795 {
5796 // We have to pay attention to the size & sign, as gcc sometimes
5797 // propagates constants that don't quite match, like a negative
5798 // value to fill an unsigned type.
5799 switch (precision)
5800 {
5801 case -1: n = lex_cast< int8_t>(sn); break;
5802 case 1: n = lex_cast< uint8_t>(sn); break;
5803 case -2: n = lex_cast< int16_t>(sn); break;
5804 case 2: n = lex_cast<uint16_t>(sn); break;
5805 case -4: n = lex_cast< int32_t>(sn); break;
5806 case 4: n = lex_cast<uint32_t>(sn); break;
5807 default:
5808 case -8: n = lex_cast< int64_t>(sn); break;
5809 case 8: n = lex_cast<uint64_t>(sn); break;
5810 }
5811 }
5812 catch (std::runtime_error&)
5813 {
5814 goto not_matched;
5815 }
5816 literal_number* ln = new literal_number(n);
8aabf152
FCE
5817 ln->tok = e->tok;
5818 argexpr = ln;
5819 goto matched;
5820 }
5821
14900130
SC
5822 if (dwarf_regs.empty())
5823 goto not_matched;
d5b83cee 5824
8aabf152
FCE
5825 // Build regex pieces out of the known dwarf_regs. We keep two separate
5826 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5827 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5828 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5829 {
5830 string regname = ri->first;
5831 assert (regname != "");
5832 regnames += string("|")+regname;
5833 if (regname[0]=='%')
5834 percent_regnames += string("|")+regname;
5835 }
5836 // clip off leading |
5837 regnames = regnames.substr(1);
272c9036
WF
5838 if (percent_regnames != "")
5839 percent_regnames = percent_regnames.substr(1);
8aabf152
FCE
5840
5841 // test for REGISTER
5842 // NB: Because PR11821, we must use percent_regnames here.
272c9036 5843 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
9109f487
SC
5844 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5845 else
332ba7e7 5846 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5847 if (! rc)
5848 {
5849 string regname = matches[1];
46a94997
SC
5850 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5851 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5852 {
5853 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5854 string width_adjust;
46a94997 5855 switch (ri->second.second)
19c22e1f 5856 {
892ec39a
SC
5857 case QI: width_adjust = ") & 0xff)"; break;
5858 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5859 case HI:
71e5e13d 5860 // preserve 16 bit register signness
892ec39a
SC
5861 width_adjust = ") & 0xffff)";
5862 if (precision < 0)
55b377f4 5863 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5864 break;
5865 case SI:
5866 // preserve 32 bit register signness
892ec39a
SC
5867 width_adjust = ") & 0xffffffff)";
5868 if (precision < 0)
55b377f4 5869 width_adjust += " << 32 >> 32";
19c22e1f 5870 break;
892ec39a 5871 default: width_adjust = "))";
19c22e1f 5872 }
55b377f4
SC
5873 string type = "";
5874 if (probe_type == uprobe3_type)
5875 type = (precision < 0
5876 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5877 type = type + "((";
8aabf152
FCE
5878 get_arg1->tok = e->tok;
5879 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5880 + string(" ((int64_t)") + type
8aabf152
FCE
5881 + (is_user_module (process_name)
5882 ? string("u_fetch_register(")
5883 : string("k_fetch_register("))
46a94997 5884 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5885 + width_adjust;
8aabf152
FCE
5886 argexpr = get_arg1;
5887 goto matched;
5888 }
5889 // invalid register name, fall through
5890 }
40fe32e0 5891
272c9036 5892 int reg, offset1;
e5b7b83f 5893 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5894 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 5895 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
5896 // On ARM test for [REGISTER, OFFSET]
5897 if (elf_machine == EM_ARM)
5898 {
669a2feb 5899 rc = regexp_match (asmarg, string("^\\[(")+regnames+string(")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$"), matches);
272c9036 5900 reg = 1;
669a2feb 5901 offset1 = 3;
272c9036
WF
5902 }
5903 else
5904 {
5905 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
5906 reg = 4;
5907 offset1 = 1;
5908 }
8aabf152
FCE
5909 if (! rc)
5910 {
e5b7b83f 5911 string regname;
8aabf152 5912 int64_t disp = 0;
272c9036
WF
5913 if (matches[reg].length())
5914 regname = matches[reg];
8095a157
FCE
5915 if (dwarf_regs.find (regname) == dwarf_regs.end())
5916 goto not_matched;
5917
272c9036 5918 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
5919 if (matches[i].length())
5920 try
5921 {
5922 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5923 }
8aabf152
FCE
5924 catch (const runtime_error& f) // unparseable offset
5925 {
5926 goto not_matched; // can't just 'break' out of
5927 // this case or use a sentinel
5928 // value, unfortunately
5929 }
5930
8aabf152 5931 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
5932 embedded_expr *get_arg1 = new embedded_expr;
5933 get_arg1->tok = e->tok;
5934 get_arg1->code = string("/* unprivileged */ /* pure */")
5935 + (is_user_module (process_name)
5936 ? string("u_fetch_register(")
5937 : string("k_fetch_register("))
46a94997 5938 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5939 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5940
8aabf152
FCE
5941 literal_number* inc = new literal_number(disp);
5942 inc->tok = e->tok;
40fe32e0 5943
8aabf152
FCE
5944 binary_expression *be = new binary_expression;
5945 be->tok = e->tok;
5946 be->left = get_arg1;
5947 be->op = "+";
5948 be->right = inc;
40fe32e0 5949
8aabf152 5950 functioncall *fc = new functioncall;
40fe32e0
SC
5951 switch (precision)
5952 {
7f6ce9ab
SC
5953 case 1: case -1:
5954 fc->function = "user_int8"; break;
5955 case 2:
5956 fc->function = "user_uint16"; break;
5957 case -2:
5958 fc->function = "user_int16"; break;
5959 case 4:
5960 fc->function = "user_uint32"; break;
5961 case -4:
5962 fc->function = "user_int32"; break;
5963 case 8: case -8:
5964 fc->function = "user_int64"; break;
40fe32e0
SC
5965 default: fc->function = "user_long";
5966 }
8aabf152
FCE
5967 fc->tok = e->tok;
5968 fc->args.push_back(be);
366af4e7 5969
8aabf152
FCE
5970 argexpr = fc;
5971 goto matched;
5972 }
8095a157
FCE
5973
5974 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
5975 // NB: Despite PR11821, we can use regnames here, since the parentheses
5976 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 5977 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
5978 if (! rc)
5979 {
5980 string baseregname;
5981 string indexregname;
5982 int64_t disp = 0;
5983 short scale = 1;
5984
5985 if (matches[6].length())
5986 try
5987 {
5988 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
5989 // We could verify that scale is one of 1,2,4,8,
5990 // but it doesn't really matter. An erroneous
5991 // address merely results in run-time errors.
8aabf152 5992 }
8095a157
FCE
5993 catch (const runtime_error &f) // unparseable scale
5994 {
5995 goto not_matched;
5996 }
5997
5998 if (matches[4].length())
5999 baseregname = matches[4];
6000 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6001 goto not_matched;
6002
6003 if (matches[5].length())
6004 indexregname = matches[5];
6005 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6006 goto not_matched;
6007
f7719b3d 6008 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
6009 if (matches[i].length())
6010 try
6011 {
6012 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
6013 }
6014 catch (const runtime_error& f) // unparseable offset
6015 {
6016 goto not_matched; // can't just 'break' out of
6017 // this case or use a sentinel
6018 // value, unfortunately
6019 }
6020
6021 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6022
6023 embedded_expr *get_arg1 = new embedded_expr;
6024 string regfn = is_user_module (process_name)
6025 ? string("u_fetch_register")
6026 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
6027
6028 get_arg1->tok = e->tok;
6029 get_arg1->code = string("/* unprivileged */ /* pure */")
6030 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6031 + string("+(")
6032 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6033 + string("*")
6034 + lex_cast(scale)
6035 + string(")");
6036
6037 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6038 literal_number* inc = new literal_number(disp);
6039 inc->tok = e->tok;
6040
6041 binary_expression *be = new binary_expression;
6042 be->tok = e->tok;
6043 be->left = get_arg1;
6044 be->op = "+";
6045 be->right = inc;
6046
6047 functioncall *fc = new functioncall;
6048 switch (precision)
6049 {
6050 case 1: case -1:
6051 fc->function = "user_int8"; break;
6052 case 2:
6053 fc->function = "user_uint16"; break;
6054 case -2:
6055 fc->function = "user_int16"; break;
6056 case 4:
6057 fc->function = "user_uint32"; break;
6058 case -4:
6059 fc->function = "user_int32"; break;
6060 case 8: case -8:
6061 fc->function = "user_int64"; break;
6062 default: fc->function = "user_long";
6063 }
6064 fc->tok = e->tok;
6065 fc->args.push_back(be);
6066
6067 argexpr = fc;
6068 goto matched;
8aabf152
FCE
6069 }
6070
8aabf152
FCE
6071
6072 not_matched:
6073 // The asmarg operand was not recognized. Back down to dwarf.
6074 if (! session.suppress_warnings)
84fef8ee
FCE
6075 {
6076 if (probe_type == UPROBE3_TYPE)
6c9e1946 6077 session.print_warning (_F("Can't parse SDT_V3 operand '%s' [man error::sdt]", asmarg.c_str()), e->tok);
84fef8ee 6078 else // must be *PROBE2; others don't get asm operands
6c9e1946 6079 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s' [man error::sdt]",
84fef8ee
FCE
6080 asmarg.c_str()), e->tok);
6081 }
8aabf152
FCE
6082 assert (argexpr == 0);
6083 need_debug_info = true;
dc09353a 6084 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo [man error::sdt]"), e->tok);
366af4e7 6085
8aabf152
FCE
6086 matched:
6087 assert (argexpr != 0);
366af4e7
RM
6088
6089 if (session.verbose > 2)
1e41115c 6090 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6091 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6092
aff5d390 6093 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6094 {
6095 if (e->addressof)
dc09353a 6096 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
6097 provide (argexpr);
6098 return;
6099 }
6100 else // $var->foo
6101 {
6102 cast_op *cast = new cast_op;
6103 cast->name = "@cast";
6104 cast->tok = e->tok;
6105 cast->operand = argexpr;
6106 cast->components = e->components;
6107 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6108 cast->module = process_name;
6109 cast->visit(this);
6110 return;
6111 }
366af4e7 6112
8aabf152 6113 /* NOTREACHED */
aff5d390
SC
6114 }
6115 catch (const semantic_error &er)
6116 {
6117 e->chain (er);
6118 provide (e);
6119 }
6120}
6121
6122
6ef331c8
SC
6123void
6124sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6125{
6126 try
6127 {
49131a6d 6128 assert(e->name.size() > 0
bd1fcbad 6129 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6130
6131 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6132 visit_target_symbol_context (e);
6133 else
6134 visit_target_symbol_arg (e);
6135 }
6136 catch (const semantic_error &er)
6137 {
6138 e->chain (er);
6139 provide (e);
6140 }
6141}
6142
6143
bd1fcbad
YZ
6144void
6145sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6146{
6147 need_debug_info = true;
6148
6149 // Fill in our current module context if needed
6150 if (e->module.empty())
6151 e->module = process_name;
6152
6153 var_expanding_visitor::visit_atvar_op(e);
6154}
6155
6156
40a0c64e
JS
6157void
6158sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6159{
6160 // Fill in our current module context if needed
6161 if (e->module.empty())
6162 e->module = process_name;
6163
6164 var_expanding_visitor::visit_cast_op(e);
6165}
6166
6167
576eaefe
SC
6168void
6169plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6170{
6171 try
6172 {
6173 if (e->name == "$$name")
6174 {
6175 literal_string *myname = new literal_string (entry);
6176 myname->tok = e->tok;
6177 provide(myname);
6178 return;
6179 }
3d69c03f
JS
6180
6181 // variable not found -> throw a semantic error
6182 // (only to be caught right away, but this may be more complex later...)
6183 string alternatives = "$$name";
dc09353a 6184 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6185 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6186 }
6187 catch (const semantic_error &er)
6188 {
6189 e->chain (er);
6190 provide (e);
6191 }
6192}
6193
6194
edce5b67
JS
6195struct sdt_query : public base_query
6196{
6197 sdt_query(probe * base_probe, probe_point * base_loc,
6198 dwflpp & dw, literal_map_t const & params,
51d6bda3 6199 vector<derived_probe *> & results, const string user_lib);
edce5b67 6200
51d6bda3 6201 void query_library (const char *data);
576eaefe 6202 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6203 void handle_query_module();
6204
6205private:
15284963 6206 stap_sdt_probe_type probe_type;
d61ea602 6207 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6208 probe * base_probe;
6209 probe_point * base_loc;
6846cfc8 6210 literal_map_t const & params;
edce5b67 6211 vector<derived_probe *> & results;
a794dbeb
FCE
6212 string pp_mark;
6213 string pp_provider;
51d6bda3 6214 string user_lib;
edce5b67
JS
6215
6216 set<string> probes_handled;
6217
6218 Elf_Data *pdata;
6219 size_t probe_scn_offset;
6220 size_t probe_scn_addr;
aff5d390 6221 uint64_t arg_count;
40fe32e0 6222 GElf_Addr base;
c57ea854 6223 GElf_Addr pc;
aff5d390 6224 string arg_string;
edce5b67 6225 string probe_name;
a794dbeb 6226 string provider_name;
909ab234 6227 GElf_Addr semaphore_load_offset;
79a0ca08 6228 Dwarf_Addr semaphore;
edce5b67
JS
6229
6230 bool init_probe_scn();
6b51ee12 6231 bool get_next_probe();
c57ea854
SC
6232 void iterate_over_probe_entries();
6233 void handle_probe_entry();
edce5b67 6234
40fe32e0
SC
6235 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
6236 void setup_note_probe_entry (int type, const char *data, size_t len);
6237
edce5b67 6238 void convert_probe(probe *base);
4ddb6dd0 6239 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6240 probe* convert_location();
40fe32e0 6241 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6242 bool have_debuginfo_uprobe(bool need_debug_info)
6243 {return probe_type == uprobe1_type
40fe32e0 6244 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6245 && need_debug_info);}
40fe32e0 6246 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6247};
6248
6249
6250sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6251 dwflpp & dw, literal_map_t const & params,
51d6bda3 6252 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6253 base_query(dw, params), probe_type(unknown_probe_type),
6254 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6255 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6256 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6257 semaphore_load_offset(0), semaphore(0)
edce5b67 6258{
a794dbeb
FCE
6259 assert(get_string_param(params, TOK_MARK, pp_mark));
6260 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6261
ef428667
FCE
6262 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6263 // map it to double-underscores.
6264 size_t pos = 0;
6265 while (1) // there may be more than one
6266 {
a794dbeb 6267 size_t i = pp_mark.find("-", pos);
ef428667 6268 if (i == string::npos) break;
a794dbeb 6269 pp_mark.replace (i, 1, "__");
ef428667
FCE
6270 pos = i+1; // resume searching after the inserted __
6271 }
a794dbeb
FCE
6272
6273 // XXX: same for pp_provider?
edce5b67
JS
6274}
6275
6276
6277void
c57ea854 6278sdt_query::handle_probe_entry()
edce5b67 6279{
c57ea854
SC
6280 if (! have_uprobe()
6281 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6282 return;
6283
6284 if (sess.verbose > 3)
c57ea854 6285 {
b530b5b3
LB
6286 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
6287 //TRANSLATORS: is matched to.
6288 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6289 switch (probe_type)
6290 {
6291 case uprobe1_type:
6292 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6293 break;
6294 case uprobe2_type:
6295 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6296 break;
40fe32e0
SC
6297 case uprobe3_type:
6298 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6299 break;
d61ea602
JS
6300 default:
6301 clog << "unknown!" << endl;
6302 break;
c57ea854
SC
6303 }
6304 }
edce5b67 6305
c57ea854
SC
6306 // Extend the derivation chain
6307 probe *new_base = convert_location();
6308 probe_point *new_location = new_base->locations[0];
6309
c57ea854
SC
6310 bool need_debug_info = false;
6311
7d395255
JS
6312 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6313 // or dwfl_module_getelf(...). We only need it for the machine type, which
6314 // should be the same. The bias is used for relocating debuginfoless probes,
6315 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6316 Dwarf_Addr bias;
7d395255 6317 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6318
1cc41cd6
DS
6319 /* Figure out the architecture of this particular ELF file. The
6320 dwarfless register-name mappings depend on it. */
6321 GElf_Ehdr ehdr_mem;
6322 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
6323 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6324 assert(em);
1cc41cd6
DS
6325 int elf_machine = em->e_machine;
6326 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine, module_val,
6327 provider_name, probe_name,
6328 probe_type, arg_string, arg_count);
6329 svv.replace (new_base->body);
6330 need_debug_info = svv.need_debug_info;
c57ea854 6331
1cc41cd6
DS
6332 // XXX: why not derive_probes() in the uprobes case too?
6333 literal_map_t params;
6334 for (unsigned i = 0; i < new_location->components.size(); ++i)
6335 {
6336 probe_point::component *c = new_location->components[i];
6337 params[c->functor] = c->arg;
6338 }
c57ea854 6339
73d53dd2 6340 unsigned prior_results_size = results.size();
1cc41cd6
DS
6341 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6342 q.has_mark = true; // enables mid-statement probing
30263a73 6343
73d53dd2
JS
6344 // V1 probes always need dwarf info
6345 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6
DS
6346 if (have_debuginfo_uprobe(need_debug_info))
6347 dw.iterate_over_modules(&query_module, &q);
73d53dd2
JS
6348
6349 // For V2+ probes, if variable references weren't used or failed (PR14369),
6350 // then try with the more direct approach. Unresolved $vars might still
6351 // cause their own error, but this gives them a chance to be optimized out.
6352 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6353 {
6354 string section;
6355 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6356 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6357 {
6358 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6359 section = ".dynamic";
6360 }
6361 else
6362 section = ".absolute";
edce5b67 6363
1cc41cd6
DS
6364 uprobe_derived_probe* p =
6365 new uprobe_derived_probe ("", "", 0,
6366 path_remove_sysroot(sess,q.module_val),
6367 section,
6368 q.statement_num_val, reloc_addr, q, 0);
6369 p->saveargs (arg_count);
6370 results.push_back (p);
c57ea854 6371 }
487bf4e2 6372 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6373 record_semaphore(results, prior_results_size);
c57ea854 6374}
edce5b67 6375
4ddb6dd0 6376
c57ea854
SC
6377void
6378sdt_query::handle_query_module()
6379{
6380 if (!init_probe_scn())
6381 return;
edce5b67 6382
c57ea854
SC
6383 if (sess.verbose > 3)
6384 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6385
40fe32e0
SC
6386 if (probe_loc == note_section)
6387 {
6388 GElf_Shdr shdr_mem;
6389 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6390
909ab234
JS
6391 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6392 // effects. The 'semaphore_load_offset' accounts for the difference in
6393 // load addresses between text and data, so the semaphore can be
6394 // converted to a file offset if needed.
40fe32e0 6395 if (shdr)
909ab234
JS
6396 {
6397 base = shdr->sh_addr;
6398 GElf_Addr base_offset = shdr->sh_offset;
6399 shdr = dw.get_section (".probes", &shdr_mem);
6400 if (shdr)
6401 semaphore_load_offset =
6402 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6403 }
40fe32e0 6404 else
909ab234
JS
6405 base = semaphore_load_offset = 0;
6406
40fe32e0
SC
6407 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
6408 }
d61ea602 6409 else if (probe_loc == probe_section)
40fe32e0 6410 iterate_over_probe_entries ();
edce5b67
JS
6411}
6412
6413
6414bool
6415sdt_query::init_probe_scn()
6416{
448a86b7 6417 Elf* elf;
edce5b67 6418 GElf_Shdr shdr_mem;
40fe32e0
SC
6419
6420 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6421 if (shdr)
6422 {
6423 probe_loc = note_section;
6424 return true;
6425 }
edce5b67 6426
448a86b7 6427 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6428 if (shdr)
edce5b67 6429 {
fea74777
SC
6430 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6431 probe_scn_offset = 0;
6432 probe_scn_addr = shdr->sh_addr;
6433 assert (pdata != NULL);
6434 if (sess.verbose > 4)
ce0f6648
LB
6435 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6436 << pdata->d_size << endl;
40fe32e0 6437 probe_loc = probe_section;
fea74777 6438 return true;
edce5b67 6439 }
fea74777 6440 else
edce5b67 6441 return false;
edce5b67
JS
6442}
6443
40fe32e0
SC
6444void
6445sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
6446{
6447 sdt_query *me = (sdt_query*)object;
6448 me->setup_note_probe_entry (type, data, len);
6449}
6450
6451
6452void
6453sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
6454{
6455 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
6456 // && !memcmp (data->d_buf + name_off,
6457 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
6458
6459 // probes are in the .note.stapsdt section
6460#define _SDT_NOTE_TYPE 3
6461 if (type != _SDT_NOTE_TYPE)
6462 return;
6463
6464 union
6465 {
6466 Elf64_Addr a64[3];
6467 Elf32_Addr a32[3];
6468 } buf;
6469 Dwarf_Addr bias;
6470 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6471 Elf_Data dst =
6472 {
6473 &buf, ELF_T_ADDR, EV_CURRENT,
6474 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6475 };
6476 assert (dst.d_size <= sizeof buf);
6477
6478 if (len < dst.d_size + 3)
6479 return;
6480
6481 Elf_Data src =
6482 {
6483 (void *) data, ELF_T_ADDR, EV_CURRENT,
6484 dst.d_size, 0, 0
6485 };
6486
6487 if (gelf_xlatetom (elf, &dst, &src,
6488 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6489 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6490
6491 probe_type = uprobe3_type;
6492 const char * provider = data + dst.d_size;
3f803f9e 6493
40fe32e0 6494 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6495 if(name++ == NULL)
6496 return;
6497
6498 const char *args = (const char*)memchr (name, '\0', data + len - name);
6499 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6500 return;
6501
6502 provider_name = provider;
6503 probe_name = name;
6504 arg_string = args;
40fe32e0
SC
6505
6506 // Did we find a matching probe?
6507 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6508 && ((pp_provider == "")
6509 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6510 return;
6511
e9a90eee
JS
6512 // PR13934: Assembly probes are not forced to use the N@OP form.
6513 // If we have '@' then great, else count based on space-delimiters.
6514 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6515 if (!arg_count && !arg_string.empty())
6516 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6517
40fe32e0
SC
6518 GElf_Addr base_ref;
6519 if (gelf_getclass (elf) == ELFCLASS32)
6520 {
6521 pc = buf.a32[0];
6522 base_ref = buf.a32[1];
6523 semaphore = buf.a32[2];
6524 }
6525 else
6526 {
6527 pc = buf.a64[0];
6528 base_ref = buf.a64[1];
6529 semaphore = buf.a64[2];
6530 }
6531
6532 semaphore += base - base_ref;
6533 pc += base - base_ref;
6534
7d395255
JS
6535 // The semaphore also needs the ELF bias added now, so
6536 // record_semaphore can properly relocate it later.
6537 semaphore += bias;
6538
40fe32e0 6539 if (sess.verbose > 4)
b530b5b3 6540 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
6541
6542 handle_probe_entry();
6543}
6544
6545
c57ea854
SC
6546void
6547sdt_query::iterate_over_probe_entries()
edce5b67 6548{
c57ea854 6549 // probes are in the .probe section
edce5b67
JS
6550 while (probe_scn_offset < pdata->d_size)
6551 {
aff5d390
SC
6552 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6553 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6554 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6555 if (! have_uprobe())
edce5b67
JS
6556 {
6557 // Unless this is a mangled .probes section, this happens
6558 // because the name of the probe comes first, followed by
6559 // the sentinel.
6560 if (sess.verbose > 5)
b530b5b3 6561 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6562 probe_scn_offset += sizeof(__uint32_t);
6563 continue;
6564 }
aff5d390
SC
6565 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6566 {
6567 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6568 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6569 continue;
6570 }
6571
1cc41cd6 6572 if (probe_type == uprobe1_type)
aff5d390 6573 {
79a0ca08 6574 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6575 return;
79a0ca08 6576 semaphore = 0;
aff5d390 6577 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6578 provider_name = ""; // unknown
1cc41cd6
DS
6579 pc = pbe_v1->arg;
6580 arg_count = 0;
aff5d390
SC
6581 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6582 }
08b5a50c 6583 else if (probe_type == uprobe2_type)
aff5d390 6584 {
79a0ca08 6585 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6586 return;
79a0ca08 6587 semaphore = pbe_v2->semaphore;
aff5d390 6588 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6589 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6590 arg_count = pbe_v2->arg_count;
6591 pc = pbe_v2->pc;
6592 if (pbe_v2->arg_string)
6593 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6594 // skip over pbe_v2, probe_name text and provider text
6595 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6596 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6597 }
edce5b67 6598 if (sess.verbose > 4)
b530b5b3 6599 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6600 << "@0x" << hex << pc << dec << endl;
edce5b67 6601
a794dbeb
FCE
6602 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6603 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6604 handle_probe_entry ();
edce5b67 6605 }
edce5b67
JS
6606}
6607
6608
6846cfc8 6609void
4ddb6dd0 6610sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6611{
a794dbeb
FCE
6612 for (unsigned i=0; i<2; i++) {
6613 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6614 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6615 // XXX: multiple addresses?
6616 if (sess.verbose > 2)
b530b5b3 6617 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6618
79a0ca08
SC
6619 Dwarf_Addr addr;
6620 if (this->semaphore)
6621 addr = this->semaphore;
6622 else
6623 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6624 if (addr)
6625 {
7d395255 6626 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6627 dwfl_module_relocate_address (dw.module, &addr);
6628 // XXX: relocation basis?
909ab234
JS
6629
6630 // Dyninst needs the *file*-based offset for semaphores,
6631 // so subtract the difference in load addresses between .text and .probes
6632 if (dw.sess.runtime_usermode_p())
6633 addr -= semaphore_load_offset;
6634
a794dbeb
FCE
6635 for (unsigned i = start; i < results.size(); ++i)
6636 results[i]->sdt_semaphore_addr = addr;
6637 if (sess.verbose > 2)
b530b5b3 6638 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6639 return;
6640 }
6641 else
6642 if (sess.verbose > 2)
b530b5b3 6643 clog << _(", not found") << endl;
a794dbeb 6644 }
6846cfc8
SC
6645}
6646
6647
edce5b67
JS
6648void
6649sdt_query::convert_probe (probe *base)
6650{
6651 block *b = new block;
6652 b->tok = base->body->tok;
6653
edce5b67
JS
6654 // Generate: if (arg1 != mark("label")) next;
6655 functioncall *fc = new functioncall;
bbafcb1e 6656 fc->function = "ulong_arg";
edce5b67 6657 fc->tok = b->tok;
bbafcb1e 6658 literal_number* num = new literal_number(1);
edce5b67
JS
6659 num->tok = b->tok;
6660 fc->args.push_back(num);
6661
6662 functioncall *fcus = new functioncall;
6663 fcus->function = "user_string";
6664 fcus->type = pe_string;
6665 fcus->tok = b->tok;
6666 fcus->args.push_back(fc);
6667
6668 if_statement *is = new if_statement;
6669 is->thenblock = new next_statement;
6670 is->elseblock = NULL;
6671 is->tok = b->tok;
63ea4244 6672 is->thenblock->tok = b->tok;
edce5b67
JS
6673 comparison *be = new comparison;
6674 be->op = "!=";
6675 be->tok = b->tok;
6676 be->left = fcus;
6677 be->right = new literal_string(probe_name);
63ea4244 6678 be->right->tok = b->tok;
edce5b67
JS
6679 is->condition = be;
6680 b->statements.push_back(is);
6681
6682 // Now replace the body
6683 b->statements.push_back(base->body);
6684 base->body = b;
6685}
6686
6687
c72aa911
JS
6688probe*
6689sdt_query::convert_location ()
edce5b67 6690{
c72aa911 6691 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6692 vector<probe_point::component*> derived_comps;
edce5b67 6693
662539d9
JS
6694 vector<probe_point::component*>::iterator it;
6695 for (it = specific_loc->components.begin();
6696 it != specific_loc->components.end(); ++it)
6697 if ((*it)->functor == TOK_PROCESS)
6698 {
1cc41cd6
DS
6699 // copy the process name
6700 derived_comps.push_back(*it);
662539d9
JS
6701 }
6702 else if ((*it)->functor == TOK_LIBRARY)
6703 {
1cc41cd6
DS
6704 // copy the library name for process probes
6705 derived_comps.push_back(*it);
662539d9
JS
6706 }
6707 else if ((*it)->functor == TOK_PROVIDER)
6708 {
6709 // replace the possibly wildcarded arg with the specific provider name
6710 *it = new probe_point::component(TOK_PROVIDER,
6711 new literal_string(provider_name));
6712 }
6713 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6714 {
6715 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6716 *it = new probe_point::component(TOK_MARK,
6717 new literal_string(probe_name));
a794dbeb 6718
aff5d390
SC
6719 if (sess.verbose > 3)
6720 switch (probe_type)
6721 {
6722 case uprobe1_type:
b530b5b3 6723 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6724 << hex << pc << dec << endl;
6725 break;
6726 case uprobe2_type:
b530b5b3 6727 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6728 << hex << pc << dec << endl;
6729 break;
40fe32e0 6730 case uprobe3_type:
b530b5b3 6731 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6732 << hex << pc << dec << endl;
6733 break;
aff5d390 6734 default:
b530b5b3
LB
6735 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6736 pp_mark.c_str()) << endl;
aff5d390
SC
6737 }
6738
c72aa911
JS
6739 switch (probe_type)
6740 {
aff5d390
SC
6741 case uprobe1_type:
6742 case uprobe2_type:
40fe32e0 6743 case uprobe3_type:
c72aa911 6744 // process("executable").statement(probe_arg)
662539d9
JS
6745 derived_comps.push_back
6746 (new probe_point::component(TOK_STATEMENT,
6747 new literal_number(pc, true)));
c72aa911
JS
6748 break;
6749
a794dbeb 6750 default: // deprecated
c72aa911 6751 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6752 derived_comps.push_back
6753 (new probe_point::component(TOK_FUNCTION,
6754 new literal_string("*")));
6755 derived_comps.push_back
c72aa911 6756 (new probe_point::component(TOK_LABEL,
a794dbeb 6757 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6758 break;
6759 }
6760 }
edce5b67 6761
662539d9
JS
6762 probe_point* derived_loc = new probe_point(*specific_loc);
6763 derived_loc->components = derived_comps;
8159bf55 6764 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
6765}
6766
6767
51d6bda3
SC
6768void
6769sdt_query::query_library (const char *library)
6770{
6771 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6772}
6773
6774
0508c45f
JL
6775string
6776suggest_dwarf_functions(systemtap_session& sess,
6777 const set<string>& modules,
6778 string func)
44ffe90c
JL
6779{
6780 // Trim any @ component
6781 size_t pos = func.find('@');
6782 if (pos != string::npos)
6783 func.erase(pos);
6784
0508c45f 6785 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
6786 return "";
6787
6788 // We must first aggregate all the functions from the cache
6789 set<string> funcs;
6790 const map<string, module_info*> &cache = sess.module_cache->cache;
6791
0508c45f
JL
6792 for (set<string>::iterator itmod = modules.begin();
6793 itmod != modules.end(); ++itmod)
44ffe90c
JL
6794 {
6795 map<string, module_info*>::const_iterator itcache;
6796 if ((itcache = cache.find(*itmod)) != cache.end())
6797 funcs.insert(itcache->second->sym_seen.begin(),
6798 itcache->second->sym_seen.end());
6799 }
6800
6801 if (sess.verbose > 2)
6802 clog << "suggesting from " << funcs.size() << " functions" << endl;
6803
6804 if (funcs.empty())
6805 return "";
6806
593f09eb 6807 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
6808}
6809
20c6c071 6810void
5227f1ea 6811dwarf_builder::build(systemtap_session & sess,
7a053d3b 6812 probe * base,
20c6c071 6813 probe_point * location,
86bf665e 6814 literal_map_t const & parameters,
20c6c071
GH
6815 vector<derived_probe *> & finished_results)
6816{
b20febf3
FCE
6817 // NB: the kernel/user dwlfpp objects are long-lived.
6818 // XXX: but they should be per-session, as this builder object
6819 // may be reused if we try to cross-instrument multiple targets.
84048984 6820
7a24d422 6821 dwflpp* dw = 0;
6d5d594e 6822 literal_map_t filled_parameters = parameters;
7a24d422 6823
7a24d422 6824 string module_name;
ae2552da
FCE
6825 if (has_null_param (parameters, TOK_KERNEL))
6826 {
6827 dw = get_kern_dw(sess, "kernel");
6828 }
6829 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6830 {
c523a015
LB
6831 size_t dash_pos = 0;
6832 while((dash_pos=module_name.find('-'))!=string::npos)
6833 module_name.replace(int(dash_pos),1,"_");
6834 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6835 // NB: glob patterns get expanded later, during the offline
6836 // elfutils module listing.
ae2552da 6837 dw = get_kern_dw(sess, module_name);
b8da0ad1 6838 }
6d5d594e 6839 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6840 {
05fb3e0c 6841 module_name = sess.sysroot + module_name;
6d5d594e
LB
6842 if(has_null_param(filled_parameters, TOK_PROCESS))
6843 {
6844 wordexp_t words;
6845 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6846 if(rc || words.we_wordc <= 0)
dc09353a 6847 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without a -c COMMAND"));
05fb3e0c 6848 module_name = sess.sysroot + words.we_wordv[0];
6d5d594e
LB
6849 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6850 // in the case of TOK_MARK we need to modify locations as well
6851 if(location->components[0]->functor==TOK_PROCESS &&
6852 location->components[0]->arg == 0)
6853 location->components[0]->arg = new literal_string(module_name);
6854 wordfree (& words);
6855 }
5750ecc6 6856
37001baa
FCE
6857 // PR6456 process("/bin/*") glob handling
6858 if (contains_glob_chars (module_name))
6859 {
6860 // Expand glob via rewriting the probe-point process("....")
6861 // parameter, asserted to be the first one.
6862
6863 assert (location->components.size() > 0);
6864 assert (location->components[0]->functor == TOK_PROCESS);
6865 assert (location->components[0]->arg);
6866 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6867 assert (lit);
6868
6869 // Evaluate glob here, and call derive_probes recursively with each match.
6870 glob_t the_blob;
88f8e2c0 6871 set<string> dupes;
37001baa 6872 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 6873 if (rc)
dc09353a 6874 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 6875 unsigned results_pre = finished_results.size();
37001baa
FCE
6876 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6877 {
e19ebcf7 6878 assert_no_interrupts();
37001baa
FCE
6879
6880 const char* globbed = the_blob.gl_pathv[i];
6881 struct stat st;
6882
6883 if (access (globbed, X_OK) == 0
6884 && stat (globbed, &st) == 0
6885 && S_ISREG (st.st_mode)) // see find_executable()
6886 {
7977a734
FCE
6887 // Need to call canonicalize here, in order to path-expand
6888 // patterns like process("stap*"). Otherwise it may go through
6889 // to the next round of expansion as ("stap"), leading to a $PATH
6890 // search that's not consistent with the glob search already done.
5bca76a8
JS
6891 string canononicalized = resolve_path (globbed);
6892 globbed = canononicalized.c_str();
7977a734 6893
88f8e2c0
JS
6894 // The canonical names can result in duplication, for example
6895 // having followed symlinks that are common with shared
6896 // libraries. Filter those out.
6897 if (!dupes.insert(canononicalized).second)
6898 continue;
6899
37001baa
FCE
6900 // synthesize a new probe_point, with the glob-expanded string
6901 probe_point *pp = new probe_point (*location);
5750ecc6
FCE
6902 // PR13338: quote results to prevent recursion
6903 string eglobbed = escape_glob_chars (globbed);
6904
6905 if (sess.verbose > 1)
6906 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6907 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 6908 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 6909
37001baa 6910 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6911 new literal_string (eglobbed_tgt));
37001baa
FCE
6912 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6913 pp->components[0] = ppc;
6914
d885563b 6915 probe* new_probe = new probe (base, pp);
7977a734
FCE
6916
6917 // We override "optional = true" here, as if the
6918 // wildcarded probe point was given a "?" suffix.
6919
6920 // This is because wildcard probes will be expected
6921 // by users to apply only to some subset of the
6922 // matching binaries, in the sense of "any", rather
6923 // than "all", sort of similarly how
6924 // module("*").function("...") patterns work.
6925
6926 derive_probes (sess, new_probe, finished_results,
6927 true /* NB: not location->optional */ );
37001baa
FCE
6928 }
6929 }
6930
6931 globfree (& the_blob);
44ffe90c
JL
6932
6933 unsigned results_post = finished_results.size();
6934
6935 // Did we fail to find a function by name? Let's suggest
6936 // something!
6937 string func;
6938 if (results_pre == results_post
6939 && get_param(filled_parameters, TOK_FUNCTION, func)
6940 && !func.empty())
6941 {
6942 if (sess.verbose > 2)
6943 {
6944 clog << "suggesting functions from modules:" << endl;
6945 for (set<string>::const_iterator it = modules_seen.begin();
6946 it != modules_seen.end(); ++it)
6947 {
6948 clog << *it << endl;
6949 }
6950 }
0508c45f 6951 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
6952 modules_seen.clear();
6953 if (!sugs.empty())
dc09353a 6954 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
6955 "no match (similar functions: %s)",
6956 sugs.find(',') == string::npos,
6957 sugs.c_str()));
6958 }
6959
37001baa
FCE
6960 return; // avoid falling through
6961 }
6962
5750ecc6
FCE
6963 // PR13338: unquote glob results
6964 module_name = unescape_glob_chars (module_name);
05fb3e0c 6965 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
6966
6967 // if the executable starts with "#!", we look for the interpreter of the script
6968 {
6969 ifstream script_file (user_path.c_str () );
6970
6971 if (script_file.good ())
6972 {
6973 string line;
6974
6975 getline (script_file, line);
6976
6977 if (line.compare (0, 2, "#!") == 0)
6978 {
6979 string path_head = line.substr(2);
6980
6981 // remove white spaces at the beginning of the string
6982 size_t p2 = path_head.find_first_not_of(" \t");
6983
6984 if (p2 != string::npos)
6985 {
6986 string path = path_head.substr(p2);
6987
6988 // remove white spaces at the end of the string
6989 p2 = path.find_last_not_of(" \t\n");
6990 if (string::npos != p2)
6991 path.erase(p2+1);
6992
8e13c1a1
RH
6993 // handle "#!/usr/bin/env" redirect
6994 size_t offset = 0;
6995 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
6996 {
6997 offset = sizeof("/bin/env")-1;
6998 }
6999 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7000 {
7001 offset = sizeof("/usr/bin/env")-1;
7002 }
7003
7004 if (offset != 0)
7005 {
7006 size_t p3 = path.find_first_not_of(" \t", offset);
7007
7008 if (p3 != string::npos)
7009 {
7010 string env_path = path.substr(p3);
05fb3e0c
WF
7011 user_path = find_executable (env_path, sess.sysroot,
7012 sess.sysenv);
8e13c1a1
RH
7013 }
7014 }
7015 else
7016 {
05fb3e0c 7017 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7018 }
d1bcbe71
RH
7019
7020 struct stat st;
7021
7022 if (access (user_path.c_str(), X_OK) == 0
7023 && stat (user_path.c_str(), &st) == 0
7024 && S_ISREG (st.st_mode)) // see find_executable()
7025 {
7026 if (sess.verbose > 1)
b530b5b3
LB
7027 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7028 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7029
7030 assert (location->components.size() > 0);
7031 assert (location->components[0]->functor == TOK_PROCESS);
7032 assert (location->components[0]->arg);
7033 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7034 assert (lit);
7035
7036 // synthesize a new probe_point, with the expanded string
7037 probe_point *pp = new probe_point (*location);
05fb3e0c 7038 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7039 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7040 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7041 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7042 pp->components[0] = ppc;
7043
d885563b 7044 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7045
7046 derive_probes (sess, new_probe, finished_results);
7047
7048 script_file.close();
7049 return;
7050 }
7051 }
7052 }
7053 }
7054 script_file.close();
7055 }
7056
47e226ed 7057 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7058 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7059 {
7060 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7061 "LD_LIBRARY_PATH");
7062 if (module_name.find('/') == string::npos)
7063 // We didn't find user_lib so use iterate_over_libraries
7064 module_name = user_path;
7065 }
63b4fd14 7066 else
b642c901 7067 module_name = user_path; // canonicalize it
d0a7f5a9 7068
3667d615 7069 // uretprobes aren't available everywhere
536f1261 7070 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7071 {
3667d615
JS
7072 if (kernel_supports_inode_uprobes(sess) &&
7073 !kernel_supports_inode_uretprobes(sess))
dc09353a 7074 throw SEMANTIC_ERROR
3ffeaf3c 7075 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7076 }
3667d615 7077
f4000852
MW
7078 // There is a similar check in pass 4 (buildrun), but it is
7079 // needed here too to make sure alternatives for optional
7080 // (? or !) process probes are disposed and/or alternatives
7081 // are selected.
3667d615
JS
7082 if (!sess.runtime_usermode_p())
7083 check_process_probe_kernel_support(sess);
e34d5d13 7084
7a24d422
FCE
7085 // user-space target; we use one dwflpp instance per module name
7086 // (= program or shared library)
707bf35e 7087 dw = get_user_dw(sess, module_name);
c8959a29 7088 }
20c6c071 7089
1acfc030
JS
7090 assert(dw);
7091
5896cd05 7092 if (sess.verbose > 3)
b530b5b3 7093 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7094
a794dbeb
FCE
7095 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7096 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7097 {
51d6bda3 7098 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
7099 dw->iterate_over_modules(&query_module, &sdtq);
7100 return;
7a05f484 7101 }
20c6c071 7102
8f14e444 7103 unsigned results_pre = finished_results.size();
6d5d594e 7104 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7105
7106 // XXX: kernel.statement.absolute is a special case that requires no
7107 // dwfl processing. This code should be in a separate builder.
7a24d422 7108 if (q.has_kernel && q.has_absolute)
37ebca01 7109 {
4baf0e53 7110 // assert guru mode for absolute probes
37ebca01
FCE
7111 if (! q.base_probe->privileged)
7112 {
dc09353a 7113 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7114 q.base_probe->tok);
37ebca01
FCE
7115 }
7116
7117 // For kernel.statement(NUM).absolute probe points, we bypass
7118 // all the debuginfo stuff: We just wire up a
7119 // dwarf_derived_probe right here and now.
4baf0e53 7120 dwarf_derived_probe* p =
b8da0ad1
FCE
7121 new dwarf_derived_probe ("", "", 0, "kernel", "",
7122 q.statement_num_val, q.statement_num_val,
7123 q, 0);
37ebca01 7124 finished_results.push_back (p);
1a0dbc5a 7125 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7126 return;
7127 }
7128
51178501 7129 dw->iterate_over_modules(&query_module, &q);
8f14e444 7130
44ffe90c
JL
7131 // We need to update modules_seen with the modules we've visited
7132 modules_seen.insert(q.visited_modules.begin(),
7133 q.visited_modules.end());
8f14e444
FCE
7134
7135 // PR11553 special processing: .return probes requested, but
7136 // some inlined function instances matched.
7137 unsigned i_n_r = q.inlined_non_returnable.size();
7138 unsigned results_post = finished_results.size();
7139 if (i_n_r > 0)
7140 {
7141 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7142 {
7143 string quicklist;
7144 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7145 it != q.inlined_non_returnable.end();
7146 it++)
7147 {
7148 quicklist += " " + (*it);
7149 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7150 {
7151 quicklist += " ...";
7152 break;
7153 }
7154 }
c57ea854 7155
52c2652f 7156 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7157 "cannot probe .return of %u inlined functions %s",
52c2652f 7158 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7159 // There will be also a "no matches" semantic error generated.
7160 }
7161 if (sess.verbose > 1)
52c2652f
NMA
7162 clog << _NF("skipped .return probe of %u inlined function",
7163 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7164 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7165 {
7166 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7167 it != q.inlined_non_returnable.end();
7168 it++)
7169 clog << (*it) << " ";
7170 clog << endl;
7171 }
7172 } // i_n_r > 0
44ffe90c
JL
7173
7174 // Did we fail to find a function by name? Let's suggest something! We
7175 // need to check for optional because otherwise, we will be suggesting
7176 // things during intermediate results without including all the
7177 // possible functions. For example, process("/usr/bin/*").function
7178 // will go through here for each executable found (all labelled as
7179 // optionals). Similarly for library(glob) probes. TODO: find a
7180 // mechanism to have suggestions for optional probes as well when no
7181 // probes could be derived, e.g. probepoint1?, probepoint2 should
7182 // suggest for both 1 and 2 if both fail to resolve (maybe print as a
7183 // warning?). This may entails detecting the difference between script
7184 // optional probes and probes that are optional in recursive calls.
7185 string func;
7186 if (results_pre == results_post && !location->optional
7187 && get_param(filled_parameters, TOK_FUNCTION, func)
7188 && !func.empty())
7189 {
7190 if (sess.verbose > 2)
7191 {
7192 clog << "suggesting functions from modules:" << endl;
7193 for (set<string>::const_iterator it = modules_seen.begin();
7194 it != modules_seen.end(); ++it)
7195 clog << *it << endl;
7196 }
0508c45f 7197 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7198 modules_seen.clear();
7199 if (!sugs.empty())
7200 // Note that this error will not even be printed out if it is
7201 // exactly the same suggestion as a previous throw (since
7202 // print_error() filters out identical errors). Which makes
7203 // sense since it's possible that the user misspelled the same
7204 // function in different probes, in which case the first
7205 // suggestion is sufficient.
dc09353a 7206 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7207 "no match (similar functions: %s)",
7208 sugs.find(',') == string::npos,
7209 sugs.c_str()));
7210 }
7211 else if (results_pre != results_post)
7212 // Something was derived so we won't need to suggest something
7213 modules_seen.clear();
5f0a03a6
JK
7214}
7215
7216symbol_table::~symbol_table()
7217{
c9efa5c9 7218 delete_map(map_by_addr);
5f0a03a6
JK
7219}
7220
7221void
2867a2a1 7222symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7223 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7224{
ab91b232
JK
7225#ifdef __powerpc__
7226 // Map ".sys_foo" to "sys_foo".
7227 if (name[0] == '.')
7228 name++;
7229#endif
5f0a03a6
JK
7230 func_info *fi = new func_info();
7231 fi->addr = addr;
7232 fi->name = name;
ab91b232 7233 fi->weak = weak;
2867a2a1 7234 fi->descriptor = descriptor;
5f0a03a6
JK
7235 map_by_name[fi->name] = fi;
7236 // TODO: Use a multimap in case there are multiple static
7237 // functions with the same name?
1c6b77e5 7238 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7239}
7240
7241enum info_status
7242symbol_table::read_symbols(FILE *f, const string& path)
7243{
7244 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
7245 int ret;
2e67a43b
TM
7246 char *name = 0;
7247 char *mod = 0;
5f0a03a6
JK
7248 char type;
7249 unsigned long long addr;
7250 Dwarf_Addr high_addr = 0;
7251 int line = 0;
7252
62a4021d
FCE
7253#if __GLIBC__ >2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)
7254#define MS_FMT "%ms"
7255#else
7256#define MS_FMT "%as"
7257#endif
7258 // %ms (newer than %as) mallocs space for the string and stores its address.
7259 while ((ret = fscanf(f, "%llx %c " MS_FMT " [" MS_FMT, &addr, &type, &name, &mod)) > 0)
5f0a03a6 7260 {
2e67a43b
TM
7261 auto_free free_name(name);
7262 auto_free free_mod(mod);
5f0a03a6
JK
7263 line++;
7264 if (ret < 3)
7265 {
3d372d6b 7266 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 7267 line, path.c_str());
5f0a03a6
JK
7268 // Caller should delete symbol_table object.
7269 return info_absent;
7270 }
2e67a43b 7271 else if (ret > 3)
5f0a03a6
JK
7272 {
7273 // Modules are loaded above the kernel, so if we're getting
7274 // modules, we're done.
2e67a43b 7275 break;
5f0a03a6 7276 }
ab91b232 7277 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 7278 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
7279 }
7280
1c6b77e5 7281 if (map_by_addr.size() < 1)
5f0a03a6 7282 {
3d372d6b 7283 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 7284 path.c_str()) << endl;
5f0a03a6
JK
7285 return info_absent;
7286 }
7287 return info_present;
7288}
7289
7290// NB: This currently unused. We use get_from_elf() instead because
7291// that gives us raw addresses -- which we need for modules -- whereas
7292// nm provides the address relative to the beginning of the section.
7293enum info_status
83ca3872 7294symbol_table::read_from_elf_file(const string &path,
2713ea24 7295 systemtap_session &sess)
5f0a03a6 7296{
58502ae4
JS
7297 vector<string> cmd;
7298 cmd.push_back("/usr/bin/nm");
7299 cmd.push_back("-n");
7300 cmd.push_back("--defined-only");
7301 cmd.push_back("path");
7302
5f0a03a6 7303 FILE *f;
58502ae4
JS
7304 int child_fd;
7305 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
7306 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 7307 {
58502ae4 7308 // nm failures are detected by stap_waitpid
3d372d6b 7309 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 7310 path.c_str(), strerror(errno));
5f0a03a6
JK
7311 return info_absent;
7312 }
7313 enum info_status status = read_symbols(f, path);
58502ae4 7314 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 7315 {
2713ea24
CM
7316 if (status == info_present)
7317 sess.print_warning("nm cannot read symbol table from " + path);
5f0a03a6
JK
7318 return info_absent;
7319 }
7320 return status;
7321}
7322
7323enum info_status
83ca3872 7324symbol_table::read_from_text_file(const string& path,
2713ea24 7325 systemtap_session &sess)
5f0a03a6
JK
7326{
7327 FILE *f = fopen(path.c_str(), "r");
7328 if (!f)
7329 {
2713ea24 7330 sess.print_warning("cannot read symbol table from " + path + " -- " + strerror(errno));
5f0a03a6
JK
7331 return info_absent;
7332 }
7333 enum info_status status = read_symbols(f, path);
7334 (void) fclose(f);
7335 return status;
7336}
7337
46f7b6be 7338void
f98c6346 7339symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7340{
7341#ifdef __powerpc__
7342 /*
7343 * The .opd section contains function descriptors that can look
7344 * just like function entry points. For example, there's a function
7345 * descriptor called "do_exit" that links to the entry point ".do_exit".
7346 * Reject all symbols in .opd.
7347 */
7348 opd_section = SHN_UNDEF;
7349 Dwarf_Addr bias;
7350 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7351 ?: dwfl_module_getelf (mod, &bias));
7352 Elf_Scn* scn = 0;
7353 size_t shstrndx;
7354
7355 if (!elf)
7356 return;
fcc30d6d 7357 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7358 return;
7359 while ((scn = elf_nextscn(elf, scn)) != NULL)
7360 {
7361 GElf_Shdr shdr_mem;
7362 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7363 if (!shdr)
7364 continue;
7365 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7366 if (!strcmp(name, ".opd"))
7367 {
7368 opd_section = elf_ndxscn(scn);
7369 return;
7370 }
7371 }
7372#endif
7373}
7374
7375bool
7376symbol_table::reject_section(GElf_Word section)
7377{
7378 if (section == SHN_UNDEF)
7379 return true;
7380#ifdef __powerpc__
7381 if (section == opd_section)
7382 return true;
7383#endif
7384 return false;
7385}
7386
5f0a03a6
JK
7387enum info_status
7388symbol_table::get_from_elf()
7389{
7390 Dwarf_Addr high_addr = 0;
7391 Dwfl_Module *mod = mod_info->mod;
7392 int syments = dwfl_module_getsymtab(mod);
7393 assert(syments);
46f7b6be 7394 prepare_section_rejection(mod);
5f0a03a6
JK
7395 for (int i = 1; i < syments; ++i)
7396 {
7397 GElf_Sym sym;
ab91b232
JK
7398 GElf_Word section;
7399 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 7400 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7401 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 7402 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
7403 }
7404 return info_present;
7405}
7406
5f0a03a6
JK
7407func_info *
7408symbol_table::get_func_containing_address(Dwarf_Addr addr)
7409{
1c6b77e5
JS
7410 iterator_t iter = map_by_addr.upper_bound(addr);
7411 if (iter == map_by_addr.begin())
5f0a03a6 7412 return NULL;
2e67a43b 7413 else
1c6b77e5 7414 return (--iter)->second;
5f0a03a6
JK
7415}
7416
3d372d6b
SC
7417func_info *
7418symbol_table::get_first_func()
7419{
7420 iterator_t iter = map_by_addr.begin();
7421 return (iter)->second;
7422}
7423
5f0a03a6
JK
7424func_info *
7425symbol_table::lookup_symbol(const string& name)
7426{
7427 map<string, func_info*>::iterator i = map_by_name.find(name);
7428 if (i == map_by_name.end())
7429 return NULL;
7430 return i->second;
7431}
7432
7433Dwarf_Addr
7434symbol_table::lookup_symbol_address(const string& name)
7435{
7436 func_info *fi = lookup_symbol(name);
7437 if (fi)
7438 return fi->addr;
7439 return 0;
7440}
7441
ab91b232
JK
7442// This is the kernel symbol table. The kernel macro cond_syscall creates
7443// a weak symbol for each system call and maps it to sys_ni_syscall.
7444// For system calls not implemented elsewhere, this weak symbol shows up
7445// in the kernel symbol table. Following the precedent of dwarfful stap,
7446// we refuse to consider such symbols. Here we delete them from our
7447// symbol table.
7448// TODO: Consider generalizing this and/or making it part of blacklist
7449// processing.
7450void
7451symbol_table::purge_syscall_stubs()
7452{
7453 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7454 if (stub_addr == 0)
7455 return;
1c6b77e5 7456 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7457 for (iterator_t iter = purge_range.first;
7458 iter != purge_range.second;
1c6b77e5 7459 )
ab91b232 7460 {
1c6b77e5 7461 func_info *fi = iter->second;
2e67a43b 7462 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7463 {
2e67a43b 7464 map_by_name.erase(fi->name);
1c6b77e5 7465 map_by_addr.erase(iter++);
2e67a43b 7466 delete fi;
2e67a43b 7467 }
1c6b77e5
JS
7468 else
7469 iter++;
ab91b232
JK
7470 }
7471}
7472
5f0a03a6
JK
7473void
7474module_info::get_symtab(dwarf_query *q)
7475{
1c6b77e5
JS
7476 if (symtab_status != info_unknown)
7477 return;
7478
5f0a03a6
JK
7479 sym_table = new symbol_table(this);
7480 if (!elf_path.empty())
7481 {
5f0a03a6
JK
7482 symtab_status = sym_table->get_from_elf();
7483 }
7484 else
7485 {
7486 assert(name == TOK_KERNEL);
ab3ed72d
DS
7487 symtab_status = info_absent;
7488 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
7489 }
7490 if (symtab_status == info_absent)
7491 {
7492 delete sym_table;
7493 sym_table = NULL;
7494 return;
7495 }
7496
ab91b232
JK
7497 if (name == TOK_KERNEL)
7498 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7499}
7500
1c6b77e5
JS
7501// update_symtab reconciles data between the elf symbol table and the dwarf
7502// function enumeration. It updates the symbol table entries with the dwarf
7503// die that describes the function, which also signals to query_module_symtab
7504// that a statement probe isn't needed. In return, it also adds aliases to the
7505// function table for names that share the same addr/die.
7506void
7507module_info::update_symtab(cu_function_cache_t *funcs)
7508{
7509 if (!sym_table)
7510 return;
7511
7512 cu_function_cache_t new_funcs;
7513
7514 for (cu_function_cache_t::iterator func = funcs->begin();
7515 func != funcs->end(); func++)
7516 {
6059d7c4
JL
7517 sym_seen.insert(func->first);
7518
1c6b77e5
JS
7519 // optimization: inlines will never be in the symbol table
7520 if (dwarf_func_inline(&func->second) != 0)
7521 continue;
7522
1ffb8bd1
JS
7523 // XXX We may want to make additional efforts to match mangled elf names
7524 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
7525 // missing, so we may also need to try matching by address. See also the
7526 // notes about _Z in dwflpp::iterate_over_functions().
7527
1c6b77e5
JS
7528 func_info *fi = sym_table->lookup_symbol(func->first);
7529 if (!fi)
7530 continue;
7531
7532 // iterate over all functions at the same address
7533 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
7534 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
7535 {
7536 // update this function with the dwarf die
7537 it->second->die = func->second;
7538
7539 // if this function is a new alias, then
7540 // save it to merge into the function cache
7541 if (it->second != fi)
b7478964 7542 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
7543 }
7544 }
7545
7546 // add all discovered aliases back into the function cache
7547 // NB: this won't replace any names that dwarf may have already found
7548 funcs->insert(new_funcs.begin(), new_funcs.end());
7549}
7550
5f0a03a6
JK
7551module_info::~module_info()
7552{
7553 if (sym_table)
7554 delete sym_table;
b55bc428
FCE
7555}
7556
935447c8 7557// ------------------------------------------------------------------------
888af770 7558// user-space probes
935447c8
DS
7559// ------------------------------------------------------------------------
7560
935447c8 7561
888af770 7562struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7563{
89ba3085
FCE
7564private:
7565 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 7566 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
7567 }
7568
cfcab6c7
JS
7569 void emit_module_maxuprobes (systemtap_session& s);
7570
2b69faaf
JS
7571 // Using our own utrace-based uprobes
7572 void emit_module_utrace_decls (systemtap_session& s);
7573 void emit_module_utrace_init (systemtap_session& s);
7574 void emit_module_utrace_exit (systemtap_session& s);
7575
7576 // Using the upstream inode-based uprobes
7577 void emit_module_inode_decls (systemtap_session& s);
7578 void emit_module_inode_init (systemtap_session& s);
7579 void emit_module_inode_exit (systemtap_session& s);
7580
3a894f7e
JS
7581 // Using the dyninst backend (via stapdyn)
7582 void emit_module_dyninst_decls (systemtap_session& s);
7583 void emit_module_dyninst_init (systemtap_session& s);
7584 void emit_module_dyninst_exit (systemtap_session& s);
7585
935447c8 7586public:
888af770 7587 void emit_module_decls (systemtap_session& s);
935447c8
DS
7588 void emit_module_init (systemtap_session& s);
7589 void emit_module_exit (systemtap_session& s);
7590};
7591
7592
888af770
FCE
7593void
7594uprobe_derived_probe::join_group (systemtap_session& s)
7595{
7596 if (! s.uprobe_derived_probes)
7597 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7598 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
7599 if (s.runtime_usermode_p())
7600 enable_dynprobes(s);
7601 else
4441e344 7602 enable_task_finder(s);
a96d1db0 7603
8a03658e 7604 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
7605 // signal staprun to load that module. If we're using the builtin
7606 // inode-uprobes, we still need to know that it is required.
8a03658e 7607 s.need_uprobes = true;
a96d1db0
DN
7608}
7609
888af770 7610
c0f84e7b
SC
7611void
7612uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7613{
7614 dwarf_derived_probe::getargs(arg_set);
7615 arg_set.insert(arg_set.end(), args.begin(), args.end());
7616}
7617
7618
7619void
7620uprobe_derived_probe::saveargs(int nargs)
7621{
7622 for (int i = 1; i <= nargs; i++)
7623 args.push_back("$arg" + lex_cast (i) + ":long");
7624}
7625
7626
2865d17a 7627void
42e38653 7628uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
7629{
7630 // These probes are allowed for unprivileged users, but only in the
7631 // context of processes which they own.
7632 emit_process_owner_assertion (o);
7633}
7634
7635
888af770 7636struct uprobe_builder: public derived_probe_builder
a96d1db0 7637{
888af770 7638 uprobe_builder() {}
2b69faaf 7639 virtual void build(systemtap_session & sess,
a96d1db0
DN
7640 probe * base,
7641 probe_point * location,
86bf665e 7642 literal_map_t const & parameters,
a96d1db0
DN
7643 vector<derived_probe *> & finished_results)
7644 {
888af770 7645 int64_t process, address;
a96d1db0 7646
2b69faaf 7647 if (kernel_supports_inode_uprobes(sess))
dc09353a 7648 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 7649
888af770 7650 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7651 (void) b1;
888af770 7652 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7653 (void) b2;
888af770
FCE
7654 bool rr = has_null_param (parameters, TOK_RETURN);
7655 assert (b1 && b2); // by pattern_root construction
a96d1db0 7656
0973d815 7657 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7658 }
7659};
7660
7661
7662void
cfcab6c7 7663uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 7664{
43241c44
FCE
7665 // We'll probably need at least this many:
7666 unsigned minuprobes = probes.size();
7667 // .. but we don't want so many that .bss is inflated (PR10507):
7668 unsigned uprobesize = 64;
7669 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7670 unsigned maxuprobes = maxuprobesmem / uprobesize;
7671
aaf7ffe8
FCE
7672 // Let's choose a value on the geometric middle. This should end up
7673 // between minuprobes and maxuprobes. It's OK if this number turns
7674 // out to be < minuprobes or > maxuprobes. At worst, we get a
7675 // run-time error of one kind (too few: missed uprobe registrations)
7676 // or another (too many: vmalloc errors at module load time).
7677 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7678
6d0f3f0c 7679 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7680 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7681 s.op->newline() << "#endif";
cfcab6c7
JS
7682}
7683
7684
7685void
7686uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
7687{
7688 if (probes.empty()) return;
7689 s.op->newline() << "/* ---- utrace uprobes ---- */";
7690 // If uprobes isn't in the kernel, pull it in from the runtime.
7691
7692 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7693 s.op->newline() << "#include <linux/uprobes.h>";
7694 s.op->newline() << "#else";
2ba1736a 7695 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
7696 s.op->newline() << "#endif";
7697 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7698 s.op->newline() << "#define UPROBES_API_VERSION 1";
7699 s.op->newline() << "#endif";
7700
7701 emit_module_maxuprobes (s);
a96d1db0 7702
cc52276b 7703 // Forward decls
2ba1736a 7704 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 7705
5e112f92
FCE
7706 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7707 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7708 // XXX: consider a slab cache or somesuch for stap_uprobes
7709 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 7710 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7711
89ba3085
FCE
7712 s.op->assert_0_indent();
7713
89ba3085
FCE
7714 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7715 // This means we process probes[] in two passes.
7716 map <string,unsigned> module_index;
7717 unsigned module_index_ctr = 0;
7718
cc52276b
WC
7719 // not const since embedded task_finder_target struct changes
7720 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7721 s.op->indent(1);
7722 for (unsigned i=0; i<probes.size(); i++)
7723 {
7724 uprobe_derived_probe *p = probes[i];
7725 string pbmkey = make_pbm_key (p);
7726 if (module_index.find (pbmkey) == module_index.end())
7727 {
7728 module_index[pbmkey] = module_index_ctr++;
7729
7730 s.op->newline() << "{";
7731 // NB: it's essential that make_pbm_key() use all of and
7732 // only the same fields as we're about to emit.
7733 s.op->line() << " .finder={";
1af100fc 7734 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 7735 if (p->pid != 0)
68910c97
JK
7736 s.op->line() << " .pid=" << p->pid << ",";
7737
7738 if (p->section == "") // .statement(addr).absolute
7739 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7740 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7741 {
7742 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7743 s.op->line() << " .callback=&stap_uprobe_process_found,";
7744 }
68910c97 7745 else if (p->section != ".absolute") // ET_DYN
89ba3085 7746 {
4ad95bbc
SC
7747 if (p->has_library)
7748 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7749 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7750 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7751 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7752 }
89ba3085 7753 s.op->line() << " },";
68910c97
JK
7754 if (p->module != "")
7755 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7756 s.op->line() << " },";
7757 }
c57ea854 7758 else
822a6a3d 7759 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7760 }
7761 s.op->newline(-1) << "};";
7762
7763 s.op->assert_0_indent();
7764
3689db05
SC
7765 unsigned pci;
7766 for (pci=0; pci<probes.size(); pci++)
7767 {
7768 // List of perf counters used by each probe
7769 // This list is an index into struct stap_perf_probe,
7770 uprobe_derived_probe *p = probes[pci];
698de6cc 7771 std::set<derived_probe*>::iterator pcii;
3689db05
SC
7772 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
7773 for (pcii = p->perf_counter_refs.begin();
7774 pcii != p->perf_counter_refs.end(); pcii++)
7775 {
7776 map<string, pair<string,derived_probe*> >::iterator it;
7777 unsigned i = 0;
7778 // Find the associated perf.counter probe
7779 for (it=s.perf_counters.begin() ;
7780 it != s.perf_counters.end(); it++, i++)
7781 if ((*it).second.second == (*pcii))
7782 break;
7783 s.op->line() << lex_cast(i) << ", ";
7784 }
7785 s.op->newline() << "};";
7786 }
7787
cc52276b
WC
7788 // NB: read-only structure
7789 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7790 s.op->indent(1);
888af770
FCE
7791 for (unsigned i =0; i<probes.size(); i++)
7792 {
7793 uprobe_derived_probe* p = probes[i];
7794 s.op->newline() << "{";
89ba3085
FCE
7795 string key = make_pbm_key (p);
7796 unsigned value = module_index[key];
759e1d76
FCE
7797 if (value != 0)
7798 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7799 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7800 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7801
038c38c6 7802 if (p->sdt_semaphore_addr != 0)
63b4fd14 7803 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7804 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 7805
0d049a1d 7806 // XXX: don't bother emit if array is empty
3689db05
SC
7807 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
7808 // List of perf counters used by a probe from above
0d049a1d 7809 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 7810
4ddb6dd0
JS
7811 if (p->has_return)
7812 s.op->line() << " .return_p=1,";
888af770
FCE
7813 s.op->line() << " },";
7814 }
7815 s.op->newline(-1) << "};";
a96d1db0 7816
89ba3085
FCE
7817 s.op->assert_0_indent();
7818
48e685da 7819 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7820 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7821 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7822 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7823 "stp_probe_type_uprobe");
0e090c74 7824 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7825 << "sup->spec_index >= " << probes.size() << ") {";
7826 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7827 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7828 s.op->newline() << "atomic_dec (&c->busy);";
7829 s.op->newline() << "goto probe_epilogue;";
7830 s.op->newline(-1) << "}";
d9aed31e 7831 s.op->newline() << "c->uregs = regs;";
e04b5d74 7832 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7833
7834 // Make it look like the IP is set as it would in the actual user
7835 // task when calling real probe handler. Reset IP regs on return, so
7836 // we don't confuse uprobes. PR10458
7837 s.op->newline() << "{";
7838 s.op->indent(1);
d9aed31e 7839 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7840 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7841 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7842 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7843 s.op->newline(-1) << "}";
7844
f887a8c9 7845 common_probe_entryfn_epilogue (s, true);
888af770 7846 s.op->newline(-1) << "}";
a96d1db0 7847
48e685da 7848 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7849 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7850 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7851 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7852 "stp_probe_type_uretprobe");
6dceb5c9 7853 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7854 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7855 << "sup->spec_index >= " << probes.size() << ") {";
7856 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7857 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7858 s.op->newline() << "atomic_dec (&c->busy);";
7859 s.op->newline() << "goto probe_epilogue;";
7860 s.op->newline(-1) << "}";
7861
d9aed31e 7862 s.op->newline() << "c->uregs = regs;";
e04b5d74 7863 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7864
7865 // Make it look like the IP is set as it would in the actual user
7866 // task when calling real probe handler. Reset IP regs on return, so
7867 // we don't confuse uprobes. PR10458
7868 s.op->newline() << "{";
7869 s.op->indent(1);
d9aed31e 7870 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7871 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7872 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7873 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7874 s.op->newline(-1) << "}";
7875
f887a8c9 7876 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
7877 s.op->newline(-1) << "}";
7878
89ba3085 7879 s.op->newline();
2ba1736a 7880 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 7881 s.op->newline();
888af770 7882}
935447c8
DS
7883
7884
888af770 7885void
2b69faaf 7886uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 7887{
888af770 7888 if (probes.empty()) return;
935447c8 7889
2b69faaf 7890 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 7891
01b05e2e 7892 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
7893 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
7894 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
7895 // NB: we assume the rest of the struct (specificaly, sup->up) is
7896 // initialized to zero. This is so that we can use
7897 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
7898 s.op->newline(-1) << "}";
7899 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 7900
89ba3085
FCE
7901 // Set up the task_finders
7902 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
7903 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 7904 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 7905 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 7906
5e112f92
FCE
7907 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
7908 // finders already registered, since mere registration does not
7909 // cause any utrace or memory allocation actions. That happens only
7910 // later, once the task finder engine starts running. So, for a
7911 // partial initialization requiring unwind, we need do nothing.
7912 s.op->newline() << "if (rc) break;";
a7a68293 7913
888af770
FCE
7914 s.op->newline(-1) << "}";
7915}
d0ea46ce 7916
d0a7f5a9 7917
888af770 7918void
2b69faaf 7919uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
7920{
7921 if (probes.empty()) return;
2b69faaf 7922 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 7923
6d0f3f0c
FCE
7924 // NB: there is no stap_unregister_task_finder_target call;
7925 // important stuff like utrace cleanups are done by
d41d451c
FCE
7926 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7927 //
7928 // This function blocks until all callbacks are completed, so there
7929 // is supposed to be no possibility of any registration-related code starting
7930 // to run in parallel with our shutdown here. So we don't need to protect the
7931 // stap_uprobes[] array with the mutex.
d0a7f5a9 7932
01b05e2e 7933 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7934 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7935 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7936 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7937
8faa1fc5 7938 // PR10655: decrement that ENABLED semaphore
c116c31b 7939 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7940 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7941 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7942 s.op->newline() << "struct task_struct *tsk;";
7943 s.op->newline() << "rcu_read_lock();";
6846cfc8 7944
86229a55
DS
7945 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7946 // that the pid is always in the global namespace, not in any
7947 // private namespace.
8faa1fc5 7948 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7949 // We'd like to call find_task_by_pid_ns() here, but it isn't
7950 // exported. So, we call what it calls...
7951 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7952 s.op->newline() << "#else";
7953 s.op->newline() << " tsk = find_task_by_pid (pid);";
7954 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7955
7956 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7957 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7958 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7959 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7960 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7961 s.op->newline() << "#endif";
3c5b8e2b 7962 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7963 s.op->newline(-1) << "}";
8faa1fc5
FCE
7964 // XXX: need to analyze possibility of race condition
7965 s.op->newline(-1) << "}";
7966 s.op->newline() << "rcu_read_unlock();";
7967 s.op->newline(-1) << "}";
6846cfc8 7968
3568f1dd
FCE
7969 s.op->newline() << "if (sups->return_p) {";
7970 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7971 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 7972 s.op->newline() << "#endif";
80b4ad8b
FCE
7973 // NB: PR6829 does not change that we still need to unregister at
7974 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7975 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7976 s.op->newline(-1) << "} else {";
7977 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7978 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
7979 s.op->newline() << "#endif";
7980 s.op->newline() << "unregister_uprobe (& sup->up);";
7981 s.op->newline(-1) << "}";
935447c8 7982
6d0f3f0c 7983 s.op->newline() << "sup->spec_index = -1;";
935447c8 7984
3568f1dd
FCE
7985 // XXX: uprobe missed counts?
7986
6d0f3f0c 7987 s.op->newline(-1) << "}";
935447c8 7988
5e112f92 7989 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
7990}
7991
2b69faaf
JS
7992
7993void
7994uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
7995{
7996 if (probes.empty()) return;
7997 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 7998 emit_module_maxuprobes (s);
2ba1736a 7999 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8000
8001 // Write the probe handler.
79af55c3
JS
8002 s.op->newline() << "static int stapiu_probe_handler "
8003 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8004 s.op->newline(1);
2dbbd473
JS
8005
8006 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8007 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8008 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8009 probe_type);
8010
3bff6634 8011 s.op->newline() << "c->uregs = regs;";
e04b5d74 8012 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8013 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8014 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8015
f887a8c9 8016 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8017 s.op->newline() << "return 0;";
8018 s.op->newline(-1) << "}";
8019 s.op->assert_0_indent();
8020
8021 // Index of all the modules for which we need inodes.
8022 map<string, unsigned> module_index;
8023 unsigned module_index_ctr = 0;
8024
8025 // Discover and declare targets for each unique path.
cfcab6c7 8026 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8027 << "stap_inode_uprobe_targets[] = {";
8028 s.op->indent(1);
8029 for (unsigned i=0; i<probes.size(); i++)
8030 {
8031 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8032 const string key = make_pbm_key(p);
8033 if (module_index.find (key) == module_index.end())
2b69faaf 8034 {
cfcab6c7
JS
8035 module_index[key] = module_index_ctr++;
8036 s.op->newline() << "{";
8037 s.op->line() << " .finder={";
1af100fc 8038 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8039 if (p->pid != 0)
8040 s.op->line() << " .pid=" << p->pid << ",";
8041
8042 if (p->section == "") // .statement(addr).absolute XXX?
8043 s.op->line() << " .callback=&stapiu_process_found,";
8044 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8045 {
8046 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8047 s.op->line() << " .callback=&stapiu_process_found,";
8048 }
8049 else if (p->section != ".absolute") // ET_DYN
8050 {
8051 if (p->has_library)
8052 s.op->line() << " .procname=\"" << p->path << "\", ";
8053 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8054 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8055 s.op->line() << " .callback=&stapiu_process_munmap,";
8056 }
8057 s.op->line() << " },";
8058 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8059 s.op->line() << " },";
2b69faaf
JS
8060 }
8061 }
8062 s.op->newline(-1) << "};";
8063 s.op->assert_0_indent();
8064
8065 // Declare the actual probes.
3689db05
SC
8066 unsigned pci;
8067 for (pci=0; pci<probes.size(); pci++)
8068 {
8069 // List of perf counters used by each probe
8070 // This list is an index into struct stap_perf_probe,
8071 uprobe_derived_probe *p = probes[pci];
698de6cc 8072 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8073 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8074 for (pcii = p->perf_counter_refs.begin();
8075 pcii != p->perf_counter_refs.end(); pcii++)
8076 {
8077 map<string, pair<string,derived_probe*> >::iterator it;
8078 unsigned i = 0;
8079 // Find the associated perf.counter probe
4fa83377
SC
8080 for (it=s.perf_counters.begin() ;
8081 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8082 if ((*it).second.second == (*pcii))
8083 break;
8084 s.op->line() << lex_cast(i) << ", ";
8085 }
8086 s.op->newline() << "};";
8087 }
8088
cfcab6c7 8089 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8090 << "stap_inode_uprobe_consumers[] = {";
8091 s.op->indent(1);
8092 for (unsigned i=0; i<probes.size(); i++)
8093 {
8094 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8095 unsigned index = module_index[make_pbm_key(p)];
8096 s.op->newline() << "{";
79af55c3
JS
8097 if (p->has_return)
8098 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8099 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8100 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8101 if (p->sdt_semaphore_addr)
8102 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8103 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8104 // XXX: don't bother emit if array is empty
3689db05
SC
8105 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8106 // List of perf counters used by a probe from above
0d049a1d 8107 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8108 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8109 s.op->line() << " },";
2b69faaf
JS
8110 }
8111 s.op->newline(-1) << "};";
8112 s.op->assert_0_indent();
8113}
8114
8115
8116void
8117uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8118{
8119 if (probes.empty()) return;
8120 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8121 // Let stapiu_init() handle reporting errors by setting probe_point
8122 // to NULL.
8123 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8124 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8125 << "stap_inode_uprobe_targets, "
8126 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8127 << "stap_inode_uprobe_consumers, "
8128 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8129}
8130
8131
8132void
8133uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8134{
8135 if (probes.empty()) return;
8136 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8137 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8138 << "stap_inode_uprobe_targets, "
8139 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8140 << "stap_inode_uprobe_consumers, "
8141 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8142}
8143
8144
3a894f7e
JS
8145void
8146uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8147{
8148 if (probes.empty()) return;
8149 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8150 emit_module_maxuprobes (s);
e00f3fb7 8151 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8152
f31a77f5
DS
8153 // Let the dynprobe_derived_probe_group handle outputting targets
8154 // and probes. This allows us to merge different types of probes.
8155 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8156 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8157 {
8158 uprobe_derived_probe *p = probes[i];
e00f3fb7 8159
f31a77f5
DS
8160 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8161 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8162 common_probe_init(p));
3a894f7e 8163 }
874d38bf
JS
8164 // loc2c-generated code assumes pt_regs are available, so use this to make
8165 // sure we always have *something* for it to dereference...
f31a77f5 8166 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8167
3a894f7e
JS
8168 // Write the probe handler.
8169 // NB: not static, so dyninst can find it
8170 s.op->newline() << "int enter_dyninst_uprobe "
8171 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8172 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8173
8174 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8175 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8176 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8177 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8178 probe_type);
8179
874d38bf 8180 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8181 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8182 // XXX: once we have regs, check how dyninst sets the IP
8183 // XXX: the way that dyninst rewrites stuff is probably going to be
8184 // ... very confusing to our backtracer (at least if we stay in process)
8185 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8186 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8187 s.op->newline() << "return 0;";
8188 s.op->newline(-1) << "}";
3debb935 8189 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8190 s.op->assert_0_indent();
8191}
8192
8193
8194void
8195uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8196{
8197 if (probes.empty()) return;
8198
8199 /* stapdyn handles the dirty work via dyninst */
8200 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8201 s.op->newline() << "/* this section left intentionally blank */";
8202}
8203
8204
8205void
8206uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8207{
8208 if (probes.empty()) return;
8209
8210 /* stapdyn handles the dirty work via dyninst */
8211 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8212 s.op->newline() << "/* this section left intentionally blank */";
8213}
8214
8215
2b69faaf
JS
8216void
8217uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8218{
ac3af990 8219 if (s.runtime_usermode_p())
4441e344
JS
8220 emit_module_dyninst_decls (s);
8221 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8222 emit_module_inode_decls (s);
8223 else
8224 emit_module_utrace_decls (s);
8225}
8226
8227
8228void
8229uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8230{
ac3af990 8231 if (s.runtime_usermode_p())
4441e344
JS
8232 emit_module_dyninst_init (s);
8233 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8234 emit_module_inode_init (s);
8235 else
8236 emit_module_utrace_init (s);
8237}
8238
8239
8240void
8241uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8242{
ac3af990 8243 if (s.runtime_usermode_p())
4441e344
JS
8244 emit_module_dyninst_exit (s);
8245 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8246 emit_module_inode_exit (s);
8247 else
8248 emit_module_utrace_exit (s);
8249}
8250
8251
e6fe60e7
AM
8252// ------------------------------------------------------------------------
8253// Kprobe derived probes
8254// ------------------------------------------------------------------------
8255
4627ed58 8256static const string TOK_KPROBE("kprobe");
935447c8 8257
bae55db9 8258struct kprobe_derived_probe: public derived_probe
d0ea46ce 8259{
23dc94f6
DS
8260 kprobe_derived_probe (systemtap_session& sess,
8261 vector<derived_probe *> & results,
8262 probe *base,
bae55db9
JS
8263 probe_point *location,
8264 const string& name,
8265 int64_t stmt_addr,
8266 bool has_return,
8267 bool has_statement,
8268 bool has_maxactive,
b642c901
SC
8269 bool has_path,
8270 bool has_library,
8271 long maxactive_val,
8272 const string& path,
8273 const string& library
bae55db9
JS
8274 );
8275 string symbol_name;
8276 Dwarf_Addr addr;
8277 bool has_return;
8278 bool has_statement;
8279 bool has_maxactive;
b642c901
SC
8280 bool has_path;
8281 bool has_library;
bae55db9 8282 long maxactive_val;
b642c901
SC
8283 string path;
8284 string library;
bae55db9
JS
8285 bool access_var;
8286 void printsig (std::ostream &o) const;
8287 void join_group (systemtap_session& s);
8288};
d0ea46ce 8289
bae55db9
JS
8290struct kprobe_derived_probe_group: public derived_probe_group
8291{
8292private:
8293 multimap<string,kprobe_derived_probe*> probes_by_module;
8294 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8295
bae55db9
JS
8296public:
8297 void enroll (kprobe_derived_probe* probe);
8298 void emit_module_decls (systemtap_session& s);
8299 void emit_module_init (systemtap_session& s);
8300 void emit_module_exit (systemtap_session& s);
8301};
d0ea46ce 8302
23dc94f6
DS
8303struct kprobe_var_expanding_visitor: public var_expanding_visitor
8304{
8305 systemtap_session& sess;
8306 block *add_block;
8307 block *add_call_probe; // synthesized from .return probes with saved $vars
8308 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8309 bool has_return;
23dc94f6 8310
bd5b25e1 8311 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8312 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8313 add_block_tid(false), add_call_probe_tid(false),
8314 has_return(has_return) {}
23dc94f6
DS
8315
8316 void visit_entry_op (entry_op* e);
8317};
8318
8319
8320kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8321 vector<derived_probe *> & results,
8322 probe *base,
e6fe60e7 8323 probe_point *location,
b6371390 8324 const string& name,
e6fe60e7 8325 int64_t stmt_addr,
b6371390
JS
8326 bool has_return,
8327 bool has_statement,
8328 bool has_maxactive,
b642c901
SC
8329 bool has_path,
8330 bool has_library,
8331 long maxactive_val,
8332 const string& path,
8333 const string& library
b6371390 8334 ):
4c5d1300 8335 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 8336 symbol_name (name), addr (stmt_addr),
b6371390 8337 has_return (has_return), has_statement (has_statement),
b642c901
SC
8338 has_maxactive (has_maxactive), has_path (has_path),
8339 has_library (has_library),
8340 maxactive_val (maxactive_val),
8341 path (path), library (library)
e6fe60e7
AM
8342{
8343 this->tok = base->tok;
8344 this->access_var = false;
d0ea46ce 8345
e6fe60e7
AM
8346#ifndef USHRT_MAX
8347#define USHRT_MAX 32767
8348#endif
d0ea46ce 8349
46856d8d
JS
8350 // Expansion of $target variables in the probe body produces an error during
8351 // translate phase, since we're not using debuginfo
d0ea46ce 8352
e6fe60e7 8353 vector<probe_point::component*> comps;
46856d8d 8354 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8355
46856d8d
JS
8356 if (has_statement)
8357 {
9ea68eb9
JS
8358 comps.push_back (new probe_point::component(TOK_STATEMENT,
8359 new literal_number(addr, true)));
46856d8d
JS
8360 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8361 }
8362 else
8363 {
8364 size_t pos = name.find(':');
8365 if (pos != string::npos)
d0ea46ce 8366 {
46856d8d
JS
8367 string module = name.substr(0, pos);
8368 string function = name.substr(pos + 1);
8369 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8370 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8371 }
8372 else
8373 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8374 }
d0ea46ce 8375
b6371390
JS
8376 if (has_return)
8377 comps.push_back (new probe_point::component(TOK_RETURN));
8378 if (has_maxactive)
8379 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8380
bd5b25e1 8381 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8382 v.replace (this->body);
8383
8384 // If during target-variable-expanding the probe, we added a new block
8385 // of code, add it to the start of the probe.
8386 if (v.add_block)
8387 this->body = new block(v.add_block, this->body);
8388
8389 // If when target-variable-expanding the probe, we need to
8390 // synthesize a sibling function-entry probe. We don't go through
8391 // the whole probe derivation business (PR10642) that could lead to
8392 // wildcard/alias resolution, or for that dwarf-induced duplication.
8393 if (v.add_call_probe)
8394 {
8395 assert (has_return);
8396
8397 // We temporarily replace base.
8398 statement* old_body = base->body;
8399 base->body = v.add_call_probe;
8400
8401 derived_probe *entry_handler
8402 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8403 false, has_statement, has_maxactive,
8404 has_path, has_library, maxactive_val,
8405 path, library);
8406 results.push_back (entry_handler);
8407
8408 base->body = old_body;
8409 }
8410
e6fe60e7
AM
8411 this->sole_location()->components = comps;
8412}
d0ea46ce 8413
e6fe60e7
AM
8414void kprobe_derived_probe::printsig (ostream& o) const
8415{
8416 sole_location()->print (o);
8417 o << " /* " << " name = " << symbol_name << "*/";
8418 printsig_nested (o);
8419}
d0ea46ce 8420
e6fe60e7
AM
8421void kprobe_derived_probe::join_group (systemtap_session& s)
8422{
d0ea46ce 8423
e6fe60e7
AM
8424 if (! s.kprobe_derived_probes)
8425 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8426 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8427
e6fe60e7 8428}
d0ea46ce 8429
e6fe60e7
AM
8430void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8431{
8432 probes_by_module.insert (make_pair (p->symbol_name, p));
8433 // probes of same symbol should share single kprobe/kretprobe
8434}
d0ea46ce 8435
e6fe60e7
AM
8436void
8437kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8438{
8439 if (probes_by_module.empty()) return;
d0ea46ce 8440
e6fe60e7 8441 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8442
e6fe60e7
AM
8443 // Warn of misconfigured kernels
8444 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8445 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8446 s.op->newline() << "#endif";
8447 s.op->newline();
d0ea46ce 8448
f07c3b68 8449 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8450 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8451 s.op->newline() << "#endif";
8452
e6fe60e7 8453 // Forward declare the master entry functions
88747011 8454 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8455 s.op->line() << " struct pt_regs *regs);";
88747011 8456 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8457 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8458
e6fe60e7
AM
8459 // Emit an array of kprobe/kretprobe pointers
8460 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8461 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8462 s.op->newline() << "#endif";
d0ea46ce 8463
e6fe60e7 8464 // Emit the actual probe list.
d0ea46ce 8465
e6fe60e7
AM
8466 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8467 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8468 s.op->newline() << "#ifdef __ia64__";
8469 s.op->newline() << "struct kprobe dummy;";
8470 s.op->newline() << "#endif";
8471 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8472 // NB: bss!
d0ea46ce 8473
e6fe60e7
AM
8474 s.op->newline() << "static struct stap_dwarfless_probe {";
8475 s.op->newline(1) << "const unsigned return_p:1;";
8476 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8477 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8478 s.op->newline() << "unsigned registered_p:1;";
8479 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 8480
e6fe60e7
AM
8481 // Function Names are mostly small and uniform enough to justify putting
8482 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 8483
faea5e16
JS
8484 size_t symbol_string_name_max = 0;
8485 size_t symbol_string_name_tot = 0;
e6fe60e7 8486 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 8487 {
e6fe60e7
AM
8488 kprobe_derived_probe* p = it->second;
8489#define DOIT(var,expr) do { \
8490 size_t var##_size = (expr) + 1; \
8491 var##_max = max (var##_max, var##_size); \
8492 var##_tot += var##_size; } while (0)
e6fe60e7
AM
8493 DOIT(symbol_string_name, p->symbol_name.size());
8494#undef DOIT
6270adc1
MH
8495 }
8496
e6fe60e7
AM
8497#define CALCIT(var) \
8498 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 8499
e6fe60e7
AM
8500 CALCIT(symbol_string);
8501#undef CALCIT
6270adc1 8502
bd659351 8503 s.op->newline() << "unsigned long address;";
7c3e97f4 8504 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
8505 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
8506 s.op->indent(1);
6270adc1 8507
e6fe60e7
AM
8508 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
8509 {
8510 kprobe_derived_probe* p = it->second;
8511 s.op->newline() << "{";
8512 if (p->has_return)
8513 s.op->line() << " .return_p=1,";
6270adc1 8514
e6fe60e7
AM
8515 if (p->has_maxactive)
8516 {
8517 s.op->line() << " .maxactive_p=1,";
8518 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
8519 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
8520 }
6270adc1 8521
b350f56b
JS
8522 if (p->locations[0]->optional)
8523 s.op->line() << " .optional_p=1,";
8524
e6fe60e7 8525 if (p->has_statement)
c8d9d15e 8526 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 8527 else
c8d9d15e 8528 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 8529
faea5e16 8530 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 8531 s.op->line() << " },";
935447c8
DS
8532 }
8533
e6fe60e7 8534 s.op->newline(-1) << "};";
5d67b47c 8535
e6fe60e7
AM
8536 // Emit the kprobes callback function
8537 s.op->newline();
88747011 8538 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
8539 s.op->line() << " struct pt_regs *regs) {";
8540 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8541 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8542 // Check that the index is plausible
8543 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8544 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8545 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8546 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8547 s.op->line() << "];";
71db462b 8548 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8549 "stp_probe_type_kprobe");
d9aed31e 8550 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
8551
8552 // Make it look like the IP is set as it wouldn't have been replaced
8553 // by a breakpoint instruction when calling real probe handler. Reset
8554 // IP regs on return, so we don't confuse kprobes. PR10458
8555 s.op->newline() << "{";
8556 s.op->indent(1);
d9aed31e 8557 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8558 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 8559 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8560 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8561 s.op->newline(-1) << "}";
8562
f887a8c9 8563 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8564 s.op->newline() << "return 0;";
8565 s.op->newline(-1) << "}";
935447c8 8566
e6fe60e7
AM
8567 // Same for kretprobes
8568 s.op->newline();
88747011 8569 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
8570 s.op->line() << " struct pt_regs *regs) {";
8571 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 8572
e6fe60e7
AM
8573 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8574 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8575 // Check that the index is plausible
8576 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8577 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8578 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8579 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8580 s.op->line() << "];";
935447c8 8581
71db462b 8582 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8583 "stp_probe_type_kretprobe");
d9aed31e 8584 s.op->newline() << "c->kregs = regs;";
6dceb5c9 8585 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
8586
8587 // Make it look like the IP is set as it wouldn't have been replaced
8588 // by a breakpoint instruction when calling real probe handler. Reset
8589 // IP regs on return, so we don't confuse kprobes. PR10458
8590 s.op->newline() << "{";
8591 s.op->indent(1);
d9aed31e 8592 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8593 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 8594 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8595 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8596 s.op->newline(-1) << "}";
8597
f887a8c9 8598 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8599 s.op->newline() << "return 0;";
8600 s.op->newline(-1) << "}";
bd659351 8601
03a4ec63 8602 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8603 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
8604 s.op->newline() << " struct module *owner,";
8605 s.op->newline() << " unsigned long val) {";
8606 s.op->newline(1) << "int i;";
fc1d2aa2
MW
8607 s.op->newline() << "int *p = (int *) data;";
8608 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
8609 << " && *p > 0; i++) {";
bd659351 8610 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
8611 s.op->newline() << "if (! sdp->address) {";
8612 s.op->indent(1);
8613 s.op->newline() << "const char *colon;";
8614 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
8615 s.op->indent(1);
8616 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
8617 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
8618 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
8619 s.op->newline(1) << "sdp->address = val;";
8620 s.op->newline() << "(*p)--;";
8621 s.op->newline(-1) << "}";
8622 s.op->newline(-1) << "}";
8623 s.op->newline() << "else {";
fc1d2aa2 8624 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 8625 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
8626 s.op->newline() << "(*p)--;";
8627 s.op->newline(-1) << "}";
8c272819
YW
8628 s.op->newline(-1) << "}";
8629 s.op->newline(-1) << "}";
8630 s.op->newline(-1) << "}";
fc1d2aa2 8631 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 8632 s.op->newline(-1) << "}";
03a4ec63 8633 s.op->newline() << "#endif";
935447c8
DS
8634}
8635
e6fe60e7 8636
6270adc1 8637void
e6fe60e7 8638kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 8639{
03a4ec63 8640 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
8641 s.op->newline() << "{";
8642 s.op->newline(1) << "int p = 0;";
8643 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
8644 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8645 s.op->newline() << "if (! sdp->address)";
8646 s.op->newline(1) << "p++;";
8647 s.op->newline(-2) << "}";
8648 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
8649 s.op->newline(-1) << "}";
03a4ec63 8650 s.op->newline() << "#endif";
bd659351 8651
e6fe60e7 8652 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 8653 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 8654 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 8655 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
8656 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
8657
8658 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8659 s.op->newline() << "if (! addr) {";
8660 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
8661 s.op->newline() << "if (!sdp->optional_p)";
8662 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
8663 s.op->newline(-1) << "continue;";
bd659351 8664 s.op->newline(-1) << "}";
03a4ec63
MW
8665 s.op->newline() << "#endif";
8666
26e63673 8667 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 8668 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 8669 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 8670 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8671 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 8672 s.op->newline() << "#endif";
e6fe60e7
AM
8673 s.op->newline() << "if (sdp->maxactive_p) {";
8674 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
8675 s.op->newline(-1) << "} else {";
f07c3b68 8676 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 8677 s.op->newline(-1) << "}";
88747011 8678 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
8679 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
8680 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8681 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 8682 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8683 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 8684 s.op->newline() << "#endif";
c8d9d15e 8685 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
8686 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8687 s.op->newline() << "if (rc == 0) {";
8688 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
8689 s.op->newline() << "if (rc != 0)";
8690 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8691 s.op->newline(-2) << "}";
8692 s.op->newline() << "#else";
8693 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
8694 s.op->newline() << "#endif";
8695 s.op->newline(-1) << "} else {";
8696 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 8697 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 8698 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8699 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 8700 s.op->newline() << "#endif";
88747011 8701 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 8702 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8703 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 8704 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 8705 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8706 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 8707 s.op->newline() << "#endif";
e6fe60e7
AM
8708 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8709 s.op->newline() << "if (rc == 0) {";
8710 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
8711 s.op->newline() << "if (rc != 0)";
8712 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8713 s.op->newline(-2) << "}";
8714 s.op->newline() << "#else";
8715 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
8716 s.op->newline() << "#endif";
8717 s.op->newline(-1) << "}";
8718 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
8719 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 8720 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 8721 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 8722 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
8723 // XXX: shall we increment numskipped?
8724 s.op->newline(-1) << "}";
6270adc1 8725
e6fe60e7
AM
8726 s.op->newline() << "else sdp->registered_p = 1;";
8727 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
8728}
8729
b4be7cbc 8730
e6fe60e7
AM
8731void
8732kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 8733{
e6fe60e7
AM
8734 //Unregister kprobes by batch interfaces.
8735 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
8736 s.op->newline() << "j = 0;";
8737 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8738 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8739 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8740 s.op->newline() << "if (! sdp->registered_p) continue;";
8741 s.op->newline() << "if (!sdp->return_p)";
c9116e99 8742 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 8743 s.op->newline(-2) << "}";
c9116e99 8744 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8745 s.op->newline() << "j = 0;";
8746 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8747 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8748 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8749 s.op->newline() << "if (! sdp->registered_p) continue;";
8750 s.op->newline() << "if (sdp->return_p)";
c9116e99 8751 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 8752 s.op->newline(-2) << "}";
c9116e99 8753 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8754 s.op->newline() << "#ifdef __ia64__";
8755 s.op->newline() << "j = 0;";
8756 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8757 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8758 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8759 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 8760 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 8761 s.op->newline(-1) << "}";
c9116e99 8762 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8763 s.op->newline() << "#endif";
8764 s.op->newline() << "#endif";
3e3bd7b6 8765
e6fe60e7
AM
8766 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8767 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8768 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8769 s.op->newline() << "if (! sdp->registered_p) continue;";
8770 s.op->newline() << "if (sdp->return_p) {";
8771 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8772 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
8773 s.op->newline() << "#endif";
065d5567 8774 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
8775 s.op->newline() << "#ifdef STP_TIMING";
8776 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 8777 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 8778 s.op->newline(-1) << "#endif";
065d5567 8779 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
8780 s.op->newline() << "#ifdef STP_TIMING";
8781 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 8782 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
8783 s.op->newline(-1) << "#endif";
8784 s.op->newline(-1) << "} else {";
8785 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8786 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
8787 s.op->newline() << "#endif";
065d5567 8788 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
8789 s.op->newline() << "#ifdef STP_TIMING";
8790 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 8791 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
8792 s.op->newline(-1) << "#endif";
8793 s.op->newline(-1) << "}";
8794 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
8795 s.op->newline() << "unregister_kprobe (&kp->dummy);";
8796 s.op->newline() << "#endif";
8797 s.op->newline() << "sdp->registered_p = 0;";
8798 s.op->newline(-1) << "}";
f8a968bc
JS
8799}
8800
e6fe60e7 8801struct kprobe_builder: public derived_probe_builder
3c1b3d06 8802{
9fdf787d 8803public:
2a639817 8804 kprobe_builder() {}
9fdf787d 8805
2a639817 8806 void build_no_more (systemtap_session &s) {}
9fdf787d 8807
e6fe60e7
AM
8808 virtual void build(systemtap_session & sess,
8809 probe * base,
8810 probe_point * location,
8811 literal_map_t const & parameters,
8812 vector<derived_probe *> & finished_results);
8813};
3c1b3d06
FCE
8814
8815
79189b84 8816void
05fb3e0c 8817kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
8818 probe * base,
8819 probe_point * location,
8820 literal_map_t const & parameters,
8821 vector<derived_probe *> & finished_results)
79189b84 8822{
e6fe60e7 8823 string function_string_val, module_string_val;
05fb3e0c 8824 string path, library, path_tgt, library_tgt;
b6371390
JS
8825 int64_t statement_num_val = 0, maxactive_val = 0;
8826 bool has_function_str, has_module_str, has_statement_num;
8827 bool has_absolute, has_return, has_maxactive;
b642c901 8828 bool has_path, has_library;
79189b84 8829
b6371390
JS
8830 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
8831 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
8832 has_return = has_null_param (parameters, TOK_RETURN);
8833 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
8834 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
8835 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
8836 has_path = get_param (parameters, TOK_PROCESS, path);
8837 has_library = get_param (parameters, TOK_LIBRARY, library);
8838
8839 if (has_path)
05fb3e0c
WF
8840 {
8841 path = find_executable (path, sess.sysroot, sess.sysenv);
8842 path_tgt = path_remove_sysroot(sess, path);
8843 }
b642c901 8844 if (has_library)
05fb3e0c
WF
8845 {
8846 library = find_executable (library, sess.sysroot, sess.sysenv,
8847 "LD_LIBRARY_PATH");
8848 library_tgt = path_remove_sysroot(sess, library);
8849 }
c57ea854 8850
b6371390 8851 if (has_function_str)
6fb70fb7 8852 {
2a639817 8853 if (has_module_str)
9fdf787d
DS
8854 {
8855 function_string_val = module_string_val + ":" + function_string_val;
8856 derived_probe *dp
23dc94f6
DS
8857 = new kprobe_derived_probe (sess, finished_results, base,
8858 location, function_string_val,
9fdf787d
DS
8859 0, has_return, has_statement_num,
8860 has_maxactive, has_path, has_library,
8861 maxactive_val, path_tgt, library_tgt);
8862 finished_results.push_back (dp);
8863 }
8864 else
8865 {
2a639817
JS
8866 vector<string> matches;
8867
8868 // Simple names can be found directly
8869 if (function_string_val.find_first_of("*?[") == string::npos)
8870 {
8871 if (sess.kernel_functions.count(function_string_val))
8872 matches.push_back(function_string_val);
8873 }
8874 else // Search function name list for matching names
8875 {
8876 for (set<string>::const_iterator it = sess.kernel_functions.begin();
8877 it != sess.kernel_functions.end(); it++)
8878 // fnmatch returns zero for matching.
8879 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
8880 matches.push_back(*it);
8881 }
86758d5f 8882
2a639817
JS
8883 for (vector<string>::const_iterator it = matches.begin();
8884 it != matches.end(); it++)
9fdf787d 8885 {
2a639817
JS
8886 derived_probe *dp
8887 = new kprobe_derived_probe (sess, finished_results, base,
8888 location, *it, 0, has_return,
8889 has_statement_num,
8890 has_maxactive, has_path,
8891 has_library, maxactive_val,
8892 path_tgt, library_tgt);
8893 finished_results.push_back (dp);
9fdf787d
DS
8894 }
8895 }
6fb70fb7 8896 }
e6fe60e7 8897 else
b6371390
JS
8898 {
8899 // assert guru mode for absolute probes
8900 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 8901 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 8902
23dc94f6
DS
8903 finished_results.push_back (new kprobe_derived_probe (sess,
8904 finished_results,
8905 base,
b6371390
JS
8906 location, "",
8907 statement_num_val,
8908 has_return,
8909 has_statement_num,
8910 has_maxactive,
b642c901
SC
8911 has_path,
8912 has_library,
8913 maxactive_val,
05fb3e0c
WF
8914 path_tgt,
8915 library_tgt));
96b030fe 8916 }
79189b84
JS
8917}
8918
23dc94f6
DS
8919
8920void
8921kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
8922{
8923 expression *repl = e;
8924
bd5b25e1
JS
8925 if (has_return)
8926 {
8927 // expand the operand as if it weren't a return probe
8928 has_return = false;
8929 replace (e->operand);
8930 has_return = true;
23dc94f6 8931
bd5b25e1
JS
8932 // XXX it would be nice to use gen_kretprobe_saved_return when
8933 // available, but it requires knowing the types already, which is
8934 // problematic for arbitrary expressons.
8935 repl = gen_mapped_saved_return (sess, e->operand, "entry",
8936 add_block, add_block_tid,
8937 add_call_probe, add_call_probe_tid);
8938 }
23dc94f6
DS
8939 provide (repl);
8940}
8941
8942
dd225250
PS
8943// ------------------------------------------------------------------------
8944// Hardware breakpoint based probes.
8945// ------------------------------------------------------------------------
8946
8947static const string TOK_HWBKPT("data");
8948static const string TOK_HWBKPT_WRITE("write");
8949static const string TOK_HWBKPT_RW("rw");
8950static const string TOK_LENGTH("length");
8951
8952#define HWBKPT_READ 0
8953#define HWBKPT_WRITE 1
8954#define HWBKPT_RW 2
8955struct hwbkpt_derived_probe: public derived_probe
8956{
8957 hwbkpt_derived_probe (probe *base,
8958 probe_point *location,
8959 uint64_t addr,
8960 string symname,
8961 unsigned int len,
8962 bool has_only_read_access,
8963 bool has_only_write_access,
8964 bool has_rw_access
8965 );
8966 Dwarf_Addr hwbkpt_addr;
8967 string symbol_name;
8968 unsigned int hwbkpt_access,hwbkpt_len;
8969
8970 void printsig (std::ostream &o) const;
8971 void join_group (systemtap_session& s);
8972};
8973
8974struct hwbkpt_derived_probe_group: public derived_probe_group
8975{
dd225250 8976private:
dac77b80 8977 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
8978
8979public:
8980 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
8981 void emit_module_decls (systemtap_session& s);
8982 void emit_module_init (systemtap_session& s);
8983 void emit_module_exit (systemtap_session& s);
8984};
8985
8986hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
8987 probe_point *location,
8988 uint64_t addr,
8989 string symname,
8990 unsigned int len,
8991 bool has_only_read_access,
8992 bool has_only_write_access,
822a6a3d 8993 bool):
4c5d1300 8994 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
8995 hwbkpt_addr (addr),
8996 symbol_name (symname),
8997 hwbkpt_len (len)
8998{
8999 this->tok = base->tok;
9000
9001 vector<probe_point::component*> comps;
9002 comps.push_back (new probe_point::component(TOK_KERNEL));
9003
9004 if (hwbkpt_addr)
9ea68eb9
JS
9005 comps.push_back (new probe_point::component (TOK_HWBKPT,
9006 new literal_number(hwbkpt_addr, true)));
9007 else if (symbol_name.size())
9008 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9009
9010 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9011
9012 if (has_only_read_access)
9ea68eb9 9013 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9014//TODO add code for comps.push_back for read, since this flag is not for x86
9015
9016 else
9ea68eb9
JS
9017 {
9018 if (has_only_write_access)
9019 {
9020 this->hwbkpt_access = HWBKPT_WRITE ;
9021 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9022 }
9023 else
9024 {
9025 this->hwbkpt_access = HWBKPT_RW ;
9026 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9027 }
9028 }
dd225250
PS
9029
9030 this->sole_location()->components = comps;
9031}
9032
9033void hwbkpt_derived_probe::printsig (ostream& o) const
9034{
9035 sole_location()->print (o);
9036 printsig_nested (o);
9037}
9038
9039void hwbkpt_derived_probe::join_group (systemtap_session& s)
9040{
dac77b80
FCE
9041 if (! s.hwbkpt_derived_probes)
9042 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9043 s.hwbkpt_derived_probes->enroll (this, s);
9044}
9045
9046void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9047{
dac77b80
FCE
9048 hwbkpt_probes.push_back (p);
9049
9050 unsigned max_hwbkpt_probes_by_arch = 0;
9051 if (s.architecture == "i386" || s.architecture == "x86_64")
9052 max_hwbkpt_probes_by_arch = 4;
9053 else if (s.architecture == "s390")
9054 max_hwbkpt_probes_by_arch = 1;
9055
c57ea854 9056 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9057 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9058 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9059}
9060
9061void
9062hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9063{
dac77b80 9064 if (hwbkpt_probes.empty()) return;
dd225250
PS
9065
9066 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9067
9068 s.op->newline() << "#include <linux/perf_event.h>";
9069 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9070 s.op->newline();
9071
9072 // Forward declare the master entry functions
23063de1 9073 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9074 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9075 s.op->line() << " int nmi,";
9076 s.op->line() << " struct perf_sample_data *data,";
9077 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9078 s.op->newline() << "#else";
9079 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9080 s.op->line() << " struct perf_sample_data *data,";
9081 s.op->line() << " struct pt_regs *regs);";
9082 s.op->newline() << "#endif";
79189b84 9083
dd225250
PS
9084 // Emit the actual probe list.
9085
9086 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9087 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9088
9089 s.op->newline() << "static struct perf_event **";
dac77b80 9090 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9091 s.op->newline() << "static struct stap_hwbkpt_probe {";
9092 s.op->newline() << "int registered_p:1;";
43650b10 9093// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9094// registered_p = 1 signifies a probe that got registered successfully
9095
faea5e16 9096 // Symbol Names are mostly small and uniform enough
dd225250 9097 // to justify putting const char*.
dac77b80 9098 s.op->newline() << "const char * const symbol;";
dd225250
PS
9099
9100 s.op->newline() << "const unsigned long address;";
9101 s.op->newline() << "uint8_t atype;";
bb0a4e12 9102 s.op->newline() << "unsigned int len;";
7c3e97f4 9103 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9104 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9105 s.op->indent(1);
9106
dac77b80 9107 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9108 {
dac77b80 9109 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9110 s.op->newline() << "{";
dd225250
PS
9111 if (p->symbol_name.size())
9112 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9113 else
9114 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9115 switch(p->hwbkpt_access){
9116 case HWBKPT_READ:
9117 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9118 break;
dd225250
PS
9119 case HWBKPT_WRITE:
9120 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9121 break;
dd225250
PS
9122 case HWBKPT_RW:
9123 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9124 break;
dd225250
PS
9125 };
9126 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9127 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9128 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9129 s.op->line() << " },";
9130 }
dac77b80 9131 s.op->newline(-1) << "};";
dd225250
PS
9132
9133 // Emit the hwbkpt callback function
9134 s.op->newline() ;
23063de1 9135 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9136 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9137 s.op->line() << " int nmi,";
9138 s.op->line() << " struct perf_sample_data *data,";
9139 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9140 s.op->newline() << "#else";
9141 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9142 s.op->line() << " struct perf_sample_data *data,";
9143 s.op->line() << " struct pt_regs *regs) {";
9144 s.op->newline() << "#endif";
dac77b80
FCE
9145 s.op->newline(1) << "unsigned int i;";
9146 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9147 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9148 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9149 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9150 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) {";
9151 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9152 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9153 "stp_probe_type_hwbkpt");
d9aed31e 9154 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9155 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9156 s.op->newline() << "c->uregs = regs;";
9157 s.op->newline(-1) << "} else {";
9158 s.op->newline(1) << "c->kregs = regs;";
9159 s.op->newline(-1) << "}";
26e63673 9160 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9161 common_probe_entryfn_epilogue (s, true);
dac77b80 9162 s.op->newline(-1) << "}";
dd225250
PS
9163 s.op->newline(-1) << "}";
9164 s.op->newline() << "return 0;";
dac77b80 9165 s.op->newline(-1) << "}";
dd225250
PS
9166}
9167
9168void
9169hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9170{
dac77b80 9171 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9172 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9173 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9174 s.op->newline() << "void *addr = (void *) sdp->address;";
9175 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9176 s.op->newline() << "hw_breakpoint_init(hp);";
9177 s.op->newline() << "if (addr)";
9178 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9179 s.op->newline(-1) << "else { ";
9180 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9181 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9182 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9183 s.op->newline() << "continue;";
9184 s.op->newline(-1) << "}";
9185 s.op->newline(-1) << "}";
9186 s.op->newline() << "hp->bp_type = sdp->atype;";
9187
9188 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9189 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9190 {
9191 s.op->newline() << "switch(sdp->len) {";
9192 s.op->newline() << "case 1:";
9193 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9194 s.op->newline() << "break;";
9195 s.op->newline(-1) << "case 2:";
9196 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9197 s.op->newline() << "break;";
9198 s.op->newline(-1) << "case 3:";
9199 s.op->newline() << "case 4:";
9200 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9201 s.op->newline() << "break;";
9202 s.op->newline(-1) << "case 5:";
9203 s.op->newline() << "case 6:";
9204 s.op->newline() << "case 7:";
9205 s.op->newline() << "case 8:";
9206 s.op->newline() << "default:"; // XXX: could instead reject
9207 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9208 s.op->newline() << "break;";
9209 s.op->newline(-1) << "}";
9210 }
9211 else // other architectures presumed straightforward
9212 s.op->newline() << "hp->bp_len = sdp->len;";
9213
26e63673 9214 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9215 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9216 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9217 s.op->newline() << "#else";
dac77b80 9218 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9219 s.op->newline() << "#endif";
43650b10 9220 s.op->newline() << "rc = 0;";
dac77b80 9221 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9222 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9223 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9224 s.op->newline(-1) << "}";
217ef1f4
WC
9225 s.op->newline() << "if (rc) {";
9226 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9227 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9228 s.op->newline(-1) << "}";
dd225250 9229 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9230 s.op->newline(-1) << "}"; // for loop
9231}
9232
9233void
9234hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9235{
9236 //Unregister hwbkpt probes.
dac77b80 9237 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9238 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9239 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9240 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9241 s.op->newline() << "sdp->registered_p = 0;";
9242 s.op->newline(-1) << "}";
9243}
9244
9245struct hwbkpt_builder: public derived_probe_builder
9246{
9247 hwbkpt_builder() {}
9248 virtual void build(systemtap_session & sess,
9249 probe * base,
9250 probe_point * location,
9251 literal_map_t const & parameters,
9252 vector<derived_probe *> & finished_results);
9253};
9254
9255void
9256hwbkpt_builder::build(systemtap_session & sess,
9257 probe * base,
9258 probe_point * location,
9259 literal_map_t const & parameters,
9260 vector<derived_probe *> & finished_results)
9261{
9262 string symbol_str_val;
9263 int64_t hwbkpt_address, len;
9264 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9265
b47f3a55 9266 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9267 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9268 location->components[0]->tok);
9269 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9270 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9271 location->components[0]->tok);
9272
dd225250
PS
9273 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9274 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9275 has_len = get_param (parameters, TOK_LENGTH, len);
9276 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9277 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9278
9279 if (!has_len)
9280 len = 1;
9281
9282 if (has_addr)
9283 finished_results.push_back (new hwbkpt_derived_probe (base,
9284 location,
9285 hwbkpt_address,
9286 "",len,0,
9287 has_write,
9288 has_rw));
5d8a0aea 9289 else if (has_symbol_str)
dd225250
PS
9290 finished_results.push_back (new hwbkpt_derived_probe (base,
9291 location,
9292 0,
9293 symbol_str_val,len,0,
9294 has_write,
9295 has_rw));
5d8a0aea
FCE
9296 else
9297 assert (0);
dd225250 9298}
342d3f96 9299
0a6f5a3f
JS
9300// ------------------------------------------------------------------------
9301// statically inserted kernel-tracepoint derived probes
9302// ------------------------------------------------------------------------
9303
6fb70fb7 9304struct tracepoint_arg
79189b84 9305{
ad370dcc 9306 string name, c_type, typecast;
dcaa1a65 9307 bool usable, used, isptr;
f8a968bc 9308 Dwarf_Die type_die;
dcaa1a65 9309 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9310};
79189b84 9311
0a6f5a3f
JS
9312struct tracepoint_derived_probe: public derived_probe
9313{
79189b84
JS
9314 tracepoint_derived_probe (systemtap_session& s,
9315 dwflpp& dw, Dwarf_Die& func_die,
9316 const string& tracepoint_name,
9317 probe* base_probe, probe_point* location);
bc9a523d 9318
79189b84 9319 systemtap_session& sess;
6fb70fb7
JS
9320 string tracepoint_name, header;
9321 vector <struct tracepoint_arg> args;
bc9a523d 9322
6fb70fb7 9323 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9324 void getargs (std::list<std::string> &arg_set) const;
79189b84 9325 void join_group (systemtap_session& s);
3e3bd7b6 9326 void print_dupe_stamp(ostream& o);
0a6f5a3f 9327};
79189b84
JS
9328
9329
0a6f5a3f 9330struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9331{
79189b84
JS
9332 void emit_module_decls (systemtap_session& s);
9333 void emit_module_init (systemtap_session& s);
9334 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9335};
79189b84 9336
bc9a523d 9337
f8a968bc
JS
9338struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9339{
9340 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9341 vector <struct tracepoint_arg>& args):
9342 dw (dw), probe_name (probe_name), args (args) {}
9343 dwflpp& dw;
9344 const string& probe_name;
9345 vector <struct tracepoint_arg>& args;
bc9a523d 9346
f8a968bc
JS
9347 void visit_target_symbol (target_symbol* e);
9348 void visit_target_symbol_arg (target_symbol* e);
9349 void visit_target_symbol_context (target_symbol* e);
9350};
79189b84
JS
9351
9352
f8a968bc
JS
9353void
9354tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9355{
cc9001af 9356 string argname = e->sym_name();
75ead1f7 9357
f8a968bc
JS
9358 // search for a tracepoint parameter matching this name
9359 tracepoint_arg *arg = NULL;
9360 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9361 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9362 {
9363 arg = &args[i];
9364 arg->used = true;
9365 break;
9366 }
75ead1f7 9367
f8a968bc
JS
9368 if (arg == NULL)
9369 {
1d0499c2 9370 set<string> vars;
f8a968bc 9371 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
9372 vars.insert("$" + args[i].name);
9373 vars.insert("$$name");
9374 vars.insert("$$parms");
9375 vars.insert("$$vars");
9376 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 9377
f8a968bc
JS
9378 // We hope that this value ends up not being referenced after all, so it
9379 // can be optimized out quietly.
1d0499c2
JL
9380 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
9381 e->name.c_str(), sugs.empty() ? "" :
9382 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
9383 // NB: we use 'alternatives' because we list all
f8a968bc
JS
9384 // NB: we can have multiple errors, since a target variable
9385 // may be expanded in several different contexts:
9386 // trace ("*") { $foo->bar }
f8a968bc 9387 }
75ead1f7 9388
f8a968bc 9389 // make sure we're not dereferencing base types
dc5a09fc 9390 if (!arg->isptr)
d19a9a82 9391 e->assert_no_components("tracepoint", true);
75ead1f7 9392
f8a968bc
JS
9393 // we can only write to dereferenced fields, and only if guru mode is on
9394 bool lvalue = is_active_lvalue(e);
9395 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 9396 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 9397
ad370dcc
JS
9398 // XXX: if a struct/union arg is passed by value, then writing to its fields
9399 // is also meaningless until you dereference past a pointer member. It's
9400 // harder to detect and prevent that though...
75ead1f7 9401
f8a968bc
JS
9402 if (e->components.empty())
9403 {
03c75a4a 9404 if (e->addressof)
dc09353a 9405 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 9406
3e3bd7b6 9407 // Just grab the value from the probe locals
a45664f4
JS
9408 symbol* sym = new symbol;
9409 sym->tok = e->tok;
9410 sym->name = "__tracepoint_arg_" + arg->name;
9411 provide (sym);
f8a968bc
JS
9412 }
9413 else
9414 {
5f36109e
JS
9415 // make a copy of the original as a bare target symbol for the tracepoint
9416 // value, which will be passed into the dwarf dereferencing code
9417 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9418 e2->components.clear();
9419
9420 if (e->components.back().type == target_symbol::comp_pretty_print)
9421 {
9422 if (lvalue)
dc09353a 9423 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9424
d19a9a82 9425 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9426 dpp.expand()->visit (this);
9427 return;
9428 }
9429
1c0be8c7 9430 bool userspace_p = false;
f8a968bc 9431 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9432 + "_" + e->sym_name()
aca66a36 9433 + "_" + lex_cast(tick++));
75ead1f7 9434
1c0be8c7
JS
9435 exp_type type = pe_long;
9436 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 9437
1c0be8c7
JS
9438 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
9439 userspace_p, lvalue, e, e2);
75ead1f7 9440
f8a968bc
JS
9441 if (lvalue)
9442 {
9443 // Provide the functioncall to our parent, so that it can be
9444 // used to substitute for the assignment node immediately above
9445 // us.
9446 assert(!target_symbol_setter_functioncalls.empty());
9447 *(target_symbol_setter_functioncalls.top()) = n;
9448 }
75ead1f7 9449
1c0be8c7
JS
9450 // Revisit the functioncall so arguments can be expanded.
9451 n->visit (this);
f8a968bc 9452 }
75ead1f7
JS
9453}
9454
9455
f8a968bc
JS
9456void
9457tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9458{
03c75a4a 9459 if (e->addressof)
dc09353a 9460 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 9461
f8a968bc 9462 if (is_active_lvalue (e))
dc09353a 9463 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 9464
277c21bc 9465 if (e->name == "$$name")
f8a968bc 9466 {
5f36109e
JS
9467 e->assert_no_components("tracepoint");
9468
bfdaad1e
DS
9469 // Synthesize an embedded expression.
9470 embedded_expr *expr = new embedded_expr;
9471 expr->tok = e->tok;
9472 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 9473 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 9474 provide (expr);
f8a968bc 9475 }
277c21bc 9476 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 9477 {
5f36109e
JS
9478 e->assert_no_components("tracepoint", true);
9479
f8a968bc
JS
9480 token* pf_tok = new token(*e->tok);
9481 pf_tok->content = "sprintf";
0a6f5a3f 9482
d5e178c1 9483 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 9484
f8a968bc 9485 for (unsigned i = 0; i < args.size(); ++i)
b278033a 9486 {
dcaa1a65
JS
9487 if (!args[i].usable)
9488 continue;
f8a968bc
JS
9489 if (i > 0)
9490 pf->raw_components += " ";
9491 pf->raw_components += args[i].name;
3e3bd7b6 9492 target_symbol *tsym = new target_symbol;
f8a968bc 9493 tsym->tok = e->tok;
277c21bc 9494 tsym->name = "$" + args[i].name;
5f36109e 9495 tsym->components = e->components;
b278033a 9496
f8a968bc
JS
9497 // every variable should always be accessible!
9498 tsym->saved_conversion_error = 0;
8c2f50c0 9499 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
9500 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
9501 {
9502 if (dw.sess.verbose>2)
e26c2f83 9503 for (const semantic_error *c = tsym->saved_conversion_error;
14a97852 9504 c != 0; c = c->chain)
4c5d9906 9505 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
9506 pf->raw_components += "=?";
9507 continue;
9508 }
b278033a 9509
5f36109e
JS
9510 if (!e->components.empty() &&
9511 e->components[0].type == target_symbol::comp_pretty_print)
9512 pf->raw_components += "=%s";
9513 else
9514 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
9515 pf->args.push_back(texp);
9516 }
0a6f5a3f 9517
f8a968bc
JS
9518 pf->components = print_format::string_to_components(pf->raw_components);
9519 provide (pf);
b278033a 9520 }
f8a968bc
JS
9521 else
9522 assert(0); // shouldn't get here
0a6f5a3f
JS
9523}
9524
0a6f5a3f 9525void
f8a968bc 9526tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 9527{
aff5d390 9528 try
c69a87e0 9529 {
bd1fcbad 9530 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 9531
277c21bc 9532 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 9533 visit_target_symbol_context (e);
bd1fcbad 9534
c69a87e0
FCE
9535 else
9536 visit_target_symbol_arg (e);
9537 }
9538 catch (const semantic_error &er)
9539 {
1af1e62d 9540 e->chain (er);
c69a87e0
FCE
9541 provide (e);
9542 }
0a6f5a3f
JS
9543}
9544
9545
79189b84
JS
9546tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
9547 dwflpp& dw, Dwarf_Die& func_die,
9548 const string& tracepoint_name,
9549 probe* base, probe_point* loc):
4c5d1300 9550 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 9551 sess (s), tracepoint_name (tracepoint_name)
56894e91 9552{
79189b84
JS
9553 // create synthetic probe point name; preserve condition
9554 vector<probe_point::component*> comps;
9555 comps.push_back (new probe_point::component (TOK_KERNEL));
9556 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
9557 this->sole_location()->components = comps;
9558
6fb70fb7
JS
9559 // fill out the available arguments in this tracepoint
9560 build_args(dw, func_die);
56894e91 9561
6fb70fb7
JS
9562 // determine which header defined this tracepoint
9563 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
9564 header = decl_file;
9565
9566#if 0 /* This convention is not enforced. */
6fb70fb7
JS
9567 size_t header_pos = decl_file.rfind("trace/");
9568 if (header_pos == string::npos)
dc09353a 9569 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
9570 + tracepoint_name + "' in '"
9571 + decl_file + "'");
9572 header = decl_file.substr(header_pos);
d4393459 9573#endif
56894e91 9574
6fb70fb7
JS
9575 // tracepoints from FOO_event_types.h should really be included from FOO.h
9576 // XXX can dwarf tell us the include hierarchy? it would be better to
9577 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 9578 // XXX: see also PR9993.
d4393459 9579 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
9580 if (header_pos != string::npos)
9581 header.erase(header_pos, 12);
56894e91 9582
f8a968bc
JS
9583 // Now expand the local variables in the probe body
9584 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 9585 v.replace (this->body);
a45664f4
JS
9586 for (unsigned i = 0; i < args.size(); i++)
9587 if (args[i].used)
9588 {
9589 vardecl* v = new vardecl;
9590 v->name = "__tracepoint_arg_" + args[i].name;
9591 v->tok = this->tok;
58701b78 9592 v->set_arity(0, this->tok);
a45664f4 9593 v->type = pe_long;
69aa668e 9594 v->synthetic = true;
a45664f4
JS
9595 this->locals.push_back (v);
9596 }
56894e91 9597
79189b84 9598 if (sess.verbose > 2)
ce0f6648 9599 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 9600}
dc38c0ae 9601
56894e91 9602
f8a968bc 9603static bool
dcaa1a65 9604resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 9605{
d19a9a82 9606 Dwarf_Die type;
dcaa1a65 9607 switch (dwarf_tag(&arg.type_die))
b20febf3 9608 {
f8a968bc
JS
9609 case DW_TAG_typedef:
9610 case DW_TAG_const_type:
9611 case DW_TAG_volatile_type:
9612 // iterate on the referent type
3d1ad340 9613 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 9614 && resolve_tracepoint_arg_type(arg));
f8a968bc 9615 case DW_TAG_base_type:
a52d2ac0 9616 case DW_TAG_enumeration_type:
f8a968bc 9617 // base types will simply be treated as script longs
dcaa1a65 9618 arg.isptr = false;
f8a968bc
JS
9619 return true;
9620 case DW_TAG_pointer_type:
dcaa1a65
JS
9621 // pointers can be treated as script longs,
9622 // and if we know their type, they can also be dereferenced
d19a9a82
JS
9623 type = arg.type_die;
9624 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
9625 {
9626 // It still might be a non-type, e.g. const void,
9627 // so we need to strip away all qualifiers.
9628 int tag = dwarf_tag(&arg.type_die);
9629 if (tag != DW_TAG_typedef &&
9630 tag != DW_TAG_const_type &&
9631 tag != DW_TAG_volatile_type)
9632 {
9633 arg.isptr = true;
9634 break;
9635 }
9636 }
9637 if (!arg.isptr)
9638 arg.type_die = type;
ad370dcc
JS
9639 arg.typecast = "(intptr_t)";
9640 return true;
9641 case DW_TAG_structure_type:
9642 case DW_TAG_union_type:
9643 // for structs/unions which are passed by value, we turn it into
9644 // a pointer that can be dereferenced.
9645 arg.isptr = true;
9646 arg.typecast = "(intptr_t)&";
dcaa1a65 9647 return true;
f8a968bc
JS
9648 default:
9649 // should we consider other types too?
9650 return false;
b20febf3 9651 }
56894e91
JS
9652}
9653
9654
9655void
822a6a3d 9656tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 9657{
6fb70fb7
JS
9658 Dwarf_Die arg;
9659 if (dwarf_child(&func_die, &arg) == 0)
9660 do
9661 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
9662 {
9663 // build a tracepoint_arg for this parameter
9664 tracepoint_arg tparg;
23d106b9 9665 tparg.name = dwarf_diename(&arg);
56894e91 9666
6fb70fb7 9667 // read the type of this parameter
3d1ad340 9668 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 9669 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 9670 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 9671 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 9672
dcaa1a65 9673 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
9674 args.push_back(tparg);
9675 if (sess.verbose > 4)
a52d2ac0
JS
9676 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
9677 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
9678 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
9679 }
9680 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
9681}
9682
dc38c0ae 9683void
d0bfd2ac 9684tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 9685{
dcaa1a65
JS
9686 for (unsigned i = 0; i < args.size(); ++i)
9687 if (args[i].usable)
d0bfd2ac 9688 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
9689}
9690
79189b84
JS
9691void
9692tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 9693{
79189b84
JS
9694 if (! s.tracepoint_derived_probes)
9695 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
9696 s.tracepoint_derived_probes->enroll (this);
9697}
e38d6504 9698
56894e91 9699
197a4d62 9700void
3e3bd7b6 9701tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 9702{
3e3bd7b6
JS
9703 for (unsigned i = 0; i < args.size(); i++)
9704 if (args[i].used)
9705 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 9706}
56894e91 9707
3e3bd7b6 9708
c9ccb642 9709static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 9710{
3c1b3d06
FCE
9711 vector<string> they_live;
9712 // PR 9993
9713 // XXX: may need this to be configurable
d4393459 9714 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
9715
9716 // PR11649: conditional extra header
9717 // for kvm tracepoints in 2.6.33ish
9718 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
9719 they_live.push_back ("#include <linux/kvm_host.h>");
9720 }
9721
50b72692 9722 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 9723 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
9724 if (s.kernel_source_tree != "")
9725 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
9726 they_live.push_back ("struct xfs_mount;");
9727 they_live.push_back ("struct xfs_inode;");
9728 they_live.push_back ("struct xfs_buf;");
9729 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 9730 they_live.push_back ("struct xfs_trans;");
9e0cd21a 9731 }
d4393459 9732
50b72692 9733 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
9734 they_live.push_back ("struct rpc_task;");
9735 }
b64d65e2
FCE
9736 // RHEL6.3
9737 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
9738 they_live.push_back ("struct rpc_clnt;");
9739 they_live.push_back ("struct rpc_wait_queue;");
9740 }
d4393459
FCE
9741
9742 they_live.push_back ("#include <asm/cputime.h>");
9743
c2cf1b87
FCE
9744 // linux 3.0
9745 they_live.push_back ("struct cpu_workqueue_struct;");
9746
50b72692 9747 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
9748 if (s.kernel_source_tree != "")
9749 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
9750
50b72692
HP
9751 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
9752 they_live.push_back ("struct ext3_reserve_window_node;");
9753
3c1b3d06
FCE
9754 return they_live;
9755}
47dd066d
WC
9756
9757
9758void
79189b84 9759tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 9760{
79189b84
JS
9761 if (probes.empty())
9762 return;
47dd066d 9763
96b030fe
JS
9764 s.op->newline() << "/* ---- tracepoint probes ---- */";
9765 s.op->newline();
79189b84 9766
47dd066d 9767
a4b9c3b3
FCE
9768 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
9769 // to be separately compiled. That's because kernel tracepoint headers sometimes
9770 // conflict. PR13155.
9771
9772 map<string,translator_output*> per_header_aux;
9773 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 9774
6fb70fb7
JS
9775 for (unsigned i = 0; i < probes.size(); ++i)
9776 {
9777 tracepoint_derived_probe *p = probes[i];
75ae2ec9 9778 string header = p->header;
5f73a260 9779
a4b9c3b3
FCE
9780 // We cache the auxiliary output files on a per-header basis. We don't
9781 // need one aux file per tracepoint, only one per tracepoint-header.
9782 translator_output *tpop = per_header_aux[header];
9783 if (tpop == 0)
9784 {
9785 tpop = s.op_create_auxiliary();
9786 per_header_aux[header] = tpop;
9787
9788 // PR9993: Add extra headers to work around undeclared types in individual
9789 // include/trace/foo.h files
9790 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
9791 for (unsigned z=0; z<extra_decls.size(); z++)
9792 tpop->newline() << extra_decls[z] << "\n";
720c435f 9793
a4b9c3b3
FCE
9794 // strip include/ substring, the same way as done in get_tracequery_module()
9795 size_t root_pos = header.rfind("include/");
9796 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443
FCE
9797
9798 tpop->newline() << "#include <linux/tracepoint.h>" << endl;
a4b9c3b3 9799 tpop->newline() << "#include <" << header << ">";
720c435f 9800
a4b9c3b3
FCE
9801 // Starting in 2.6.35, at the same time NOARGS was added, the callback
9802 // always has a void* as the first parameter. PR11599
9803 tpop->newline() << "#ifdef DECLARE_TRACE_NOARGS";
9804 tpop->newline() << "#define STAP_TP_DATA , NULL";
9805 tpop->newline() << "#define STAP_TP_PROTO void *cb_data"
9806 << " __attribute__ ((unused))";
9807 if (!p->args.empty())
9808 tpop->line() << ",";
9809 tpop->newline() << "#else";
9810 tpop->newline() << "#define STAP_TP_DATA";
9811 tpop->newline() << "#define STAP_TP_PROTO";
9812 if (p->args.empty())
9813 tpop->line() << " void";
9814 tpop->newline() << "#endif";
720c435f
JS
9815
9816 tpop->newline() << "#define intptr_t long";
a4b9c3b3
FCE
9817 }
9818
720c435f
JS
9819 // collect the args that are actually in use
9820 vector<const tracepoint_arg*> used_args;
6fb70fb7 9821 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
9822 if (p->args[j].used)
9823 used_args.push_back(&p->args[j]);
9824
a4b9c3b3
FCE
9825 // forward-declare the generated-side tracepoint callback
9826 tpop->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9827 tpop->indent(2);
9828 if (used_args.empty())
9829 tpop->line() << "void";
9830 for (unsigned j = 0; j < used_args.size(); ++j)
6fb70fb7
JS
9831 {
9832 if (j > 0)
a4b9c3b3
FCE
9833 tpop->line() << ", ";
9834 tpop->line() << "int64_t";
6fb70fb7 9835 }
720c435f
JS
9836 tpop->line() << ");";
9837 tpop->indent(-2);
5f73a260 9838
a4b9c3b3
FCE
9839 // define the generated-side tracepoint callback - in the main translator-output
9840 s.op->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9841 s.op->indent(2);
9842 if (used_args.empty())
9843 s.op->newline() << "void";
9844 for (unsigned j = 0; j < used_args.size(); ++j)
a4b9c3b3 9845 {
a4b9c3b3
FCE
9846 if (j > 0)
9847 s.op->line() << ", ";
720c435f 9848 s.op->newline() << "int64_t __tracepoint_arg_" << used_args[j]->name;
6fb70fb7 9849 }
5f73a260
JS
9850 s.op->newline() << ")";
9851 s.op->newline(-2) << "{";
7c3e97f4 9852 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 9853 << common_probe_init (p) << ";";
71db462b 9854 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 9855 "stp_probe_type_tracepoint");
6dceb5c9 9856 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
9857 << lex_cast_qstring (p->tracepoint_name)
9858 << ";";
720c435f
JS
9859 for (unsigned j = 0; j < used_args.size(); ++j)
9860 {
9861 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 9862 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
9863 << " = __tracepoint_arg_" << used_args[j]->name << ";";
9864 }
26e63673 9865 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 9866 common_probe_entryfn_epilogue (s, true);
6fb70fb7 9867 s.op->newline(-1) << "}";
47dd066d 9868
a4b9c3b3 9869 // define the real tracepoint callback function
720c435f 9870 tpop->newline() << "static void enter_tracepoint_probe_" << i << "(";
a4b9c3b3
FCE
9871 tpop->newline(2) << "STAP_TP_PROTO";
9872 for (unsigned j = 0; j < p->args.size(); ++j)
9873 {
9874 if (j > 0)
9875 tpop->line() << ", ";
9876 tpop->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
9877 }
9878 tpop->newline() << ")";
9879 tpop->newline(-2) << "{";
720c435f
JS
9880 tpop->newline(1) << "enter_real_tracepoint_probe_" << i << "(";
9881 tpop->indent(2);
9882 for (unsigned j = 0; j < used_args.size(); ++j)
9883 {
9884 if (j > 0)
9885 tpop->line() << ", ";
9886 tpop->newline() << "(int64_t)" << used_args[j]->typecast
9887 << "__tracepoint_arg_" << used_args[j]->name;
9888 }
9889 tpop->newline() << ");";
9890 tpop->newline(-3) << "}";
a4b9c3b3
FCE
9891
9892
96b030fe 9893 // emit normalized registration functions
720c435f 9894 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9895 tpop->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 9896 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3 9897 tpop->newline(-1) << "}";
47dd066d 9898
86758d5f
JS
9899 // NB: we're not prepared to deal with unreg failures. However, failures
9900 // can only occur if the tracepoint doesn't exist (yet?), or if we
9901 // weren't even registered. The former should be OKed by the initial
9902 // registration call, and the latter is safe to ignore.
720c435f 9903 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9904 tpop->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 9905 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3
FCE
9906 tpop->newline(-1) << "}";
9907 tpop->newline();
5f73a260 9908
720c435f
JS
9909 // declare normalized registration functions
9910 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
9911 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 9912
a4b9c3b3 9913 tpop->assert_0_indent();
af304783
DS
9914 }
9915
96b030fe
JS
9916 // emit an array of registration functions for easy init/shutdown
9917 s.op->newline() << "static struct stap_tracepoint_probe {";
9918 s.op->newline(1) << "int (*reg)(void);";
86758d5f 9919 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
9920 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
9921 s.op->indent(1);
9922 for (unsigned i = 0; i < probes.size(); ++i)
9923 {
9924 s.op->newline () << "{";
9925 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
9926 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
9927 s.op->line() << " },";
9928 }
9929 s.op->newline(-1) << "};";
9930 s.op->newline();
47dd066d
WC
9931}
9932
9933
79189b84
JS
9934void
9935tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 9936{
79189b84
JS
9937 if (probes.size () == 0)
9938 return;
47dd066d 9939
79189b84 9940 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
9941 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
9942 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
9943 s.op->newline() << "if (rc) {";
9944 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
9945 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
9946 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
9947 s.op->newline(-1) << "}";
9948 s.op->newline(-1) << "}";
47dd066d 9949
bc9a523d
FCE
9950 // This would be technically proper (on those autoconf-detectable
9951 // kernels that include this function in tracepoint.h), however we
9952 // already make several calls to synchronze_sched() during our
9953 // shutdown processes.
47dd066d 9954
bc9a523d
FCE
9955 // s.op->newline() << "if (rc)";
9956 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
9957 // s.op->indent(-1);
79189b84 9958}
47dd066d
WC
9959
9960
79189b84
JS
9961void
9962tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 9963{
79189b84
JS
9964 if (probes.empty())
9965 return;
47dd066d 9966
96b030fe
JS
9967 s.op->newline() << "/* deregister tracepoint probes */";
9968 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
9969 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
9970 s.op->indent(-1);
47dd066d 9971
bc9a523d 9972 // Not necessary: see above.
47dd066d 9973
bc9a523d 9974 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 9975}
b20febf3 9976
47dd066d 9977
75ead1f7 9978struct tracepoint_query : public base_query
47dd066d 9979{
75ead1f7
JS
9980 tracepoint_query(dwflpp & dw, const string & tracepoint,
9981 probe * base_probe, probe_point * base_loc,
9982 vector<derived_probe *> & results):
9983 base_query(dw, "*"), tracepoint(tracepoint),
9984 base_probe(base_probe), base_loc(base_loc),
9985 results(results) {}
47dd066d 9986
75ead1f7 9987 const string& tracepoint;
47dd066d 9988
75ead1f7
JS
9989 probe * base_probe;
9990 probe_point * base_loc;
9991 vector<derived_probe *> & results;
f982c59b 9992 set<string> probed_names;
47dd066d 9993
75ead1f7
JS
9994 void handle_query_module();
9995 int handle_query_cu(Dwarf_Die * cudie);
9996 int handle_query_func(Dwarf_Die * func);
822a6a3d 9997 void query_library (const char *) {}
576eaefe 9998 void query_plt (const char *entry, size_t addr) {}
b20febf3 9999
75ead1f7
JS
10000 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
10001 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
10002};
47dd066d
WC
10003
10004
10005void
75ead1f7 10006tracepoint_query::handle_query_module()
47dd066d 10007{
75ead1f7 10008 // look for the tracepoints in each CU
337b7c44 10009 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10010}
10011
10012
75ead1f7
JS
10013int
10014tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10015{
75ead1f7 10016 dw.focus_on_cu (cudie);
47dd066d 10017
75ead1f7
JS
10018 // look at each function to see if it's a tracepoint
10019 string function = "stapprobe_" + tracepoint;
10020 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10021}
10022
10023
75ead1f7
JS
10024int
10025tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10026{
75ead1f7 10027 dw.focus_on_function (func);
47dd066d 10028
60d98537 10029 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10030 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10031
10032 // check for duplicates -- sometimes tracepoint headers may be indirectly
10033 // included in more than one of our tracequery modules.
10034 if (!probed_names.insert(tracepoint_instance).second)
10035 return DWARF_CB_OK;
10036
79189b84
JS
10037 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10038 tracepoint_instance,
10039 base_probe, base_loc);
10040 results.push_back (dp);
75ead1f7 10041 return DWARF_CB_OK;
47dd066d
WC
10042}
10043
10044
75ead1f7
JS
10045int
10046tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 10047{
75ead1f7 10048 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 10049 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10050 return q->handle_query_cu(cudie);
47dd066d
WC
10051}
10052
10053
75ead1f7
JS
10054int
10055tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 10056{
75ead1f7 10057 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 10058 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10059 return q->handle_query_func(func);
47dd066d
WC
10060}
10061
10062
0a6f5a3f 10063struct tracepoint_builder: public derived_probe_builder
47dd066d 10064{
0a6f5a3f
JS
10065private:
10066 dwflpp *dw;
10067 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10068 void get_tracequery_modules(systemtap_session& s,
10069 const vector<string>& headers,
10070 vector<string>& modules);
47dd066d 10071
0a6f5a3f 10072public:
47dd066d 10073
0a6f5a3f
JS
10074 tracepoint_builder(): dw(0) {}
10075 ~tracepoint_builder() { delete dw; }
47dd066d 10076
0a6f5a3f
JS
10077 void build_no_more (systemtap_session& s)
10078 {
10079 if (dw && s.verbose > 3)
b530b5b3 10080 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10081 delete dw;
10082 dw = NULL;
435f53a7
FCE
10083
10084 delete_session_module_cache (s);
0a6f5a3f 10085 }
47dd066d 10086
0a6f5a3f
JS
10087 void build(systemtap_session& s,
10088 probe *base, probe_point *location,
10089 literal_map_t const& parameters,
10090 vector<derived_probe*>& finished_results);
10091};
47dd066d 10092
47dd066d 10093
c9ccb642 10094
2a0e62a8 10095// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10096// tracepoint-related header files given. Return the generated or cached
10097// modules[].
10098
10099void
10100tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10101 const vector<string>& headers,
10102 vector<string>& modules)
0a6f5a3f 10103{
c95eddf7 10104 if (s.verbose > 2)
55e50c24 10105 {
ce0f6648 10106 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10107 for (size_t i = 0; i < headers.size(); ++i)
10108 clog << " " << headers[i] << endl;
10109 }
c95eddf7 10110
2a0e62a8
JS
10111 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10112 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10113 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10114 // so we prefer not to repeat this.
10115 vector<string> uncached_headers;
10116 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10117 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10118
10119 // They may be in the cache already.
10120 if (s.use_cache && !s.poison_cache)
10121 for (size_t i=0; i<headers.size(); i++)
10122 {
10123 // see if the cached module exists
2a0e62a8 10124 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10125 if (!tracequery_path.empty() && file_exists(tracequery_path))
10126 {
10127 if (s.verbose > 2)
10128 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10129
c252fca2
JS
10130 // an empty file is a cached failure
10131 if (get_file_size(tracequery_path) > 0)
10132 modules.push_back (tracequery_path);
c9ccb642
FCE
10133 }
10134 else
10135 uncached_headers.push_back(headers[i]);
10136 }
10137 else
10138 uncached_headers = headers;
f982c59b 10139
c9ccb642
FCE
10140 // If we have nothing left to search for, quit
10141 if (uncached_headers.empty()) return;
55e50c24 10142
c9ccb642 10143 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10144
c9ccb642
FCE
10145 // We could query several subsets of headers[] to make this go
10146 // faster, but let's KISS and do one at a time.
10147 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10148 {
c9ccb642
FCE
10149 const string& header = uncached_headers[i];
10150
10151 // create a tracequery source file
10152 ostringstream osrc;
10153
10154 // PR9993: Add extra headers to work around undeclared types in individual
10155 // include/trace/foo.h files
10156 vector<string> short_decls = tracepoint_extra_decls(s, header);
10157
10158 // add each requested tracepoint header
75ae2ec9 10159 size_t root_pos = header.rfind("include/");
832f100d 10160 short_decls.push_back(string("#include <") +
75ae2ec9 10161 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10162 string(">"));
f982c59b 10163
c9ccb642
FCE
10164 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10165 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10166
10167 // the kernel has changed this naming a few times, previously TPPROTO,
10168 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10169 osrc << "#ifndef PARAMS" << endl;
10170 osrc << "#define PARAMS(args...) args" << endl;
10171 osrc << "#endif" << endl;
10172
c9ccb642
FCE
10173 // override DECLARE_TRACE to synthesize probe functions for us
10174 osrc << "#undef DECLARE_TRACE" << endl;
10175 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10176 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10177
c9ccb642
FCE
10178 // 2.6.35 added the NOARGS variant, but it's the same for us
10179 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10180 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10181 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10182
10183 // 2.6.38 added the CONDITION variant, which can also just redirect
10184 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10185 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10186 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10187
c9ccb642
FCE
10188 // older tracepoints used DEFINE_TRACE, so redirect that too
10189 osrc << "#undef DEFINE_TRACE" << endl;
10190 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10191 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10192
c9ccb642
FCE
10193 // add the specified decls/#includes
10194 for (unsigned z=0; z<short_decls.size(); z++)
10195 osrc << "#undef TRACE_INCLUDE_FILE\n"
10196 << "#undef TRACE_INCLUDE_PATH\n"
10197 << short_decls[z] << "\n";
10198
10199 // finish up the module source
10200 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10201
c9ccb642
FCE
10202 // save the source file away
10203 headers_tracequery_src[header] = osrc.str();
55e50c24 10204 }
f982c59b 10205
c9ccb642 10206 // now build them all together
2a0e62a8 10207 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10208
c9ccb642 10209 // now plop them into the cache
b278033a 10210 if (s.use_cache)
c9ccb642
FCE
10211 for (size_t i=0; i<uncached_headers.size(); i++)
10212 {
10213 const string& header = uncached_headers[i];
2a0e62a8
JS
10214 const string& tracequery_obj = tracequery_objs[header];
10215 const string& tracequery_path = headers_cache_obj[header];
10216 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10217 {
2a0e62a8 10218 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10219 modules.push_back (tracequery_path);
10220 }
c252fca2
JS
10221 else
10222 // cache an empty file for failures
10223 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10224 }
f982c59b
JS
10225}
10226
10227
d4393459 10228
f982c59b
JS
10229bool
10230tracepoint_builder::init_dw(systemtap_session& s)
10231{
10232 if (dw != NULL)
10233 return true;
10234
10235 vector<string> tracequery_modules;
55e50c24 10236 vector<string> system_headers;
f982c59b
JS
10237
10238 glob_t trace_glob;
d4393459
FCE
10239
10240 // find kernel_source_tree
10241 if (s.kernel_source_tree == "")
f982c59b 10242 {
d4393459
FCE
10243 unsigned found;
10244 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
10245 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
10246 if (found)
10247 {
10248 Dwarf_Die *cudie = 0;
10249 Dwarf_Addr bias;
10250 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10251 {
e19ebcf7 10252 assert_no_interrupts();
d4393459
FCE
10253 Dwarf_Attribute attr;
10254 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10255 if (name)
d4393459 10256 {
36d65b45
JS
10257 // check that the path actually exists locally before we try to use it
10258 if (file_exists(name))
10259 {
10260 if (s.verbose > 2)
10261 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10262 s.kernel_source_tree = name;
10263 }
10264 else
10265 {
10266 if (s.verbose > 2)
10267 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10268 }
61f1a63b 10269
d4393459
FCE
10270 break; // skip others; modern Kbuild uses same comp_dir for them all
10271 }
10272 }
10273 }
10274 }
10275
10276 // prefixes
10277 vector<string> glob_prefixes;
10278 glob_prefixes.push_back (s.kernel_build_tree);
10279 if (s.kernel_source_tree != "")
10280 glob_prefixes.push_back (s.kernel_source_tree);
10281
10282 // suffixes
10283 vector<string> glob_suffixes;
10284 glob_suffixes.push_back("include/trace/events/*.h");
10285 glob_suffixes.push_back("include/trace/*.h");
10286 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
b1966849 10287 glob_suffixes.push_back("arch/x86/include/asm/trace/*.h");
f89ff3e2 10288 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
ca51c2cd 10289 glob_suffixes.push_back("fs/xfs/xfs_trace*.h");
d4393459
FCE
10290
10291 // compute cartesian product
10292 vector<string> globs;
10293 for (unsigned i=0; i<glob_prefixes.size(); i++)
10294 for (unsigned j=0; j<glob_suffixes.size(); j++)
10295 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10296
8aa43b8d 10297 set<string> duped_headers;
d4393459
FCE
10298 for (unsigned z = 0; z < globs.size(); z++)
10299 {
10300 string glob_str = globs[z];
10301 if (s.verbose > 3)
b530b5b3 10302 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10303
067cc66f
CM
10304 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10305 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10306 throw runtime_error("Error globbing tracepoint");
10307
f982c59b
JS
10308 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10309 {
10310 string header(trace_glob.gl_pathv[i]);
10311
10312 // filter out a few known "internal-only" headers
60d98537
JS
10313 if (endswith(header, "/define_trace.h") ||
10314 endswith(header, "/ftrace.h") ||
10315 endswith(header, "/trace_events.h") ||
10316 endswith(header, "_event_types.h"))
f982c59b
JS
10317 continue;
10318
b1966849
FCE
10319 // With headers now plopped under arch/FOO/include/asm/*,
10320 // the following logic miss some tracepoints.
10321#if 0
8aa43b8d
JS
10322 // skip identical headers from the build and source trees.
10323 size_t root_pos = header.rfind("include/");
10324 if (root_pos != string::npos &&
10325 !duped_headers.insert(header.substr(root_pos + 8)).second)
10326 continue;
b1966849 10327#endif
8aa43b8d 10328
55e50c24 10329 system_headers.push_back(header);
f982c59b
JS
10330 }
10331 globfree(&trace_glob);
10332 }
10333
c9ccb642
FCE
10334 // Build tracequery modules
10335 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 10336
f982c59b
JS
10337 // TODO: consider other sources of tracepoint headers too, like from
10338 // a command-line parameter or some environment or .systemtaprc
47dd066d 10339
59c11f91 10340 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
10341 return true;
10342}
47dd066d 10343
0a6f5a3f
JS
10344void
10345tracepoint_builder::build(systemtap_session& s,
10346 probe *base, probe_point *location,
10347 literal_map_t const& parameters,
10348 vector<derived_probe*>& finished_results)
10349{
10350 if (!init_dw(s))
10351 return;
47dd066d 10352
75ead1f7
JS
10353 string tracepoint;
10354 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 10355
75ead1f7 10356 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 10357 dw->iterate_over_modules(&query_module, &q);
47dd066d 10358}
47dd066d 10359
e6fe60e7 10360
b55bc428 10361// ------------------------------------------------------------------------
bd2b1e68 10362// Standard tapset registry.
b55bc428
FCE
10363// ------------------------------------------------------------------------
10364
7a053d3b 10365void
f8220a7b 10366register_standard_tapsets(systemtap_session & s)
b55bc428 10367{
47e0478e 10368 register_tapset_been(s);
93646f4d 10369 register_tapset_itrace(s);
dd0e4fa7 10370 register_tapset_mark(s);
7a212aa8 10371 register_tapset_procfs(s);
912e8c59 10372 register_tapset_timers(s);
8d9609f5 10373 register_tapset_netfilter(s);
b84779a5 10374 register_tapset_utrace(s);
b98a8d73 10375
7a24d422 10376 // dwarf-based kprobe/uprobe parts
c4ce66a1 10377 dwarf_derived_probe::register_patterns(s);
30a279be 10378
888af770
FCE
10379 // XXX: user-space starter set
10380 s.pattern_root->bind_num(TOK_PROCESS)
10381 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10382 ->bind_privilege(pr_all)
888af770
FCE
10383 ->bind(new uprobe_builder ());
10384 s.pattern_root->bind_num(TOK_PROCESS)
10385 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10386 ->bind_privilege(pr_all)
888af770
FCE
10387 ->bind(new uprobe_builder ());
10388
0a6f5a3f
JS
10389 // kernel tracepoint probes
10390 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10391 ->bind(new tracepoint_builder());
10392
e6fe60e7
AM
10393 // Kprobe based probe
10394 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10395 ->bind(new kprobe_builder());
3c57fe1f
JS
10396 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
10397 ->bind(new kprobe_builder());
e6fe60e7
AM
10398 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10399 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
10400 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10401 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
10402 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10403 ->bind(new kprobe_builder());
b6371390
JS
10404 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10405 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10406 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10407 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10408 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10409 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10410 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10411 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10412 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
10413
10414 //Hwbkpt based probe
b47f3a55
FCE
10415 // NB: we formerly registered the probe point types only if the kernel configuration
10416 // allowed it. However, we get better error messages if we allow probes to resolve.
10417 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10418 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10419 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10420 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10421 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10422 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10423 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10424 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10425 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10426 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10427 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10428 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10429 // length supported with address only, not symbol names
83ea76b1
WC
10430
10431 //perf event based probe
4763f713 10432 register_tapset_perf(s);
a29858ef 10433 register_tapset_java(s);
b55bc428 10434}
dc38c0ae
DS
10435
10436
b20febf3
FCE
10437vector<derived_probe_group*>
10438all_session_groups(systemtap_session& s)
dc38c0ae 10439{
b20febf3 10440 vector<derived_probe_group*> g;
912e8c59
JS
10441
10442#define DOONE(x) \
10443 if (s. x##_derived_probes) \
10444 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
10445
10446 // Note that order *is* important here. We want to make sure we
10447 // register (actually run) begin probes before any other probe type
10448 // is run. Similarly, when unregistering probes, we want to
10449 // unregister (actually run) end probes after every other probe type
10450 // has be unregistered. To do the latter,
10451 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
10452 DOONE(be);
10453 DOONE(dwarf);
888af770 10454 DOONE(uprobe);
b20febf3
FCE
10455 DOONE(timer);
10456 DOONE(profile);
10457 DOONE(mark);
0a6f5a3f 10458 DOONE(tracepoint);
e6fe60e7 10459 DOONE(kprobe);
dd225250 10460 DOONE(hwbkpt);
83ea76b1 10461 DOONE(perf);
b20febf3 10462 DOONE(hrtimer);
ce82316f 10463 DOONE(procfs);
8d9609f5 10464 DOONE(netfilter);
935447c8
DS
10465
10466 // Another "order is important" item. We want to make sure we
10467 // "register" the dummy task_finder probe group after all probe
10468 // groups that use the task_finder.
10469 DOONE(utrace);
a96d1db0 10470 DOONE(itrace);
f31a77f5 10471 DOONE(dynprobe);
e7d4410d 10472 DOONE(java);
935447c8 10473 DOONE(task_finder);
b20febf3
FCE
10474#undef DOONE
10475 return g;
46b84a80 10476}
73267b89
JS
10477
10478/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.774564 seconds and 5 git commands to generate.