]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
Set git-describe --abbrev=12 for consistency and future-proofing
[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
508059f0
MW
66// Old elf.h doesn't know about this machine type.
67#ifndef EM_AARCH64
68#define EM_AARCH64 183
69#endif
70
56e12059
FCE
71
72using namespace std;
2171f774 73using namespace __gnu_cxx;
56e12059 74
47dd066d 75
b20febf3
FCE
76
77// ------------------------------------------------------------------------
faea5e16
JS
78
79string
80common_probe_init (derived_probe* p)
81{
26e63673
JS
82 assert(p->session_index != (unsigned)-1);
83 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
84}
85
86
b20febf3 87void
71db462b
DS
88common_probe_entryfn_prologue (systemtap_session& s,
89 string statestr, string probe,
90 string probe_type, bool overload_processing)
b20febf3 91{
944c9a7a 92 if (s.runtime_usermode_p())
ac34f2aa
JS
93 {
94 // If session_state() is NULL, then we haven't even initialized shm yet,
95 // and there's *nothing* for the probe to do. (even alibi is in shm)
96 // So failure skips this whole block through the end of the epilogue.
97 s.op->newline() << "if (likely(session_state())) {";
e481ab2e 98 s.op->indent(1);
ac34f2aa
JS
99 }
100
71db462b 101 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 102 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 103 s.op->newline() << "#else";
653e6a9a 104
e481ab2e
JS
105 if (s.runtime_usermode_p())
106 s.op->newline() << "int _stp_saved_errno = errno;";
107
fee09ad5 108 s.op->newline() << "struct context* __restrict__ c = NULL;";
71db462b
DS
109 s.op->newline() << "#if !INTERRUPTIBLE";
110 s.op->newline() << "unsigned long flags;";
111 s.op->newline() << "#endif";
b20febf3 112
f887a8c9 113 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 114 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
115 s.op->newline() << "#endif";
116 if (overload_processing && !s.runtime_usermode_p())
71db462b 117 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 118 else
71db462b 119 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 120
f887a8c9
DS
121 if (! s.runtime_usermode_p())
122 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
123 else
124 {
125 s.op->newline() << "struct timespec timespec_atstart;";
45639d96 126 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atstart);";
f887a8c9 127 }
71db462b 128 s.op->newline() << "#endif";
994aac0e 129
71db462b
DS
130 s.op->newline() << "#if INTERRUPTIBLE";
131 s.op->newline() << "preempt_disable ();";
132 s.op->newline() << "#else";
133 s.op->newline() << "local_irq_save (flags);";
134 s.op->newline() << "#endif";
b20febf3 135
ac3af990 136 if (! s.runtime_usermode_p())
71db462b
DS
137 {
138 // Check for enough free enough stack space
139 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
140 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
141 // XXX: may need porting to platforms where task_struct is not
142 // at bottom of kernel stack NB: see also
143 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 144 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 145 s.op->newline() << "#ifdef STP_TIMING";
065d5567 146 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
147 s.op->newline() << "#endif";
148 s.op->newline() << "goto probe_epilogue;";
149 s.op->newline(-1) << "}";
150 }
c931ec8a 151
065d5567 152 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
153 s.op->newline(1) << "goto probe_epilogue;";
154 s.op->indent(-1);
9a604fac 155
1d0e697d
DS
156 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
157 if (s.runtime_usermode_p())
158 {
159 s.op->newline() << "if (!c) {";
160 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 161 s.op->newline() << "atomic_inc (skipped_count());";
1d0e697d
DS
162 s.op->newline() << "#endif";
163 s.op->newline() << "#ifdef STP_TIMING";
065d5567 164 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
1d0e697d
DS
165 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
166 s.op->newline() << "_stp_warn (\"Skipped %s\\n\", " << probe << "->pp);";
167 s.op->newline() << "#endif";
168 s.op->newline() << "#endif";
169 s.op->newline() << "goto probe_epilogue;";
170 s.op->newline(-1) << "}";
171 }
172
71db462b
DS
173 s.op->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
174 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 175 s.op->newline() << "atomic_inc (skipped_count());";
71db462b
DS
176 s.op->newline() << "#endif";
177 s.op->newline() << "#ifdef STP_TIMING";
065d5567 178 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
71db462b
DS
179 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
180 s.op->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 181 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
182 // NB: There is a conceivable race condition here with reading
183 // c->probe_point, knowing that this other probe is sort of running.
184 // However, in reality, it's interrupted. Plus even if it were able
185 // to somehow start again, and stop before we read c->probe_point,
186 // at least we have that ?: "?" bit in there to avoid a NULL deref.
71db462b
DS
187 s.op->newline() << "#endif";
188 s.op->newline() << "#endif";
189 s.op->newline() << "atomic_dec (& c->busy);";
190 s.op->newline() << "goto probe_epilogue;";
191 s.op->newline(-1) << "}";
192 s.op->newline();
193 s.op->newline() << "c->last_stmt = 0;";
194 s.op->newline() << "c->last_error = 0;";
195 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
196 s.op->newline() << "c->uregs = 0;";
197 s.op->newline() << "c->kregs = 0;";
198 s.op->newline() << "#if defined __ia64__";
199 s.op->newline() << "c->unwaddr = 0;";
200 s.op->newline() << "#endif";
f4d70a33
JS
201 if (s.runtime_usermode_p())
202 s.op->newline() << "c->probe_index = " << probe << "->index;";
71db462b
DS
203 s.op->newline() << "c->probe_point = " << probe << "->pp;";
204 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
205 s.op->newline() << "c->probe_name = " << probe << "->pn;";
206 s.op->newline() << "#endif";
207 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 208 // reset Individual Probe State union
71db462b 209 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 210 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
211 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
212 s.op->newline() << "c->regparm = 0;";
213 s.op->newline() << "#endif";
e0a17418 214
152fa051
LB
215 if(!s.suppress_time_limits){
216 s.op->newline() << "#if INTERRUPTIBLE";
217 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
218 s.op->newline() << "#else";
219 s.op->newline() << "c->actionremaining = MAXACTION;";
220 s.op->newline() << "#endif";
221 }
9915575b
FCE
222 // NB: The following would actually be incorrect.
223 // That's because cycles_sum/cycles_base values are supposed to survive
224 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
225 // cycles), the values will be reset.
226 /*
71db462b
DS
227 s.op->newline() << "#ifdef STP_OVERLOAD";
228 s.op->newline() << "c->cycles_sum = 0;";
229 s.op->newline() << "c->cycles_base = 0;";
230 s.op->newline() << "#endif";
9915575b 231 */
44cfbe25
SM
232
233 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
234 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
235 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
236 s.op->newline() << "#endif";
b20febf3 237}
9a604fac 238
a44a0785 239
b20febf3 240void
f887a8c9
DS
241common_probe_entryfn_epilogue (systemtap_session& s,
242 bool overload_processing)
b20febf3 243{
f887a8c9
DS
244 if (overload_processing && !s.runtime_usermode_p())
245 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 246 else
f887a8c9
DS
247 s.op->newline() << "#ifdef STP_TIMING";
248 s.op->newline() << "{";
249 s.op->indent(1);
250 if (! s.runtime_usermode_p())
251 {
252 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
253 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
254 // fewer, if the hardware counter rolls over really quickly. We
255 // handle 32-bit wraparound here.
256 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
257 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
258 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
259 s.op->indent(-1);
260 }
261 else
262 {
263 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
264 s.op->newline() << "long cycles_elapsed;";
45639d96 265 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atend);";
f887a8c9
DS
266 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
267 // 'cycles_elapsed' is really elapsed nanoseconds
268 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
269 }
270
271 s.op->newline() << "#ifdef STP_TIMING";
272 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
273 s.op->newline() << "#endif";
274
275 if (overload_processing && !s.runtime_usermode_p())
276 {
277 s.op->newline() << "#ifdef STP_OVERLOAD";
278 s.op->newline() << "{";
a58d79d0
DS
279 // If the cycle count has wrapped (cycles_atend > cycles_base),
280 // let's go ahead and pretend the interval has been reached.
281 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
282 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
283 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
284 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
285 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
286
287 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
288 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
289 // has overloaded the system and we need to quit.
7baf48e9
FCE
290 // NB: this is not suppressible via --suppress-runtime-errors,
291 // because this is a system safety metric that we cannot trust
292 // unprivileged users to override.
f887a8c9
DS
293 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
294 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
295 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
296 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
297 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
298 s.op->newline(-1) << "}";
299
300 s.op->newline() << "c->cycles_base = cycles_atend;";
301 s.op->newline() << "c->cycles_sum = 0;";
302 s.op->newline(-1) << "}";
303 s.op->newline(-1) << "}";
304 s.op->newline() << "#endif";
a58d79d0 305 }
e57b735a 306
f887a8c9
DS
307 s.op->newline(-1) << "}";
308 s.op->newline() << "#endif";
e57b735a 309
f887a8c9
DS
310 s.op->newline() << "c->probe_point = 0;"; // vacated
311 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
312 s.op->newline() << "c->probe_name = 0;";
313 s.op->newline() << "#endif";
314 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
315
316
f887a8c9
DS
317 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
318 s.op->indent(1);
319 if (s.suppress_handler_errors) // PR 13306
b78a0fbb 320 {
065d5567 321 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
322 }
323 else
324 {
f887a8c9
DS
325 s.op->newline() << "if (c->last_stmt != NULL)";
326 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
327 s.op->newline(-1) << "else";
328 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
329 s.op->indent(-1);
065d5567
JS
330 s.op->newline() << "atomic_inc (error_count());";
331 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
332 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
333 s.op->newline() << "_stp_exit ();";
334 s.op->newline(-1) << "}";
7baf48e9
FCE
335 }
336
f887a8c9 337 s.op->newline(-1) << "}";
7baf48e9
FCE
338
339
f887a8c9 340 s.op->newline() << "atomic_dec (&c->busy);";
e57b735a 341
f887a8c9
DS
342 s.op->newline(-1) << "probe_epilogue:"; // context is free
343 s.op->indent(1);
e57b735a 344
8ca891c4
DS
345 // In dyninst mode, we're not done with the context yet, since
346 // _stp_error() still needs a context structure (since the log
347 // buffers are stored there).
348 if (!s.runtime_usermode_p())
349 {
e481ab2e 350 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
8ca891c4 351 }
f887a8c9 352 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
353 {
354 // Check for excessive skip counts.
065d5567
JS
355 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
356 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
357 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
358 s.op->newline(-1) << "}";
7baf48e9 359 }
e57b735a 360
f887a8c9
DS
361 s.op->newline() << "#if INTERRUPTIBLE";
362 s.op->newline() << "preempt_enable_no_resched ();";
363 s.op->newline() << "#else";
364 s.op->newline() << "local_irq_restore (flags);";
365 s.op->newline() << "#endif";
653e6a9a 366
944c9a7a 367 if (s.runtime_usermode_p())
ac34f2aa 368 {
e481ab2e 369 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
ac34f2aa 370 s.op->newline() << "errno = _stp_saved_errno;";
ac34f2aa 371 }
e481ab2e
JS
372
373 s.op->newline() << "#endif // STP_ALIBI";
374
375 if (s.runtime_usermode_p())
376 s.op->newline(-1) << "}";
440f755a 377}
e57b735a 378
e57b735a 379
440f755a 380// ------------------------------------------------------------------------
e57b735a 381
440f755a
JS
382// ------------------------------------------------------------------------
383// Dwarf derived probes. "We apologize for the inconvience."
384// ------------------------------------------------------------------------
e57b735a 385
4627ed58
JS
386static const string TOK_KERNEL("kernel");
387static const string TOK_MODULE("module");
388static const string TOK_FUNCTION("function");
389static const string TOK_INLINE("inline");
390static const string TOK_CALL("call");
4bda987e 391static const string TOK_EXPORTED("exported");
4627ed58
JS
392static const string TOK_RETURN("return");
393static const string TOK_MAXACTIVE("maxactive");
394static const string TOK_STATEMENT("statement");
395static const string TOK_ABSOLUTE("absolute");
396static const string TOK_PROCESS("process");
a794dbeb 397static const string TOK_PROVIDER("provider");
4627ed58
JS
398static const string TOK_MARK("mark");
399static const string TOK_TRACE("trace");
400static const string TOK_LABEL("label");
63b4fd14 401static const string TOK_LIBRARY("library");
576eaefe 402static const string TOK_PLT("plt");
e7d4410d
LB
403static const string TOK_METHOD("method");
404static const string TOK_CLASS("class");;
e57b735a 405
1adf8ef1 406static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 407static void query_addr(Dwarf_Addr addr, dwarf_query *q);
f4faaf86 408static void query_plt_statement(dwarf_query *q);
e57b735a 409
440f755a
JS
410// Can we handle this query with just symbol-table info?
411enum dbinfo_reqt
412{
413 dbr_unknown,
414 dbr_none, // kernel.statement(NUM).absolute
415 dbr_need_symtab, // can get by with symbol table if there's no dwarf
416 dbr_need_dwarf
417};
e57b735a 418
20e4a32c 419
440f755a
JS
420struct base_query; // forward decls
421struct dwarf_query;
422struct dwflpp;
423struct symbol_table;
20e4a32c 424
a781f401 425
440f755a
JS
426struct
427symbol_table
428{
429 module_info *mod_info; // associated module
430 map<string, func_info*> map_by_name;
1c6b77e5
JS
431 multimap<Dwarf_Addr, func_info*> map_by_addr;
432 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
433 typedef pair<iterator_t, iterator_t> range_t;
434#ifdef __powerpc__
435 GElf_Word opd_section;
436#endif
2867a2a1
JS
437 void add_symbol(const char *name, bool weak, bool descriptor,
438 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 439 enum info_status read_symbols(FILE *f, const string& path);
83ca3872 440 enum info_status read_from_elf_file(const string& path,
2713ea24 441 systemtap_session &sess);
83ca3872 442 enum info_status read_from_text_file(const string& path,
2713ea24 443 systemtap_session &sess);
440f755a
JS
444 enum info_status get_from_elf();
445 void prepare_section_rejection(Dwfl_Module *mod);
446 bool reject_section(GElf_Word section);
440f755a
JS
447 void purge_syscall_stubs();
448 func_info *lookup_symbol(const string& name);
449 Dwarf_Addr lookup_symbol_address(const string& name);
450 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 451 func_info *get_first_func();
7a053d3b 452
440f755a
JS
453 symbol_table(module_info *mi) : mod_info(mi) {}
454 ~symbol_table();
455};
77de5e9e 456
440f755a
JS
457static bool null_die(Dwarf_Die *die)
458{
822a6a3d 459 static Dwarf_Die null;
440f755a
JS
460 return (!die || !memcmp(die, &null, sizeof(null)));
461}
c4ce66a1
JS
462
463
7a053d3b 464enum
bd2b1e68 465function_spec_type
7a053d3b 466 {
bd2b1e68
GH
467 function_alone,
468 function_and_file,
7a053d3b 469 function_file_and_line
bd2b1e68
GH
470 };
471
ec4373ff 472
bd2b1e68 473struct dwarf_builder;
f10534c6 474struct dwarf_var_expanding_visitor;
77de5e9e 475
2930abc7 476
b20febf3
FCE
477// XXX: This class is a candidate for subclassing to separate
478// the relocation vs non-relocation variants. Likewise for
479// kprobe vs kretprobe variants.
480
481struct dwarf_derived_probe: public derived_probe
b55bc428 482{
b20febf3
FCE
483 dwarf_derived_probe (const string& function,
484 const string& filename,
485 int line,
486 const string& module,
487 const string& section,
488 Dwarf_Addr dwfl_addr,
2930abc7 489 Dwarf_Addr addr,
b20febf3
FCE
490 dwarf_query & q,
491 Dwarf_Die* scope_die);
20e4a32c 492
b20febf3
FCE
493 string module;
494 string section;
495 Dwarf_Addr addr;
63b4fd14 496 string path;
27dc09b1 497 bool has_process;
2930abc7 498 bool has_return;
c9bad430 499 bool has_maxactive;
63b4fd14 500 bool has_library;
c9bad430 501 long maxactive_val;
4ad95bbc 502 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
503 string user_path;
504 string user_lib;
b95e2b79 505 bool access_vars;
2930abc7 506
af234c40
JS
507 unsigned saved_longs, saved_strings;
508 dwarf_derived_probe* entry_handler;
509
b8da0ad1 510 void printsig (std::ostream &o) const;
6b66b9f7 511 virtual void join_group (systemtap_session& s);
3689db05 512 void emit_probe_local_init(systemtap_session& s, translator_output * o);
d0bfd2ac 513 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 514
42e38653 515 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
516 void print_dupe_stamp(ostream& o);
517
bd2b1e68 518 // Pattern registration helpers.
7a053d3b 519 static void register_statement_variants(match_node * root,
27dc09b1 520 dwarf_builder * dw,
42e38653 521 privilege_t privilege);
fd6602a0 522 static void register_function_variants(match_node * root,
27dc09b1 523 dwarf_builder * dw,
42e38653 524 privilege_t privilege);
440d9b00
DB
525 static void register_function_and_statement_variants(systemtap_session& s,
526 match_node * root,
27dc09b1 527 dwarf_builder * dw,
42e38653 528 privilege_t privilege);
b1615c74
JS
529 static void register_sdt_variants(systemtap_session& s,
530 match_node * root,
531 dwarf_builder * dw);
532 static void register_plt_variants(systemtap_session& s,
533 match_node * root,
534 dwarf_builder * dw);
c4ce66a1 535 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
536
537protected:
538 dwarf_derived_probe(probe *base,
539 probe_point *location,
540 Dwarf_Addr addr,
541 bool has_return):
74fe61bc
LB
542 derived_probe(base, location), addr(addr), has_process(0),
543 has_return(has_return), has_maxactive(0), has_library(0),
544 maxactive_val(0), access_vars(false), saved_longs(0),
545 saved_strings(0), entry_handler(0)
6b66b9f7
JS
546 {}
547
548private:
d0bfd2ac 549 list<string> args;
8c67c337 550 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
551};
552
dc38c0ae 553
6b66b9f7 554struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 555{
6d0f3f0c 556 int pid; // 0 => unrestricted
0973d815 557
6d0f3f0c
FCE
558 uprobe_derived_probe (const string& function,
559 const string& filename,
560 int line,
561 const string& module,
6d0f3f0c
FCE
562 const string& section,
563 Dwarf_Addr dwfl_addr,
564 Dwarf_Addr addr,
565 dwarf_query & q,
6b66b9f7
JS
566 Dwarf_Die* scope_die):
567 dwarf_derived_probe(function, filename, line, module, section,
568 dwfl_addr, addr, q, scope_die), pid(0)
569 {}
6d0f3f0c 570
0973d815
FCE
571 // alternate constructor for process(PID).statement(ADDR).absolute
572 uprobe_derived_probe (probe *base,
573 probe_point *location,
574 int pid,
575 Dwarf_Addr addr,
6b66b9f7
JS
576 bool has_return):
577 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
578 {}
9ace370f 579
6d0f3f0c 580 void join_group (systemtap_session& s);
2865d17a 581
42e38653 582 void emit_privilege_assertion (translator_output*);
8f6d8c2b 583 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
584 void getargs(std::list<std::string> &arg_set) const;
585 void saveargs(int nargs);
586private:
587 list<string> args;
6d0f3f0c
FCE
588};
589
dc38c0ae
DS
590struct dwarf_derived_probe_group: public derived_probe_group
591{
592private:
b20febf3
FCE
593 multimap<string,dwarf_derived_probe*> probes_by_module;
594 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
595
596public:
08b5a50c 597 dwarf_derived_probe_group() {}
b20febf3
FCE
598 void enroll (dwarf_derived_probe* probe);
599 void emit_module_decls (systemtap_session& s);
600 void emit_module_init (systemtap_session& s);
b4be7cbc 601 void emit_module_refresh (systemtap_session& s);
b20febf3 602 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
603};
604
605
20c6c071 606// Helper struct to thread through the dwfl callbacks.
2c384610 607struct base_query
20c6c071 608{
c4ce66a1
JS
609 base_query(dwflpp & dw, literal_map_t const & params);
610 base_query(dwflpp & dw, const string & module_val);
2c384610 611 virtual ~base_query() {}
bd2b1e68 612
5227f1ea 613 systemtap_session & sess;
2c384610 614 dwflpp & dw;
5227f1ea 615
070764c0
JL
616 // Used to keep track of which modules were visited during
617 // iterate_over_modules()
618 set<string> visited_modules;
619
bd2b1e68 620 // Parameter extractors.
86bf665e 621 static bool has_null_param(literal_map_t const & params,
888af770 622 string const & k);
86bf665e 623 static bool get_string_param(literal_map_t const & params,
bd2b1e68 624 string const & k, string & v);
86bf665e 625 static bool get_number_param(literal_map_t const & params,
bd2b1e68 626 string const & k, long & v);
86bf665e 627 static bool get_number_param(literal_map_t const & params,
c239d28c 628 string const & k, Dwarf_Addr & v);
f301a9ff 629 static void query_library_callback (void *object, const char *data);
576eaefe 630 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 631 virtual void query_library (const char *data) = 0;
576eaefe 632 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 633
b55bc428 634
2c384610
DS
635 // Extracted parameters.
636 bool has_kernel;
91af0778
FCE
637 bool has_module;
638 bool has_process;
63b4fd14 639 bool has_library;
576eaefe
SC
640 bool has_plt;
641 bool has_statement;
2c384610 642 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 643 string path; // executable path if module is a .so
576eaefe 644 string plt_val; // has_plt => plt wildcard
2c384610
DS
645
646 virtual void handle_query_module() = 0;
647};
648
649
c4ce66a1 650base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 651 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 652{
91af0778 653 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
654 if (has_kernel)
655 module_val = "kernel";
91af0778
FCE
656
657 has_module = get_string_param (params, TOK_MODULE, module_val);
658 if (has_module)
659 has_process = false;
4baf0e53 660 else
d0a7f5a9 661 {
63b4fd14 662 string library_name;
576eaefe 663 long statement_num_val;
d0a7f5a9 664 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 665 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
666 if ((has_plt = has_null_param (params, TOK_PLT)))
667 plt_val = "*";
668 else has_plt = get_string_param (params, TOK_PLT, plt_val);
669 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
670
84c84ac4 671 if (has_process)
05fb3e0c 672 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
673 if (has_library)
674 {
675 if (! contains_glob_chars (library_name))
676 {
05fb3e0c
WF
677 path = path_remove_sysroot(sess, module_val);
678 module_val = find_executable (library_name, sess.sysroot,
679 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
680 if (module_val.find('/') == string::npos)
681 {
682 // We didn't find library_name so use iterate_over_libraries
683 module_val = path;
684 path = library_name;
685 }
84c84ac4
SC
686 }
687 else
688 path = library_name;
689 }
d0a7f5a9 690 }
91af0778
FCE
691
692 assert (has_kernel || has_process || has_module);
2c384610
DS
693}
694
c4ce66a1 695base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
696 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
697 module_val(module_val)
c4ce66a1
JS
698{
699 // NB: This uses '/' to distinguish between kernel modules and userspace,
700 // which means that userspace modules won't get any PATH searching.
701 if (module_val.find('/') == string::npos)
702 {
703 has_kernel = (module_val == TOK_KERNEL);
704 has_module = !has_kernel;
705 has_process = false;
706 }
707 else
708 {
709 has_kernel = has_module = false;
710 has_process = true;
711 }
712}
713
2c384610 714bool
86bf665e 715base_query::has_null_param(literal_map_t const & params,
2c384610
DS
716 string const & k)
717{
888af770 718 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
719}
720
721
722bool
86bf665e 723base_query::get_string_param(literal_map_t const & params,
2c384610
DS
724 string const & k, string & v)
725{
726 return derived_probe_builder::get_param (params, k, v);
727}
728
729
730bool
86bf665e 731base_query::get_number_param(literal_map_t const & params,
2c384610
DS
732 string const & k, long & v)
733{
734 int64_t value;
735 bool present = derived_probe_builder::get_param (params, k, value);
736 v = (long) value;
737 return present;
738}
739
740
741bool
86bf665e 742base_query::get_number_param(literal_map_t const & params,
2c384610
DS
743 string const & k, Dwarf_Addr & v)
744{
745 int64_t value;
746 bool present = derived_probe_builder::get_param (params, k, value);
747 v = (Dwarf_Addr) value;
748 return present;
749}
750
2c384610
DS
751struct dwarf_query : public base_query
752{
e1278bd4 753 dwarf_query(probe * base_probe,
2c384610
DS
754 probe_point * base_loc,
755 dwflpp & dw,
86bf665e 756 literal_map_t const & params,
b642c901
SC
757 vector<derived_probe *> & results,
758 const string user_path,
759 const string user_lib);
2c384610 760
c4ce66a1 761 vector<derived_probe *> & results;
8f14e444 762 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
763 probe * base_probe;
764 probe_point * base_loc;
b642c901
SC
765 string user_path;
766 string user_lib;
c4ce66a1 767
2c384610 768 virtual void handle_query_module();
5f0a03a6
JK
769 void query_module_dwarf();
770 void query_module_symtab();
5d5bd369 771 void query_library (const char *data);
576eaefe 772 void query_plt (const char *entry, size_t addr);
2c384610 773
2930abc7
FCE
774 void add_probe_point(string const & funcname,
775 char const * filename,
776 int line,
777 Dwarf_Die *scope_die,
778 Dwarf_Addr addr);
36f9dd1d 779
857bdfd1
JS
780 // Track addresses we've already seen in a given module
781 set<Dwarf_Addr> alias_dupes;
782
7fdd3e2c
JS
783 // Track inlines we've already seen as well
784 // NB: this can't be compared just by entrypc, as inlines can overlap
785 set<inline_instance_info> inline_dupes;
786
2930abc7 787 // Extracted parameters.
7a053d3b 788 string function_val;
20c6c071
GH
789
790 bool has_function_str;
791 bool has_statement_str;
792 bool has_function_num;
793 bool has_statement_num;
7a053d3b
RM
794 string statement_str_val;
795 string function_str_val;
c239d28c
GH
796 Dwarf_Addr statement_num_val;
797 Dwarf_Addr function_num_val;
20c6c071 798
b8da0ad1 799 bool has_call;
4bda987e 800 bool has_exported;
b8da0ad1 801 bool has_inline;
20c6c071
GH
802 bool has_return;
803
c9bad430
DS
804 bool has_maxactive;
805 long maxactive_val;
806
20c6c071
GH
807 bool has_label;
808 string label_val;
809
810 bool has_relative;
811 long relative_val;
812
37ebca01
FCE
813 bool has_absolute;
814
467bea43
SC
815 bool has_mark;
816
5f0a03a6
JK
817 enum dbinfo_reqt dbinfo_reqt;
818 enum dbinfo_reqt assess_dbinfo_reqt();
819
7d6d0afc 820 void parse_function_spec(const string & spec);
20c6c071 821 function_spec_type spec_type;
7d6d0afc 822 vector<string> scopes;
20c6c071
GH
823 string function;
824 string file;
0c8b7d37 825 line_t line_type;
879eb9e9 826 int line[2];
5f0a03a6 827 bool query_done; // Found exact match
20c6c071 828
bd25380d 829 set<string> filtered_srcfiles;
7e1279ea
FCE
830
831 // Map official entrypc -> func_info object
86bf665e
TM
832 inline_instance_map_t filtered_inlines;
833 func_info_map_t filtered_functions;
7e1279ea
FCE
834 bool choose_next_line;
835 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
836
837 void query_module_functions ();
b55bc428
FCE
838};
839
98afd80e 840
435f53a7
FCE
841static void delete_session_module_cache (systemtap_session& s); // forward decl
842
843
98afd80e 844struct dwarf_builder: public derived_probe_builder
b55bc428 845{
665e1256 846 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 847 map <string,dwflpp*> user_dw;
b642c901
SC
848 string user_path;
849 string user_lib;
44ffe90c
JL
850
851 // Holds modules to suggest functions from. NB: aggregates over
852 // recursive calls to build() when deriving globby probes.
853 set <string> modules_seen;
854
ae2552da 855 dwarf_builder() {}
aa30ccd3 856
ae2552da 857 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 858 {
ea14cf67
FCE
859 if (kern_dw[module] == 0)
860 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 861 return kern_dw[module];
707bf35e
JS
862 }
863
864 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
865 {
ea14cf67
FCE
866 if (user_dw[module] == 0)
867 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
868 return user_dw[module];
869 }
7a24d422
FCE
870
871 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 872 void dwarf_build_no_more (bool)
aa30ccd3 873 {
435f53a7
FCE
874 delete_map(kern_dw);
875 delete_map(user_dw);
7a24d422
FCE
876 }
877
878 void build_no_more (systemtap_session &s)
879 {
880 dwarf_build_no_more (s.verbose > 3);
435f53a7 881 delete_session_module_cache (s);
aa30ccd3
FCE
882 }
883
e38d6504
RM
884 ~dwarf_builder()
885 {
7a24d422 886 dwarf_build_no_more (false);
c8959a29 887 }
aa30ccd3 888
5227f1ea 889 virtual void build(systemtap_session & sess,
7a053d3b 890 probe * base,
20c6c071 891 probe_point * location,
86bf665e 892 literal_map_t const & parameters,
20c6c071 893 vector<derived_probe *> & finished_results);
b55bc428
FCE
894};
895
5111fc3e 896
e1278bd4 897dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
898 probe_point * base_loc,
899 dwflpp & dw,
86bf665e 900 literal_map_t const & params,
b642c901
SC
901 vector<derived_probe *> & results,
902 const string user_path,
903 const string user_lib)
c4ce66a1 904 : base_query(dw, params), results(results),
b642c901 905 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
906 user_path(user_path), user_lib(user_lib), has_relative(false),
907 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
908{
909 // Reduce the query to more reasonable semantic values (booleans,
910 // extracted strings, numbers, etc).
bd2b1e68
GH
911 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
912 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
913
914 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
915 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
916
0f336e95
SC
917 has_label = get_string_param(params, TOK_LABEL, label_val);
918
b8da0ad1 919 has_call = has_null_param(params, TOK_CALL);
4bda987e 920 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 921 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 922 has_return = has_null_param(params, TOK_RETURN);
c9bad430 923 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 924 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 925 has_mark = false;
37ebca01 926
bd2b1e68 927 if (has_function_str)
7d6d0afc 928 parse_function_spec(function_str_val);
bd2b1e68 929 else if (has_statement_str)
7d6d0afc 930 parse_function_spec(statement_str_val);
0daad364 931
5f0a03a6
JK
932 dbinfo_reqt = assess_dbinfo_reqt();
933 query_done = false;
0daad364
JS
934}
935
936
440f755a
JS
937func_info_map_t *
938get_filtered_functions(dwarf_query *q)
939{
940 return &q->filtered_functions;
941}
942
943
944inline_instance_map_t *
945get_filtered_inlines(dwarf_query *q)
946{
947 return &q->filtered_inlines;
948}
949
950
2c384610 951void
5f0a03a6 952dwarf_query::query_module_dwarf()
2c384610
DS
953{
954 if (has_function_num || has_statement_num)
955 {
956 // If we have module("foo").function(0xbeef) or
957 // module("foo").statement(0xbeef), the address is relative
958 // to the start of the module, so we seek the function
959 // number plus the module's bias.
6b517475
JS
960 Dwarf_Addr addr = has_function_num ?
961 function_num_val : statement_num_val;
08d1d520
MW
962
963 // These are raw addresses, we need to know what the elf_bias
964 // is to feed it to libdwfl based functions.
965 Dwarf_Addr elf_bias;
966 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
967 assert(elf);
968 addr += elf_bias;
6b517475 969 query_addr(addr, this);
2c384610
DS
970 }
971 else
972 {
973 // Otherwise if we have a function("foo") or statement("foo")
974 // specifier, we have to scan over all the CUs looking for
975 // the function(s) in question
976 assert(has_function_str || has_statement_str);
4df79aaf
JS
977
978 // For simple cases, no wildcard and no source:line, we can do a very
979 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
980 if (spec_type == function_alone &&
981 !dw.name_has_wildcard(function) &&
982 !startswith(function, "_Z"))
4df79aaf
JS
983 query_module_functions();
984 else
337b7c44 985 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
986 }
987}
988
5f0a03a6
JK
989static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
990 dwarf_query * q);
991
91bb9081
LB
992static void
993query_symtab_func_info (func_info & fi, dwarf_query * q)
994{
995 assert(null_die(&fi.die));
996
997 Dwarf_Addr addr = fi.addr;
998
999 // Now compensate for the dw bias because the addresses come
1000 // from dwfl_module_symtab, so fi->addr is NOT a normal dw address.
1001 q->dw.get_module_dwarf(false, false);
1002 addr -= q->dw.module_bias;
1003
1004 // If there are already probes in this module, lets not duplicate.
1005 // This can come from other weak symbols/aliases or existing
1006 // matches from Dwarf DIE functions.
1007 if (q->alias_dupes.size() > 0)
1008 {
1009 for (set<Dwarf_Addr>::iterator it=q->alias_dupes.begin(); it!=q->alias_dupes.end(); ++it)
1010 {
1011 // If we've already got a probe at that pc, skip it
1012 if (*it == addr)
1013 return;
1014 if (*it != addr && ++it==q->alias_dupes.end())
1015 {
1016 // Build a probe at this point
1017 query_func_info(addr, fi, q);
1018 return;
1019 }
1020 }
1021 }
1022 else
1023 query_func_info(addr,fi,q);
1024}
1025
5f0a03a6
JK
1026void
1027dwarf_query::query_module_symtab()
1028{
1029 // Get the symbol table if it's necessary, sufficient, and not already got.
1030 if (dbinfo_reqt == dbr_need_dwarf)
1031 return;
1032
1033 module_info *mi = dw.mod_info;
1034 if (dbinfo_reqt == dbr_need_symtab)
1035 {
1036 if (mi->symtab_status == info_unknown)
1037 mi->get_symtab(this);
1038 if (mi->symtab_status == info_absent)
1039 return;
1040 }
1041
1042 func_info *fi = NULL;
1043 symbol_table *sym_table = mi->sym_table;
1044
1045 if (has_function_str)
1046 {
1047 // Per dwarf_query::assess_dbinfo_reqt()...
1048 assert(spec_type == function_alone);
1049 if (dw.name_has_wildcard(function_str_val))
1050 {
2e67a43b 1051 symbol_table::iterator_t iter;
1c6b77e5
JS
1052 for (iter = sym_table->map_by_addr.begin();
1053 iter != sym_table->map_by_addr.end();
2e67a43b 1054 ++iter)
5f0a03a6 1055 {
1c6b77e5 1056 fi = iter->second;
5f0a03a6
JK
1057 if (!null_die(&fi->die))
1058 continue; // already handled in query_module_dwarf()
1059 if (dw.function_name_matches_pattern(fi->name, function_str_val))
91bb9081 1060 query_symtab_func_info(*fi, this);
5f0a03a6
JK
1061 }
1062 }
1063 else
1064 {
1065 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1066 if (fi && !fi->descriptor && null_die(&fi->die))
91bb9081 1067 query_symtab_func_info(*fi, this);
5f0a03a6 1068 }
5f0a03a6
JK
1069 }
1070}
1071
1072void
1073dwarf_query::handle_query_module()
1074{
f4faaf86
JS
1075 if (has_plt && has_statement_num)
1076 {
1077 query_plt_statement (this);
1078 return;
1079 }
1080
0035051e 1081 bool report = dbinfo_reqt == dbr_need_dwarf;
1c6b77e5
JS
1082 dw.get_module_dwarf(false, report);
1083
1084 // prebuild the symbol table to resolve aliases
1085 dw.mod_info->get_symtab(this);
1086
857bdfd1
JS
1087 // reset the dupe-checking for each new module
1088 alias_dupes.clear();
7fdd3e2c 1089 inline_dupes.clear();
857bdfd1 1090
5f0a03a6
JK
1091 if (dw.mod_info->dwarf_status == info_present)
1092 query_module_dwarf();
1c6b77e5 1093
91bb9081
LB
1094 // Consult the symbol table, asm and weak functions can show up
1095 // in the symbol table but not in dwarf and minidebuginfo is
1096 // located in the gnu_debugdata section, alias_dupes checking
1097 // is done before adding any probe points
1098 if (!query_done && !pending_interrupts)
5f0a03a6
JK
1099 query_module_symtab();
1100}
1101
2c384610 1102
7d6d0afc
JS
1103void
1104dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1105{
1d12a9b2
JS
1106 line_type = ABSOLUTE;
1107 line[0] = line[1] = 0;
1108
91699a70 1109 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1110
7d6d0afc 1111 // look for named scopes
91699a70
JS
1112 scope_pos = spec.rfind("::");
1113 if (scope_pos != string::npos)
bd2b1e68 1114 {
91699a70
JS
1115 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1116 scope_pos += 2;
bd2b1e68 1117 }
91699a70
JS
1118 else
1119 scope_pos = 0;
bd2b1e68 1120
7d6d0afc
JS
1121 // look for a source separator
1122 src_pos = spec.find('@', scope_pos);
1123 if (src_pos == string::npos)
bd2b1e68 1124 {
7d6d0afc
JS
1125 function = spec.substr(scope_pos);
1126 spec_type = function_alone;
bd2b1e68 1127 }
7d6d0afc 1128 else
879eb9e9 1129 {
7d6d0afc 1130 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1131
7d6d0afc
JS
1132 // look for a line-number separator
1133 line_pos = spec.find_first_of(":+", src_pos);
1134 if (line_pos == string::npos)
1135 {
1136 file = spec.substr(src_pos + 1);
1137 spec_type = function_and_file;
1138 }
1139 else
1140 {
1141 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1142
1143 // classify the line spec
1144 spec_type = function_file_and_line;
1145 if (spec[line_pos] == '+')
1146 line_type = RELATIVE;
1147 else if (spec[line_pos + 1] == '*' &&
1148 spec.length() == line_pos + 2)
1149 line_type = WILDCARD;
1150 else
1151 line_type = ABSOLUTE;
1152
1153 if (line_type != WILDCARD)
1154 try
1155 {
1156 // try to parse either N or N-M
1157 dash_pos = spec.find('-', line_pos + 1);
1158 if (dash_pos == string::npos)
1159 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1160 else
1161 {
1162 line_type = RANGE;
1163 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1164 dash_pos - line_pos - 1));
1165 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1166 }
1167 }
1168 catch (runtime_error & exn)
1169 {
1170 goto bad;
1171 }
1172 }
bd2b1e68
GH
1173 }
1174
7d6d0afc
JS
1175 if (function.empty() ||
1176 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1177 goto bad;
1178
7d6d0afc 1179 if (sess.verbose > 2)
bd2b1e68 1180 {
b530b5b3
LB
1181 //clog << "parsed '" << spec << "'";
1182 clog << _F("parse '%s'", spec.c_str());
41c262f3 1183
7d6d0afc
JS
1184 if (!scopes.empty())
1185 clog << ", scope '" << scopes[0] << "'";
1186 for (unsigned i = 1; i < scopes.size(); ++i)
1187 clog << "::'" << scopes[i] << "'";
41c262f3 1188
7d6d0afc
JS
1189 clog << ", func '" << function << "'";
1190
1191 if (spec_type != function_alone)
1192 clog << ", file '" << file << "'";
1193
1194 if (spec_type == function_file_and_line)
1195 {
1196 clog << ", line ";
1197 switch (line_type)
1198 {
1199 case ABSOLUTE:
1200 clog << line[0];
1201 break;
1202
1203 case RELATIVE:
1204 clog << "+" << line[0];
1205 break;
1206
1207 case RANGE:
1208 clog << line[0] << " - " << line[1];
1209 break;
1210
1211 case WILDCARD:
1212 clog << "*";
1213 break;
1214 }
1215 }
1216
1217 clog << endl;
bd2b1e68
GH
1218 }
1219
7d6d0afc
JS
1220 return;
1221
1222bad:
dc09353a 1223 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1224 base_probe->tok);
bd2b1e68
GH
1225}
1226
05fb3e0c
WF
1227string path_remove_sysroot(const systemtap_session& sess, const string& path)
1228{
1229 size_t pos;
1230 string retval = path;
1231 if (!sess.sysroot.empty() &&
1232 (pos = retval.find(sess.sysroot)) != string::npos)
1233 retval.replace(pos, sess.sysroot.length(), "/");
1234 return retval;
1235}
bd2b1e68 1236
36f9dd1d 1237void
1ffb8bd1 1238dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1239 const char* filename,
36f9dd1d 1240 int line,
b20febf3 1241 Dwarf_Die* scope_die,
36f9dd1d
FCE
1242 Dwarf_Addr addr)
1243{
b20febf3 1244 string reloc_section; // base section for relocation purposes
27646582 1245 Dwarf_Addr reloc_addr; // relocated
b20febf3 1246 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1247 string funcname = dw_funcname;
36f9dd1d 1248
37ebca01
FCE
1249 assert (! has_absolute); // already handled in dwarf_builder::build()
1250
f4faaf86 1251 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1252
1ffb8bd1 1253 // If we originally used the linkage name, then let's call it that way
1ffb8bd1 1254 const char* linkage_name;
91bb9081 1255 if (!null_die(scope_die) && startswith (this->function, "_Z")
f450a7e3 1256 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1257 funcname = linkage_name;
1258
7f9f3386
FCE
1259 if (sess.verbose > 1)
1260 {
b530b5b3 1261 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1262 if (string(module) == TOK_KERNEL)
b530b5b3 1263 clog << _(" kernel");
91af0778 1264 else if (has_module)
b530b5b3 1265 clog << _(" module=") << module;
91af0778 1266 else if (has_process)
b530b5b3 1267 clog << _(" process=") << module;
b20febf3 1268 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1269 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1270 }
4baf0e53 1271
27646582 1272 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1273 addr, has_return);
b20febf3
FCE
1274 if (sess.verbose > 1)
1275 clog << endl;
7f9f3386 1276
84048984
FCE
1277 if (module == TOK_KERNEL)
1278 {
1279 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1280 reloc_addr = addr - sess.sym_stext;
37ebca01 1281 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1282 }
1283
b20febf3
FCE
1284 if (! bad)
1285 {
1a0dbc5a 1286 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1287
1288 if (has_process)
1289 {
05fb3e0c 1290 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1291 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1292 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1293 *this, scope_die));
1294 }
1295 else
1296 {
1297 assert (has_kernel || has_module);
1298 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1299 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1300 *this, scope_die));
1301 }
b20febf3 1302 }
2930abc7
FCE
1303}
1304
5f0a03a6
JK
1305enum dbinfo_reqt
1306dwarf_query::assess_dbinfo_reqt()
1307{
1308 if (has_absolute)
1309 {
1310 // kernel.statement(NUM).absolute
1311 return dbr_none;
1312 }
1313 if (has_inline)
1314 {
1315 // kernel.function("f").inline or module("m").function("f").inline
1316 return dbr_need_dwarf;
1317 }
1318 if (has_function_str && spec_type == function_alone)
1319 {
1320 // kernel.function("f") or module("m").function("f")
1321 return dbr_need_symtab;
1322 }
1323 if (has_statement_num)
1324 {
1325 // kernel.statement(NUM) or module("m").statement(NUM)
1326 // Technically, all we need is the module offset (or _stext, for
1327 // the kernel). But for that we need either the ELF file or (for
1328 // _stext) the symbol table. In either case, the symbol table
1329 // is available, and that allows us to map the NUM (address)
1330 // to a function, which is goodness.
1331 return dbr_need_symtab;
1332 }
1333 if (has_function_num)
1334 {
1335 // kernel.function(NUM) or module("m").function(NUM)
1336 // Need the symbol table so we can back up from NUM to the
1337 // start of the function.
1338 return dbr_need_symtab;
1339 }
1340 // Symbol table tells us nothing about source files or line numbers.
1341 return dbr_need_dwarf;
1342}
2930abc7
FCE
1343
1344
b8da0ad1
FCE
1345// The critical determining factor when interpreting a pattern
1346// string is, perhaps surprisingly: "presence of a lineno". The
1347// presence of a lineno changes the search strategy completely.
1348//
1349// Compare the two cases:
1350//
1351// 1. {statement,function}(foo@file.c:lineno)
1352// - find the files matching file.c
1353// - in each file, find the functions matching foo
1354// - query the file for line records matching lineno
1355// - iterate over the line records,
1356// - and iterate over the functions,
1357// - if(haspc(function.DIE, line.addr))
1358// - if looking for statements: probe(lineno.addr)
1359// - if looking for functions: probe(function.{entrypc,return,etc.})
1360//
1361// 2. {statement,function}(foo@file.c)
1362// - find the files matching file.c
1363// - in each file, find the functions matching foo
1364// - probe(function.{entrypc,return,etc.})
1365//
1366// Thus the first decision we make is based on the presence of a
1367// lineno, and we enter entirely different sets of callbacks
1368// depending on that decision.
1369//
1370// Note that the first case is a generalization fo the second, in that
1371// we could theoretically search through line records for matching
1372// file names (a "table scan" in rdbms lingo). Luckily, file names
1373// are already cached elsewhere, so we can do an "index scan" as an
1374// optimization.
7e1279ea 1375
bd2b1e68 1376static void
4cd232e4 1377query_statement (string const & func,
20e4a32c 1378 char const * file,
4cd232e4 1379 int line,
bcc12710 1380 Dwarf_Die *scope_die,
20e4a32c 1381 Dwarf_Addr stmt_addr,
4cd232e4 1382 dwarf_query * q)
bd2b1e68 1383{
39bcd429
FCE
1384 try
1385 {
cee35f73 1386 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1387 line, scope_die, stmt_addr);
39bcd429
FCE
1388 }
1389 catch (const semantic_error& e)
1390 {
1391 q->sess.print_error (e);
1392 }
bd2b1e68
GH
1393}
1394
6b517475
JS
1395static void
1396query_addr(Dwarf_Addr addr, dwarf_query *q)
1397{
1398 dwflpp &dw = q->dw;
1399
08d1d520
MW
1400 if (q->sess.verbose > 2)
1401 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1402
1403 // First pick which CU contains this address
1404 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1405 if (!cudie) // address could be wildly out of range
1406 return;
1407 dw.focus_on_cu(cudie);
1408
1409 // Now compensate for the dw bias
1410 addr -= dw.module_bias;
1411
1412 // Per PR5787, we look up the scope die even for
1413 // statement_num's, for blacklist sensitivity and $var
1414 // resolution purposes.
1415
1416 // Find the scopes containing this address
1417 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1418 if (scopes.empty())
1419 return;
1420
1421 // Look for the innermost containing function
1422 Dwarf_Die *fnscope = NULL;
1423 for (size_t i = 0; i < scopes.size(); ++i)
1424 {
1425 int tag = dwarf_tag(&scopes[i]);
1426 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1427 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1428 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1429 {
1430 fnscope = &scopes[i];
1431 break;
1432 }
1433 }
1434 if (!fnscope)
1435 return;
1436 dw.focus_on_function(fnscope);
1437
1438 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1439
1440 const char *file = dwarf_decl_file(fnscope);
1441 int line;
1442 dwarf_decl_line(fnscope, &line);
1443
1444 // Function probes should reset the addr to the function entry
1445 // and possibly perform prologue searching
1446 if (q->has_function_num)
1447 {
1bbf3f90
JS
1448 if (!dw.die_entrypc(fnscope, &addr))
1449 return;
6b517475
JS
1450 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1451 (q->sess.prologue_searching || q->has_process)) // PR 6871
1452 {
1453 func_info func;
1454 func.die = *fnscope;
1455 func.name = dw.function_name;
1456 func.decl_file = file;
1457 func.decl_line = line;
1458 func.entrypc = addr;
1459
1460 func_info_map_t funcs(1, func);
1461 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1462 if (q->has_return) // PR13200
1463 {
1464 if (q->sess.verbose > 2)
1465 clog << "ignoring prologue for .return probes" << endl;
1466 }
1467 else
1468 {
1469 if (funcs[0].prologue_end)
1470 addr = funcs[0].prologue_end;
1471 }
6b517475
JS
1472 }
1473 }
1474 else
1475 {
1476 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1477 if (address_line)
1478 {
1479 file = address_line.linesrc();
1480 line = address_line.lineno();
1481 }
1482
1483 // Verify that a raw address matches the beginning of a
1484 // statement. This is a somewhat lame check that the address
1485 // is at the start of an assembly instruction. Mark probes are in the
1486 // middle of a macro and thus not strictly at a statement beginning.
1487 // Guru mode may override this check.
1488 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1489 {
1490 stringstream msg;
2a97f50b 1491 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1492 addr);
6b517475 1493 if (address_line)
2a97f50b 1494 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1495 else
b530b5b3
LB
1496 msg << _F(" (no line info found for '%s', in module '%s')",
1497 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475 1498 if (! q->sess.guru_mode)
dc09353a 1499 throw SEMANTIC_ERROR(msg.str());
2713ea24 1500 else
6b517475
JS
1501 q->sess.print_warning(msg.str());
1502 }
1503 }
1504
1505 // Build a probe at this point
1506 query_statement(dw.function_name, file, line, scope, addr, q);
1507}
1508
f4faaf86
JS
1509static void
1510query_plt_statement(dwarf_query *q)
1511{
1512 assert (q->has_plt && q->has_statement_num);
1513
1514 Dwarf_Addr addr = q->statement_num_val;
1515 if (q->sess.verbose > 2)
1516 clog << "query_plt_statement 0x" << hex << addr << dec << endl;
1517
1518 // First adjust the raw address to dwfl's elf bias.
1519 Dwarf_Addr elf_bias;
1520 Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
1521 assert(elf);
1522 addr += elf_bias;
1523
1524 // Now compensate for the dw bias
1525 q->dw.get_module_dwarf(false, false);
1526 addr -= q->dw.module_bias;
1527
1528 // Build a probe at this point
1529 query_statement(q->plt_val, NULL, -1, NULL, addr, q);
1530}
1531
8096dd7d
JS
1532static void
1533query_label (string const & func,
1534 char const * label,
1535 char const * file,
1536 int line,
1537 Dwarf_Die *scope_die,
1538 Dwarf_Addr stmt_addr,
1539 dwarf_query * q)
1540{
6b517475
JS
1541 assert (q->has_statement_str || q->has_function_str);
1542
8096dd7d
JS
1543 size_t i = q->results.size();
1544
1545 // weed out functions whose decl_file isn't one of
1546 // the source files that we actually care about
6b517475 1547 if (q->spec_type != function_alone &&
8096dd7d
JS
1548 q->filtered_srcfiles.count(file) == 0)
1549 return;
1550
1551 query_statement(func, file, line, scope_die, stmt_addr, q);
1552
c72aa911
JS
1553 // after the fact, insert the label back into the derivation chain
1554 probe_point::component* ppc =
1555 new probe_point::component(TOK_LABEL, new literal_string (label));
1556 for (; i < q->results.size(); ++i)
1557 {
1558 derived_probe* p = q->results[i];
1559 probe_point* pp = new probe_point(*p->locations[0]);
1560 pp->components.push_back (ppc);
1561 p->base = p->base->create_alias(p->locations[0], pp);
1562 }
8096dd7d
JS
1563}
1564
7e1279ea 1565static void
3e961ba6 1566query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1567 dwarf_query * q)
1568{
b6581717 1569 try
7e1279ea 1570 {
8f14e444
FCE
1571 assert (! q->has_return); // checked by caller already
1572 if (q->sess.verbose>2)
b530b5b3
LB
1573 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1574 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1575 query_statement (ii.name, ii.decl_file, ii.decl_line,
1576 &ii.die, ii.entrypc, q);
7e1279ea 1577 }
b6581717 1578 catch (semantic_error &e)
7e1279ea 1579 {
b6581717 1580 q->sess.print_error (e);
7e1279ea
FCE
1581 }
1582}
1583
1584static void
1585query_func_info (Dwarf_Addr entrypc,
bcc12710 1586 func_info & fi,
7e1279ea
FCE
1587 dwarf_query * q)
1588{
b6581717 1589 try
7e1279ea 1590 {
b6581717
GH
1591 if (q->has_return)
1592 {
1593 // NB. dwarf_derived_probe::emit_registrations will emit a
1594 // kretprobe based on the entrypc in this case.
464379bb
FCE
1595 if (fi.prologue_end != 0 && q->has_return) // PR13200
1596 {
1597 if (q->sess.verbose > 2)
1598 clog << "ignoring prologue for .return probes" << endl;
1599 }
20e4a32c 1600 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1601 &fi.die, entrypc, q);
1602 }
1603 else
1604 {
35dc8b04 1605 if (fi.prologue_end != 0)
44f75386 1606 {
44f75386
FCE
1607 query_statement (fi.name, fi.decl_file, fi.decl_line,
1608 &fi.die, fi.prologue_end, q);
1609 }
1610 else
1611 {
1612 query_statement (fi.name, fi.decl_file, fi.decl_line,
1613 &fi.die, entrypc, q);
1614 }
b6581717 1615 }
7e1279ea 1616 }
b6581717 1617 catch (semantic_error &e)
7e1279ea 1618 {
b6581717 1619 q->sess.print_error (e);
7e1279ea
FCE
1620 }
1621}
1622
1623
bd4b874d
SC
1624static void
1625query_srcfile_label (const dwarf_line_t& line, void * arg)
1626{
1627 dwarf_query * q = static_cast<dwarf_query *>(arg);
1628
1629 Dwarf_Addr addr = line.addr();
1630
1631 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1632 i != q->filtered_functions.end(); ++i)
1633 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1634 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1635 q, query_label);
1636
1637 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1638 i != q->filtered_inlines.end(); ++i)
1639 if (q->dw.die_has_pc (i->die, addr))
1640 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1641 q, query_label);
bd4b874d
SC
1642}
1643
7e1279ea 1644static void
86bf665e 1645query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1646{
1647 dwarf_query * q = static_cast<dwarf_query *>(arg);
1648
86bf665e 1649 Dwarf_Addr addr = line.addr();
4cd232e4 1650
86bf665e 1651 int lineno = line.lineno();
847bf07f 1652
86bf665e 1653 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1654 i != q->filtered_functions.end(); ++i)
1655 {
3e961ba6 1656 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1657 {
b0ee93c4 1658 if (q->sess.verbose>3)
b530b5b3 1659 clog << _("function DIE lands on srcfile\n");
4cd232e4 1660 if (q->has_statement_str)
f5958c8f
JS
1661 {
1662 Dwarf_Die scope;
1663 q->dw.inner_die_containing_pc(i->die, addr, scope);
1664 query_statement (i->name, i->decl_file,
1665 lineno, // NB: not q->line !
1666 &scope, addr, q);
1667 }
4cd232e4 1668 else
3e961ba6 1669 query_func_info (i->entrypc, *i, q);
7e1279ea 1670 }
20e4a32c
RM
1671 }
1672
86bf665e 1673 for (inline_instance_map_t::iterator i
897820ca
GH
1674 = q->filtered_inlines.begin();
1675 i != q->filtered_inlines.end(); ++i)
1676 {
3e961ba6 1677 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1678 {
b0ee93c4 1679 if (q->sess.verbose>3)
b530b5b3 1680 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1681 if (q->has_statement_str)
f5958c8f
JS
1682 {
1683 Dwarf_Die scope;
1684 q->dw.inner_die_containing_pc(i->die, addr, scope);
1685 query_statement (i->name, i->decl_file,
d807e0ab
JS
1686 lineno, // NB: not q->line !
1687 &scope, addr, q);
f5958c8f 1688 }
897820ca 1689 else
3e961ba6 1690 query_inline_instance_info (*i, q);
897820ca 1691 }
20e4a32c 1692 }
7e1279ea
FCE
1693}
1694
1695
7fdd3e2c
JS
1696bool
1697inline_instance_info::operator<(const inline_instance_info& other) const
1698{
1699 if (entrypc != other.entrypc)
1700 return entrypc < other.entrypc;
1701
1702 if (decl_line != other.decl_line)
1703 return decl_line < other.decl_line;
1704
1705 int cmp = name.compare(other.name);
1706 if (!cmp)
1707 cmp = strcmp(decl_file, other.decl_file);
1708 return cmp < 0;
1709}
1710
1711
4fa7b22b 1712static int
7e1279ea 1713query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1714{
1715 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475 1716 assert (q->has_statement_str || q->has_function_str);
4bda987e 1717 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1718
39bcd429 1719 try
7a053d3b 1720 {
b0ee93c4 1721 if (q->sess.verbose>2)
b530b5b3 1722 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1723
6b517475
JS
1724 Dwarf_Addr entrypc;
1725 if (q->dw.die_entrypc (die, &entrypc))
1726 {
1727 inline_instance_info inl;
1728 inl.die = *die;
1729 inl.name = q->dw.function_name;
1730 inl.entrypc = entrypc;
1731 q->dw.function_file (&inl.decl_file);
1732 q->dw.function_line (&inl.decl_line);
1733
1734 // make sure that this inline hasn't already
1735 // been matched from a different CU
1736 if (q->inline_dupes.insert(inl).second)
1737 q->filtered_inlines.push_back(inl);
1738 }
7e1279ea
FCE
1739 return DWARF_CB_OK;
1740 }
1741 catch (const semantic_error& e)
1742 {
1743 q->sess.print_error (e);
1744 return DWARF_CB_ABORT;
1745 }
1746}
bb788f9f 1747
7e1279ea 1748static int
2da9cedb 1749query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1750{
2da9cedb 1751 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1752 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1753
bd25380d
JS
1754 // weed out functions whose decl_file isn't one of
1755 // the source files that we actually care about
6b517475 1756 if (q->spec_type != function_alone &&
bd25380d 1757 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1758 return DWARF_CB_OK;
bd25380d 1759
7e1279ea
FCE
1760 try
1761 {
7e1279ea
FCE
1762 q->dw.focus_on_function (func);
1763
7d6d0afc
JS
1764 if (!q->dw.function_scope_matches(q->scopes))
1765 return DWARF_CB_OK;
1766
857bdfd1
JS
1767 // make sure that this function address hasn't
1768 // already been matched under an aliased name
1769 Dwarf_Addr addr;
1770 if (!q->dw.func_is_inline() &&
1771 dwarf_entrypc(func, &addr) == 0 &&
1772 !q->alias_dupes.insert(addr).second)
1773 return DWARF_CB_OK;
1774
4bda987e 1775 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1776 {
4bda987e 1777 if (q->sess.verbose>3)
b530b5b3 1778 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1779 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1780 }
8f14e444
FCE
1781 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1782 {
1783 q->inlined_non_returnable.insert (q->dw.function_name);
1784 }
396afcee 1785 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1786 {
4bda987e
SC
1787 if (q->has_exported && !q->dw.func_is_exported ())
1788 return DWARF_CB_OK;
6b517475 1789 if (q->sess.verbose>2)
b530b5b3 1790 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1791
1792 func_info func;
1793 q->dw.function_die (&func.die);
1794 func.name = q->dw.function_name;
1795 q->dw.function_file (&func.decl_file);
1796 q->dw.function_line (&func.decl_line);
1797
1798 Dwarf_Addr entrypc;
1799 if (q->dw.function_entrypc (&entrypc))
1800 {
1801 func.entrypc = entrypc;
1802 q->filtered_functions.push_back (func);
1803 }
1804 /* else this function is fully inlined, just ignore it */
7e1279ea 1805 }
39bcd429 1806 return DWARF_CB_OK;
bd2b1e68 1807 }
39bcd429 1808 catch (const semantic_error& e)
bd2b1e68 1809 {
39bcd429
FCE
1810 q->sess.print_error (e);
1811 return DWARF_CB_ABORT;
bd2b1e68 1812 }
bd2b1e68
GH
1813}
1814
1815static int
1816query_cu (Dwarf_Die * cudie, void * arg)
1817{
20c6c071 1818 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1819 assert (q->has_statement_str || q->has_function_str);
1820
85007c04 1821 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1822
39bcd429 1823 try
bd2b1e68 1824 {
7e1279ea 1825 q->dw.focus_on_cu (cudie);
b5d77020 1826
b0ee93c4 1827 if (false && q->sess.verbose>2)
b530b5b3
LB
1828 clog << _F("focused on CU '%s', in module '%s'\n",
1829 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1830
6b517475
JS
1831 q->filtered_srcfiles.clear();
1832 q->filtered_functions.clear();
1833 q->filtered_inlines.clear();
1834
1835 // In this path, we find "abstract functions", record
1836 // information about them, and then (depending on lineno
1837 // matching) possibly emit one or more of the function's
1838 // associated addresses. Unfortunately the control of this
1839 // cannot easily be turned inside out.
1840
1841 if (q->spec_type != function_alone)
39bcd429 1842 {
6b517475
JS
1843 // If we have a pattern string with a filename, we need
1844 // to elaborate the srcfile mask in question first.
1845 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1846
1847 // If we have a file pattern and *no* srcfile matches, there's
1848 // no need to look further into this CU, so skip.
1849 if (q->filtered_srcfiles.empty())
1850 return DWARF_CB_OK;
1851 }
e4c58386 1852
6b517475
JS
1853 // Pick up [entrypc, name, DIE] tuples for all the functions
1854 // matching the query, and fill in the prologue endings of them
1855 // all in a single pass.
5898b6e1 1856 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1857 if (rc != DWARF_CB_OK)
1858 q->query_done = true;
1859
1860 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1861 && !q->has_statement_str) // PR 2608
1862 if (! q->filtered_functions.empty())
1863 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1864 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1865 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1866
1867 if (q->spec_type == function_file_and_line)
1868 {
58b070fb 1869 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1870 if (q->has_function_str)
b530b5b3 1871 q->sess.print_warning (_("For probing a particular line, use a "
b78a0fbb 1872 ".statement() probe, not .function()"),
af2e341f 1873 q->base_probe->tok);
58b070fb 1874
6b517475
JS
1875 // If we have a pattern string with target *line*, we
1876 // have to look at lines in all the matched srcfiles.
1877 void (* callback) (const dwarf_line_t&, void*) =
1878 q->has_label ? query_srcfile_label : query_srcfile_line;
1879 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1880 i != q->filtered_srcfiles.end(); ++i)
1881 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1882 q->line_type, callback, q->function, q);
1883 }
1884 else if (q->has_label)
1885 {
1886 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1887 i != q->filtered_functions.end(); ++i)
1888 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1889 q, query_label);
1890
1891 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1892 i != q->filtered_inlines.end(); ++i)
1893 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1894 q, query_label);
39bcd429 1895 }
6b517475
JS
1896 else
1897 {
1898 // Otherwise, simply probe all resolved functions.
1899 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1900 i != q->filtered_functions.end(); ++i)
1901 query_func_info (i->entrypc, *i, q);
1902
1903 // And all inline instances (if we're not excluding inlines with ".call")
1904 if (! q->has_call)
1905 for (inline_instance_map_t::iterator i
1906 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1907 query_inline_instance_info (*i, q);
1908 }
39bcd429 1909 return DWARF_CB_OK;
bd2b1e68 1910 }
39bcd429 1911 catch (const semantic_error& e)
bd2b1e68 1912 {
39bcd429
FCE
1913 q->sess.print_error (e);
1914 return DWARF_CB_ABORT;
bd2b1e68 1915 }
bd2b1e68
GH
1916}
1917
0ce64fb8 1918
4df79aaf
JS
1919void
1920dwarf_query::query_module_functions ()
1921{
1922 try
1923 {
1924 filtered_srcfiles.clear();
1925 filtered_functions.clear();
1926 filtered_inlines.clear();
1927
1928 // Collect all module functions so we know which CUs are interesting
1929 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1930 if (rc != DWARF_CB_OK)
1931 {
1932 query_done = true;
1933 return;
1934 }
1935
1936 set<void*> used_cus; // by cu->addr
1937 vector<Dwarf_Die> cus;
1938 Dwarf_Die cu_mem;
1939
1940 for (func_info_map_t::iterator i = filtered_functions.begin();
1941 i != filtered_functions.end(); ++i)
1942 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1943 used_cus.insert(cu_mem.addr).second)
1944 cus.push_back(cu_mem);
1945
1946 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1947 i != filtered_inlines.end(); ++i)
1948 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1949 used_cus.insert(cu_mem.addr).second)
1950 cus.push_back(cu_mem);
1951
1952 // Reset the dupes since we didn't actually collect them the first time
1953 alias_dupes.clear();
1954 inline_dupes.clear();
1955
1956 // Run the query again on the individual CUs
91bb9081
LB
1957 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i){
1958 rc = query_cu(&*i, this);
1959 if (rc != DWARF_CB_OK)
1960 {
1961 query_done = true;
1962 return;
1963 }
1964 }
4df79aaf
JS
1965 }
1966 catch (const semantic_error& e)
1967 {
1968 sess.print_error (e);
1969 }
1970}
1971
1972
5f0a03a6
JK
1973static void
1974validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1975{
1976 // Validate the machine code in this elf file against the
1977 // session machine. This is important, in case the wrong kind
1978 // of debuginfo is being automagically processed by elfutils.
1979 // While we can tell i686 apart from x86-64, unfortunately
1980 // we can't help confusing i586 vs i686 (both EM_386).
1981
1982 Dwarf_Addr bias;
1983 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1984 // because dwfl_module_getelf can force costly section relocations
1985 // we don't really need, while either will do for this purpose.
1986 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1987 ?: dwfl_module_getelf (mod, &bias));
1988
1989 GElf_Ehdr ehdr_mem;
1990 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1991 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 1992 assert(em);
5f0a03a6
JK
1993 int elf_machine = em->e_machine;
1994 const char* debug_filename = "";
1995 const char* main_filename = "";
1996 (void) dwfl_module_info (mod, NULL, NULL,
1997 NULL, NULL, NULL,
1998 & main_filename,
1999 & debug_filename);
2000 const string& sess_machine = q->sess.architecture;
756c9462
FCE
2001
2002 string expect_machine; // to match sess.machine (i.e., kernel machine)
2003 string expect_machine2;
5f0a03a6 2004
d27e6fd5 2005 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
2006 switch (elf_machine)
2007 {
756c9462
FCE
2008 // x86 and ppc are bi-architecture; a 64-bit kernel
2009 // can normally run either 32-bit or 64-bit *userspace*.
2010 case EM_386:
2011 expect_machine = "i?86";
2012 if (! q->has_process) break; // 32-bit kernel/module
2013 /* FALLSTHROUGH */
2014 case EM_X86_64:
2015 expect_machine2 = "x86_64";
2016 break;
2017 case EM_PPC:
756c9462 2018 case EM_PPC64:
5a1c472e 2019 expect_machine = "powerpc";
756c9462 2020 break;
3fe7d888 2021 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2022 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2023 case EM_ARM: expect_machine = "arm*"; break;
86aae990 2024 case EM_AARCH64: expect_machine = "arm64"; break;
5f0a03a6
JK
2025 // XXX: fill in some more of these
2026 default: expect_machine = "?"; break;
2027 }
2028
2029 if (! debug_filename) debug_filename = main_filename;
2030 if (! debug_filename) debug_filename = name;
2031
756c9462
FCE
2032 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2033 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2034 {
2035 stringstream msg;
b530b5b3
LB
2036 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2037 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2038 sess_machine.c_str(), debug_filename);
dc09353a 2039 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2040 }
2041
b57082de 2042 if (q->sess.verbose>1)
b78a0fbb 2043 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2044 " file %s ELF machine %s|%s (code %d)\n",
2045 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2046 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2047 expect_machine2.c_str(), elf_machine);
5f0a03a6 2048}
1d3a40b6 2049
91af0778
FCE
2050
2051
2052static Dwarf_Addr
2053lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2054{
2055 int syments = dwfl_module_getsymtab(m);
2056 assert(syments);
2057 for (int i = 1; i < syments; ++i)
2058 {
2059 GElf_Sym sym;
2060 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2061 if (name != NULL && strcmp(name, wanted) == 0)
2062 return sym.st_value;
2063 }
2064
2065 return 0;
2066}
2067
2068
2069
bd2b1e68 2070static int
b8da0ad1 2071query_module (Dwfl_Module *mod,
91af0778 2072 void **,
b8da0ad1 2073 const char *name,
6f4c1275 2074 Dwarf_Addr addr,
b8da0ad1 2075 void *arg)
bd2b1e68 2076{
91af0778 2077 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 2078
39bcd429 2079 try
e38d6504 2080 {
91af0778
FCE
2081 module_info* mi = q->sess.module_cache->cache[name];
2082 if (mi == 0)
2083 {
2084 mi = q->sess.module_cache->cache[name] = new module_info(name);
2085
6f4c1275
FCE
2086 mi->mod = mod;
2087 mi->addr = addr;
91af0778 2088
6f4c1275
FCE
2089 const char* debug_filename = "";
2090 const char* main_filename = "";
2091 (void) dwfl_module_info (mod, NULL, NULL,
2092 NULL, NULL, NULL,
2093 & main_filename,
2094 & debug_filename);
2095
ab3ed72d 2096 if (debug_filename || main_filename)
91af0778 2097 {
6f4c1275
FCE
2098 mi->elf_path = debug_filename ?: main_filename;
2099 }
2100 else if (name == TOK_KERNEL)
2101 {
2102 mi->dwarf_status = info_absent;
91af0778 2103 }
91af0778
FCE
2104 }
2105 // OK, enough of that module_info caching business.
2106
5f0a03a6 2107 q->dw.focus_on_module(mod, mi);
d9b516ca 2108
39bcd429
FCE
2109 // If we have enough information in the pattern to skip a module and
2110 // the module does not match that information, return early.
b8da0ad1 2111 if (!q->dw.module_name_matches(q->module_val))
85007c04 2112 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2113
2114 // Don't allow module("*kernel*") type expressions to match the
2115 // elfutils module "kernel", which we refer to in the probe
2116 // point syntax exclusively as "kernel.*".
2117 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2118 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2119
5f0a03a6
JK
2120 if (mod)
2121 validate_module_elf(mod, name, q);
2122 else
91af0778
FCE
2123 assert(q->has_kernel); // and no vmlinux to examine
2124
2125 if (q->sess.verbose>2)
b530b5b3 2126 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2127
2128
2129 // Collect a few kernel addresses. XXX: these belong better
2130 // to the sess.module_info["kernel"] struct.
2131 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2132 {
91af0778
FCE
2133 if (! q->sess.sym_kprobes_text_start)
2134 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2135 if (! q->sess.sym_kprobes_text_end)
2136 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2137 if (! q->sess.sym_stext)
2138 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2139 }
2140
47e226ed
SC
2141 // We either have a wildcard or an unresolved library
2142 if (q->has_library && (contains_glob_chars (q->path)
2143 || q->path.find('/') == string::npos))
84c84ac4
SC
2144 // handle .library(GLOB)
2145 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2146 // .plt is translated to .plt.statement(N). We only want to iterate for the
2147 // .plt case
2148 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2149 {
2150 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2151 q->visited_modules.insert(name);
2152 }
84c84ac4 2153 else
070764c0
JL
2154 {
2155 // search the module for matches of the probe point.
2156 q->handle_query_module();
2157 q->visited_modules.insert(name);
2158 }
bb788f9f 2159
b8da0ad1 2160 // If we know that there will be no more matches, abort early.
85007c04 2161 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2162 return DWARF_CB_ABORT;
2163 else
2164 return DWARF_CB_OK;
7a053d3b 2165 }
39bcd429 2166 catch (const semantic_error& e)
bd2b1e68 2167 {
39bcd429
FCE
2168 q->sess.print_error (e);
2169 return DWARF_CB_ABORT;
bd2b1e68 2170 }
bd2b1e68
GH
2171}
2172
35d4ab18 2173
84c84ac4 2174void
5d5bd369 2175base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2176{
2177 base_query *me = (base_query*)q;
5d5bd369 2178 me->query_library (data);
84c84ac4
SC
2179}
2180
2181
2cbcfa9c 2182string
51d6bda3
SC
2183query_one_library (const char *library, dwflpp & dw,
2184 const string user_lib, probe * base_probe, probe_point *base_loc,
2185 vector<derived_probe *> & results)
84c84ac4 2186{
47e226ed 2187 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2188 {
05fb3e0c
WF
2189 string library_path = find_executable (library, "", dw.sess.sysenv,
2190 "LD_LIBRARY_PATH");
84c84ac4
SC
2191 probe_point* specific_loc = new probe_point(*base_loc);
2192 specific_loc->optional = true;
2193 vector<probe_point::component*> derived_comps;
2194
2195 vector<probe_point::component*>::iterator it;
2196 for (it = specific_loc->components.begin();
2197 it != specific_loc->components.end(); ++it)
2198 if ((*it)->functor == TOK_LIBRARY)
2199 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2200 new literal_string(library_path)));
2201 else
2202 derived_comps.push_back(*it);
2203 probe_point* derived_loc = new probe_point(*specific_loc);
2204 derived_loc->components = derived_comps;
8159bf55 2205 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2206 derive_probes(dw.sess, new_base, results);
2207 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2208 clog << _("module=") << library_path << endl;
2209 return library_path;
84c84ac4 2210 }
2cbcfa9c 2211 return "";
84c84ac4
SC
2212}
2213
2214
51d6bda3
SC
2215void
2216dwarf_query::query_library (const char *library)
2217{
2cbcfa9c
JL
2218 string library_path =
2219 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2220 if (!library_path.empty())
2221 visited_modules.insert(library_path);
51d6bda3
SC
2222}
2223
576eaefe
SC
2224struct plt_expanding_visitor: public var_expanding_visitor
2225{
2226 plt_expanding_visitor(const string & entry):
2227 entry (entry)
2228 {
2229 }
2230 const string & entry;
2231
2232 void visit_target_symbol (target_symbol* e);
2233};
2234
2235
2236void
2237base_query::query_plt_callback (void *q, const char *entry, size_t address)
2238{
2239 base_query *me = (base_query*)q;
2240 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2241 me->query_plt (entry, address);
7f4964f1 2242 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2243}
2244
2245
2246void
2247query_one_plt (const char *entry, long addr, dwflpp & dw,
2248 probe * base_probe, probe_point *base_loc,
2249 vector<derived_probe *> & results)
2250{
2251 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2252 vector<probe_point::component*> derived_comps;
2253
2254 if (dw.sess.verbose > 2)
2255 clog << _F("plt entry=%s\n", entry);
2256
576eaefe
SC
2257 vector<probe_point::component*>::iterator it;
2258 for (it = specific_loc->components.begin();
2259 it != specific_loc->components.end(); ++it)
2260 if ((*it)->functor == TOK_PLT)
3d372d6b 2261 {
8159bf55
FCE
2262 *it = new probe_point::component(TOK_PLT,
2263 new literal_string(entry));
3d372d6b
SC
2264 derived_comps.push_back(*it);
2265 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2266 new literal_number(addr, true)));
3d372d6b 2267 }
576eaefe
SC
2268 else
2269 derived_comps.push_back(*it);
2270 probe_point* derived_loc = new probe_point(*specific_loc);
2271 derived_loc->components = derived_comps;
02c34e38
FCE
2272 probe *new_base = new probe (new probe (base_probe, specific_loc),
2273 derived_loc);
576eaefe
SC
2274 string e = string(entry);
2275 plt_expanding_visitor pltv (e);
2276 pltv.replace (new_base->body);
2277 derive_probes(dw.sess, new_base, results);
2278}
2279
2280
2281void
2282dwarf_query::query_plt (const char *entry, size_t address)
2283{
2284 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2285}
51d6bda3 2286
435f53a7
FCE
2287// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2288// but the needed declaration for module_cache is not available there.
2289// Nor for that matter in session.cxx. Only in this CU is that field ever
2290// set (in query_module() above), so we clean it up here too.
2291static void
2292delete_session_module_cache (systemtap_session& s)
2293{
2294 if (s.module_cache) {
2295 if (s.verbose > 3)
b530b5b3 2296 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2297 delete s.module_cache;
2298 s.module_cache = 0;
2299 }
2300}
2301
2302
de688825 2303struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2304{
77de5e9e 2305 dwarf_query & q;
bcc12710 2306 Dwarf_Die *scope_die;
77de5e9e 2307 Dwarf_Addr addr;
8c819921 2308 block *add_block;
2260f4e3 2309 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2310 // NB: tids are not always collected in add_block & add_call_probe, because
2311 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2312 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2313 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2314 unsigned saved_longs, saved_strings; // data saved within kretprobes
2315 map<std::string, expression *> return_ts_map;
729455a7 2316 vector<Dwarf_Die> scopes;
3689db05 2317 // probe counter name -> pointer of associated probe
698de6cc 2318 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2319 bool visited;
77de5e9e 2320
de688825 2321 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2322 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2323 add_block_tid(false), add_call_probe_tid(false),
af234c40 2324 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2325 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2326 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2327 void visit_target_symbol_saved_return (target_symbol* e);
2328 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2329 void visit_target_symbol (target_symbol* e);
bd1fcbad 2330 void visit_atvar_op (atvar_op* e);
c24447be 2331 void visit_cast_op (cast_op* e);
8cc799a5 2332 void visit_entry_op (entry_op* e);
3689db05 2333 void visit_perf_op (perf_op* e);
729455a7
JS
2334private:
2335 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2336};
2337
2338
de688825 2339unsigned var_expanding_visitor::tick = 0;
77de5e9e 2340
a50de939 2341
74fe61bc 2342var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2343{
2344 // FIXME: for the time being, by default we only support plain '$foo
2345 // = bar', not '+=' or any other op= variant. This is fixable, but a
2346 // bit ugly.
2347 //
2348 // If derived classes desire to add additional operator support, add
2349 // new operators to this list in the derived class constructor.
2350 valid_ops.insert ("=");
2351}
2352
2353
87214add
JS
2354bool
2355var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2356 expression*& lvalue, expression*& rvalue)
77de5e9e 2357{
e57b735a
GH
2358 // Our job would normally be to require() the left and right sides
2359 // into a new assignment. What we're doing is slightly trickier:
2360 // we're pushing a functioncall** onto a stack, and if our left
2361 // child sets the functioncall* for that value, we're going to
2362 // assume our left child was a target symbol -- transformed into a
2363 // set_target_foo(value) call, and it wants to take our right child
2364 // as the argument "value".
2365 //
2366 // This is why some people claim that languages with
2367 // constructor-decomposing case expressions have a leg up on
2368 // visitors.
2369
2370 functioncall *fcall = NULL;
d9b516ca 2371
a50de939 2372 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2373 const string* old_op = op;
2374 op = &eop;
a50de939 2375
e57b735a 2376 target_symbol_setter_functioncalls.push (&fcall);
87214add 2377 replace (lvalue);
e57b735a 2378 target_symbol_setter_functioncalls.pop ();
87214add
JS
2379 replace (rvalue);
2380
2381 op = old_op;
e57b735a
GH
2382
2383 if (fcall != NULL)
77de5e9e 2384 {
e57b735a
GH
2385 // Our left child is informing us that it was a target variable
2386 // and it has been replaced with a set_target_foo() function
2387 // call; we are going to provide that function call -- with the
2388 // right child spliced in as sole argument -- in place of
de688825 2389 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2390
87214add 2391 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2392 {
2393 // Build up a list of supported operators.
2394 string ops;
2395 std::set<string>::iterator i;
b530b5b3 2396 int valid_ops_size = 0;
a50de939 2397 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2398 {
a50de939 2399 ops += " " + *i + ",";
b530b5b3
LB
2400 valid_ops_size++;
2401 }
a50de939
DS
2402 ops.resize(ops.size() - 1); // chop off the last ','
2403
2404 // Throw the error.
dc09353a 2405 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2406 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2407 valid_ops_size, ops.c_str()), tok);
b530b5b3 2408
a50de939 2409 }
e57b735a 2410
87214add
JS
2411 assert (lvalue == fcall);
2412 if (rvalue)
2413 fcall->args.push_back (rvalue);
4ed05b15 2414 provide (fcall);
87214add 2415 return true;
77de5e9e 2416 }
e57b735a 2417 else
87214add
JS
2418 return false;
2419}
2420
2421
2422void
2423var_expanding_visitor::visit_assignment (assignment* e)
2424{
2425 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2426 provide (e);
2427}
2428
2429
2430void
2431var_expanding_visitor::visit_pre_crement (pre_crement* e)
2432{
2433 expression *dummy = NULL;
2434 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2435 provide (e);
2436}
2437
2438
2439void
2440var_expanding_visitor::visit_post_crement (post_crement* e)
2441{
2442 expression *dummy = NULL;
2443 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2444 provide (e);
2445}
2446
2447
2448void
2449var_expanding_visitor::visit_delete_statement (delete_statement* s)
2450{
2451 string fakeop = "delete";
2452 expression *dummy = NULL;
2453 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2454 provide (s);
e57b735a 2455}
d9b516ca 2456
d7f3e0c5 2457
30263a73
FCE
2458void
2459var_expanding_visitor::visit_defined_op (defined_op* e)
2460{
2461 bool resolved = true;
2462
2463 defined_ops.push (e);
2464 try {
2465 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2466 // defined with a target_symbol* operand, a subsidiary call may attempt to
2467 // rewrite it to a general expression* instead, and require<> happily
2468 // casts to/from void*, causing possible memory corruption. We use
2469 // expression* here, being the general case of rewritten $variable.
2470 expression *foo1 = e->operand;
2471 foo1 = require (foo1);
2472
c69a87e0 2473 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2474 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2475 // erroneous resolutions. Some would signal a visit_target_symbol failure
2476 // with an exception, with a set flag within the target_symbol, or nothing
2477 // at all.
30263a73 2478 //
c69a87e0
FCE
2479 // Now, failures always have to be signalled with a
2480 // saved_conversion_error being chained to the target_symbol.
2481 // Successes have to result in an attempted rewrite of the
850bfddd 2482 // target_symbol (via provide()).
780f11ff 2483 //
c69a87e0
FCE
2484 // Edna Mode: "no capes". fche: "no exceptions".
2485
30263a73
FCE
2486 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2487 //
2488 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2489 //
2490 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2491 // dwarf probe to take care of it.
2492 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2493 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2494 //
30263a73
FCE
2495 // utrace: success: rewrites to function; failure: semantic_error
2496 //
850bfddd 2497 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2498
2499 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2500 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2501 resolved = false;
a45664f4 2502 else if (foo2) // unresolved but not marked failing
b7aedf26 2503 {
780f11ff
JS
2504 // There are some visitors that won't touch certain target_symbols,
2505 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2506 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2507 e->operand = foo2;
2508 provide (e);
2509 return;
2510 }
30263a73
FCE
2511 else // resolved, rewritten to some other expression type
2512 resolved = true;
780f11ff 2513 } catch (const semantic_error& e) {
c69a87e0 2514 assert (0); // should not happen
30263a73
FCE
2515 }
2516 defined_ops.pop ();
2517
2518 literal_number* ln = new literal_number (resolved ? 1 : 0);
2519 ln->tok = e->tok;
2520 provide (ln);
2521}
2522
2523
5f36109e
JS
2524struct dwarf_pretty_print
2525{
2526 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2527 const string& local, bool userspace_p,
2528 const target_symbol& e):
d19a9a82
JS
2529 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2530 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2531 {
2532 init_ts (e);
2533 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2534 }
2535
2536 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2537 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2538 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2539 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2540 {
2541 init_ts (e);
2542 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2543 }
2544
2545 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2546 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2547 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2548 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2549 {
2550 init_ts (e);
2551 dw.type_die_for_pointer (type_die, ts, &base_type);
2552 }
2553
2554 functioncall* expand ();
ce83ff57 2555 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2556
2557private:
2558 dwflpp& dw;
2559 target_symbol* ts;
7d11d8c9 2560 bool print_full;
5f36109e
JS
2561 Dwarf_Die base_type;
2562
2563 string local;
2564 vector<Dwarf_Die> scopes;
2565 Dwarf_Addr pc;
2566
2567 expression* pointer;
2568 Dwarf_Die pointer_type;
2569
d19a9a82 2570 const bool userspace_p, deref_p;
5f36109e
JS
2571
2572 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2573 print_format* pf, bool top=false);
600551ca
JS
2574 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2575 print_format* pf);
5f36109e 2576 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2577 print_format* pf);
5f36109e 2578 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2579 print_format* pf, bool top);
5f36109e 2580 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2581 print_format* pf, bool top);
5f36109e 2582 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2583 print_format* pf, bool top);
5f36109e 2584 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2585 print_format* pf, int& count);
bbee5bb8 2586 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2587
2588 void init_ts (const target_symbol& e);
2589 expression* deref (target_symbol* e);
c55ea10d 2590 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2591};
2592
2593
2594void
2595dwarf_pretty_print::init_ts (const target_symbol& e)
2596{
2597 // Work with a new target_symbol so we can modify arguments
2598 ts = new target_symbol (e);
2599
2600 if (ts->addressof)
dc09353a 2601 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2602
2603 if (ts->components.empty() ||
2604 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2605 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2606 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2607 ts->components.pop_back();
2608}
2609
2610
2611functioncall*
2612dwarf_pretty_print::expand ()
2613{
2614 static unsigned tick = 0;
2615
2616 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2617 // try {
2618 // return sprintf("{.foo=...}", (ts)->foo, ...)
2619 // } catch {
2620 // return "ERROR"
2621 // }
5f36109e
JS
2622 // }
2623
2624 // Create the function decl and call.
2625
2626 functiondecl *fdecl = new functiondecl;
2627 fdecl->tok = ts->tok;
2628 fdecl->synthetic = true;
2629 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2630 fdecl->type = pe_string;
2631
2632 functioncall* fcall = new functioncall;
2633 fcall->tok = ts->tok;
2634 fcall->function = fdecl->name;
140be17a 2635 fcall->type = pe_string;
5f36109e
JS
2636
2637 // If there's a <pointer>, replace it with a new var and make that
2638 // the first function argument.
2639 if (pointer)
2640 {
2641 vardecl *v = new vardecl;
2642 v->type = pe_long;
2643 v->name = "pointer";
2644 v->tok = ts->tok;
2645 fdecl->formal_args.push_back (v);
2646 fcall->args.push_back (pointer);
2647
2648 symbol* sym = new symbol;
2649 sym->tok = ts->tok;
2650 sym->name = v->name;
5f36109e
JS
2651 pointer = sym;
2652 }
2653
2654 // For each expression argument, replace it with a function argument.
2655 for (unsigned i = 0; i < ts->components.size(); ++i)
2656 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2657 {
2658 vardecl *v = new vardecl;
2659 v->type = pe_long;
2660 v->name = "index" + lex_cast(i);
2661 v->tok = ts->tok;
2662 fdecl->formal_args.push_back (v);
2663 fcall->args.push_back (ts->components[i].expr_index);
2664
2665 symbol* sym = new symbol;
2666 sym->tok = ts->tok;
2667 sym->name = v->name;
5f36109e
JS
2668 ts->components[i].expr_index = sym;
2669 }
2670
2671 // Create the return sprintf.
1c922ad7 2672 print_format* pf = print_format::create(ts->tok, "sprintf");
5f36109e
JS
2673 return_statement* rs = new return_statement;
2674 rs->tok = ts->tok;
2675 rs->value = pf;
5f36109e
JS
2676
2677 // Recurse into the actual values.
7d11d8c9 2678 recurse (&base_type, ts, pf, true);
5f36109e
JS
2679 pf->components = print_format::string_to_components(pf->raw_components);
2680
7d11d8c9
JS
2681 // Create the try-catch net
2682 try_block* tb = new try_block;
2683 tb->tok = ts->tok;
2684 tb->try_block = rs;
2685 tb->catch_error_var = 0;
2686 return_statement* rs2 = new return_statement;
2687 rs2->tok = ts->tok;
2688 rs2->value = new literal_string ("ERROR");
2689 rs2->value->tok = ts->tok;
2690 tb->catch_block = rs2;
2691 fdecl->body = tb;
2692
f8809d54 2693 fdecl->join (dw.sess);
5f36109e
JS
2694 return fcall;
2695}
2696
2697
2698void
2699dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2700 print_format* pf, bool top)
5f36109e
JS
2701{
2702 Dwarf_Die type;
2703 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2704
2705 switch (dwarf_tag(&type))
2706 {
2707 default:
2708 // XXX need a warning?
2709 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2710 // + ") for " + dwarf_type_name(&type), e->tok);
2711 pf->raw_components.append("?");
2712 break;
2713
2714 case DW_TAG_enumeration_type:
2715 case DW_TAG_base_type:
7d11d8c9 2716 recurse_base (&type, e, pf);
5f36109e
JS
2717 break;
2718
2719 case DW_TAG_array_type:
7d11d8c9 2720 recurse_array (&type, e, pf, top);
5f36109e
JS
2721 break;
2722
2723 case DW_TAG_pointer_type:
2724 case DW_TAG_reference_type:
2725 case DW_TAG_rvalue_reference_type:
7d11d8c9 2726 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2727 break;
2728
2729 case DW_TAG_subroutine_type:
c55ea10d 2730 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2731 break;
2732
2733 case DW_TAG_union_type:
5f36109e
JS
2734 case DW_TAG_structure_type:
2735 case DW_TAG_class_type:
7d11d8c9 2736 recurse_struct (&type, e, pf, top);
5f36109e
JS
2737 break;
2738 }
2739}
2740
2741
600551ca
JS
2742// Bit fields are handled as a special-case combination of recurse() and
2743// recurse_base(), only called from recurse_struct_members(). The main
2744// difference is that the value is always printed numerically, even if the
2745// underlying type is a char.
2746void
2747dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2748 print_format* pf)
2749{
2750 Dwarf_Die type;
2751 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2752
2753 int tag = dwarf_tag(&type);
2754 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2755 {
2756 // XXX need a warning?
2757 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2758 // + ") for " + dwarf_type_name(&type), e->tok);
2759 pf->raw_components.append("?");
2760 return;
2761 }
2762
2763 Dwarf_Attribute attr;
2764 Dwarf_Word encoding = (Dwarf_Word) -1;
2765 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2766 &encoding);
2767 switch (encoding)
2768 {
2769 case DW_ATE_float:
2770 case DW_ATE_complex_float:
2771 // XXX need a warning?
2772 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2773 // + ") for " + dwarf_type_name(&type), e->tok);
2774 pf->raw_components.append("?");
2775 break;
2776
2777 case DW_ATE_unsigned:
2778 case DW_ATE_unsigned_char:
2779 push_deref (pf, "%u", e);
2780 break;
2781
2782 case DW_ATE_signed:
2783 case DW_ATE_signed_char:
2784 default:
2785 push_deref (pf, "%i", e);
2786 break;
2787 }
2788}
2789
2790
5f36109e
JS
2791void
2792dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2793 print_format* pf)
5f36109e
JS
2794{
2795 Dwarf_Attribute attr;
2796 Dwarf_Word encoding = (Dwarf_Word) -1;
2797 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2798 &encoding);
5f36109e
JS
2799 switch (encoding)
2800 {
2801 case DW_ATE_float:
2802 case DW_ATE_complex_float:
2803 // XXX need a warning?
2804 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2805 // + ") for " + dwarf_type_name(type), e->tok);
2806 pf->raw_components.append("?");
5f36109e
JS
2807 break;
2808
6561d8d1 2809 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2810 case DW_ATE_signed_char:
2811 case DW_ATE_unsigned_char:
941101c1
JS
2812 // Use escapes to make sure that non-printable characters
2813 // don't interrupt our stream (especially '\0' values).
2814 push_deref (pf, "'%#c'", e);
5f36109e
JS
2815 break;
2816
2817 case DW_ATE_unsigned:
c55ea10d 2818 push_deref (pf, "%u", e);
5f36109e
JS
2819 break;
2820
600551ca 2821 case DW_ATE_signed:
5f36109e 2822 default:
c55ea10d 2823 push_deref (pf, "%i", e);
5f36109e
JS
2824 break;
2825 }
5f36109e
JS
2826}
2827
2828
2829void
2830dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2831 print_format* pf, bool top)
5f36109e 2832{
7d11d8c9
JS
2833 if (!top && !print_full)
2834 {
2835 pf->raw_components.append("[...]");
2836 return;
2837 }
2838
5f36109e
JS
2839 Dwarf_Die childtype;
2840 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2841
2842 if (print_chars (&childtype, e, pf))
2843 return;
2844
5f36109e
JS
2845 pf->raw_components.append("[");
2846
2847 // We print the array up to the first 5 elements.
2848 // XXX how can we determine the array size?
2849 // ... for now, just print the first element
64cddf39 2850 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2851 unsigned i, size = 1;
64cddf39 2852 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2853 {
2854 if (i > 0)
2855 pf->raw_components.append(", ");
2856 target_symbol* e2 = new target_symbol(*e);
2857 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2858 recurse (&childtype, e2, pf);
5f36109e
JS
2859 }
2860 if (i < size || 1/*XXX until real size is known */)
2861 pf->raw_components.append(", ...");
2862 pf->raw_components.append("]");
2863}
2864
2865
2866void
2867dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2868 print_format* pf, bool top)
5f36109e 2869{
7d11d8c9 2870 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2871 bool void_p = true;
7d11d8c9 2872 Dwarf_Die pointee;
bbee5bb8 2873 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2874 {
2875 try
2876 {
2877 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2878 void_p = false;
2879 }
2880 catch (const semantic_error&) {}
2881 }
2882
2883 if (!void_p)
5f36109e 2884 {
bbee5bb8
JS
2885 if (print_chars (&pointee, e, pf))
2886 return;
2887
2888 if (top)
2889 {
2890 recurse (&pointee, e, pf, top);
2891 return;
2892 }
5f36109e 2893 }
bbee5bb8 2894
c55ea10d 2895 push_deref (pf, "%p", e);
5f36109e
JS
2896}
2897
2898
2899void
2900dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2901 print_format* pf, bool top)
5f36109e 2902{
bdec0e18
JS
2903 if (dwarf_hasattr(type, DW_AT_declaration))
2904 {
a44a7cb5 2905 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2906 if (!resolved)
2907 {
2908 // could be an error, but for now just stub it
2909 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2910 pf->raw_components.append("{...}");
2911 return;
2912 }
2913 type = resolved;
2914 }
2915
5f36109e
JS
2916 int count = 0;
2917 pf->raw_components.append("{");
7d11d8c9
JS
2918 if (top || print_full)
2919 recurse_struct_members (type, e, pf, count);
2920 else
2921 pf->raw_components.append("...");
5f36109e
JS
2922 pf->raw_components.append("}");
2923}
2924
2925
2926void
2927dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2928 print_format* pf, int& count)
5f36109e 2929{
a80f28d8
JS
2930 /* With inheritance, a subclass may mask member names of parent classes, so
2931 * our search among the inheritance tree must be breadth-first rather than
2932 * depth-first (recursive). The type die is still our starting point. When
2933 * we encounter a masked name, just skip it. */
2934 set<string> dupes;
2935 deque<Dwarf_Die> inheritees(1, *type);
2936 for (; !inheritees.empty(); inheritees.pop_front())
2937 {
dee830d9 2938 Dwarf_Die child, childtype, import;
a80f28d8
JS
2939 if (dwarf_child (&inheritees.front(), &child) == 0)
2940 do
2941 {
2942 target_symbol* e2 = e;
5f36109e 2943
a80f28d8
JS
2944 // skip static members
2945 if (dwarf_hasattr(&child, DW_AT_declaration))
2946 continue;
5f36109e 2947
a80f28d8 2948 int tag = dwarf_tag (&child);
5f36109e 2949
dee830d9
MW
2950 /* Pretend imported units contain members by recursing into
2951 struct_member printing with the same count. */
2952 if (tag == DW_TAG_imported_unit
2953 && dwarf_attr_die (&child, DW_AT_import, &import))
2954 recurse_struct_members (&import, e2, pf, count);
2955
a80f28d8
JS
2956 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2957 continue;
5f36109e 2958
a80f28d8 2959 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2960
a80f28d8
JS
2961 if (tag == DW_TAG_inheritance)
2962 {
2963 inheritees.push_back(childtype);
2964 continue;
2965 }
5f36109e 2966
a80f28d8
JS
2967 int childtag = dwarf_tag (&childtype);
2968 const char *member = dwarf_diename (&child);
3a147004 2969
a80f28d8
JS
2970 // "_vptr.foo" members are C++ virtual function tables,
2971 // which (generally?) aren't interesting for users.
2972 if (member && startswith(member, "_vptr."))
2973 continue;
3a147004 2974
a80f28d8
JS
2975 // skip inheritance-masked duplicates
2976 if (member && !dupes.insert(member).second)
2977 continue;
64cddf39 2978
a80f28d8
JS
2979 if (++count > 1)
2980 pf->raw_components.append(", ");
64cddf39 2981
a80f28d8
JS
2982 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2983 if (pf->args.size() >= 32)
2984 {
2985 pf->raw_components.append("...");
2986 break;
2987 }
2988
2989 if (member)
2990 {
2991 pf->raw_components.append(".");
2992 pf->raw_components.append(member);
5f36109e 2993
a80f28d8
JS
2994 e2 = new target_symbol(*e);
2995 e2->components.push_back (target_symbol::component(e->tok, member));
2996 }
2997 else if (childtag == DW_TAG_union_type)
2998 pf->raw_components.append("<union>");
2999 else if (childtag == DW_TAG_structure_type)
3000 pf->raw_components.append("<class>");
3001 else if (childtag == DW_TAG_class_type)
3002 pf->raw_components.append("<struct>");
3003 pf->raw_components.append("=");
600551ca
JS
3004
3005 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
3006 recurse_bitfield (&childtype, e2, pf);
3007 else
3008 recurse (&childtype, e2, pf);
5f36109e 3009 }
a80f28d8
JS
3010 while (dwarf_siblingof (&child, &child) == 0);
3011 }
5f36109e
JS
3012}
3013
3014
bbee5bb8
JS
3015bool
3016dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
3017 print_format* pf)
3018{
3019 Dwarf_Die type;
3020 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
3021
3022 Dwarf_Attribute attr;
3023 Dwarf_Word encoding = (Dwarf_Word) -1;
3024 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3025 &encoding);
3026 switch (encoding)
bbee5bb8 3027 {
6561d8d1
JS
3028 case DW_ATE_UTF:
3029 case DW_ATE_signed_char:
3030 case DW_ATE_unsigned_char:
3031 break;
3032 default:
3033 return false;
3034 }
3035
3036 string function = userspace_p ? "user_string2" : "kernel_string2";
3037 Dwarf_Word size = (Dwarf_Word) -1;
3038 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3039 switch (size)
3040 {
3041 case 1:
3042 break;
3043 case 2:
3044 function += "_utf16";
3045 break;
3046 case 4:
3047 function += "_utf32";
3048 break;
3049 default:
3050 return false;
3051 }
3052
3053 if (push_deref (pf, "\"%s\"", e))
3054 {
3055 // steal the last arg for a string access
3056 assert (!pf->args.empty());
3057 functioncall* fcall = new functioncall;
3058 fcall->tok = e->tok;
3059 fcall->function = function;
3060 fcall->args.push_back (pf->args.back());
3061 expression *err_msg = new literal_string ("<unknown>");
3062 err_msg->tok = e->tok;
3063 fcall->args.push_back (err_msg);
3064 pf->args.back() = fcall;
bbee5bb8 3065 }
6561d8d1 3066 return true;
bbee5bb8
JS
3067}
3068
a5ce5211
MW
3069// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3070static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3071 + "#define fetch_register k_fetch_register\n"
3072 + "#define store_register k_store_register\n"
3073 + "#define deref kderef\n"
3074 + "#define store_deref store_kderef\n";
a5ce5211
MW
3075
3076static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3077 + "#define fetch_register u_fetch_register\n"
3078 + "#define store_register u_store_register\n"
3079 + "#define deref uderef\n"
3080 + "#define store_deref store_uderef\n";
a5ce5211
MW
3081
3082#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3083 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3084
3085static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3086 + "#undef fetch_register\n"
3087 + "#undef store_register\n"
3088 + "#undef deref\n"
3089 + "#undef store_deref\n";
bbee5bb8 3090
1c0be8c7
JS
3091static functioncall*
3092synthetic_embedded_deref_call(systemtap_session& session,
3093 const string& function_name,
3094 const string& function_code,
3095 exp_type function_type,
3096 bool userspace_p,
3097 bool lvalue_p,
3098 target_symbol* e,
3099 expression* pointer=NULL)
3100{
3101 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3102 functiondecl *fdecl = new functiondecl;
3103 fdecl->synthetic = true;
3104 fdecl->tok = e->tok;
1c0be8c7
JS
3105 fdecl->name = function_name;
3106 fdecl->type = function_type;
3107
5f36109e
JS
3108 embeddedcode *ec = new embeddedcode;
3109 ec->tok = e->tok;
1c0be8c7
JS
3110 ec->code += "/* unprivileged */";
3111 if (! lvalue_p)
3112 ec->code += "/* pure */";
3113 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3114 ec->code += function_code;
3115 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3116 fdecl->body = ec;
3117
3118 // Synthesize a functioncall.
3119 functioncall* fcall = new functioncall;
3120 fcall->tok = e->tok;
3121 fcall->function = fdecl->name;
1c0be8c7 3122 fcall->type = fdecl->type;
5f36109e 3123
1c0be8c7
JS
3124 // If this code snippet uses a precomputed pointer,
3125 // pass that as the first argument.
5f36109e
JS
3126 if (pointer)
3127 {
5f36109e
JS
3128 vardecl *v = new vardecl;
3129 v->type = pe_long;
3130 v->name = "pointer";
3131 v->tok = e->tok;
3132 fdecl->formal_args.push_back(v);
3133 fcall->args.push_back(pointer);
3134 }
5f36109e 3135
1c0be8c7 3136 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3137 for (unsigned i = 0; i < e->components.size(); ++i)
3138 if (e->components[i].type == target_symbol::comp_expression_array_index)
3139 {
3140 vardecl *v = new vardecl;
3141 v->type = pe_long;
3142 v->name = "index" + lex_cast(i);
3143 v->tok = e->tok;
3144 fdecl->formal_args.push_back(v);
3145 fcall->args.push_back(e->components[i].expr_index);
3146 }
3147
1c0be8c7
JS
3148 // If this code snippet is assigning to an lvalue,
3149 // add a final argument for the rvalue.
3150 if (lvalue_p)
3151 {
3152 // Modify the fdecl so it carries a single pe_long formal
3153 // argument called "value".
5f36109e 3154
1c0be8c7
JS
3155 // FIXME: For the time being we only support setting target
3156 // variables which have base types; these are 'pe_long' in
3157 // stap's type vocabulary. Strings and pointers might be
3158 // reasonable, some day, but not today.
5f36109e 3159
1c0be8c7
JS
3160 vardecl *v = new vardecl;
3161 v->type = pe_long;
3162 v->name = "value";
3163 v->tok = e->tok;
3164 fdecl->formal_args.push_back(v);
3165 // NB: We don't know the value for fcall argument yet.
3166 // (see target_symbol_setter_functioncalls)
3167 }
3168
3169 // Add the synthesized decl to the session, and return the call.
3170 fdecl->join (session);
5f36109e
JS
3171 return fcall;
3172}
3173
1c0be8c7
JS
3174expression*
3175dwarf_pretty_print::deref (target_symbol* e)
3176{
3177 static unsigned tick = 0;
3178
3179 if (!deref_p)
3180 {
3181 assert (pointer && e->components.empty());
3182 return pointer;
3183 }
3184
3185 bool lvalue_p = false;
3186 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3187
3188 string code;
3189 exp_type type = pe_long;
3190 if (pointer)
3191 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3192 else if (!local.empty())
3193 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3194 else
3195 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3196
3197 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3198 userspace_p, lvalue_p, e, pointer);
3199}
3200
5f36109e 3201
c55ea10d
JS
3202bool
3203dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3204 target_symbol* e)
3205{
3206 expression* e2 = NULL;
3207 try
3208 {
3209 e2 = deref (e);
3210 }
3211 catch (const semantic_error&)
3212 {
3213 pf->raw_components.append ("?");
3214 return false;
3215 }
3216 pf->raw_components.append (fmt);
3217 pf->args.push_back (e2);
3218 return true;
3219}
3220
3221
e57b735a 3222void
a7999c82 3223dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3224{
a7999c82
JS
3225 // Get the full name of the target symbol.
3226 stringstream ts_name_stream;
3227 e->print(ts_name_stream);
3228 string ts_name = ts_name_stream.str();
3229
3230 // Check and make sure we haven't already seen this target
3231 // variable in this return probe. If we have, just return our
3232 // last replacement.
af234c40 3233 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3234 if (i != return_ts_map.end())
85ecf79a 3235 {
a7999c82
JS
3236 provide (i->second);
3237 return;
3238 }
85ecf79a 3239
70208613
JS
3240 // Attempt the expansion directly first, so if there's a problem with the
3241 // variable we won't have a bogus entry probe lying around. Like in
3242 // saveargs(), we pretend for a moment that we're not in a .return.
3243 bool saved_has_return = q.has_return;
3244 q.has_return = false;
3245 expression *repl = e;
3246 replace (repl);
3247 q.has_return = saved_has_return;
3248 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3249 if (n && n->saved_conversion_error)
3250 {
3251 provide (repl);
3252 return;
3253 }
3254
af234c40
JS
3255 expression *exp;
3256 if (!q.has_process &&
3257 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3258 exp = gen_kretprobe_saved_return(repl);
af234c40 3259 else
cc9001af 3260 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3261
3262 // Provide the variable to our parent so it can be used as a
3263 // substitute for the target symbol.
3264 provide (exp);
3265
3266 // Remember this replacement since we might be able to reuse
3267 // it later if the same return probe references this target
3268 // symbol again.
3269 return_ts_map[ts_name] = exp;
3270}
3271
4a2970a3 3272static expression*
23dc94f6
DS
3273gen_mapped_saved_return(systemtap_session &sess, expression* e,
3274 const string& name,
3275 block *& add_block, bool& add_block_tid,
3276 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3277{
23dc94f6
DS
3278 static unsigned tick = 0;
3279
a7999c82
JS
3280 // We've got to do several things here to handle target
3281 // variables in return probes.
85ecf79a 3282
a7999c82
JS
3283 // (1) Synthesize two global arrays. One is the cache of the
3284 // target variable and the other contains a thread specific
3285 // nesting level counter. The arrays will look like
3286 // this:
3287 //
23dc94f6
DS
3288 // _entry_tvar_{name}_{num}
3289 // _entry_tvar_{name}_{num}_ctr
a7999c82 3290
23dc94f6 3291 string aname = (string("_entry_tvar_")
cc9001af 3292 + name
aca66a36 3293 + "_" + lex_cast(tick++));
a7999c82
JS
3294 vardecl* vd = new vardecl;
3295 vd->name = aname;
3296 vd->tok = e->tok;
23dc94f6 3297 sess.globals.push_back (vd);
a7999c82
JS
3298
3299 string ctrname = aname + "_ctr";
3300 vd = new vardecl;
3301 vd->name = ctrname;
3302 vd->tok = e->tok;
23dc94f6 3303 sess.globals.push_back (vd);
a7999c82
JS
3304
3305 // (2) Create a new code block we're going to insert at the
3306 // beginning of this probe to get the cached value into a
3307 // temporary variable. We'll replace the target variable
3308 // reference with the temporary variable reference. The code
3309 // will look like this:
3310 //
23dc94f6
DS
3311 // _entry_tvar_tid = tid()
3312 // _entry_tvar_{name}_{num}_tmp
3313 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3314 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3315 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3316 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3317 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3318 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3319
3320 // (2a) Synthesize the tid temporary expression, which will look
3321 // like this:
3322 //
23dc94f6 3323 // _entry_tvar_tid = tid()
a7999c82 3324 symbol* tidsym = new symbol;
23dc94f6 3325 tidsym->name = string("_entry_tvar_tid");
a7999c82 3326 tidsym->tok = e->tok;
85ecf79a 3327
a7999c82
JS
3328 if (add_block == NULL)
3329 {
3330 add_block = new block;
3331 add_block->tok = e->tok;
8cc799a5 3332 }
8c819921 3333
8cc799a5
JS
3334 if (!add_block_tid)
3335 {
a7999c82
JS
3336 // Synthesize a functioncall to grab the thread id.
3337 functioncall* fc = new functioncall;
3338 fc->tok = e->tok;
3339 fc->function = string("tid");
8c819921 3340
23dc94f6 3341 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3342 assignment* a = new assignment;
3343 a->tok = e->tok;
3344 a->op = "=";
a7999c82
JS
3345 a->left = tidsym;
3346 a->right = fc;
8c819921
DS
3347
3348 expr_statement* es = new expr_statement;
3349 es->tok = e->tok;
3350 es->value = a;
8c819921 3351 add_block->statements.push_back (es);
8cc799a5 3352 add_block_tid = true;
a7999c82 3353 }
8c819921 3354
a7999c82
JS
3355 // (2b) Synthesize an array reference and assign it to a
3356 // temporary variable (that we'll use as replacement for the
3357 // target variable reference). It will look like this:
3358 //
23dc94f6
DS
3359 // _entry_tvar_{name}_{num}_tmp
3360 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3361 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3362
3363 arrayindex* ai_tvar_base = new arrayindex;
3364 ai_tvar_base->tok = e->tok;
3365
3366 symbol* sym = new symbol;
3367 sym->name = aname;
3368 sym->tok = e->tok;
3369 ai_tvar_base->base = sym;
3370
3371 ai_tvar_base->indexes.push_back(tidsym);
3372
3373 // We need to create a copy of the array index in its current
3374 // state so we can have 2 variants of it (the original and one
3375 // that post-decrements the second index).
3376 arrayindex* ai_tvar = new arrayindex;
3377 arrayindex* ai_tvar_postdec = new arrayindex;
3378 *ai_tvar = *ai_tvar_base;
3379 *ai_tvar_postdec = *ai_tvar_base;
3380
3381 // Synthesize the
23dc94f6 3382 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3383 // second index into the array.
3384 arrayindex* ai_ctr = new arrayindex;
3385 ai_ctr->tok = e->tok;
3386
3387 sym = new symbol;
3388 sym->name = ctrname;
3389 sym->tok = e->tok;
3390 ai_ctr->base = sym;
3391 ai_ctr->indexes.push_back(tidsym);
3392 ai_tvar->indexes.push_back(ai_ctr);
3393
3394 symbol* tmpsym = new symbol;
3395 tmpsym->name = aname + "_tmp";
3396 tmpsym->tok = e->tok;
3397
3398 assignment* a = new assignment;
3399 a->tok = e->tok;
3400 a->op = "=";
3401 a->left = tmpsym;
3402 a->right = ai_tvar;
3403
3404 expr_statement* es = new expr_statement;
3405 es->tok = e->tok;
3406 es->value = a;
3407
3408 add_block->statements.push_back (es);
3409
3410 // (2c) Add a post-decrement to the second array index and
3411 // delete the array value. It will look like this:
3412 //
23dc94f6
DS
3413 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3414 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3415
3416 post_crement* pc = new post_crement;
3417 pc->tok = e->tok;
3418 pc->op = "--";
3419 pc->operand = ai_ctr;
3420 ai_tvar_postdec->indexes.push_back(pc);
3421
3422 delete_statement* ds = new delete_statement;
3423 ds->tok = e->tok;
3424 ds->value = ai_tvar_postdec;
3425
3426 add_block->statements.push_back (ds);
3427
3428 // (2d) Delete the counter value if it is 0. It will look like
3429 // this:
23dc94f6
DS
3430 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3431 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3432
3433 ds = new delete_statement;
3434 ds->tok = e->tok;
3435 ds->value = ai_ctr;
3436
3437 unary_expression *ue = new unary_expression;
3438 ue->tok = e->tok;
3439 ue->op = "!";
3440 ue->operand = ai_ctr;
3441
3442 if_statement *ifs = new if_statement;
3443 ifs->tok = e->tok;
3444 ifs->condition = ue;
3445 ifs->thenblock = ds;
3446 ifs->elseblock = NULL;
3447
3448 add_block->statements.push_back (ifs);
3449
3450 // (3) We need an entry probe that saves the value for us in the
3451 // global array we created. Create the entry probe, which will
3452 // look like this:
3453 //
2260f4e3 3454 // probe kernel.function("{function}").call {
23dc94f6
DS
3455 // _entry_tvar_tid = tid()
3456 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3457 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3458 // = ${param}
3459 // }
3460
2260f4e3 3461 if (add_call_probe == NULL)
a7999c82 3462 {
2260f4e3
FCE
3463 add_call_probe = new block;
3464 add_call_probe->tok = e->tok;
8cc799a5 3465 }
4baf0e53 3466
8cc799a5
JS
3467 if (!add_call_probe_tid)
3468 {
a7999c82
JS
3469 // Synthesize a functioncall to grab the thread id.
3470 functioncall* fc = new functioncall;
3471 fc->tok = e->tok;
3472 fc->function = string("tid");
4baf0e53 3473
23dc94f6 3474 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3475 assignment* a = new assignment;
8fc05e57
DS
3476 a->tok = e->tok;
3477 a->op = "=";
a7999c82
JS
3478 a->left = tidsym;
3479 a->right = fc;
8fc05e57 3480
a7999c82 3481 expr_statement* es = new expr_statement;
8fc05e57
DS
3482 es->tok = e->tok;
3483 es->value = a;
2260f4e3 3484 add_call_probe = new block(add_call_probe, es);
8cc799a5 3485 add_call_probe_tid = true;
85ecf79a 3486 }
cf2a1f85 3487
a7999c82 3488 // Save the value, like this:
23dc94f6
DS
3489 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3490 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3491 // = ${param}
3492 arrayindex* ai_tvar_preinc = new arrayindex;
3493 *ai_tvar_preinc = *ai_tvar_base;
3494
3495 pre_crement* preinc = new pre_crement;
3496 preinc->tok = e->tok;
3497 preinc->op = "++";
3498 preinc->operand = ai_ctr;
3499 ai_tvar_preinc->indexes.push_back(preinc);
3500
3501 a = new assignment;
3502 a->tok = e->tok;
3503 a->op = "=";
3504 a->left = ai_tvar_preinc;
3505 a->right = e;
3506
3507 es = new expr_statement;
3508 es->tok = e->tok;
3509 es->value = a;
3510
2260f4e3 3511 add_call_probe = new block(add_call_probe, es);
a7999c82 3512
23dc94f6 3513 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3514 // our parent so it can be used as a substitute for the target
3515 // symbol.
3f803f9e 3516 delete ai_tvar_base;
af234c40
JS
3517 return tmpsym;
3518}
a7999c82 3519
af234c40 3520
23dc94f6
DS
3521expression*
3522dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3523 const string& name)
3524{
3525 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3526 add_block_tid, add_call_probe,
3527 add_call_probe_tid);
3528}
3529
3530
af234c40 3531expression*
140be17a 3532dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3533{
3534 // The code for this is simple.
3535 //
3536 // .call:
3537 // _set_kretprobe_long(index, $value)
3538 //
3539 // .return:
3540 // _get_kretprobe_long(index)
3541 //
3542 // (or s/long/string/ for things like $$parms)
3543
3544 unsigned index;
3545 string setfn, getfn;
3546
140be17a
JS
3547 // We need the caller to predetermine the type of the expression!
3548 switch (e->type)
af234c40 3549 {
140be17a 3550 case pe_string:
af234c40
JS
3551 index = saved_strings++;
3552 setfn = "_set_kretprobe_string";
3553 getfn = "_get_kretprobe_string";
140be17a
JS
3554 break;
3555 case pe_long:
af234c40
JS
3556 index = saved_longs++;
3557 setfn = "_set_kretprobe_long";
3558 getfn = "_get_kretprobe_long";
140be17a
JS
3559 break;
3560 default:
dc09353a 3561 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3562 }
3563
3564 // Create the entry code
3565 // _set_kretprobe_{long|string}(index, $value)
3566
3567 if (add_call_probe == NULL)
3568 {
3569 add_call_probe = new block;
3570 add_call_probe->tok = e->tok;
3571 }
3572
3573 functioncall* set_fc = new functioncall;
3574 set_fc->tok = e->tok;
3575 set_fc->function = setfn;
3576 set_fc->args.push_back(new literal_number(index));
3577 set_fc->args.back()->tok = e->tok;
3578 set_fc->args.push_back(e);
3579
3580 expr_statement* set_es = new expr_statement;
3581 set_es->tok = e->tok;
3582 set_es->value = set_fc;
3583
3584 add_call_probe->statements.push_back(set_es);
3585
3586 // Create the return code
3587 // _get_kretprobe_{long|string}(index)
3588
3589 functioncall* get_fc = new functioncall;
3590 get_fc->tok = e->tok;
3591 get_fc->function = getfn;
3592 get_fc->args.push_back(new literal_number(index));
3593 get_fc->args.back()->tok = e->tok;
3594
3595 return get_fc;
a7999c82 3596}
a43ba433 3597
2cb3fe26 3598
a7999c82
JS
3599void
3600dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3601{
b78a0fbb
LB
3602 if (null_die(scope_die)) {
3603 print_format* pf = print_format::create(e->tok, "sprintf");
3604 pf->raw_components = "";
3605 pf->components = print_format::string_to_components(pf->raw_components);
3606 pf->type = pe_string;
3607 provide (pf);
a7999c82 3608 return;
b78a0fbb 3609 }
2cb3fe26 3610
5f36109e
JS
3611 target_symbol *tsym = new target_symbol(*e);
3612
fde50242
JS
3613 bool pretty = (!e->components.empty() &&
3614 e->components[0].type == target_symbol::comp_pretty_print);
3615 string format = pretty ? "=%s" : "=%#x";
a43ba433 3616
a7999c82
JS
3617 // Convert $$parms to sprintf of a list of parms and active local vars
3618 // which we recursively evaluate
a43ba433 3619
1c922ad7 3620 print_format* pf = print_format::create(e->tok, "sprintf");
a7999c82 3621
277c21bc 3622 if (q.has_return && (e->name == "$$return"))
a7999c82 3623 {
277c21bc 3624 tsym->name = "$return";
a7999c82
JS
3625
3626 // Ignore any variable that isn't accessible.
3627 tsym->saved_conversion_error = 0;
3628 expression *texp = tsym;
8b095b45 3629 replace (texp); // NB: throws nothing ...
a7999c82 3630 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3631 {
2cb3fe26 3632
a43ba433
FCE
3633 }
3634 else
3635 {
a7999c82 3636 pf->raw_components += "return";
5f36109e 3637 pf->raw_components += format;
a7999c82
JS
3638 pf->args.push_back(texp);
3639 }
3640 }
3641 else
3642 {
3643 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3644 bool first = true;
a7999c82 3645 Dwarf_Die result;
d48bc7eb
JS
3646 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3647 for (unsigned i = 0; i < scopes.size(); ++i)
3648 {
3649 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3650 break; // we don't want file-level variables
3651 if (dwarf_child (&scopes[i], &result) == 0)
3652 do
00cf3709 3653 {
d48bc7eb
JS
3654 switch (dwarf_tag (&result))
3655 {
3656 case DW_TAG_variable:
3657 if (e->name == "$$parms")
3658 continue;
3659 break;
3660 case DW_TAG_formal_parameter:
3661 if (e->name == "$$locals")
3662 continue;
3663 break;
3664
3665 default:
3666 continue;
3667 }
41c262f3 3668
d48bc7eb
JS
3669 const char *diename = dwarf_diename (&result);
3670 if (! diename) continue;
f76427a2 3671
d48bc7eb
JS
3672 if (! first)
3673 pf->raw_components += " ";
3674 pf->raw_components += diename;
fde50242
JS
3675 first = false;
3676
3677 // Write a placeholder for ugly aggregates
3678 Dwarf_Die type;
3679 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3680 {
3681 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3682 switch (dwarf_tag(&type))
3683 {
3684 case DW_TAG_union_type:
3685 case DW_TAG_structure_type:
3686 case DW_TAG_class_type:
3687 pf->raw_components += "={...}";
3688 continue;
3689
3690 case DW_TAG_array_type:
3691 pf->raw_components += "=[...]";
3692 continue;
3693 }
3694 }
345bbb3d 3695
d48bc7eb
JS
3696 tsym->name = "$";
3697 tsym->name += diename;
41c262f3 3698
d48bc7eb
JS
3699 // Ignore any variable that isn't accessible.
3700 tsym->saved_conversion_error = 0;
3701 expression *texp = tsym;
3702 replace (texp); // NB: throws nothing ...
3703 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3704 {
d48bc7eb
JS
3705 if (q.sess.verbose>2)
3706 {
e26c2f83 3707 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb
JS
3708 c != 0;
3709 c = c->chain) {
4c5d9906 3710 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3711 }
3712 }
3713
3714 pf->raw_components += "=?";
a43ba433 3715 }
d48bc7eb
JS
3716 else
3717 {
3718 pf->raw_components += format;
3719 pf->args.push_back(texp);
3720 }
a7999c82 3721 }
d48bc7eb
JS
3722 while (dwarf_siblingof (&result, &result) == 0);
3723 }
a7999c82 3724 }
2cb3fe26 3725
a7999c82 3726 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3727 pf->type = pe_string;
a7999c82
JS
3728 provide (pf);
3729}
3730
2cb3fe26 3731
bd1fcbad
YZ
3732void
3733dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3734{
3735 // Fill in our current module context if needed
3736 if (e->module.empty())
3737 e->module = q.dw.module_name;
3738
3739 if (e->module == q.dw.module_name && e->cu_name.empty())
3740 {
3741 // process like any other local
3742 // e->sym_name() will do the right thing
3743 visit_target_symbol(e);
3744 return;
3745 }
3746
3747 var_expanding_visitor::visit_atvar_op(e);
3748}
3749
3750
a7999c82
JS
3751void
3752dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3753{
bd1fcbad 3754 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3755 visited = true;
30263a73
FCE
3756 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3757 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3758
70208613 3759 try
a7999c82 3760 {
c69a87e0
FCE
3761 bool lvalue = is_active_lvalue(e);
3762 if (lvalue && !q.sess.guru_mode)
dc09353a 3763 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3764
100a540e 3765 // XXX: process $context vars should be writable
70208613 3766
c69a87e0
FCE
3767 // See if we need to generate a new probe to save/access function
3768 // parameters from a return probe. PR 1382.
3769 if (q.has_return
3770 && !defined_being_checked
277c21bc
JS
3771 && e->name != "$return" // not the special return-value variable handled below
3772 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3773 {
3774 if (lvalue)
dc09353a 3775 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3776 visit_target_symbol_saved_return(e);
3777 return;
3778 }
e57b735a 3779
277c21bc
JS
3780 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3781 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3782 {
3783 if (lvalue)
dc09353a 3784 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3785
c69a87e0 3786 if (e->addressof)
dc09353a 3787 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3788
5f36109e
JS
3789 e->assert_no_components("dwarf", true);
3790
c69a87e0
FCE
3791 visit_target_symbol_context(e);
3792 return;
3793 }
70208613 3794
5f36109e
JS
3795 if (!e->components.empty() &&
3796 e->components.back().type == target_symbol::comp_pretty_print)
3797 {
3798 if (lvalue)
dc09353a 3799 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3800
277c21bc 3801 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3802 {
3803 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3804 q.has_process, *e);
3805 dpp.expand()->visit(this);
3806 }
3807 else
3808 {
3809 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3810 e->sym_name(),
5f36109e
JS
3811 q.has_process, *e);
3812 dpp.expand()->visit(this);
3813 }
3814 return;
3815 }
3816
1c0be8c7 3817 bool userspace_p = q.has_process;
c69a87e0 3818 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3819 + "_" + e->sym_name()
c69a87e0 3820 + "_" + lex_cast(tick++));
70208613 3821
70208613 3822
1c0be8c7
JS
3823 exp_type type = pe_long;
3824 string code;
277c21bc 3825 if (q.has_return && (e->name == "$return"))
1c0be8c7 3826 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 3827 else
1c0be8c7
JS
3828 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
3829 e, lvalue, type);
70208613 3830
1c0be8c7
JS
3831 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
3832 userspace_p, lvalue, e);
70208613 3833
c69a87e0
FCE
3834 if (lvalue)
3835 {
3836 // Provide the functioncall to our parent, so that it can be
3837 // used to substitute for the assignment node immediately above
3838 // us.
3839 assert(!target_symbol_setter_functioncalls.empty());
3840 *(target_symbol_setter_functioncalls.top()) = n;
3841 }
70208613 3842
1c0be8c7
JS
3843 // Revisit the functioncall so arguments can be expanded.
3844 n->visit (this);
66d284f4
FCE
3845 }
3846 catch (const semantic_error& er)
3847 {
9fab2262
JS
3848 // We suppress this error message, and pass the unresolved
3849 // target_symbol to the next pass. We hope that this value ends
3850 // up not being referenced after all, so it can be optimized out
3851 // quietly.
1af1e62d 3852 e->chain (er);
9fab2262 3853 provide (e);
66d284f4 3854 }
77de5e9e
GH
3855}
3856
3857
c24447be
JS
3858void
3859dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3860{
3861 // Fill in our current module context if needed
3862 if (e->module.empty())
3863 e->module = q.dw.module_name;
3864
3865 var_expanding_visitor::visit_cast_op(e);
3866}
3867
3868
8cc799a5
JS
3869void
3870dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3871{
3872 expression *repl = e;
3873 if (q.has_return)
3874 {
3875 // expand the operand as if it weren't a return probe
3876 q.has_return = false;
3877 replace (e->operand);
3878 q.has_return = true;
3879
3880 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3881 // but it requires knowing the types already, which is problematic for
3882 // arbitrary expressons.
cc9001af 3883 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3884 }
3885 provide (repl);
3886}
3887
3689db05
SC
3888void
3889dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
3890{
ace7c23f 3891 string e_lit_val = e->operand->value;
b78a0fbb 3892
3689db05 3893 add_block = new block;
9eaaceaa 3894 add_block->tok = e->tok;
3689db05
SC
3895
3896 systemtap_session &s = this->q.sess;
3897 map<string, pair<string,derived_probe*> >::iterator it;
3898 // Find the associated perf.counter probe
3899 for (it=s.perf_counters.begin();
3900 it != s.perf_counters.end();
3901 it++)
3902 if ((*it).first == e_lit_val)
3903 {
3904 // if perf .function("name") omitted, then set it to this process name
3905 if ((*it).second.first.length() == 0)
3906 ((*it).second).first = this->q.user_path;
3907 if (((*it).second).first == this->q.user_path)
3908 break;
3909 }
3910
3911 if (it != s.perf_counters.end())
3912 {
698de6cc 3913 perf_counter_refs.insert((*it).second.second);
3689db05
SC
3914 // __perf_read_N is assigned in the probe prologue
3915 symbol* sym = new symbol;
4653caf1 3916 sym->tok = e->tok;
3689db05
SC
3917 sym->name = "__perf_read_" + (*it).first;
3918 provide (sym);
3919 }
3920 else
dc09353a 3921 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
3922}
3923
8cc799a5 3924
729455a7
JS
3925vector<Dwarf_Die>&
3926dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3927{
3928 if (scopes.empty())
3929 {
f25a9197
CM
3930 if(scope_die != NULL)
3931 scopes = q.dw.getscopes(scope_die);
729455a7 3932 if (scopes.empty())
b530b5b3
LB
3933 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3934 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 3935 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7
JS
3936 + lex_cast_hex(addr)
3937 + ((scope_die == NULL) ? ""
3938 : (string (" in ")
3939 + (dwarf_diename(scope_die) ?: "<unknown>")
3940 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3941 + ")"))
3942 + " while searching for local '"
cc9001af 3943 + e->sym_name() + "'",
729455a7
JS
3944 e->tok);
3945 }
3946 return scopes;
3947}
3948
3949
5f36109e
JS
3950struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3951{
3952 systemtap_session& s;
3953 dwarf_builder& db;
3954
3955 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3956 s(s), db(db) {}
3957 void visit_cast_op (cast_op* e);
3958 void filter_special_modules(string& module);
3959};
3960
3961
c4ce66a1
JS
3962struct dwarf_cast_query : public base_query
3963{
946e1a48 3964 cast_op& e;
c4ce66a1 3965 const bool lvalue;
5f36109e
JS
3966 const bool userspace_p;
3967 functioncall*& result;
c4ce66a1 3968
5f36109e
JS
3969 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3970 const bool userspace_p, functioncall*& result):
abb41d92 3971 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3972 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3973
3974 void handle_query_module();
822a6a3d 3975 void query_library (const char *) {}
576eaefe 3976 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3977};
3978
3979
c4ce66a1
JS
3980void
3981dwarf_cast_query::handle_query_module()
3982{
5f36109e
JS
3983 static unsigned tick = 0;
3984
3985 if (result)
c4ce66a1
JS
3986 return;
3987
ea1e477a 3988 // look for the type in any CU
a44a7cb5
JS
3989 Dwarf_Die* type_die = NULL;
3990 if (startswith(e.type_name, "class "))
3991 {
3992 // normalize to match dwflpp::global_alias_caching_callback
3993 string struct_name = "struct " + e.type_name.substr(6);
3994 type_die = dw.declaration_resolve_other_cus(struct_name);
3995 }
3996 else
3997 type_die = dw.declaration_resolve_other_cus(e.type_name);
3998
3999 // NB: We now index the types as "struct name"/"union name"/etc. instead of
4000 // just "name". But since we didn't require users to be explicit before, and
4001 // actually sort of discouraged it, we must be flexible now. So if a lookup
4002 // fails with a bare name, try augmenting it.
4003 if (!type_die &&
4004 !startswith(e.type_name, "class ") &&
4005 !startswith(e.type_name, "struct ") &&
4006 !startswith(e.type_name, "union ") &&
4007 !startswith(e.type_name, "enum "))
4008 {
4009 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
4010 if (!type_die)
4011 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
4012 if (!type_die)
4013 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
4014 }
4015
ea1e477a
JS
4016 if (!type_die)
4017 return;
c4ce66a1 4018
5f36109e
JS
4019 string code;
4020 exp_type type = pe_long;
4021
ea1e477a 4022 try
c4ce66a1 4023 {
ea1e477a
JS
4024 Dwarf_Die cu_mem;
4025 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4026
4027 if (!e.components.empty() &&
4028 e.components.back().type == target_symbol::comp_pretty_print)
4029 {
4030 if (lvalue)
dc09353a 4031 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4032
d19a9a82 4033 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4034 result = dpp.expand();
4035 return;
4036 }
4037
4038 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4039 }
4040 catch (const semantic_error& er)
4041 {
4042 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4043 // may be attempted using several different modules:
4044 // @cast(ptr, "type", "module1:module2:...")
4045 e.chain (er);
c4ce66a1 4046 }
c4ce66a1 4047
5f36109e
JS
4048 if (code.empty())
4049 return;
c4ce66a1 4050
5f36109e 4051 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4052 + "_" + e.sym_name()
5f36109e 4053 + "_" + lex_cast(tick++));
c4ce66a1 4054
1c0be8c7
JS
4055 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4056 userspace_p, lvalue, &e, e.operand);
5f36109e 4057}
c4ce66a1
JS
4058
4059
fb0274bc
JS
4060void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4061{
d90053e7 4062 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4063 // for those cases, build a module including that header
d90053e7 4064 if (module[module.size() - 1] == '>' &&
60d98537 4065 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4066 {
4067 string cached_module;
4068 if (s.use_cache)
4069 {
4070 // see if the cached module exists
a2639cb7 4071 cached_module = find_typequery_hash(s, module);
d105f664 4072 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4073 {
4074 int fd = open(cached_module.c_str(), O_RDONLY);
4075 if (fd != -1)
4076 {
4077 if (s.verbose > 2)
b530b5b3
LB
4078 //TRANSLATORS: Here we're using a cached module.
4079 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4080 module = cached_module;
4081 close(fd);
4082 return;
4083 }
4084 }
4085 }
4086
4087 // no cached module, time to make it
d90053e7 4088 if (make_typequery(s, module) == 0)
fb0274bc 4089 {
e16dc041 4090 // try to save typequery in the cache
fb0274bc 4091 if (s.use_cache)
e16dc041 4092 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4093 }
4094 }
4095}
4096
4097
c4ce66a1
JS
4098void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4099{
4100 bool lvalue = is_active_lvalue(e);
4101 if (lvalue && !s.guru_mode)
dc09353a 4102 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4103
4104 if (e->module.empty())
4105 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4106
5f36109e 4107 functioncall* result = NULL;
8b31197b
JS
4108
4109 // split the module string by ':' for alternatives
4110 vector<string> modules;
4111 tokenize(e->module, modules, ":");
b5a0dd41 4112 bool userspace_p=false; // PR10601
5f36109e 4113 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4114 {
8b31197b 4115 string& module = modules[i];
fb0274bc 4116 filter_special_modules(module);
abb41d92 4117
c4ce66a1
JS
4118 // NB: This uses '/' to distinguish between kernel modules and userspace,
4119 // which means that userspace modules won't get any PATH searching.
4120 dwflpp* dw;
707bf35e
JS
4121 try
4122 {
b5a0dd41
FCE
4123 userspace_p=is_user_module (module);
4124 if (! userspace_p)
707bf35e
JS
4125 {
4126 // kernel or kernel module target
ae2552da 4127 dw = db.get_kern_dw(s, module);
707bf35e
JS
4128 }
4129 else
4130 {
05fb3e0c 4131 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4132 dw = db.get_user_dw(s, module);
4133 }
4134 }
4135 catch (const semantic_error& er)
4136 {
4137 /* ignore and go to the next module */
4138 continue;
4139 }
c4ce66a1 4140
5f36109e 4141 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 4142 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 4143 }
abb41d92 4144
5f36109e 4145 if (!result)
c4ce66a1 4146 {
946e1a48
JS
4147 // We pass the unresolved cast_op to the next pass, and hope
4148 // that this value ends up not being referenced after all, so
4149 // it can be optimized out quietly.
c4ce66a1
JS
4150 provide (e);
4151 return;
4152 }
4153
c4ce66a1
JS
4154 if (lvalue)
4155 {
4156 // Provide the functioncall to our parent, so that it can be
4157 // used to substitute for the assignment node immediately above
4158 // us.
4159 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4160 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4161 }
4162
5f36109e 4163 result->visit (this);
77de5e9e
GH
4164}
4165
4166
bd1fcbad
YZ
4167struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4168{
4169 systemtap_session& s;
4170 dwarf_builder& db;
4171
4172 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4173 s(s), db(db) {}
4174 void visit_atvar_op (atvar_op* e);
4175};
4176
4177
4178struct dwarf_atvar_query: public base_query
4179{
4180 atvar_op& e;
4181 const bool userspace_p, lvalue;
4182 functioncall*& result;
4183 unsigned& tick;
4184 const string cu_name_pattern;
4185
4186 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4187 const bool userspace_p, const bool lvalue,
4188 functioncall*& result,
4189 unsigned& tick):
4190 base_query(dw, module), e(e),
4191 userspace_p(userspace_p), lvalue(lvalue), result(result),
4192 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4193
4194 void handle_query_module ();
4195 void query_library (const char *) {}
4196 void query_plt (const char *entry, size_t addr) {}
4197 static int atvar_query_cu (Dwarf_Die *cudie, void *data);
4198};
4199
4200
4201int
4202dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, void * data)
4203{
4204 dwarf_atvar_query * q = static_cast<dwarf_atvar_query *>(data);
4205
4206 if (! q->e.cu_name.empty())
4207 {
4208 const char *die_name = dwarf_diename(cudie);
4209
4210 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4211 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4212 {
4213 return DWARF_CB_OK;
4214 }
4215 }
4216
4217 try
4218 {
4219 vector<Dwarf_Die> scopes(1, *cudie);
4220
4221 q->dw.focus_on_cu (cudie);
4222
4223 if (! q->e.components.empty() &&
4224 q->e.components.back().type == target_symbol::comp_pretty_print)
4225 {
4226 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4227 q->userspace_p, q->e);
4228 q->result = dpp.expand();
4229 return DWARF_CB_ABORT;
4230 }
4231
4232 exp_type type = pe_long;
4233 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4234 &q->e, q->lvalue, type);
4235
4236 if (code.empty())
4237 return DWARF_CB_OK;
4238
4239 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4240 : "_dwarf_tvar_get")
4241 + "_" + q->e.sym_name()
4242 + "_" + lex_cast(q->tick++));
4243
4244 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4245 q->userspace_p, q->lvalue,
4246 &q->e);
4247 }
4248 catch (const semantic_error& er)
4249 {
4250 // Here we suppress the error because we often just have too many
4251 // when scanning all the CUs.
4252 return DWARF_CB_OK;
4253 }
4254
4255 if (q->result) {
4256 return DWARF_CB_ABORT;
4257 }
4258
4259 return DWARF_CB_OK;
4260}
4261
4262
4263void
4264dwarf_atvar_query::handle_query_module ()
4265{
4266
4267 dw.iterate_over_cus(atvar_query_cu, this, false);
4268}
4269
4270
4271void
4272dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4273{
4274 const bool lvalue = is_active_lvalue(e);
4275 if (lvalue && !s.guru_mode)
dc09353a 4276 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4277 "need stap -g"), e->tok);
4278
4279 if (e->module.empty())
4280 e->module = "kernel";
4281
4282 functioncall* result = NULL;
4283
4284 // split the module string by ':' for alternatives
4285 vector<string> modules;
4286 tokenize(e->module, modules, ":");
4287 bool userspace_p = false;
4288 for (unsigned i = 0; !result && i < modules.size(); ++i)
4289 {
4290 string& module = modules[i];
4291
4292 dwflpp* dw;
4293 try
4294 {
4295 userspace_p = is_user_module(module);
4296 if (!userspace_p)
4297 {
4298 // kernel or kernel module target
4299 dw = db.get_kern_dw(s, module);
4300 }
4301 else
4302 {
4303 module = find_executable(module, "", s.sysenv);
4304 dw = db.get_user_dw(s, module);
4305 }
4306 }
4307 catch (const semantic_error& er)
4308 {
4309 /* ignore and go to the next module */
4310 continue;
4311 }
4312
4313 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
4314 dw->iterate_over_modules(&query_module, &q);
4315
4316 if (result)
4317 {
4318 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4319
4320 if (lvalue)
4321 {
4322 // Provide the functioncall to our parent, so that it can be
4323 // used to substitute for the assignment node immediately above
4324 // us.
4325 assert(!target_symbol_setter_functioncalls.empty());
4326 *(target_symbol_setter_functioncalls.top()) = result;
4327 }
4328
4329 result->visit(this);
4330 return;
4331 }
4332
4333 /* Unable to find the variable in the current module, so we chain
4334 * an error in atvar_op */
dc09353a 4335 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4336 e->sym_name().c_str(), module.c_str(),
4337 e->cu_name.empty() ? "" : _(", in "),
4338 e->cu_name.c_str()));
4339 e->chain (er);
4340 }
4341
4342 provide(e);
4343}
4344
4345
b8da0ad1
FCE
4346void
4347dwarf_derived_probe::printsig (ostream& o) const
4348{
4349 // Instead of just printing the plain locations, we add a PC value
4350 // as a comment as a way of telling e.g. apart multiple inlined
4351 // function instances. This is distinct from the verbose/clog
4352 // output, since this part goes into the cache hash calculations.
4353 sole_location()->print (o);
6d0f3f0c 4354 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4355 printsig_nested (o);
4356}
4357
4358
4359
dc38c0ae 4360void
b20febf3
FCE
4361dwarf_derived_probe::join_group (systemtap_session& s)
4362{
af234c40
JS
4363 // skip probes which are paired entry-handlers
4364 if (!has_return && (saved_longs || saved_strings))
4365 return;
4366
b20febf3
FCE
4367 if (! s.dwarf_derived_probes)
4368 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4369 s.dwarf_derived_probes->enroll (this);
4370}
4371
4372
2b69faaf
JS
4373static bool
4374kernel_supports_inode_uprobes(systemtap_session& s)
4375{
4376 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4377 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4378 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4379 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4380 && s.kernel_config["CONFIG_UPROBES"] == "y");
4381}
4382
4383
3667d615
JS
4384static bool
4385kernel_supports_inode_uretprobes(systemtap_session& s)
4386{
766013af
JS
4387 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4388 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4389 return kernel_supports_inode_uprobes(s) &&
af9e147f 4390 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4391}
4392
4393
5261f7ab
DS
4394void
4395check_process_probe_kernel_support(systemtap_session& s)
4396{
4397 // If we've got utrace, we're good to go.
4398 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4399 return;
4400
8c021542
DS
4401 // We don't have utrace. For process probes that aren't
4402 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4403 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4404 // specific autoconf test for its needs.
8c021542
DS
4405 //
4406 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4407 // approximation.
4408 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4409 return;
4410
d3e959b0
DS
4411 // For uprobes-based process probes, we need the task_finder plus
4412 // the builtin inode-uprobes.
8c021542
DS
4413 if (s.need_uprobes
4414 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4415 && kernel_supports_inode_uprobes(s))
8c021542
DS
4416 return;
4417
dc09353a 4418 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4419}
4420
4421
b20febf3
FCE
4422dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4423 const string& filename,
4424 int line,
91af0778 4425 // module & section specify a relocation
b20febf3
FCE
4426 // base for <addr>, unless section==""
4427 // (equivalently module=="kernel")
4428 const string& module,
4429 const string& section,
4430 // NB: dwfl_addr is the virtualized
4431 // address for this symbol.
4432 Dwarf_Addr dwfl_addr,
4433 // addr is the section-offset for
4434 // actual relocation.
4435 Dwarf_Addr addr,
4436 dwarf_query& q,
37ebca01 4437 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4438 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4439 module (module), section (section), addr (addr),
63b4fd14 4440 path (q.path),
27dc09b1 4441 has_process (q.has_process),
c9bad430
DS
4442 has_return (q.has_return),
4443 has_maxactive (q.has_maxactive),
c57ea854 4444 has_library (q.has_library),
6b66b9f7 4445 maxactive_val (q.maxactive_val),
b642c901
SC
4446 user_path (q.user_path),
4447 user_lib (q.user_lib),
af234c40 4448 access_vars(false),
c57ea854 4449 saved_longs(0), saved_strings(0),
af234c40 4450 entry_handler(0)
bd2b1e68 4451{
b642c901
SC
4452 if (user_lib.size() != 0)
4453 has_library = true;
4454
6b66b9f7
JS
4455 if (q.has_process)
4456 {
4457 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4458 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4459 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4460 // by the incoming section value (".absolute" vs. ".dynamic").
4461 // XXX Assert invariants here too?
2b69faaf
JS
4462
4463 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4464 // ditto for userspace runtimes (dyninst)
ac3af990 4465 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4466 section == ".absolute" && addr == dwfl_addr &&
4467 addr >= q.dw.module_start && addr < q.dw.module_end)
4468 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4469 }
4470 else
4471 {
4472 // Assert kernel relocation invariants
4473 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4474 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4475 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4476 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4477 }
2930abc7 4478
21beacc9
FCE
4479 // XXX: hack for strange g++/gcc's
4480#ifndef USHRT_MAX
4481#define USHRT_MAX 32767
4482#endif
4483
606fd9c8 4484 // Range limit maxactive() value
6b66b9f7 4485 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4486 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4487 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4488
de688825 4489 // Expand target variables in the probe body
b78a0fbb 4490 if (!null_die(scope_die) || (!q.has_kernel && q.dw.has_gnu_debugdata()))
8fc05e57 4491 {
6b66b9f7 4492 // XXX: user-space deref's for q.has_process!
de688825 4493 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4494 v.replace (this->body);
3689db05
SC
4495
4496 // Propagate perf.counters so we can emit later
4497 this->perf_counter_refs = v.perf_counter_refs;
4498 // Emit local var used to save the perf counter read value
698de6cc 4499 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4500 for (pcii = v.perf_counter_refs.begin();
4501 pcii != v.perf_counter_refs.end(); pcii++)
4502 {
4503 map<string, pair<string,derived_probe*> >::iterator it;
4504 // Find the associated perf counter probe
4505 for (it=q.sess.perf_counters.begin() ;
4506 it != q.sess.perf_counters.end();
4507 it++)
4508 if ((*it).second.second == (*pcii))
4509 break;
4510 vardecl* vd = new vardecl;
4511 vd->name = "__perf_read_" + (*it).first;
4512 vd->tok = this->tok;
4513 vd->set_arity(0, this->tok);
4514 vd->type = pe_long;
4515 vd->synthetic = true;
4516 this->locals.push_back (vd);
4517 }
4518
4519
6b66b9f7
JS
4520 if (!q.has_process)
4521 access_vars = v.visited;
37ebca01
FCE
4522
4523 // If during target-variable-expanding the probe, we added a new block
4524 // of code, add it to the start of the probe.
4525 if (v.add_block)
ba6f838d 4526 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4527
4528 // If when target-variable-expanding the probe, we need to synthesize a
4529 // sibling function-entry probe. We don't go through the whole probe derivation
4530 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4531 // dwarf-induced duplication.
4532 if (v.add_call_probe)
37ebca01 4533 {
2260f4e3
FCE
4534 assert (q.has_return && !q.has_call);
4535
4536 // We temporarily replace q.base_probe.
4537 statement* old_body = q.base_probe->body;
4538 q.base_probe->body = v.add_call_probe;
4539 q.has_return = false;
4540 q.has_call = true;
af234c40 4541
da23eceb 4542 if (q.has_process)
af234c40
JS
4543 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4544 module, section, dwfl_addr,
4545 addr, q, scope_die);
da23eceb 4546 else
af234c40
JS
4547 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4548 module, section, dwfl_addr,
4549 addr, q, scope_die);
4550
4551 saved_longs = entry_handler->saved_longs = v.saved_longs;
4552 saved_strings = entry_handler->saved_strings = v.saved_strings;
4553
4554 q.results.push_back (entry_handler);
2260f4e3
FCE
4555
4556 q.has_return = true;
4557 q.has_call = false;
4558 q.base_probe->body = old_body;
37ebca01 4559 }
f10534c6
WH
4560 // Save the local variables for listing mode
4561 if (q.sess.listing_mode_vars)
8c67c337 4562 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4563 }
37ebca01 4564 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4565
f10534c6 4566 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4567
5d23847d 4568 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4569 // "reverse-engineered" form of the incoming (q.base_loc) probe
4570 // point. This allows a user to see what function / file / line
4571 // number any particular match of the wildcards.
2930abc7 4572
a229fcd7 4573 vector<probe_point::component*> comps;
91af0778
FCE
4574 if (q.has_kernel)
4575 comps.push_back (new probe_point::component(TOK_KERNEL));
4576 else if(q.has_module)
4577 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4578 else if(q.has_process)
4579 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4580 else
4581 assert (0);
b5d77020 4582
db520b00
FCE
4583 string fn_or_stmt;
4584 if (q.has_function_str || q.has_function_num)
4585 fn_or_stmt = "function";
4586 else
4587 fn_or_stmt = "statement";
a229fcd7 4588
b8da0ad1 4589 if (q.has_function_str || q.has_statement_str)
db520b00 4590 {
4cd232e4 4591 string retro_name = funcname;
b20febf3 4592 if (filename != "")
cee35f73 4593 {
fb84c077 4594 retro_name += ("@" + string (filename));
cee35f73 4595 if (line > 0)
aca66a36 4596 retro_name += (":" + lex_cast (line));
cee35f73 4597 }
db520b00
FCE
4598 comps.push_back
4599 (new probe_point::component
4600 (fn_or_stmt, new literal_string (retro_name)));
4601 }
b8da0ad1 4602 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4603 {
4604 Dwarf_Addr retro_addr;
4605 if (q.has_function_num)
4606 retro_addr = q.function_num_val;
4607 else
4608 retro_addr = q.statement_num_val;
db520b00
FCE
4609 comps.push_back (new probe_point::component
4610 (fn_or_stmt,
9ea68eb9 4611 new literal_number(retro_addr, true)));
37ebca01
FCE
4612
4613 if (q.has_absolute)
4614 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4615 }
4616
b8da0ad1
FCE
4617 if (q.has_call)
4618 comps.push_back (new probe_point::component(TOK_CALL));
4bda987e
SC
4619 if (q.has_exported)
4620 comps.push_back (new probe_point::component(TOK_EXPORTED));
b8da0ad1
FCE
4621 if (q.has_inline)
4622 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4623 if (has_return)
b8da0ad1
FCE
4624 comps.push_back (new probe_point::component(TOK_RETURN));
4625 if (has_maxactive)
4626 comps.push_back (new probe_point::component
4627 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4628
5d23847d
FCE
4629 // Overwrite it.
4630 this->sole_location()->components = comps;
2930abc7
FCE
4631}
4632
bd2b1e68 4633
0a98fd42 4634void
8c67c337
JS
4635dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4636 Dwarf_Addr dwfl_addr)
0a98fd42 4637{
9aa8ffce 4638 if (null_die(scope_die))
0a98fd42 4639 return;
0a98fd42 4640
8c67c337 4641 bool verbose = q.sess.verbose > 2;
0a98fd42 4642
8c67c337 4643 if (verbose)
b530b5b3 4644 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4645
8c67c337
JS
4646 if (has_return)
4647 {
4648 /* Only save the return value if it has a type. */
4649 string type_name;
4650 Dwarf_Die type_die;
4651 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4652 dwarf_type_name(&type_die, type_name))
4653 args.push_back("$return:"+type_name);
4654
4655 else if (verbose)
b530b5b3
LB
4656 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4657 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4658 }
d87623a1 4659
0a98fd42 4660 Dwarf_Die arg;
4ef35696
JS
4661 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4662 for (unsigned i = 0; i < scopes.size(); ++i)
4663 {
4664 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4665 break; // we don't want file-level variables
4666 if (dwarf_child (&scopes[i], &arg) == 0)
4667 do
0a98fd42 4668 {
4ef35696
JS
4669 switch (dwarf_tag (&arg))
4670 {
4671 case DW_TAG_variable:
4672 case DW_TAG_formal_parameter:
4673 break;
0a98fd42 4674
4ef35696
JS
4675 default:
4676 continue;
4677 }
0a98fd42 4678
4ef35696
JS
4679 /* Ignore this local if it has no name. */
4680 const char *arg_name = dwarf_diename (&arg);
4681 if (!arg_name)
8c67c337
JS
4682 {
4683 if (verbose)
b530b5b3
LB
4684 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4685 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4686 continue;
4687 }
4ef35696
JS
4688
4689 if (verbose)
b530b5b3
LB
4690 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4691 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4692
4693 /* Ignore this local if it has no location (or not at this PC). */
4694 /* NB: It still may not be directly accessible, e.g. if it is an
4695 * aggregate type, implicit_pointer, etc., but the user can later
4696 * figure out how to access the interesting parts. */
45b02a36
FCE
4697
4698 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4699 * several synthetic
4700 * probe foo { $var }
4701 * probes, testing them for overall resolvability.
4702 */
4703
4ef35696
JS
4704 Dwarf_Attribute attr_mem;
4705 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4706 {
4707 Dwarf_Op *expr;
4708 size_t len;
4709 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4710 {
4711 if (verbose)
b530b5b3
LB
4712 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4713 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4714 continue;
4715 }
4716 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4717 &len, 1) == 1 && len > 0))
4718 {
45b02a36
FCE
4719 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4720 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4721 &len, 1) == 1 && len > 0))) {
4722 if (verbose)
4723 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4724 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4725 continue;
4726 }
4ef35696
JS
4727 }
4728 }
4729
4730 /* Ignore this local if it has no type. */
4731 string type_name;
4732 Dwarf_Die type_die;
4733 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4734 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4735 {
4736 if (verbose)
b530b5b3
LB
4737 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4738 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4739 continue;
4740 }
8c67c337 4741
4ef35696
JS
4742 /* This local looks good -- save it! */
4743 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4744 }
4ef35696
JS
4745 while (dwarf_siblingof (&arg, &arg) == 0);
4746 }
0a98fd42
JS
4747}
4748
4749
4750void
d0bfd2ac 4751dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4752{
d0bfd2ac 4753 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4754}
4755
4756
27dc09b1 4757void
42e38653 4758dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4759{
4760 if (has_process)
4761 {
4762 // These probes are allowed for unprivileged users, but only in the
4763 // context of processes which they own.
4764 emit_process_owner_assertion (o);
4765 return;
4766 }
4767
4768 // Other probes must contain the default assertion which aborts
4769 // if executed by an unprivileged user.
42e38653 4770 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4771}
4772
4773
4774void
4775dwarf_derived_probe::print_dupe_stamp(ostream& o)
4776{
4777 if (has_process)
4778 {
4779 // These probes are allowed for unprivileged users, but only in the
4780 // context of processes which they own.
4781 print_dupe_stamp_unprivileged_process_owner (o);
4782 return;
4783 }
4784
4785 // Other probes must contain the default dupe stamp
4786 derived_probe::print_dupe_stamp (o);
4787}
4788
64211010 4789
7a053d3b 4790void
20c6c071 4791dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4792 dwarf_builder * dw,
42e38653 4793 privilege_t privilege)
bd2b1e68 4794{
27dc09b1 4795 root
42e38653 4796 ->bind_privilege(privilege)
27dc09b1 4797 ->bind(dw);
54efe513
GH
4798}
4799
7a053d3b 4800void
fd6602a0 4801dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4802 dwarf_builder * dw,
42e38653 4803 privilege_t privilege)
2865d17a 4804{
27dc09b1 4805 root
42e38653 4806 ->bind_privilege(privilege)
27dc09b1 4807 ->bind(dw);
27dc09b1 4808 root->bind(TOK_CALL)
42e38653 4809 ->bind_privilege(privilege)
27dc09b1 4810 ->bind(dw);
4bda987e
SC
4811 root->bind(TOK_EXPORTED)
4812 ->bind_privilege(privilege)
4813 ->bind(dw);
27dc09b1 4814 root->bind(TOK_RETURN)
42e38653 4815 ->bind_privilege(privilege)
27dc09b1 4816 ->bind(dw);
1e035395 4817
f6be7c06
DB
4818 // For process probes / uprobes, .maxactive() is unused.
4819 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4820 {
4821 root->bind(TOK_RETURN)
1e035395
FCE
4822 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4823 }
bd2b1e68
GH
4824}
4825
7a053d3b 4826void
27dc09b1 4827dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4828 systemtap_session& s,
27dc09b1
DB
4829 match_node * root,
4830 dwarf_builder * dw,
42e38653 4831 privilege_t privilege
27dc09b1 4832)
bd2b1e68
GH
4833{
4834 // Here we match 4 forms:
4835 //
4836 // .function("foo")
4837 // .function(0xdeadbeef)
4838 // .statement("foo")
4839 // .statement(0xdeadbeef)
4840
440d9b00 4841 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4842 register_function_variants(fv_root, dw, privilege);
7f02ca94 4843 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4844 fv_root->bind(TOK_INLINE)
42e38653 4845 ->bind_privilege(privilege)
440d9b00 4846 ->bind(dw);
7f02ca94
JS
4847 fv_root->bind_str(TOK_LABEL)
4848 ->bind_privilege(privilege)
440d9b00
DB
4849 ->bind(dw);
4850
4851 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 4852 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
4853 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4854 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4855 {
4856 fv_root->bind(TOK_INLINE)
42e38653 4857 ->bind_privilege(privilege)
440d9b00
DB
4858 ->bind(dw);
4859 }
4860
42e38653
DB
4861 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
4862 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
4863}
4864
b1615c74
JS
4865void
4866dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
4867 match_node * root,
4868 dwarf_builder * dw)
4869{
4870 root->bind_str(TOK_MARK)
f66bb29a 4871 ->bind_privilege(pr_all)
b1615c74
JS
4872 ->bind(dw);
4873 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 4874 ->bind_privilege(pr_all)
b1615c74
JS
4875 ->bind(dw);
4876}
4877
4878void
4879dwarf_derived_probe::register_plt_variants(systemtap_session& s,
4880 match_node * root,
4881 dwarf_builder * dw)
4882{
4883 root->bind(TOK_PLT)
f66bb29a 4884 ->bind_privilege(pr_all)
b1615c74
JS
4885 ->bind(dw);
4886 root->bind_str(TOK_PLT)
f66bb29a 4887 ->bind_privilege(pr_all)
b1615c74
JS
4888 ->bind(dw);
4889 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4890 ->bind_privilege(pr_all)
b1615c74
JS
4891 ->bind(dw);
4892 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4893 ->bind_privilege(pr_all)
b1615c74 4894 ->bind(dw);
bd2b1e68
GH
4895}
4896
4897void
c4ce66a1 4898dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4899{
c4ce66a1 4900 match_node* root = s.pattern_root;
bd2b1e68
GH
4901 dwarf_builder *dw = new dwarf_builder();
4902
c4ce66a1
JS
4903 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4904 s.code_filters.push_back(filter);
4905
bd1fcbad
YZ
4906 filter = new dwarf_atvar_expanding_visitor(s, *dw);
4907 s.code_filters.push_back(filter);
4908
73f52eb4
DB
4909 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
4910 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
4911 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4912 ->bind(dw);
2cab6244 4913
7f02ca94
JS
4914 match_node* uprobes[] = {
4915 root->bind(TOK_PROCESS),
4916 root->bind_str(TOK_PROCESS),
4917 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4918 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4919 };
4920 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
4921 {
f66bb29a 4922 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
4923 register_sdt_variants(s, uprobes[i], dw);
4924 register_plt_variants(s, uprobes[i], dw);
4925 }
bd2b1e68
GH
4926}
4927
9020300d 4928void
3689db05
SC
4929dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
4930{
698de6cc 4931 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4932 for (pcii = perf_counter_refs.begin();
4933 pcii != perf_counter_refs.end();
4934 pcii++)
4935 {
4936 map<string, pair<string,derived_probe*> >::iterator it;
4937 // Find the associated perf.counter probe
4938 unsigned i = 0;
4939 for (it=s.perf_counters.begin() ;
4940 it != s.perf_counters.end();
4941 it++, i++)
4942 if ((*it).second.second == (*pcii))
4943 break;
4944 // place the perf counter read so it precedes stp_lock_probe
4945 o->newline() << "l->l___perf_read_" + (*it).first
4946 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
4947 + lex_cast(i) + "))));";
4948 }
b78a0fbb 4949
b95e2b79
MH
4950 if (access_vars)
4951 {
4952 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4953 o->newline() << "#if defined __ia64__";
d9aed31e 4954 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4955 o->newline() << "#endif";
b95e2b79 4956 }
9020300d 4957}
2930abc7 4958
b20febf3 4959// ------------------------------------------------------------------------
46b84a80
DS
4960
4961void
b20febf3 4962dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4963{
b20febf3 4964 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4965
4966 // XXX: probes put at the same address should all share a
4967 // single kprobe/kretprobe, and have their handlers executed
4968 // sequentially.
b55bc428
FCE
4969}
4970
7a053d3b 4971void
775d51e5 4972dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4973{
b20febf3 4974 if (probes_by_module.empty()) return;
2930abc7 4975
775d51e5
DS
4976 s.op->newline() << "/* ---- dwarf probes ---- */";
4977
4978 // Warn of misconfigured kernels
f41595cc
FCE
4979 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4980 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4981 s.op->newline() << "#endif";
775d51e5 4982 s.op->newline();
f41595cc 4983
f07c3b68 4984 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4985 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4986 s.op->newline() << "#endif";
4987
14cf7e42 4988 // Forward decls
2ba1736a 4989 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 4990
b20febf3
FCE
4991 // Forward declare the master entry functions
4992 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4993 s.op->line() << " struct pt_regs *regs);";
4994 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4995 s.op->line() << " struct pt_regs *regs);";
4996
42cb22bd
MH
4997 // Emit an array of kprobe/kretprobe pointers
4998 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4999 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
5000 s.op->newline() << "#endif";
5001
b20febf3 5002 // Emit the actual probe list.
606fd9c8
FCE
5003
5004 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
5005 // struct stap_dwarf_probe, but it being initialized data makes it add
5006 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 5007 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
5008 // NB: bss!
5009
4c2732a1 5010 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
5011 s.op->newline(1) << "const unsigned return_p:1;";
5012 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 5013 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 5014 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 5015 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 5016
af234c40
JS
5017 // data saved in the kretprobe_instance packet
5018 s.op->newline() << "const unsigned short saved_longs;";
5019 s.op->newline() << "const unsigned short saved_strings;";
5020
faea5e16 5021 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5022 // are small and uniform enough to justify putting char[MAX]'s into
5023 // the array instead of relocated char*'s.
faea5e16
JS
5024 size_t module_name_max = 0, section_name_max = 0;
5025 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5026 size_t all_name_cnt = probes_by_module.size(); // for average
5027 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5028 {
5029 dwarf_derived_probe* p = it->second;
5030#define DOIT(var,expr) do { \
5031 size_t var##_size = (expr) + 1; \
5032 var##_max = max (var##_max, var##_size); \
5033 var##_tot += var##_size; } while (0)
5034 DOIT(module_name, p->module.size());
5035 DOIT(section_name, p->section.size());
606fd9c8
FCE
5036#undef DOIT
5037 }
5038
5039 // Decide whether it's worthwhile to use char[] or char* by comparing
5040 // the amount of average waste (max - avg) to the relocation data size
5041 // (3 native long words).
5042#define CALCIT(var) \
5043 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5044 { \
5045 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5046 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5047 << "[" << var##_name_max << "]" << endl; \
5048 } \
5049 else \
5050 { \
b0986e7a 5051 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5052 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5053 }
5054
5055 CALCIT(module);
5056 CALCIT(section);
e6fe60e7 5057#undef CALCIT
606fd9c8 5058
b0986e7a 5059 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5060 s.op->newline() << "const struct stap_probe * const probe;";
5061 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5062 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5063 s.op->indent(1);
5064
5065 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5066 {
b20febf3
FCE
5067 dwarf_derived_probe* p = it->second;
5068 s.op->newline() << "{";
5069 if (p->has_return)
5070 s.op->line() << " .return_p=1,";
c9bad430 5071 if (p->has_maxactive)
606fd9c8
FCE
5072 {
5073 s.op->line() << " .maxactive_p=1,";
5074 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5075 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5076 }
af234c40
JS
5077 if (p->saved_longs || p->saved_strings)
5078 {
5079 if (p->saved_longs)
5080 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5081 if (p->saved_strings)
5082 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5083 if (p->entry_handler)
c87ae2c1 5084 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5085 }
b350f56b
JS
5086 if (p->locations[0]->optional)
5087 s.op->line() << " .optional_p=1,";
dc38c256 5088 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5089 s.op->line() << " .module=\"" << p->module << "\",";
5090 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5091 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5092 s.op->line() << " },";
2930abc7 5093 }
2930abc7 5094
b20febf3
FCE
5095 s.op->newline(-1) << "};";
5096
5097 // Emit the kprobes callback function
5098 s.op->newline();
5099 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5100 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5101 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5102 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5103 // Check that the index is plausible
5104 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5105 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5106 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5107 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5108 s.op->line() << "];";
71db462b 5109 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5110 "stp_probe_type_kprobe");
d9aed31e 5111 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5112
5113 // Make it look like the IP is set as it wouldn't have been replaced
5114 // by a breakpoint instruction when calling real probe handler. Reset
5115 // IP regs on return, so we don't confuse kprobes. PR10458
5116 s.op->newline() << "{";
5117 s.op->indent(1);
d9aed31e 5118 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5119 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5120 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5121 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5122 s.op->newline(-1) << "}";
5123
f887a8c9 5124 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5125 s.op->newline() << "return 0;";
5126 s.op->newline(-1) << "}";
5127
5128 // Same for kretprobes
5129 s.op->newline();
af234c40
JS
5130 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5131 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5132 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5133
5134 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5135 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5136 // Check that the index is plausible
5137 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5138 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5139 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5140 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5141 s.op->line() << "];";
5142
7c3e97f4 5143 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5144 s.op->newline() << "if (sp) {";
5145 s.op->indent(1);
71db462b 5146 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5147 "stp_probe_type_kretprobe");
d9aed31e 5148 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5149
5150 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5151 s.op->newline() << "c->ips.krp.pi = inst;";
5152 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5153
5154 // Make it look like the IP is set as it wouldn't have been replaced
5155 // by a breakpoint instruction when calling real probe handler. Reset
5156 // IP regs on return, so we don't confuse kprobes. PR10458
5157 s.op->newline() << "{";
d9aed31e 5158 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5159 s.op->newline() << "if (entry)";
5160 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5161 s.op->newline(-1) << "else";
5162 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5163 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5164 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5165 s.op->newline(-1) << "}";
5166
f887a8c9 5167 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5168 s.op->newline(-1) << "}";
b20febf3
FCE
5169 s.op->newline() << "return 0;";
5170 s.op->newline(-1) << "}";
af234c40
JS
5171
5172 s.op->newline();
5173 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5174 s.op->line() << " struct pt_regs *regs) {";
5175 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5176 s.op->newline(-1) << "}";
5177
5178 s.op->newline();
5179 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5180 s.op->line() << " struct pt_regs *regs) {";
5181 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5182 s.op->newline(-1) << "}";
b642c901 5183
14cf7e42 5184 s.op->newline();
20c6c071 5185}
ec4373ff 5186
20c6c071 5187
dc38c0ae 5188void
b20febf3
FCE
5189dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5190{
5191 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5192 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5193 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5194 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5195 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5196 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5197 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5198 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5199 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5200 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5201 s.op->newline(-1) << "} else {";
f07c3b68 5202 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5203 s.op->newline(-1) << "}";
606fd9c8 5204 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5205 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5206 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5207 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5208 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5209 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5210 s.op->newline(-1) << "}";
5211 s.op->newline() << "#endif";
e4cb375f
MH
5212 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5213 s.op->newline() << "#ifdef __ia64__";
5214 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5215 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5216 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5217 s.op->newline() << "if (rc == 0) {";
5218 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5219 s.op->newline() << "if (rc != 0)";
5220 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5221 s.op->newline(-2) << "}";
5222 s.op->newline() << "#else";
606fd9c8 5223 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5224 s.op->newline() << "#endif";
b20febf3 5225 s.op->newline(-1) << "} else {";
e4cb375f 5226 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5227 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5228 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5229 s.op->newline() << "#ifdef __ia64__";
5230 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5231 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5232 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5233 s.op->newline() << "if (rc == 0) {";
5234 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5235 s.op->newline() << "if (rc != 0)";
5236 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5237 s.op->newline(-2) << "}";
5238 s.op->newline() << "#else";
606fd9c8 5239 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5240 s.op->newline() << "#endif";
b20febf3 5241 s.op->newline(-1) << "}";
9063462a
FCE
5242 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5243 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5244 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5245 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5246 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5247 // XXX: shall we increment numskipped?
5248 s.op->newline(-1) << "}";
5249
5250#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5251 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5252 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5253 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5254 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5255 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5256 s.op->newline() << "#ifdef __ia64__";
5257 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5258 s.op->newline() << "#endif";
c48cb0cc
FCE
5259 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5260 // not run for this early-abort case.
5261 s.op->newline(-1) << "}";
5262 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5263 s.op->newline(-1) << "}";
9063462a
FCE
5264#endif
5265
b20febf3
FCE
5266 s.op->newline() << "else sdp->registered_p = 1;";
5267 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5268}
5269
5270
b4be7cbc
FCE
5271void
5272dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5273{
5274 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5275 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5276 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5277 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5278 s.op->newline() << "int rc;";
5279
5280 // new module arrived?
5281 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5282 s.op->newline(1) << "if (sdp->return_p) {";
5283 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5284 s.op->newline() << "if (sdp->maxactive_p) {";
5285 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5286 s.op->newline(-1) << "} else {";
5287 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5288 s.op->newline(-1) << "}";
5289 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5290 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5291 s.op->newline() << "if (sdp->entry_probe) {";
5292 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5293 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5294 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5295 s.op->newline(-1) << "}";
5296 s.op->newline() << "#endif";
5297 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5298 s.op->newline() << "#ifdef __ia64__";
5299 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5300 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5301 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5302 s.op->newline() << "if (rc == 0) {";
5303 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5304 s.op->newline() << "if (rc != 0)";
5305 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5306 s.op->newline(-2) << "}";
5307 s.op->newline() << "#else";
5308 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5309 s.op->newline() << "#endif";
5310 s.op->newline(-1) << "} else {";
5311 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5312 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5313 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5314 s.op->newline() << "#ifdef __ia64__";
5315 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5316 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5317 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5318 s.op->newline() << "if (rc == 0) {";
5319 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5320 s.op->newline() << "if (rc != 0)";
5321 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5322 s.op->newline(-2) << "}";
5323 s.op->newline() << "#else";
5324 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5325 s.op->newline() << "#endif";
5326 s.op->newline(-1) << "}";
5327 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5328
5329 // old module disappeared?
5330 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5331 s.op->newline(1) << "if (sdp->return_p) {";
5332 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5333 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5334 s.op->newline() << "#ifdef STP_TIMING";
5335 s.op->newline() << "if (kp->u.krp.nmissed)";
5336 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5337 s.op->newline(-1) << "#endif";
065d5567 5338 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5339 s.op->newline() << "#ifdef STP_TIMING";
5340 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5341 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5342 s.op->newline(-1) << "#endif";
5343 s.op->newline(-1) << "} else {";
5344 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5345 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5346 s.op->newline() << "#ifdef STP_TIMING";
5347 s.op->newline() << "if (kp->u.kp.nmissed)";
5348 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5349 s.op->newline(-1) << "#endif";
5350 s.op->newline(-1) << "}";
5351 s.op->newline() << "#if defined(__ia64__)";
5352 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5353 s.op->newline() << "#endif";
5354 s.op->newline() << "sdp->registered_p = 0;";
5355 s.op->newline(-1) << "}";
5356
5357 s.op->newline(-1) << "}"; // for loop
5358}
5359
5360
5361
5362
46b84a80 5363void
b20febf3 5364dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5365{
42cb22bd
MH
5366 //Unregister kprobes by batch interfaces.
5367 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5368 s.op->newline() << "j = 0;";
5369 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5370 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5371 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5372 s.op->newline() << "if (! sdp->registered_p) continue;";
5373 s.op->newline() << "if (!sdp->return_p)";
5374 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5375 s.op->newline(-2) << "}";
5376 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5377 s.op->newline() << "j = 0;";
5378 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5379 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5380 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5381 s.op->newline() << "if (! sdp->registered_p) continue;";
5382 s.op->newline() << "if (sdp->return_p)";
5383 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5384 s.op->newline(-2) << "}";
5385 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5386 s.op->newline() << "#ifdef __ia64__";
5387 s.op->newline() << "j = 0;";
5388 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5389 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5390 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5391 s.op->newline() << "if (! sdp->registered_p) continue;";
5392 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5393 s.op->newline(-1) << "}";
5394 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5395 s.op->newline() << "#endif";
42cb22bd
MH
5396 s.op->newline() << "#endif";
5397
b20febf3
FCE
5398 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5399 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5400 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5401 s.op->newline() << "if (! sdp->registered_p) continue;";
5402 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5403 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5404 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5405 s.op->newline() << "#endif";
065d5567 5406 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5407 s.op->newline() << "#ifdef STP_TIMING";
5408 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5409 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5410 s.op->newline(-1) << "#endif";
065d5567 5411 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5412 s.op->newline() << "#ifdef STP_TIMING";
5413 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5414 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 5415 s.op->newline(-1) << "#endif";
557fb7a8 5416 s.op->newline(-1) << "} else {";
42cb22bd 5417 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5418 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5419 s.op->newline() << "#endif";
065d5567 5420 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5421 s.op->newline() << "#ifdef STP_TIMING";
5422 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5423 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5424 s.op->newline(-1) << "#endif";
b20febf3 5425 s.op->newline(-1) << "}";
e4cb375f
MH
5426 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5427 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5428 s.op->newline() << "#endif";
b20febf3
FCE
5429 s.op->newline() << "sdp->registered_p = 0;";
5430 s.op->newline(-1) << "}";
46b84a80
DS
5431}
5432
272c9036
WF
5433static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5434{
5435 string::size_type pos;
5436 string::size_type lastPos = str.find_first_not_of(" ", 0);
5437 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5438
5439 if (nextAt == string::npos)
5440 {
5441 // PR13934: Assembly probes are not forced to use the N@OP form.
5442 // In this case, N is inferred to be the native word size. Since we
5443 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5444 // then must not put any spaces in arguments, to avoid ambiguity.
5445 tokenize(str, tokens, " ");
5446 return;
5447 }
5448
272c9036
WF
5449 while (lastPos != string::npos)
5450 {
5451 pos = nextAt + 1;
5452 nextAt = str.find("@", pos);
5453 if (nextAt == string::npos)
5454 pos = string::npos;
5455 else
5456 pos = str.rfind(" ", nextAt);
5457
5458 tokens.push_back(str.substr(lastPos, pos - lastPos));
5459 lastPos = str.find_first_not_of(" ", pos);
5460 }
5461}
8aabf152 5462
8aabf152 5463
aff5d390 5464struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5465{
ae1418f0 5466 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
5467 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
5468 int elf_machine,
5469 const string & process_name,
a794dbeb 5470 const string & provider_name,
aff5d390 5471 const string & probe_name,
71e5e13d 5472 stap_sdt_probe_type probe_type,
aff5d390 5473 const string & arg_string,
8aabf152 5474 int ac):
332ba7e7 5475 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
5476 provider_name (provider_name), probe_name (probe_name),
5477 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5478 {
f83336a5
FCE
5479 /* Register name mapping table depends on the elf machine of this particular
5480 probe target process/file, not upon the host. So we can't just
5481 #ifdef _i686_ etc. */
ae1418f0
FCE
5482
5483#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5484 if (elf_machine == EM_X86_64) {
b78a0fbb
LB
5485 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5486 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
46a94997
SC
5487 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5488 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5489 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5490 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5491 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
b78a0fbb
LB
5492 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5493 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
46a94997
SC
5494 DRI ("%sil", 4, QI);
5495 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5496 DRI ("%dil", 5, QI);
5497 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
2c7281e7 5498 DRI ("%bpl", 6, QI);
46a94997 5499 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
2c7281e7 5500 DRI ("%spl", 7, QI);
46a94997
SC
5501 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5502 DRI ("%r8b", 8, QI);
5503 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5504 DRI ("%r9b", 9, QI);
5505 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5506 DRI ("%r10b", 10, QI);
5507 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5508 DRI ("%r11b", 11, QI);
5509 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5510 DRI ("%r12b", 12, QI);
5511 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5512 DRI ("%r13b", 13, QI);
5513 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5514 DRI ("%r14b", 14, QI);
5515 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5516 DRI ("%r15b", 15, QI);
f83336a5 5517 } else if (elf_machine == EM_386) {
46a94997
SC
5518 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5519 DRI ("%ah", 0, QIh);
5520 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5521 DRI ("%ch", 1, QIh);
5522 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5523 DRI ("%dh", 2, QIh);
5524 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5525 DRI ("%bh", 3, QIh);
b78a0fbb 5526 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
46a94997
SC
5527 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5528 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5529 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5530 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5531 DRI ("%r0", 0, DI);
5532 DRI ("%r1", 1, DI);
5533 DRI ("%r2", 2, DI);
5534 DRI ("%r3", 3, DI);
5535 DRI ("%r4", 4, DI);
5536 DRI ("%r5", 5, DI);
5537 DRI ("%r6", 6, DI);
5538 DRI ("%r7", 7, DI);
5539 DRI ("%r8", 8, DI);
5540 DRI ("%r9", 9, DI);
5541 DRI ("%r10", 10, DI);
5542 DRI ("%r11", 11, DI);
5543 DRI ("%r12", 12, DI);
5544 DRI ("%r13", 13, DI);
5545 DRI ("%r14", 14, DI);
5546 DRI ("%r15", 15, DI);
5547 DRI ("%r16", 16, DI);
5548 DRI ("%r17", 17, DI);
5549 DRI ("%r18", 18, DI);
5550 DRI ("%r19", 19, DI);
5551 DRI ("%r20", 20, DI);
5552 DRI ("%r21", 21, DI);
5553 DRI ("%r22", 22, DI);
5554 DRI ("%r23", 23, DI);
5555 DRI ("%r24", 24, DI);
5556 DRI ("%r25", 25, DI);
5557 DRI ("%r26", 26, DI);
5558 DRI ("%r27", 27, DI);
5559 DRI ("%r28", 28, DI);
5560 DRI ("%r29", 29, DI);
5561 DRI ("%r30", 30, DI);
5562 DRI ("%r31", 31, DI);
8aabf152 5563 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5564 DRI ("0", 0, DI);
5565 DRI ("1", 1, DI);
5566 DRI ("2", 2, DI);
5567 DRI ("3", 3, DI);
5568 DRI ("4", 4, DI);
5569 DRI ("5", 5, DI);
5570 DRI ("6", 6, DI);
5571 DRI ("7", 7, DI);
5572 DRI ("8", 8, DI);
5573 DRI ("9", 9, DI);
5574 DRI ("10", 10, DI);
5575 DRI ("11", 11, DI);
5576 DRI ("12", 12, DI);
5577 DRI ("13", 13, DI);
5578 DRI ("14", 14, DI);
5579 DRI ("15", 15, DI);
5580 DRI ("16", 16, DI);
5581 DRI ("17", 17, DI);
5582 DRI ("18", 18, DI);
5583 DRI ("19", 19, DI);
5584 DRI ("20", 20, DI);
5585 DRI ("21", 21, DI);
5586 DRI ("22", 22, DI);
5587 DRI ("23", 23, DI);
5588 DRI ("24", 24, DI);
5589 DRI ("25", 25, DI);
5590 DRI ("26", 26, DI);
5591 DRI ("27", 27, DI);
5592 DRI ("28", 28, DI);
5593 DRI ("29", 29, DI);
5594 DRI ("30", 30, DI);
5595 DRI ("31", 31, DI);
14900130 5596 } else if (elf_machine == EM_S390) {
46a94997
SC
5597 DRI ("%r0", 0, DI);
5598 DRI ("%r1", 1, DI);
5599 DRI ("%r2", 2, DI);
5600 DRI ("%r3", 3, DI);
5601 DRI ("%r4", 4, DI);
5602 DRI ("%r5", 5, DI);
5603 DRI ("%r6", 6, DI);
5604 DRI ("%r7", 7, DI);
5605 DRI ("%r8", 8, DI);
5606 DRI ("%r9", 9, DI);
5607 DRI ("%r10", 10, DI);
5608 DRI ("%r11", 11, DI);
5609 DRI ("%r12", 12, DI);
5610 DRI ("%r13", 13, DI);
5611 DRI ("%r14", 14, DI);
5612 DRI ("%r15", 15, DI);
272c9036
WF
5613 } else if (elf_machine == EM_ARM) {
5614 DRI ("r0", 0, SI);
5615 DRI ("r1", 1, SI);
5616 DRI ("r2", 2, SI);
5617 DRI ("r3", 3, SI);
5618 DRI ("r4", 4, SI);
5619 DRI ("r5", 5, SI);
5620 DRI ("r6", 6, SI);
5621 DRI ("r7", 7, SI);
5622 DRI ("r8", 8, SI);
5623 DRI ("r9", 9, SI);
669a2feb 5624 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
272c9036
WF
5625 DRI ("fp", 11, SI);
5626 DRI ("ip", 12, SI);
5627 DRI ("sp", 13, SI);
5628 DRI ("lr", 14, SI);
5629 DRI ("pc", 15, SI);
86aae990
WC
5630 } else if (elf_machine == EM_AARCH64) {
5631 DRI ("x0", 0, DI); DRI ("w0", 0, SI);
5632 DRI ("x1", 1, DI); DRI ("w1", 1, SI);
5633 DRI ("x2", 2, DI); DRI ("w2", 2, SI);
5634 DRI ("x3", 3, DI); DRI ("w3", 3, SI);
5635 DRI ("x4", 4, DI); DRI ("w4", 4, SI);
5636 DRI ("x5", 5, DI); DRI ("w5", 5, SI);
5637 DRI ("x6", 6, DI); DRI ("w6", 6, SI);
5638 DRI ("x7", 7, DI); DRI ("w7", 7, SI);
5639 DRI ("x8", 8, DI); DRI ("w8", 8, SI);
5640 DRI ("x9", 9, DI); DRI ("w9", 9, SI);
5641 DRI ("x10", 10, DI); DRI ("w10", 10, SI);
5642 DRI ("x11", 11, DI); DRI ("w11", 11, SI);
5643 DRI ("x12", 12, DI); DRI ("w12", 12, SI);
5644 DRI ("x13", 13, DI); DRI ("w13", 13, SI);
5645 DRI ("x14", 14, DI); DRI ("w14", 14, SI);
5646 DRI ("x15", 15, DI); DRI ("w15", 15, SI);
5647 DRI ("x16", 16, DI); DRI ("w16", 16, SI);
5648 DRI ("x17", 17, DI); DRI ("w17", 17, SI);
5649 DRI ("x18", 18, DI); DRI ("w18", 18, SI);
5650 DRI ("x19", 19, DI); DRI ("w19", 19, SI);
5651 DRI ("x20", 20, DI); DRI ("w20", 20, SI);
5652 DRI ("x21", 21, DI); DRI ("w21", 21, SI);
5653 DRI ("x22", 22, DI); DRI ("w22", 22, SI);
5654 DRI ("x23", 23, DI); DRI ("w23", 23, SI);
5655 DRI ("x24", 24, DI); DRI ("w24", 24, SI);
5656 DRI ("x25", 25, DI); DRI ("w25", 25, SI);
5657 DRI ("x26", 26, DI); DRI ("w26", 26, SI);
5658 DRI ("x27", 27, DI); DRI ("w27", 27, SI);
5659 DRI ("x28", 28, DI); DRI ("w28", 28, SI);
5660 DRI ("x29", 29, DI); DRI ("w29", 29, SI);
5661 DRI ("x30", 30, DI); DRI ("w30", 30, SI);
5662 DRI ("sp", 31, DI);
14900130 5663 } else if (arg_count) {
8aabf152 5664 /* permit this case; just fall back to dwarf */
f83336a5 5665 }
ae1418f0 5666#undef DRI
f83336a5 5667
ebbd2b45 5668 need_debug_info = false;
88e39987 5669 if (probe_type == uprobe3_type)
272c9036
WF
5670 {
5671 sdt_v3_tokenize(arg_string, arg_tokens);
5672 assert(arg_count <= 12);
5673 }
88e39987 5674 else
272c9036
WF
5675 {
5676 tokenize(arg_string, arg_tokens, " ");
5677 assert(arg_count <= 10);
5678 }
a8ec7719 5679 }
8aabf152 5680
f83336a5 5681 systemtap_session& session;
332ba7e7 5682 int elf_machine;
aff5d390 5683 const string & process_name;
a794dbeb 5684 const string & provider_name;
aff5d390 5685 const string & probe_name;
71e5e13d 5686 stap_sdt_probe_type probe_type;
8aabf152 5687 unsigned arg_count;
aff5d390 5688 vector<string> arg_tokens;
46a94997 5689 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5690 bool need_debug_info;
aff5d390
SC
5691
5692 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5693 void visit_target_symbol_arg (target_symbol* e);
5694 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5695 void visit_atvar_op (atvar_op* e);
40a0c64e 5696 void visit_cast_op (cast_op* e);
aff5d390
SC
5697};
5698
7a05f484
SC
5699
5700void
6ef331c8 5701sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5702{
6ef331c8 5703 if (e->addressof)
dc09353a 5704 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5705
5706 if (e->name == "$$name")
7a05f484 5707 {
6ef331c8
SC
5708 literal_string *myname = new literal_string (probe_name);
5709 myname->tok = e->tok;
5710 provide(myname);
5711 return;
5712 }
7a05f484 5713
6ef331c8
SC
5714 else if (e->name == "$$provider")
5715 {
5716 literal_string *myname = new literal_string (provider_name);
5717 myname->tok = e->tok;
5718 provide(myname);
5719 return;
5720 }
a794dbeb 5721
6ef331c8
SC
5722 else if (e->name == "$$vars" || e->name == "$$parms")
5723 {
5724 e->assert_no_components("sdt", true);
6ef331c8
SC
5725
5726 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
63ea4244 5727
1c922ad7 5728 print_format* pf = print_format::create(e->tok, "sprintf");
6ef331c8
SC
5729
5730 for (unsigned i = 1; i <= arg_count; ++i)
5731 {
5732 if (i > 1)
5733 pf->raw_components += " ";
5734 target_symbol *tsym = new target_symbol;
5735 tsym->tok = e->tok;
5736 tsym->name = "$arg" + lex_cast(i);
5737 pf->raw_components += tsym->name;
5738 tsym->components = e->components;
5739
8c2f50c0 5740 expression *texp = require<expression> (tsym);
6ef331c8
SC
5741 if (!e->components.empty() &&
5742 e->components[0].type == target_symbol::comp_pretty_print)
5743 pf->raw_components += "=%s";
5744 else
5745 pf->raw_components += "=%#x";
5746 pf->args.push_back(texp);
5747 }
5748
5749 pf->components = print_format::string_to_components(pf->raw_components);
5750 provide (pf);
5751 }
5752 else
5753 assert(0); // shouldn't get here
5754}
5755
5756
5757void
5758sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5759{
5760 try
5761 {
8aabf152 5762 unsigned argno = 0; // the N in $argN
c69a87e0 5763 try
aff5d390 5764 {
5ecaa5a7 5765 if (startswith(e->name, "$arg"))
8aabf152 5766 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5767 }
c69a87e0 5768 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5769 {
8aabf152 5770 argno = 0;
aff5d390 5771 }
5ecaa5a7 5772
8aabf152
FCE
5773 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5774 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5775 {
8aabf152
FCE
5776 // NB: Either
5777 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5778 // 2) uprobe2_type $FOO (no probe args)
5779 // both of which get resolved later.
73d53dd2 5780 // Throw it now, and it might be resolved by DWARF later.
8aabf152 5781 need_debug_info = true;
dc09353a 5782 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
aff5d390 5783 }
277c21bc 5784
8aabf152
FCE
5785 assert (arg_tokens.size() >= argno);
5786 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5787
8aabf152
FCE
5788 // Now we try to parse this thing, which is an assembler operand
5789 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5790 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5791 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157
FCE
5792 //
5793 // literal reg reg reg + base+index*size+offset
b874bd52 5794 // indirect offset
8095a157 5795 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S)
b874bd52 5796 // power iN R (R) N(R)
b78a0fbb 5797 // ia64 N rR [r16]
b874bd52
SC
5798 // s390 N %rR 0(rR) N(r15)
5799 // arm #N rR [rR] [rR, #N]
5800
8aabf152
FCE
5801 expression* argexpr = 0; // filled in in case of successful parse
5802
5803 string percent_regnames;
5804 string regnames;
5805 vector<string> matches;
71e5e13d 5806 long precision;
8aabf152
FCE
5807 int rc;
5808
40fe32e0
SC
5809 // Parse the leading length
5810
5811 if (asmarg.find('@') != string::npos)
5812 {
5813 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5814 asmarg = asmarg.substr(asmarg.find('@')+1);
5815 }
71e5e13d
SC
5816 else
5817 {
5818 // V1/V2 do not have precision field so default to signed long
5819 // V3 asm does not have precision field so default to unsigned long
5820 if (probe_type == uprobe3_type)
5821 precision = sizeof(long); // this is an asm probe
5822 else
5823 precision = -sizeof(long);
5824 }
40fe32e0 5825
8aabf152
FCE
5826 // test for a numeric literal.
5827 // Only accept (signed) decimals throughout. XXX
5828
5829 // PR11821. NB: on powerpc, literals are not prefixed with $,
5830 // so this regex does not match. But that's OK, since without
5831 // -mregnames, we can't tell them apart from register numbers
5832 // anyway. With -mregnames, we could, if gcc somehow
5833 // communicated to us the presence of that option, but alas it
5834 // doesn't. http://gcc.gnu.org/PR44995.
272c9036 5835 rc = regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5836 if (! rc)
5837 {
75a371ce
JS
5838 string sn = matches[0].substr(1);
5839 int64_t n;
5840 try
5841 {
5842 // We have to pay attention to the size & sign, as gcc sometimes
5843 // propagates constants that don't quite match, like a negative
5844 // value to fill an unsigned type.
5845 switch (precision)
5846 {
5847 case -1: n = lex_cast< int8_t>(sn); break;
5848 case 1: n = lex_cast< uint8_t>(sn); break;
5849 case -2: n = lex_cast< int16_t>(sn); break;
5850 case 2: n = lex_cast<uint16_t>(sn); break;
5851 case -4: n = lex_cast< int32_t>(sn); break;
5852 case 4: n = lex_cast<uint32_t>(sn); break;
5853 default:
5854 case -8: n = lex_cast< int64_t>(sn); break;
5855 case 8: n = lex_cast<uint64_t>(sn); break;
5856 }
5857 }
5858 catch (std::runtime_error&)
5859 {
5860 goto not_matched;
5861 }
5862 literal_number* ln = new literal_number(n);
8aabf152
FCE
5863 ln->tok = e->tok;
5864 argexpr = ln;
5865 goto matched;
5866 }
5867
14900130
SC
5868 if (dwarf_regs.empty())
5869 goto not_matched;
b78a0fbb 5870
8aabf152
FCE
5871 // Build regex pieces out of the known dwarf_regs. We keep two separate
5872 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5873 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5874 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5875 {
5876 string regname = ri->first;
5877 assert (regname != "");
5878 regnames += string("|")+regname;
5879 if (regname[0]=='%')
5880 percent_regnames += string("|")+regname;
5881 }
5882 // clip off leading |
5883 regnames = regnames.substr(1);
272c9036
WF
5884 if (percent_regnames != "")
5885 percent_regnames = percent_regnames.substr(1);
8aabf152
FCE
5886
5887 // test for REGISTER
5888 // NB: Because PR11821, we must use percent_regnames here.
272c9036 5889 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
9109f487
SC
5890 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5891 else
332ba7e7 5892 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5893 if (! rc)
5894 {
5895 string regname = matches[1];
46a94997
SC
5896 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5897 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5898 {
5899 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5900 string width_adjust;
46a94997 5901 switch (ri->second.second)
19c22e1f 5902 {
892ec39a
SC
5903 case QI: width_adjust = ") & 0xff)"; break;
5904 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5905 case HI:
71e5e13d 5906 // preserve 16 bit register signness
892ec39a
SC
5907 width_adjust = ") & 0xffff)";
5908 if (precision < 0)
55b377f4 5909 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5910 break;
5911 case SI:
5912 // preserve 32 bit register signness
892ec39a
SC
5913 width_adjust = ") & 0xffffffff)";
5914 if (precision < 0)
55b377f4 5915 width_adjust += " << 32 >> 32";
19c22e1f 5916 break;
892ec39a 5917 default: width_adjust = "))";
19c22e1f 5918 }
55b377f4
SC
5919 string type = "";
5920 if (probe_type == uprobe3_type)
5921 type = (precision < 0
5922 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5923 type = type + "((";
8aabf152
FCE
5924 get_arg1->tok = e->tok;
5925 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5926 + string(" ((int64_t)") + type
8aabf152
FCE
5927 + (is_user_module (process_name)
5928 ? string("u_fetch_register(")
5929 : string("k_fetch_register("))
46a94997 5930 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5931 + width_adjust;
8aabf152
FCE
5932 argexpr = get_arg1;
5933 goto matched;
5934 }
5935 // invalid register name, fall through
5936 }
40fe32e0 5937
272c9036 5938 int reg, offset1;
e5b7b83f 5939 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5940 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 5941 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
5942 // On ARM test for [REGISTER, OFFSET]
5943 if (elf_machine == EM_ARM)
5944 {
669a2feb 5945 rc = regexp_match (asmarg, string("^\\[(")+regnames+string(")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$"), matches);
272c9036 5946 reg = 1;
669a2feb 5947 offset1 = 3;
272c9036
WF
5948 }
5949 else
5950 {
5951 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
5952 reg = 4;
5953 offset1 = 1;
5954 }
8aabf152
FCE
5955 if (! rc)
5956 {
e5b7b83f 5957 string regname;
8aabf152 5958 int64_t disp = 0;
272c9036
WF
5959 if (matches[reg].length())
5960 regname = matches[reg];
8095a157
FCE
5961 if (dwarf_regs.find (regname) == dwarf_regs.end())
5962 goto not_matched;
5963
272c9036 5964 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
5965 if (matches[i].length())
5966 try
5967 {
5968 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5969 }
8aabf152
FCE
5970 catch (const runtime_error& f) // unparseable offset
5971 {
5972 goto not_matched; // can't just 'break' out of
5973 // this case or use a sentinel
5974 // value, unfortunately
5975 }
5976
8aabf152 5977 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
5978 embedded_expr *get_arg1 = new embedded_expr;
5979 get_arg1->tok = e->tok;
5980 get_arg1->code = string("/* unprivileged */ /* pure */")
5981 + (is_user_module (process_name)
5982 ? string("u_fetch_register(")
5983 : string("k_fetch_register("))
46a94997 5984 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5985 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5986
8aabf152
FCE
5987 literal_number* inc = new literal_number(disp);
5988 inc->tok = e->tok;
40fe32e0 5989
8aabf152
FCE
5990 binary_expression *be = new binary_expression;
5991 be->tok = e->tok;
5992 be->left = get_arg1;
5993 be->op = "+";
5994 be->right = inc;
40fe32e0 5995
8aabf152 5996 functioncall *fc = new functioncall;
40fe32e0
SC
5997 switch (precision)
5998 {
7f6ce9ab
SC
5999 case 1: case -1:
6000 fc->function = "user_int8"; break;
6001 case 2:
6002 fc->function = "user_uint16"; break;
6003 case -2:
6004 fc->function = "user_int16"; break;
6005 case 4:
6006 fc->function = "user_uint32"; break;
6007 case -4:
6008 fc->function = "user_int32"; break;
6009 case 8: case -8:
6010 fc->function = "user_int64"; break;
40fe32e0
SC
6011 default: fc->function = "user_long";
6012 }
8aabf152
FCE
6013 fc->tok = e->tok;
6014 fc->args.push_back(be);
366af4e7 6015
8aabf152
FCE
6016 argexpr = fc;
6017 goto matched;
6018 }
8095a157
FCE
6019
6020 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
6021 // NB: Despite PR11821, we can use regnames here, since the parentheses
6022 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 6023 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
6024 if (! rc)
6025 {
6026 string baseregname;
6027 string indexregname;
6028 int64_t disp = 0;
6029 short scale = 1;
6030
6031 if (matches[6].length())
6032 try
6033 {
6034 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
6035 // We could verify that scale is one of 1,2,4,8,
6036 // but it doesn't really matter. An erroneous
6037 // address merely results in run-time errors.
8aabf152 6038 }
8095a157
FCE
6039 catch (const runtime_error &f) // unparseable scale
6040 {
6041 goto not_matched;
6042 }
6043
6044 if (matches[4].length())
6045 baseregname = matches[4];
6046 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6047 goto not_matched;
6048
6049 if (matches[5].length())
6050 indexregname = matches[5];
6051 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6052 goto not_matched;
6053
f7719b3d 6054 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
6055 if (matches[i].length())
6056 try
6057 {
6058 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
6059 }
6060 catch (const runtime_error& f) // unparseable offset
6061 {
6062 goto not_matched; // can't just 'break' out of
6063 // this case or use a sentinel
6064 // value, unfortunately
6065 }
6066
6067 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6068
6069 embedded_expr *get_arg1 = new embedded_expr;
6070 string regfn = is_user_module (process_name)
6071 ? string("u_fetch_register")
6072 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
6073
6074 get_arg1->tok = e->tok;
6075 get_arg1->code = string("/* unprivileged */ /* pure */")
6076 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6077 + string("+(")
6078 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6079 + string("*")
6080 + lex_cast(scale)
6081 + string(")");
6082
6083 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6084 literal_number* inc = new literal_number(disp);
6085 inc->tok = e->tok;
6086
6087 binary_expression *be = new binary_expression;
6088 be->tok = e->tok;
6089 be->left = get_arg1;
6090 be->op = "+";
6091 be->right = inc;
6092
6093 functioncall *fc = new functioncall;
6094 switch (precision)
6095 {
6096 case 1: case -1:
6097 fc->function = "user_int8"; break;
6098 case 2:
6099 fc->function = "user_uint16"; break;
6100 case -2:
6101 fc->function = "user_int16"; break;
6102 case 4:
6103 fc->function = "user_uint32"; break;
6104 case -4:
6105 fc->function = "user_int32"; break;
6106 case 8: case -8:
6107 fc->function = "user_int64"; break;
6108 default: fc->function = "user_long";
6109 }
6110 fc->tok = e->tok;
6111 fc->args.push_back(be);
6112
6113 argexpr = fc;
6114 goto matched;
8aabf152
FCE
6115 }
6116
8aabf152
FCE
6117
6118 not_matched:
6119 // The asmarg operand was not recognized. Back down to dwarf.
6120 if (! session.suppress_warnings)
84fef8ee
FCE
6121 {
6122 if (probe_type == UPROBE3_TYPE)
6c9e1946 6123 session.print_warning (_F("Can't parse SDT_V3 operand '%s' [man error::sdt]", asmarg.c_str()), e->tok);
84fef8ee 6124 else // must be *PROBE2; others don't get asm operands
b78a0fbb 6125 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s' [man error::sdt]",
84fef8ee
FCE
6126 asmarg.c_str()), e->tok);
6127 }
8aabf152
FCE
6128 assert (argexpr == 0);
6129 need_debug_info = true;
dc09353a 6130 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo [man error::sdt]"), e->tok);
366af4e7 6131
8aabf152
FCE
6132 matched:
6133 assert (argexpr != 0);
366af4e7
RM
6134
6135 if (session.verbose > 2)
1e41115c 6136 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6137 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6138
aff5d390 6139 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6140 {
6141 if (e->addressof)
dc09353a 6142 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
6143 provide (argexpr);
6144 return;
6145 }
6146 else // $var->foo
6147 {
6148 cast_op *cast = new cast_op;
6149 cast->name = "@cast";
6150 cast->tok = e->tok;
6151 cast->operand = argexpr;
6152 cast->components = e->components;
6153 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6154 cast->module = process_name;
6155 cast->visit(this);
6156 return;
6157 }
366af4e7 6158
8aabf152 6159 /* NOTREACHED */
aff5d390
SC
6160 }
6161 catch (const semantic_error &er)
6162 {
6163 e->chain (er);
6164 provide (e);
6165 }
6166}
6167
6168
6ef331c8
SC
6169void
6170sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6171{
6172 try
6173 {
49131a6d 6174 assert(e->name.size() > 0
bd1fcbad 6175 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6176
6177 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6178 visit_target_symbol_context (e);
6179 else
6180 visit_target_symbol_arg (e);
6181 }
6182 catch (const semantic_error &er)
6183 {
6184 e->chain (er);
6185 provide (e);
6186 }
6187}
6188
6189
bd1fcbad
YZ
6190void
6191sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6192{
6193 need_debug_info = true;
6194
6195 // Fill in our current module context if needed
6196 if (e->module.empty())
6197 e->module = process_name;
6198
6199 var_expanding_visitor::visit_atvar_op(e);
6200}
6201
6202
40a0c64e
JS
6203void
6204sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6205{
6206 // Fill in our current module context if needed
6207 if (e->module.empty())
6208 e->module = process_name;
6209
6210 var_expanding_visitor::visit_cast_op(e);
6211}
6212
6213
576eaefe
SC
6214void
6215plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6216{
6217 try
6218 {
6219 if (e->name == "$$name")
6220 {
6221 literal_string *myname = new literal_string (entry);
6222 myname->tok = e->tok;
6223 provide(myname);
6224 return;
6225 }
3d69c03f
JS
6226
6227 // variable not found -> throw a semantic error
6228 // (only to be caught right away, but this may be more complex later...)
6229 string alternatives = "$$name";
dc09353a 6230 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6231 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6232 }
6233 catch (const semantic_error &er)
6234 {
6235 e->chain (er);
6236 provide (e);
6237 }
6238}
6239
6240
edce5b67
JS
6241struct sdt_query : public base_query
6242{
6243 sdt_query(probe * base_probe, probe_point * base_loc,
6244 dwflpp & dw, literal_map_t const & params,
51d6bda3 6245 vector<derived_probe *> & results, const string user_lib);
edce5b67 6246
51d6bda3 6247 void query_library (const char *data);
576eaefe 6248 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6249 void handle_query_module();
6250
6251private:
15284963 6252 stap_sdt_probe_type probe_type;
d61ea602 6253 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6254 probe * base_probe;
6255 probe_point * base_loc;
6846cfc8 6256 literal_map_t const & params;
edce5b67 6257 vector<derived_probe *> & results;
a794dbeb
FCE
6258 string pp_mark;
6259 string pp_provider;
51d6bda3 6260 string user_lib;
edce5b67
JS
6261
6262 set<string> probes_handled;
6263
6264 Elf_Data *pdata;
6265 size_t probe_scn_offset;
6266 size_t probe_scn_addr;
aff5d390 6267 uint64_t arg_count;
40fe32e0 6268 GElf_Addr base;
c57ea854 6269 GElf_Addr pc;
aff5d390 6270 string arg_string;
edce5b67 6271 string probe_name;
a794dbeb 6272 string provider_name;
909ab234 6273 GElf_Addr semaphore_load_offset;
79a0ca08 6274 Dwarf_Addr semaphore;
edce5b67
JS
6275
6276 bool init_probe_scn();
6b51ee12 6277 bool get_next_probe();
c57ea854
SC
6278 void iterate_over_probe_entries();
6279 void handle_probe_entry();
edce5b67 6280
40fe32e0
SC
6281 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
6282 void setup_note_probe_entry (int type, const char *data, size_t len);
6283
edce5b67 6284 void convert_probe(probe *base);
4ddb6dd0 6285 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6286 probe* convert_location();
40fe32e0 6287 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6288 bool have_debuginfo_uprobe(bool need_debug_info)
6289 {return probe_type == uprobe1_type
40fe32e0 6290 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6291 && need_debug_info);}
40fe32e0 6292 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6293};
6294
6295
6296sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6297 dwflpp & dw, literal_map_t const & params,
51d6bda3 6298 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6299 base_query(dw, params), probe_type(unknown_probe_type),
6300 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6301 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6302 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6303 semaphore_load_offset(0), semaphore(0)
edce5b67 6304{
a794dbeb
FCE
6305 assert(get_string_param(params, TOK_MARK, pp_mark));
6306 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6307
ef428667
FCE
6308 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6309 // map it to double-underscores.
6310 size_t pos = 0;
6311 while (1) // there may be more than one
6312 {
a794dbeb 6313 size_t i = pp_mark.find("-", pos);
ef428667 6314 if (i == string::npos) break;
a794dbeb 6315 pp_mark.replace (i, 1, "__");
ef428667
FCE
6316 pos = i+1; // resume searching after the inserted __
6317 }
a794dbeb
FCE
6318
6319 // XXX: same for pp_provider?
edce5b67
JS
6320}
6321
6322
6323void
c57ea854 6324sdt_query::handle_probe_entry()
edce5b67 6325{
c57ea854
SC
6326 if (! have_uprobe()
6327 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6328 return;
6329
6330 if (sess.verbose > 3)
c57ea854 6331 {
b78a0fbb 6332 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
b530b5b3
LB
6333 //TRANSLATORS: is matched to.
6334 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6335 switch (probe_type)
6336 {
6337 case uprobe1_type:
6338 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6339 break;
6340 case uprobe2_type:
6341 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6342 break;
40fe32e0
SC
6343 case uprobe3_type:
6344 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6345 break;
d61ea602
JS
6346 default:
6347 clog << "unknown!" << endl;
6348 break;
c57ea854
SC
6349 }
6350 }
edce5b67 6351
c57ea854
SC
6352 // Extend the derivation chain
6353 probe *new_base = convert_location();
6354 probe_point *new_location = new_base->locations[0];
6355
c57ea854
SC
6356 bool need_debug_info = false;
6357
7d395255
JS
6358 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6359 // or dwfl_module_getelf(...). We only need it for the machine type, which
6360 // should be the same. The bias is used for relocating debuginfoless probes,
6361 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6362 Dwarf_Addr bias;
7d395255 6363 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6364
1cc41cd6
DS
6365 /* Figure out the architecture of this particular ELF file. The
6366 dwarfless register-name mappings depend on it. */
6367 GElf_Ehdr ehdr_mem;
6368 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
6369 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6370 assert(em);
1cc41cd6
DS
6371 int elf_machine = em->e_machine;
6372 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine, module_val,
6373 provider_name, probe_name,
6374 probe_type, arg_string, arg_count);
6375 svv.replace (new_base->body);
6376 need_debug_info = svv.need_debug_info;
c57ea854 6377
1cc41cd6
DS
6378 // XXX: why not derive_probes() in the uprobes case too?
6379 literal_map_t params;
6380 for (unsigned i = 0; i < new_location->components.size(); ++i)
6381 {
6382 probe_point::component *c = new_location->components[i];
6383 params[c->functor] = c->arg;
6384 }
c57ea854 6385
73d53dd2 6386 unsigned prior_results_size = results.size();
1cc41cd6
DS
6387 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6388 q.has_mark = true; // enables mid-statement probing
30263a73 6389
73d53dd2
JS
6390 // V1 probes always need dwarf info
6391 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6
DS
6392 if (have_debuginfo_uprobe(need_debug_info))
6393 dw.iterate_over_modules(&query_module, &q);
73d53dd2
JS
6394
6395 // For V2+ probes, if variable references weren't used or failed (PR14369),
6396 // then try with the more direct approach. Unresolved $vars might still
6397 // cause their own error, but this gives them a chance to be optimized out.
6398 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6399 {
6400 string section;
6401 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6402 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6403 {
6404 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6405 section = ".dynamic";
6406 }
6407 else
6408 section = ".absolute";
edce5b67 6409
1cc41cd6
DS
6410 uprobe_derived_probe* p =
6411 new uprobe_derived_probe ("", "", 0,
6412 path_remove_sysroot(sess,q.module_val),
6413 section,
6414 q.statement_num_val, reloc_addr, q, 0);
6415 p->saveargs (arg_count);
6416 results.push_back (p);
c57ea854 6417 }
487bf4e2 6418 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6419 record_semaphore(results, prior_results_size);
c57ea854 6420}
edce5b67 6421
4ddb6dd0 6422
c57ea854
SC
6423void
6424sdt_query::handle_query_module()
6425{
6426 if (!init_probe_scn())
6427 return;
edce5b67 6428
c57ea854
SC
6429 if (sess.verbose > 3)
6430 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6431
40fe32e0
SC
6432 if (probe_loc == note_section)
6433 {
6434 GElf_Shdr shdr_mem;
6435 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6436
909ab234
JS
6437 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6438 // effects. The 'semaphore_load_offset' accounts for the difference in
6439 // load addresses between text and data, so the semaphore can be
6440 // converted to a file offset if needed.
40fe32e0 6441 if (shdr)
909ab234
JS
6442 {
6443 base = shdr->sh_addr;
6444 GElf_Addr base_offset = shdr->sh_offset;
6445 shdr = dw.get_section (".probes", &shdr_mem);
6446 if (shdr)
6447 semaphore_load_offset =
6448 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6449 }
40fe32e0 6450 else
909ab234
JS
6451 base = semaphore_load_offset = 0;
6452
40fe32e0
SC
6453 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
6454 }
d61ea602 6455 else if (probe_loc == probe_section)
40fe32e0 6456 iterate_over_probe_entries ();
edce5b67
JS
6457}
6458
6459
6460bool
6461sdt_query::init_probe_scn()
6462{
448a86b7 6463 Elf* elf;
edce5b67 6464 GElf_Shdr shdr_mem;
40fe32e0
SC
6465
6466 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6467 if (shdr)
6468 {
6469 probe_loc = note_section;
6470 return true;
6471 }
edce5b67 6472
448a86b7 6473 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6474 if (shdr)
edce5b67 6475 {
fea74777
SC
6476 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6477 probe_scn_offset = 0;
6478 probe_scn_addr = shdr->sh_addr;
6479 assert (pdata != NULL);
6480 if (sess.verbose > 4)
ce0f6648
LB
6481 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6482 << pdata->d_size << endl;
40fe32e0 6483 probe_loc = probe_section;
fea74777 6484 return true;
edce5b67 6485 }
fea74777 6486 else
edce5b67 6487 return false;
edce5b67
JS
6488}
6489
40fe32e0
SC
6490void
6491sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
6492{
6493 sdt_query *me = (sdt_query*)object;
6494 me->setup_note_probe_entry (type, data, len);
6495}
6496
6497
6498void
6499sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
6500{
6501 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
6502 // && !memcmp (data->d_buf + name_off,
6503 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
6504
6505 // probes are in the .note.stapsdt section
6506#define _SDT_NOTE_TYPE 3
6507 if (type != _SDT_NOTE_TYPE)
6508 return;
6509
6510 union
6511 {
6512 Elf64_Addr a64[3];
6513 Elf32_Addr a32[3];
6514 } buf;
6515 Dwarf_Addr bias;
6516 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6517 Elf_Data dst =
6518 {
6519 &buf, ELF_T_ADDR, EV_CURRENT,
6520 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6521 };
6522 assert (dst.d_size <= sizeof buf);
6523
6524 if (len < dst.d_size + 3)
6525 return;
6526
6527 Elf_Data src =
6528 {
6529 (void *) data, ELF_T_ADDR, EV_CURRENT,
6530 dst.d_size, 0, 0
6531 };
6532
6533 if (gelf_xlatetom (elf, &dst, &src,
6534 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6535 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6536
6537 probe_type = uprobe3_type;
6538 const char * provider = data + dst.d_size;
3f803f9e 6539
40fe32e0 6540 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6541 if(name++ == NULL)
6542 return;
6543
6544 const char *args = (const char*)memchr (name, '\0', data + len - name);
6545 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6546 return;
6547
6548 provider_name = provider;
6549 probe_name = name;
6550 arg_string = args;
40fe32e0
SC
6551
6552 // Did we find a matching probe?
6553 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6554 && ((pp_provider == "")
6555 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6556 return;
6557
e9a90eee
JS
6558 // PR13934: Assembly probes are not forced to use the N@OP form.
6559 // If we have '@' then great, else count based on space-delimiters.
6560 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6561 if (!arg_count && !arg_string.empty())
6562 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6563
40fe32e0
SC
6564 GElf_Addr base_ref;
6565 if (gelf_getclass (elf) == ELFCLASS32)
6566 {
6567 pc = buf.a32[0];
6568 base_ref = buf.a32[1];
6569 semaphore = buf.a32[2];
6570 }
6571 else
6572 {
6573 pc = buf.a64[0];
6574 base_ref = buf.a64[1];
6575 semaphore = buf.a64[2];
6576 }
6577
6578 semaphore += base - base_ref;
6579 pc += base - base_ref;
6580
7d395255
JS
6581 // The semaphore also needs the ELF bias added now, so
6582 // record_semaphore can properly relocate it later.
6583 semaphore += bias;
6584
40fe32e0 6585 if (sess.verbose > 4)
b530b5b3 6586 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
6587
6588 handle_probe_entry();
6589}
6590
6591
c57ea854
SC
6592void
6593sdt_query::iterate_over_probe_entries()
edce5b67 6594{
c57ea854 6595 // probes are in the .probe section
edce5b67
JS
6596 while (probe_scn_offset < pdata->d_size)
6597 {
aff5d390
SC
6598 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6599 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6600 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6601 if (! have_uprobe())
edce5b67
JS
6602 {
6603 // Unless this is a mangled .probes section, this happens
6604 // because the name of the probe comes first, followed by
6605 // the sentinel.
6606 if (sess.verbose > 5)
b530b5b3 6607 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6608 probe_scn_offset += sizeof(__uint32_t);
6609 continue;
6610 }
aff5d390
SC
6611 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6612 {
6613 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6614 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6615 continue;
6616 }
6617
1cc41cd6 6618 if (probe_type == uprobe1_type)
aff5d390 6619 {
79a0ca08 6620 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6621 return;
79a0ca08 6622 semaphore = 0;
aff5d390 6623 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6624 provider_name = ""; // unknown
1cc41cd6
DS
6625 pc = pbe_v1->arg;
6626 arg_count = 0;
aff5d390
SC
6627 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6628 }
08b5a50c 6629 else if (probe_type == uprobe2_type)
aff5d390 6630 {
79a0ca08 6631 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6632 return;
79a0ca08 6633 semaphore = pbe_v2->semaphore;
aff5d390 6634 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6635 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6636 arg_count = pbe_v2->arg_count;
6637 pc = pbe_v2->pc;
6638 if (pbe_v2->arg_string)
6639 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6640 // skip over pbe_v2, probe_name text and provider text
6641 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6642 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6643 }
edce5b67 6644 if (sess.verbose > 4)
b530b5b3 6645 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6646 << "@0x" << hex << pc << dec << endl;
edce5b67 6647
a794dbeb
FCE
6648 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6649 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6650 handle_probe_entry ();
edce5b67 6651 }
edce5b67
JS
6652}
6653
6654
6846cfc8 6655void
4ddb6dd0 6656sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6657{
a794dbeb
FCE
6658 for (unsigned i=0; i<2; i++) {
6659 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6660 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6661 // XXX: multiple addresses?
6662 if (sess.verbose > 2)
b530b5b3 6663 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6664
79a0ca08
SC
6665 Dwarf_Addr addr;
6666 if (this->semaphore)
6667 addr = this->semaphore;
6668 else
6669 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6670 if (addr)
6671 {
7d395255 6672 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6673 dwfl_module_relocate_address (dw.module, &addr);
6674 // XXX: relocation basis?
909ab234
JS
6675
6676 // Dyninst needs the *file*-based offset for semaphores,
6677 // so subtract the difference in load addresses between .text and .probes
6678 if (dw.sess.runtime_usermode_p())
6679 addr -= semaphore_load_offset;
6680
a794dbeb
FCE
6681 for (unsigned i = start; i < results.size(); ++i)
6682 results[i]->sdt_semaphore_addr = addr;
6683 if (sess.verbose > 2)
b530b5b3 6684 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6685 return;
6686 }
6687 else
6688 if (sess.verbose > 2)
b530b5b3 6689 clog << _(", not found") << endl;
a794dbeb 6690 }
6846cfc8
SC
6691}
6692
6693
edce5b67
JS
6694void
6695sdt_query::convert_probe (probe *base)
6696{
6697 block *b = new block;
6698 b->tok = base->body->tok;
6699
edce5b67
JS
6700 // Generate: if (arg1 != mark("label")) next;
6701 functioncall *fc = new functioncall;
bbafcb1e 6702 fc->function = "ulong_arg";
edce5b67 6703 fc->tok = b->tok;
bbafcb1e 6704 literal_number* num = new literal_number(1);
edce5b67
JS
6705 num->tok = b->tok;
6706 fc->args.push_back(num);
6707
6708 functioncall *fcus = new functioncall;
6709 fcus->function = "user_string";
6710 fcus->type = pe_string;
6711 fcus->tok = b->tok;
6712 fcus->args.push_back(fc);
6713
6714 if_statement *is = new if_statement;
6715 is->thenblock = new next_statement;
6716 is->elseblock = NULL;
6717 is->tok = b->tok;
63ea4244 6718 is->thenblock->tok = b->tok;
edce5b67
JS
6719 comparison *be = new comparison;
6720 be->op = "!=";
6721 be->tok = b->tok;
6722 be->left = fcus;
6723 be->right = new literal_string(probe_name);
63ea4244 6724 be->right->tok = b->tok;
edce5b67
JS
6725 is->condition = be;
6726 b->statements.push_back(is);
6727
6728 // Now replace the body
6729 b->statements.push_back(base->body);
6730 base->body = b;
6731}
6732
6733
c72aa911
JS
6734probe*
6735sdt_query::convert_location ()
edce5b67 6736{
c72aa911 6737 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6738 vector<probe_point::component*> derived_comps;
edce5b67 6739
662539d9
JS
6740 vector<probe_point::component*>::iterator it;
6741 for (it = specific_loc->components.begin();
6742 it != specific_loc->components.end(); ++it)
6743 if ((*it)->functor == TOK_PROCESS)
6744 {
1cc41cd6
DS
6745 // copy the process name
6746 derived_comps.push_back(*it);
662539d9
JS
6747 }
6748 else if ((*it)->functor == TOK_LIBRARY)
6749 {
1cc41cd6
DS
6750 // copy the library name for process probes
6751 derived_comps.push_back(*it);
662539d9
JS
6752 }
6753 else if ((*it)->functor == TOK_PROVIDER)
6754 {
6755 // replace the possibly wildcarded arg with the specific provider name
6756 *it = new probe_point::component(TOK_PROVIDER,
6757 new literal_string(provider_name));
6758 }
6759 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6760 {
6761 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6762 *it = new probe_point::component(TOK_MARK,
6763 new literal_string(probe_name));
a794dbeb 6764
aff5d390
SC
6765 if (sess.verbose > 3)
6766 switch (probe_type)
6767 {
6768 case uprobe1_type:
b530b5b3 6769 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6770 << hex << pc << dec << endl;
6771 break;
6772 case uprobe2_type:
b530b5b3 6773 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6774 << hex << pc << dec << endl;
6775 break;
40fe32e0 6776 case uprobe3_type:
b530b5b3 6777 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6778 << hex << pc << dec << endl;
6779 break;
aff5d390 6780 default:
b530b5b3
LB
6781 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6782 pp_mark.c_str()) << endl;
aff5d390
SC
6783 }
6784
c72aa911
JS
6785 switch (probe_type)
6786 {
aff5d390
SC
6787 case uprobe1_type:
6788 case uprobe2_type:
40fe32e0 6789 case uprobe3_type:
c72aa911 6790 // process("executable").statement(probe_arg)
662539d9
JS
6791 derived_comps.push_back
6792 (new probe_point::component(TOK_STATEMENT,
6793 new literal_number(pc, true)));
c72aa911
JS
6794 break;
6795
a794dbeb 6796 default: // deprecated
c72aa911 6797 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6798 derived_comps.push_back
6799 (new probe_point::component(TOK_FUNCTION,
6800 new literal_string("*")));
6801 derived_comps.push_back
c72aa911 6802 (new probe_point::component(TOK_LABEL,
a794dbeb 6803 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6804 break;
6805 }
6806 }
edce5b67 6807
662539d9
JS
6808 probe_point* derived_loc = new probe_point(*specific_loc);
6809 derived_loc->components = derived_comps;
8159bf55 6810 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
6811}
6812
6813
51d6bda3
SC
6814void
6815sdt_query::query_library (const char *library)
6816{
6817 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6818}
6819
40a70f52
JL
6820string
6821suggest_plt_functions(systemtap_session& sess,
6822 const set<string>& modules,
6823 const string& func)
6824{
6825 if (func.empty() || modules.empty() || sess.module_cache == NULL)
6826 return "";
6827
6828 set<string> funcs;
6829 const map<string, module_info*> &cache = sess.module_cache->cache;
6830
6831 for (set<string>::iterator itmod = modules.begin();
6832 itmod != modules.end(); ++itmod)
6833 {
6834 map<string, module_info*>::const_iterator itcache;
6835 if ((itcache = cache.find(*itmod)) != cache.end())
6836 funcs.insert(itcache->second->plt_funcs.begin(),
6837 itcache->second->plt_funcs.end());
6838 }
6839
6840 if (sess.verbose > 2)
6841 clog << "suggesting from " << funcs.size() << " functions" << endl;
6842
6843 if (funcs.empty())
6844 return "";
6845
6846 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
6847}
51d6bda3 6848
0508c45f
JL
6849string
6850suggest_dwarf_functions(systemtap_session& sess,
6851 const set<string>& modules,
6852 string func)
44ffe90c
JL
6853{
6854 // Trim any @ component
6855 size_t pos = func.find('@');
6856 if (pos != string::npos)
6857 func.erase(pos);
6858
0508c45f 6859 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
6860 return "";
6861
6862 // We must first aggregate all the functions from the cache
6863 set<string> funcs;
6864 const map<string, module_info*> &cache = sess.module_cache->cache;
6865
0508c45f
JL
6866 for (set<string>::iterator itmod = modules.begin();
6867 itmod != modules.end(); ++itmod)
44ffe90c 6868 {
6e6d9a3b
JL
6869 module_info *module;
6870
6871 // retrieve module_info from cache
44ffe90c
JL
6872 map<string, module_info*>::const_iterator itcache;
6873 if ((itcache = cache.find(*itmod)) != cache.end())
6e6d9a3b
JL
6874 module = itcache->second;
6875 else // module not found
6876 continue;
6877
6878 // add inlines
6879 funcs.insert(module->inlined_funcs.begin(),
6880 module->inlined_funcs.end());
6881
6882 // add all function symbols in cache
6883 if (module->symtab_status != info_present || module->sym_table == NULL)
6884 continue;
6885 map<string, func_info*>& modfuncs = module->sym_table->map_by_name;
6886 for (map<string, func_info*>::const_iterator itfuncs = modfuncs.begin();
6887 itfuncs != modfuncs.end(); ++itfuncs)
6888 funcs.insert(itfuncs->first);
44ffe90c
JL
6889 }
6890
6891 if (sess.verbose > 2)
6892 clog << "suggesting from " << funcs.size() << " functions" << endl;
6893
6894 if (funcs.empty())
6895 return "";
6896
593f09eb 6897 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
6898}
6899
20c6c071 6900void
5227f1ea 6901dwarf_builder::build(systemtap_session & sess,
7a053d3b 6902 probe * base,
20c6c071 6903 probe_point * location,
86bf665e 6904 literal_map_t const & parameters,
20c6c071
GH
6905 vector<derived_probe *> & finished_results)
6906{
b20febf3
FCE
6907 // NB: the kernel/user dwlfpp objects are long-lived.
6908 // XXX: but they should be per-session, as this builder object
6909 // may be reused if we try to cross-instrument multiple targets.
84048984 6910
7a24d422 6911 dwflpp* dw = 0;
6d5d594e 6912 literal_map_t filled_parameters = parameters;
7a24d422 6913
7a24d422 6914 string module_name;
ae2552da
FCE
6915 if (has_null_param (parameters, TOK_KERNEL))
6916 {
6917 dw = get_kern_dw(sess, "kernel");
6918 }
6919 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6920 {
c523a015
LB
6921 size_t dash_pos = 0;
6922 while((dash_pos=module_name.find('-'))!=string::npos)
6923 module_name.replace(int(dash_pos),1,"_");
6924 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6925 // NB: glob patterns get expanded later, during the offline
6926 // elfutils module listing.
ae2552da 6927 dw = get_kern_dw(sess, module_name);
b8da0ad1 6928 }
6d5d594e 6929 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6930 {
05fb3e0c 6931 module_name = sess.sysroot + module_name;
6d5d594e
LB
6932 if(has_null_param(filled_parameters, TOK_PROCESS))
6933 {
6934 wordexp_t words;
6935 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6936 if(rc || words.we_wordc <= 0)
dc09353a 6937 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without a -c COMMAND"));
05fb3e0c 6938 module_name = sess.sysroot + words.we_wordv[0];
6d5d594e
LB
6939 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6940 // in the case of TOK_MARK we need to modify locations as well
6941 if(location->components[0]->functor==TOK_PROCESS &&
6942 location->components[0]->arg == 0)
6943 location->components[0]->arg = new literal_string(module_name);
6944 wordfree (& words);
b78a0fbb 6945 }
5750ecc6 6946
37001baa
FCE
6947 // PR6456 process("/bin/*") glob handling
6948 if (contains_glob_chars (module_name))
6949 {
6950 // Expand glob via rewriting the probe-point process("....")
6951 // parameter, asserted to be the first one.
6952
6953 assert (location->components.size() > 0);
6954 assert (location->components[0]->functor == TOK_PROCESS);
6955 assert (location->components[0]->arg);
6956 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6957 assert (lit);
6958
6959 // Evaluate glob here, and call derive_probes recursively with each match.
6960 glob_t the_blob;
88f8e2c0 6961 set<string> dupes;
37001baa 6962 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 6963 if (rc)
dc09353a 6964 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 6965 unsigned results_pre = finished_results.size();
37001baa
FCE
6966 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6967 {
e19ebcf7 6968 assert_no_interrupts();
37001baa
FCE
6969
6970 const char* globbed = the_blob.gl_pathv[i];
6971 struct stat st;
6972
6973 if (access (globbed, X_OK) == 0
6974 && stat (globbed, &st) == 0
6975 && S_ISREG (st.st_mode)) // see find_executable()
6976 {
7977a734
FCE
6977 // Need to call canonicalize here, in order to path-expand
6978 // patterns like process("stap*"). Otherwise it may go through
6979 // to the next round of expansion as ("stap"), leading to a $PATH
6980 // search that's not consistent with the glob search already done.
5bca76a8
JS
6981 string canononicalized = resolve_path (globbed);
6982 globbed = canononicalized.c_str();
7977a734 6983
88f8e2c0
JS
6984 // The canonical names can result in duplication, for example
6985 // having followed symlinks that are common with shared
6986 // libraries. Filter those out.
6987 if (!dupes.insert(canononicalized).second)
6988 continue;
6989
37001baa
FCE
6990 // synthesize a new probe_point, with the glob-expanded string
6991 probe_point *pp = new probe_point (*location);
5750ecc6
FCE
6992 // PR13338: quote results to prevent recursion
6993 string eglobbed = escape_glob_chars (globbed);
6994
6995 if (sess.verbose > 1)
6996 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6997 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 6998 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 6999
37001baa 7000 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7001 new literal_string (eglobbed_tgt));
37001baa
FCE
7002 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7003 pp->components[0] = ppc;
7004
d885563b 7005 probe* new_probe = new probe (base, pp);
7977a734
FCE
7006
7007 // We override "optional = true" here, as if the
7008 // wildcarded probe point was given a "?" suffix.
7009
7010 // This is because wildcard probes will be expected
7011 // by users to apply only to some subset of the
7012 // matching binaries, in the sense of "any", rather
7013 // than "all", sort of similarly how
7014 // module("*").function("...") patterns work.
7015
7016 derive_probes (sess, new_probe, finished_results,
7017 true /* NB: not location->optional */ );
37001baa
FCE
7018 }
7019 }
7020
7021 globfree (& the_blob);
44ffe90c
JL
7022
7023 unsigned results_post = finished_results.size();
7024
7025 // Did we fail to find a function by name? Let's suggest
7026 // something!
7027 string func;
7028 if (results_pre == results_post
7029 && get_param(filled_parameters, TOK_FUNCTION, func)
7030 && !func.empty())
7031 {
7032 if (sess.verbose > 2)
7033 {
7034 clog << "suggesting functions from modules:" << endl;
7035 for (set<string>::const_iterator it = modules_seen.begin();
7036 it != modules_seen.end(); ++it)
7037 {
7038 clog << *it << endl;
7039 }
7040 }
0508c45f 7041 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7042 modules_seen.clear();
7043 if (!sugs.empty())
dc09353a 7044 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7045 "no match (similar functions: %s)",
7046 sugs.find(',') == string::npos,
7047 sugs.c_str()));
7048 }
40a70f52
JL
7049 else if (results_pre == results_post
7050 && get_param(filled_parameters, TOK_PLT, func)
7051 && !func.empty())
7052 {
7053 string sugs = suggest_plt_functions(sess, modules_seen, func);
7054 modules_seen.clear();
7055 if (!sugs.empty())
7056 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7057 "no match (similar functions: %s)",
7058 sugs.find(',') == string::npos,
7059 sugs.c_str()));
7060 }
44ffe90c 7061
37001baa
FCE
7062 return; // avoid falling through
7063 }
7064
5750ecc6
FCE
7065 // PR13338: unquote glob results
7066 module_name = unescape_glob_chars (module_name);
05fb3e0c 7067 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
7068
7069 // if the executable starts with "#!", we look for the interpreter of the script
7070 {
7071 ifstream script_file (user_path.c_str () );
7072
7073 if (script_file.good ())
7074 {
7075 string line;
7076
7077 getline (script_file, line);
7078
7079 if (line.compare (0, 2, "#!") == 0)
7080 {
7081 string path_head = line.substr(2);
7082
7083 // remove white spaces at the beginning of the string
7084 size_t p2 = path_head.find_first_not_of(" \t");
7085
7086 if (p2 != string::npos)
7087 {
7088 string path = path_head.substr(p2);
7089
7090 // remove white spaces at the end of the string
7091 p2 = path.find_last_not_of(" \t\n");
7092 if (string::npos != p2)
7093 path.erase(p2+1);
7094
8e13c1a1
RH
7095 // handle "#!/usr/bin/env" redirect
7096 size_t offset = 0;
7097 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7098 {
7099 offset = sizeof("/bin/env")-1;
7100 }
7101 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7102 {
7103 offset = sizeof("/usr/bin/env")-1;
7104 }
7105
7106 if (offset != 0)
7107 {
7108 size_t p3 = path.find_first_not_of(" \t", offset);
7109
7110 if (p3 != string::npos)
7111 {
7112 string env_path = path.substr(p3);
05fb3e0c
WF
7113 user_path = find_executable (env_path, sess.sysroot,
7114 sess.sysenv);
8e13c1a1
RH
7115 }
7116 }
7117 else
7118 {
05fb3e0c 7119 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7120 }
d1bcbe71
RH
7121
7122 struct stat st;
7123
7124 if (access (user_path.c_str(), X_OK) == 0
7125 && stat (user_path.c_str(), &st) == 0
7126 && S_ISREG (st.st_mode)) // see find_executable()
7127 {
7128 if (sess.verbose > 1)
b530b5b3
LB
7129 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7130 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7131
7132 assert (location->components.size() > 0);
7133 assert (location->components[0]->functor == TOK_PROCESS);
7134 assert (location->components[0]->arg);
7135 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7136 assert (lit);
7137
7138 // synthesize a new probe_point, with the expanded string
7139 probe_point *pp = new probe_point (*location);
05fb3e0c 7140 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7141 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7142 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7143 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7144 pp->components[0] = ppc;
7145
d885563b 7146 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7147
7148 derive_probes (sess, new_probe, finished_results);
7149
7150 script_file.close();
7151 return;
7152 }
7153 }
7154 }
7155 }
7156 script_file.close();
7157 }
7158
47e226ed 7159 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7160 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7161 {
7162 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7163 "LD_LIBRARY_PATH");
7164 if (module_name.find('/') == string::npos)
7165 // We didn't find user_lib so use iterate_over_libraries
7166 module_name = user_path;
7167 }
63b4fd14 7168 else
b642c901 7169 module_name = user_path; // canonicalize it
d0a7f5a9 7170
3667d615 7171 // uretprobes aren't available everywhere
536f1261 7172 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7173 {
3667d615
JS
7174 if (kernel_supports_inode_uprobes(sess) &&
7175 !kernel_supports_inode_uretprobes(sess))
dc09353a 7176 throw SEMANTIC_ERROR
3ffeaf3c 7177 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7178 }
3667d615 7179
f4000852
MW
7180 // There is a similar check in pass 4 (buildrun), but it is
7181 // needed here too to make sure alternatives for optional
7182 // (? or !) process probes are disposed and/or alternatives
7183 // are selected.
3667d615
JS
7184 if (!sess.runtime_usermode_p())
7185 check_process_probe_kernel_support(sess);
e34d5d13 7186
7a24d422
FCE
7187 // user-space target; we use one dwflpp instance per module name
7188 // (= program or shared library)
707bf35e 7189 dw = get_user_dw(sess, module_name);
c8959a29 7190 }
20c6c071 7191
1acfc030
JS
7192 assert(dw);
7193
5896cd05 7194 if (sess.verbose > 3)
b530b5b3 7195 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7196
a794dbeb
FCE
7197 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7198 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7199 {
51d6bda3 7200 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
7201 dw->iterate_over_modules(&query_module, &sdtq);
7202 return;
7a05f484 7203 }
20c6c071 7204
8f14e444 7205 unsigned results_pre = finished_results.size();
6d5d594e 7206 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7207
7208 // XXX: kernel.statement.absolute is a special case that requires no
7209 // dwfl processing. This code should be in a separate builder.
7a24d422 7210 if (q.has_kernel && q.has_absolute)
37ebca01 7211 {
4baf0e53 7212 // assert guru mode for absolute probes
37ebca01
FCE
7213 if (! q.base_probe->privileged)
7214 {
dc09353a 7215 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7216 q.base_probe->tok);
37ebca01
FCE
7217 }
7218
7219 // For kernel.statement(NUM).absolute probe points, we bypass
7220 // all the debuginfo stuff: We just wire up a
7221 // dwarf_derived_probe right here and now.
4baf0e53 7222 dwarf_derived_probe* p =
b8da0ad1
FCE
7223 new dwarf_derived_probe ("", "", 0, "kernel", "",
7224 q.statement_num_val, q.statement_num_val,
7225 q, 0);
37ebca01 7226 finished_results.push_back (p);
1a0dbc5a 7227 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7228 return;
7229 }
7230
51178501 7231 dw->iterate_over_modules(&query_module, &q);
8f14e444 7232
44ffe90c
JL
7233 // We need to update modules_seen with the modules we've visited
7234 modules_seen.insert(q.visited_modules.begin(),
7235 q.visited_modules.end());
8f14e444
FCE
7236
7237 // PR11553 special processing: .return probes requested, but
7238 // some inlined function instances matched.
7239 unsigned i_n_r = q.inlined_non_returnable.size();
7240 unsigned results_post = finished_results.size();
7241 if (i_n_r > 0)
7242 {
7243 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7244 {
7245 string quicklist;
7246 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7247 it != q.inlined_non_returnable.end();
7248 it++)
7249 {
7250 quicklist += " " + (*it);
7251 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7252 {
7253 quicklist += " ...";
7254 break;
7255 }
7256 }
c57ea854 7257
52c2652f 7258 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7259 "cannot probe .return of %u inlined functions %s",
52c2652f 7260 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7261 // There will be also a "no matches" semantic error generated.
7262 }
7263 if (sess.verbose > 1)
52c2652f
NMA
7264 clog << _NF("skipped .return probe of %u inlined function",
7265 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7266 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7267 {
7268 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7269 it != q.inlined_non_returnable.end();
7270 it++)
7271 clog << (*it) << " ";
7272 clog << endl;
7273 }
7274 } // i_n_r > 0
44ffe90c
JL
7275
7276 // Did we fail to find a function by name? Let's suggest something! We
7277 // need to check for optional because otherwise, we will be suggesting
7278 // things during intermediate results without including all the
7279 // possible functions. For example, process("/usr/bin/*").function
7280 // will go through here for each executable found (all labelled as
7281 // optionals). Similarly for library(glob) probes. TODO: find a
7282 // mechanism to have suggestions for optional probes as well when no
7283 // probes could be derived, e.g. probepoint1?, probepoint2 should
7284 // suggest for both 1 and 2 if both fail to resolve (maybe print as a
7285 // warning?). This may entails detecting the difference between script
7286 // optional probes and probes that are optional in recursive calls.
7287 string func;
7288 if (results_pre == results_post && !location->optional
7289 && get_param(filled_parameters, TOK_FUNCTION, func)
7290 && !func.empty())
7291 {
7292 if (sess.verbose > 2)
7293 {
7294 clog << "suggesting functions from modules:" << endl;
7295 for (set<string>::const_iterator it = modules_seen.begin();
7296 it != modules_seen.end(); ++it)
7297 clog << *it << endl;
7298 }
0508c45f 7299 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7300 modules_seen.clear();
7301 if (!sugs.empty())
7302 // Note that this error will not even be printed out if it is
7303 // exactly the same suggestion as a previous throw (since
7304 // print_error() filters out identical errors). Which makes
7305 // sense since it's possible that the user misspelled the same
7306 // function in different probes, in which case the first
7307 // suggestion is sufficient.
dc09353a 7308 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7309 "no match (similar functions: %s)",
7310 sugs.find(',') == string::npos,
7311 sugs.c_str()));
7312 }
40a70f52
JL
7313 else if (results_pre == results_post && !location->optional
7314 && get_param(filled_parameters, TOK_PLT, func)
7315 && !func.empty())
7316 {
7317 string sugs = suggest_plt_functions(sess, modules_seen, func);
7318 modules_seen.clear();
7319 if (!sugs.empty())
7320 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7321 "no match (similar functions: %s)",
7322 sugs.find(',') == string::npos,
7323 sugs.c_str()));
7324 }
44ffe90c
JL
7325 else if (results_pre != results_post)
7326 // Something was derived so we won't need to suggest something
7327 modules_seen.clear();
5f0a03a6
JK
7328}
7329
7330symbol_table::~symbol_table()
7331{
c9efa5c9 7332 delete_map(map_by_addr);
5f0a03a6
JK
7333}
7334
7335void
2867a2a1 7336symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7337 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7338{
ab91b232
JK
7339#ifdef __powerpc__
7340 // Map ".sys_foo" to "sys_foo".
7341 if (name[0] == '.')
7342 name++;
7343#endif
5f0a03a6
JK
7344 func_info *fi = new func_info();
7345 fi->addr = addr;
7346 fi->name = name;
ab91b232 7347 fi->weak = weak;
2867a2a1 7348 fi->descriptor = descriptor;
5f0a03a6
JK
7349 map_by_name[fi->name] = fi;
7350 // TODO: Use a multimap in case there are multiple static
7351 // functions with the same name?
1c6b77e5 7352 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7353}
7354
7355enum info_status
7356symbol_table::read_symbols(FILE *f, const string& path)
7357{
7358 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
7359 int ret;
2e67a43b
TM
7360 char *name = 0;
7361 char *mod = 0;
5f0a03a6
JK
7362 char type;
7363 unsigned long long addr;
7364 Dwarf_Addr high_addr = 0;
7365 int line = 0;
7366
62a4021d
FCE
7367#if __GLIBC__ >2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)
7368#define MS_FMT "%ms"
7369#else
7370#define MS_FMT "%as"
7371#endif
7372 // %ms (newer than %as) mallocs space for the string and stores its address.
7373 while ((ret = fscanf(f, "%llx %c " MS_FMT " [" MS_FMT, &addr, &type, &name, &mod)) > 0)
5f0a03a6 7374 {
2e67a43b
TM
7375 auto_free free_name(name);
7376 auto_free free_mod(mod);
5f0a03a6
JK
7377 line++;
7378 if (ret < 3)
7379 {
3d372d6b 7380 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 7381 line, path.c_str());
5f0a03a6
JK
7382 // Caller should delete symbol_table object.
7383 return info_absent;
7384 }
2e67a43b 7385 else if (ret > 3)
5f0a03a6
JK
7386 {
7387 // Modules are loaded above the kernel, so if we're getting
7388 // modules, we're done.
2e67a43b 7389 break;
5f0a03a6 7390 }
ab91b232 7391 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 7392 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
7393 }
7394
1c6b77e5 7395 if (map_by_addr.size() < 1)
5f0a03a6 7396 {
3d372d6b 7397 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 7398 path.c_str()) << endl;
5f0a03a6
JK
7399 return info_absent;
7400 }
7401 return info_present;
7402}
7403
7404// NB: This currently unused. We use get_from_elf() instead because
7405// that gives us raw addresses -- which we need for modules -- whereas
7406// nm provides the address relative to the beginning of the section.
7407enum info_status
83ca3872 7408symbol_table::read_from_elf_file(const string &path,
2713ea24 7409 systemtap_session &sess)
5f0a03a6 7410{
58502ae4
JS
7411 vector<string> cmd;
7412 cmd.push_back("/usr/bin/nm");
7413 cmd.push_back("-n");
7414 cmd.push_back("--defined-only");
7415 cmd.push_back("path");
7416
5f0a03a6 7417 FILE *f;
58502ae4
JS
7418 int child_fd;
7419 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
7420 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 7421 {
58502ae4 7422 // nm failures are detected by stap_waitpid
3d372d6b 7423 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 7424 path.c_str(), strerror(errno));
5f0a03a6
JK
7425 return info_absent;
7426 }
7427 enum info_status status = read_symbols(f, path);
58502ae4 7428 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 7429 {
2713ea24
CM
7430 if (status == info_present)
7431 sess.print_warning("nm cannot read symbol table from " + path);
5f0a03a6
JK
7432 return info_absent;
7433 }
7434 return status;
7435}
7436
7437enum info_status
83ca3872 7438symbol_table::read_from_text_file(const string& path,
2713ea24 7439 systemtap_session &sess)
5f0a03a6
JK
7440{
7441 FILE *f = fopen(path.c_str(), "r");
7442 if (!f)
7443 {
2713ea24 7444 sess.print_warning("cannot read symbol table from " + path + " -- " + strerror(errno));
5f0a03a6
JK
7445 return info_absent;
7446 }
7447 enum info_status status = read_symbols(f, path);
7448 (void) fclose(f);
7449 return status;
7450}
7451
46f7b6be 7452void
f98c6346 7453symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7454{
7455#ifdef __powerpc__
7456 /*
7457 * The .opd section contains function descriptors that can look
7458 * just like function entry points. For example, there's a function
7459 * descriptor called "do_exit" that links to the entry point ".do_exit".
7460 * Reject all symbols in .opd.
7461 */
7462 opd_section = SHN_UNDEF;
7463 Dwarf_Addr bias;
7464 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7465 ?: dwfl_module_getelf (mod, &bias));
7466 Elf_Scn* scn = 0;
7467 size_t shstrndx;
7468
7469 if (!elf)
7470 return;
fcc30d6d 7471 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7472 return;
7473 while ((scn = elf_nextscn(elf, scn)) != NULL)
7474 {
7475 GElf_Shdr shdr_mem;
7476 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7477 if (!shdr)
7478 continue;
7479 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7480 if (!strcmp(name, ".opd"))
7481 {
7482 opd_section = elf_ndxscn(scn);
7483 return;
7484 }
7485 }
7486#endif
7487}
7488
7489bool
7490symbol_table::reject_section(GElf_Word section)
7491{
7492 if (section == SHN_UNDEF)
7493 return true;
7494#ifdef __powerpc__
7495 if (section == opd_section)
7496 return true;
7497#endif
7498 return false;
7499}
7500
5f0a03a6
JK
7501enum info_status
7502symbol_table::get_from_elf()
7503{
7504 Dwarf_Addr high_addr = 0;
7505 Dwfl_Module *mod = mod_info->mod;
7506 int syments = dwfl_module_getsymtab(mod);
7507 assert(syments);
46f7b6be 7508 prepare_section_rejection(mod);
5f0a03a6
JK
7509 for (int i = 1; i < syments; ++i)
7510 {
7511 GElf_Sym sym;
ab91b232
JK
7512 GElf_Word section;
7513 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 7514 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7515 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 7516 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
7517 }
7518 return info_present;
7519}
7520
5f0a03a6
JK
7521func_info *
7522symbol_table::get_func_containing_address(Dwarf_Addr addr)
7523{
1c6b77e5
JS
7524 iterator_t iter = map_by_addr.upper_bound(addr);
7525 if (iter == map_by_addr.begin())
5f0a03a6 7526 return NULL;
2e67a43b 7527 else
1c6b77e5 7528 return (--iter)->second;
5f0a03a6
JK
7529}
7530
3d372d6b
SC
7531func_info *
7532symbol_table::get_first_func()
7533{
7534 iterator_t iter = map_by_addr.begin();
7535 return (iter)->second;
7536}
7537
5f0a03a6
JK
7538func_info *
7539symbol_table::lookup_symbol(const string& name)
7540{
7541 map<string, func_info*>::iterator i = map_by_name.find(name);
7542 if (i == map_by_name.end())
7543 return NULL;
7544 return i->second;
7545}
7546
7547Dwarf_Addr
7548symbol_table::lookup_symbol_address(const string& name)
7549{
7550 func_info *fi = lookup_symbol(name);
7551 if (fi)
7552 return fi->addr;
7553 return 0;
7554}
7555
ab91b232
JK
7556// This is the kernel symbol table. The kernel macro cond_syscall creates
7557// a weak symbol for each system call and maps it to sys_ni_syscall.
7558// For system calls not implemented elsewhere, this weak symbol shows up
7559// in the kernel symbol table. Following the precedent of dwarfful stap,
7560// we refuse to consider such symbols. Here we delete them from our
7561// symbol table.
7562// TODO: Consider generalizing this and/or making it part of blacklist
7563// processing.
7564void
7565symbol_table::purge_syscall_stubs()
7566{
7567 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7568 if (stub_addr == 0)
7569 return;
1c6b77e5 7570 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7571 for (iterator_t iter = purge_range.first;
7572 iter != purge_range.second;
1c6b77e5 7573 )
ab91b232 7574 {
1c6b77e5 7575 func_info *fi = iter->second;
2e67a43b 7576 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7577 {
2e67a43b 7578 map_by_name.erase(fi->name);
1c6b77e5 7579 map_by_addr.erase(iter++);
2e67a43b 7580 delete fi;
2e67a43b 7581 }
1c6b77e5
JS
7582 else
7583 iter++;
ab91b232
JK
7584 }
7585}
7586
5f0a03a6 7587void
d906ab9d 7588module_info::get_symtab(base_query *q)
5f0a03a6 7589{
1c6b77e5
JS
7590 if (symtab_status != info_unknown)
7591 return;
7592
5f0a03a6
JK
7593 sym_table = new symbol_table(this);
7594 if (!elf_path.empty())
7595 {
5f0a03a6
JK
7596 symtab_status = sym_table->get_from_elf();
7597 }
7598 else
7599 {
7600 assert(name == TOK_KERNEL);
ab3ed72d
DS
7601 symtab_status = info_absent;
7602 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
7603 }
7604 if (symtab_status == info_absent)
7605 {
7606 delete sym_table;
7607 sym_table = NULL;
7608 return;
7609 }
7610
ab91b232
JK
7611 if (name == TOK_KERNEL)
7612 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7613}
7614
1c6b77e5
JS
7615// update_symtab reconciles data between the elf symbol table and the dwarf
7616// function enumeration. It updates the symbol table entries with the dwarf
7617// die that describes the function, which also signals to query_module_symtab
7618// that a statement probe isn't needed. In return, it also adds aliases to the
7619// function table for names that share the same addr/die.
7620void
7621module_info::update_symtab(cu_function_cache_t *funcs)
7622{
7623 if (!sym_table)
7624 return;
7625
7626 cu_function_cache_t new_funcs;
7627
7628 for (cu_function_cache_t::iterator func = funcs->begin();
7629 func != funcs->end(); func++)
7630 {
7631 // optimization: inlines will never be in the symbol table
7632 if (dwarf_func_inline(&func->second) != 0)
6e6d9a3b
JL
7633 {
7634 inlined_funcs.insert(func->first);
7635 continue;
7636 }
1c6b77e5 7637
1ffb8bd1
JS
7638 // XXX We may want to make additional efforts to match mangled elf names
7639 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
7640 // missing, so we may also need to try matching by address. See also the
7641 // notes about _Z in dwflpp::iterate_over_functions().
7642
1c6b77e5
JS
7643 func_info *fi = sym_table->lookup_symbol(func->first);
7644 if (!fi)
7645 continue;
7646
7647 // iterate over all functions at the same address
7648 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
7649 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
7650 {
7651 // update this function with the dwarf die
7652 it->second->die = func->second;
7653
7654 // if this function is a new alias, then
7655 // save it to merge into the function cache
7656 if (it->second != fi)
b7478964 7657 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
7658 }
7659 }
7660
7661 // add all discovered aliases back into the function cache
7662 // NB: this won't replace any names that dwarf may have already found
7663 funcs->insert(new_funcs.begin(), new_funcs.end());
7664}
7665
5f0a03a6
JK
7666module_info::~module_info()
7667{
7668 if (sym_table)
7669 delete sym_table;
b55bc428
FCE
7670}
7671
935447c8 7672// ------------------------------------------------------------------------
888af770 7673// user-space probes
935447c8
DS
7674// ------------------------------------------------------------------------
7675
935447c8 7676
888af770 7677struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7678{
89ba3085
FCE
7679private:
7680 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 7681 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
7682 }
7683
cfcab6c7
JS
7684 void emit_module_maxuprobes (systemtap_session& s);
7685
2b69faaf
JS
7686 // Using our own utrace-based uprobes
7687 void emit_module_utrace_decls (systemtap_session& s);
7688 void emit_module_utrace_init (systemtap_session& s);
7689 void emit_module_utrace_exit (systemtap_session& s);
7690
7691 // Using the upstream inode-based uprobes
7692 void emit_module_inode_decls (systemtap_session& s);
7693 void emit_module_inode_init (systemtap_session& s);
7694 void emit_module_inode_exit (systemtap_session& s);
7695
3a894f7e
JS
7696 // Using the dyninst backend (via stapdyn)
7697 void emit_module_dyninst_decls (systemtap_session& s);
7698 void emit_module_dyninst_init (systemtap_session& s);
7699 void emit_module_dyninst_exit (systemtap_session& s);
7700
935447c8 7701public:
888af770 7702 void emit_module_decls (systemtap_session& s);
935447c8
DS
7703 void emit_module_init (systemtap_session& s);
7704 void emit_module_exit (systemtap_session& s);
7705};
7706
7707
888af770
FCE
7708void
7709uprobe_derived_probe::join_group (systemtap_session& s)
7710{
7711 if (! s.uprobe_derived_probes)
7712 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7713 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
7714 if (s.runtime_usermode_p())
7715 enable_dynprobes(s);
7716 else
4441e344 7717 enable_task_finder(s);
a96d1db0 7718
8a03658e 7719 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
7720 // signal staprun to load that module. If we're using the builtin
7721 // inode-uprobes, we still need to know that it is required.
8a03658e 7722 s.need_uprobes = true;
a96d1db0
DN
7723}
7724
888af770 7725
c0f84e7b
SC
7726void
7727uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7728{
7729 dwarf_derived_probe::getargs(arg_set);
7730 arg_set.insert(arg_set.end(), args.begin(), args.end());
7731}
7732
7733
7734void
7735uprobe_derived_probe::saveargs(int nargs)
7736{
7737 for (int i = 1; i <= nargs; i++)
7738 args.push_back("$arg" + lex_cast (i) + ":long");
7739}
7740
7741
2865d17a 7742void
42e38653 7743uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
7744{
7745 // These probes are allowed for unprivileged users, but only in the
7746 // context of processes which they own.
7747 emit_process_owner_assertion (o);
7748}
7749
7750
888af770 7751struct uprobe_builder: public derived_probe_builder
a96d1db0 7752{
888af770 7753 uprobe_builder() {}
2b69faaf 7754 virtual void build(systemtap_session & sess,
a96d1db0
DN
7755 probe * base,
7756 probe_point * location,
86bf665e 7757 literal_map_t const & parameters,
a96d1db0
DN
7758 vector<derived_probe *> & finished_results)
7759 {
888af770 7760 int64_t process, address;
a96d1db0 7761
2b69faaf 7762 if (kernel_supports_inode_uprobes(sess))
dc09353a 7763 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 7764
888af770 7765 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7766 (void) b1;
888af770 7767 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7768 (void) b2;
888af770
FCE
7769 bool rr = has_null_param (parameters, TOK_RETURN);
7770 assert (b1 && b2); // by pattern_root construction
a96d1db0 7771
0973d815 7772 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7773 }
7774};
7775
7776
7777void
cfcab6c7 7778uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 7779{
43241c44
FCE
7780 // We'll probably need at least this many:
7781 unsigned minuprobes = probes.size();
7782 // .. but we don't want so many that .bss is inflated (PR10507):
7783 unsigned uprobesize = 64;
7784 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7785 unsigned maxuprobes = maxuprobesmem / uprobesize;
7786
aaf7ffe8
FCE
7787 // Let's choose a value on the geometric middle. This should end up
7788 // between minuprobes and maxuprobes. It's OK if this number turns
7789 // out to be < minuprobes or > maxuprobes. At worst, we get a
7790 // run-time error of one kind (too few: missed uprobe registrations)
7791 // or another (too many: vmalloc errors at module load time).
7792 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7793
6d0f3f0c 7794 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7795 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7796 s.op->newline() << "#endif";
cfcab6c7
JS
7797}
7798
7799
7800void
7801uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
7802{
7803 if (probes.empty()) return;
7804 s.op->newline() << "/* ---- utrace uprobes ---- */";
7805 // If uprobes isn't in the kernel, pull it in from the runtime.
7806
7807 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7808 s.op->newline() << "#include <linux/uprobes.h>";
7809 s.op->newline() << "#else";
2ba1736a 7810 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
7811 s.op->newline() << "#endif";
7812 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7813 s.op->newline() << "#define UPROBES_API_VERSION 1";
7814 s.op->newline() << "#endif";
7815
7816 emit_module_maxuprobes (s);
a96d1db0 7817
cc52276b 7818 // Forward decls
2ba1736a 7819 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 7820
5e112f92
FCE
7821 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7822 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7823 // XXX: consider a slab cache or somesuch for stap_uprobes
7824 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 7825 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7826
89ba3085
FCE
7827 s.op->assert_0_indent();
7828
89ba3085
FCE
7829 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7830 // This means we process probes[] in two passes.
7831 map <string,unsigned> module_index;
7832 unsigned module_index_ctr = 0;
7833
cc52276b
WC
7834 // not const since embedded task_finder_target struct changes
7835 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7836 s.op->indent(1);
7837 for (unsigned i=0; i<probes.size(); i++)
7838 {
7839 uprobe_derived_probe *p = probes[i];
7840 string pbmkey = make_pbm_key (p);
7841 if (module_index.find (pbmkey) == module_index.end())
7842 {
7843 module_index[pbmkey] = module_index_ctr++;
7844
7845 s.op->newline() << "{";
7846 // NB: it's essential that make_pbm_key() use all of and
7847 // only the same fields as we're about to emit.
7848 s.op->line() << " .finder={";
1af100fc 7849 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 7850 if (p->pid != 0)
68910c97
JK
7851 s.op->line() << " .pid=" << p->pid << ",";
7852
7853 if (p->section == "") // .statement(addr).absolute
7854 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7855 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7856 {
7857 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7858 s.op->line() << " .callback=&stap_uprobe_process_found,";
7859 }
68910c97 7860 else if (p->section != ".absolute") // ET_DYN
89ba3085 7861 {
4ad95bbc
SC
7862 if (p->has_library)
7863 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7864 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7865 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7866 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7867 }
89ba3085 7868 s.op->line() << " },";
68910c97
JK
7869 if (p->module != "")
7870 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7871 s.op->line() << " },";
7872 }
c57ea854 7873 else
822a6a3d 7874 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7875 }
7876 s.op->newline(-1) << "};";
7877
7878 s.op->assert_0_indent();
7879
3689db05
SC
7880 unsigned pci;
7881 for (pci=0; pci<probes.size(); pci++)
7882 {
7883 // List of perf counters used by each probe
7884 // This list is an index into struct stap_perf_probe,
7885 uprobe_derived_probe *p = probes[pci];
698de6cc 7886 std::set<derived_probe*>::iterator pcii;
3689db05
SC
7887 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
7888 for (pcii = p->perf_counter_refs.begin();
7889 pcii != p->perf_counter_refs.end(); pcii++)
7890 {
7891 map<string, pair<string,derived_probe*> >::iterator it;
7892 unsigned i = 0;
7893 // Find the associated perf.counter probe
7894 for (it=s.perf_counters.begin() ;
7895 it != s.perf_counters.end(); it++, i++)
7896 if ((*it).second.second == (*pcii))
7897 break;
7898 s.op->line() << lex_cast(i) << ", ";
7899 }
7900 s.op->newline() << "};";
7901 }
7902
cc52276b
WC
7903 // NB: read-only structure
7904 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7905 s.op->indent(1);
888af770
FCE
7906 for (unsigned i =0; i<probes.size(); i++)
7907 {
7908 uprobe_derived_probe* p = probes[i];
7909 s.op->newline() << "{";
89ba3085
FCE
7910 string key = make_pbm_key (p);
7911 unsigned value = module_index[key];
759e1d76
FCE
7912 if (value != 0)
7913 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7914 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7915 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7916
038c38c6 7917 if (p->sdt_semaphore_addr != 0)
63b4fd14 7918 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7919 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 7920
0d049a1d 7921 // XXX: don't bother emit if array is empty
3689db05
SC
7922 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
7923 // List of perf counters used by a probe from above
0d049a1d 7924 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 7925
4ddb6dd0
JS
7926 if (p->has_return)
7927 s.op->line() << " .return_p=1,";
888af770
FCE
7928 s.op->line() << " },";
7929 }
7930 s.op->newline(-1) << "};";
a96d1db0 7931
89ba3085
FCE
7932 s.op->assert_0_indent();
7933
48e685da 7934 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7935 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7936 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7937 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7938 "stp_probe_type_uprobe");
0e090c74 7939 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7940 << "sup->spec_index >= " << probes.size() << ") {";
7941 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7942 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7943 s.op->newline() << "atomic_dec (&c->busy);";
7944 s.op->newline() << "goto probe_epilogue;";
7945 s.op->newline(-1) << "}";
d9aed31e 7946 s.op->newline() << "c->uregs = regs;";
e04b5d74 7947 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7948
7949 // Make it look like the IP is set as it would in the actual user
7950 // task when calling real probe handler. Reset IP regs on return, so
7951 // we don't confuse uprobes. PR10458
7952 s.op->newline() << "{";
7953 s.op->indent(1);
d9aed31e 7954 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7955 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7956 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7957 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7958 s.op->newline(-1) << "}";
7959
f887a8c9 7960 common_probe_entryfn_epilogue (s, true);
888af770 7961 s.op->newline(-1) << "}";
a96d1db0 7962
48e685da 7963 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7964 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7965 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7966 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7967 "stp_probe_type_uretprobe");
6dceb5c9 7968 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7969 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7970 << "sup->spec_index >= " << probes.size() << ") {";
7971 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7972 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7973 s.op->newline() << "atomic_dec (&c->busy);";
7974 s.op->newline() << "goto probe_epilogue;";
7975 s.op->newline(-1) << "}";
7976
d9aed31e 7977 s.op->newline() << "c->uregs = regs;";
e04b5d74 7978 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7979
7980 // Make it look like the IP is set as it would in the actual user
7981 // task when calling real probe handler. Reset IP regs on return, so
7982 // we don't confuse uprobes. PR10458
7983 s.op->newline() << "{";
7984 s.op->indent(1);
d9aed31e 7985 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7986 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7987 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7988 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7989 s.op->newline(-1) << "}";
7990
f887a8c9 7991 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
7992 s.op->newline(-1) << "}";
7993
89ba3085 7994 s.op->newline();
2ba1736a 7995 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 7996 s.op->newline();
888af770 7997}
935447c8
DS
7998
7999
888af770 8000void
2b69faaf 8001uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 8002{
888af770 8003 if (probes.empty()) return;
935447c8 8004
2b69faaf 8005 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 8006
01b05e2e 8007 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
8008 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
8009 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
8010 // NB: we assume the rest of the struct (specificaly, sup->up) is
8011 // initialized to zero. This is so that we can use
8012 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
8013 s.op->newline(-1) << "}";
8014 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 8015
89ba3085
FCE
8016 // Set up the task_finders
8017 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
8018 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 8019 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 8020 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 8021
5e112f92
FCE
8022 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
8023 // finders already registered, since mere registration does not
8024 // cause any utrace or memory allocation actions. That happens only
8025 // later, once the task finder engine starts running. So, for a
8026 // partial initialization requiring unwind, we need do nothing.
8027 s.op->newline() << "if (rc) break;";
a7a68293 8028
888af770
FCE
8029 s.op->newline(-1) << "}";
8030}
d0ea46ce 8031
d0a7f5a9 8032
888af770 8033void
2b69faaf 8034uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
8035{
8036 if (probes.empty()) return;
2b69faaf 8037 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 8038
6d0f3f0c
FCE
8039 // NB: there is no stap_unregister_task_finder_target call;
8040 // important stuff like utrace cleanups are done by
d41d451c
FCE
8041 // __stp_task_finder_cleanup() via stap_stop_task_finder().
8042 //
8043 // This function blocks until all callbacks are completed, so there
8044 // is supposed to be no possibility of any registration-related code starting
8045 // to run in parallel with our shutdown here. So we don't need to protect the
8046 // stap_uprobes[] array with the mutex.
d0a7f5a9 8047
01b05e2e 8048 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 8049 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 8050 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 8051 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 8052
8faa1fc5 8053 // PR10655: decrement that ENABLED semaphore
c116c31b 8054 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
8055 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
8056 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
8057 s.op->newline() << "struct task_struct *tsk;";
8058 s.op->newline() << "rcu_read_lock();";
6846cfc8 8059
86229a55
DS
8060 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
8061 // that the pid is always in the global namespace, not in any
8062 // private namespace.
8faa1fc5 8063 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
8064 // We'd like to call find_task_by_pid_ns() here, but it isn't
8065 // exported. So, we call what it calls...
8066 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
8067 s.op->newline() << "#else";
8068 s.op->newline() << " tsk = find_task_by_pid (pid);";
8069 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
8070
8071 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 8072 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 8073 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 8074 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 8075 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 8076 s.op->newline() << "#endif";
3c5b8e2b 8077 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 8078 s.op->newline(-1) << "}";
8faa1fc5
FCE
8079 // XXX: need to analyze possibility of race condition
8080 s.op->newline(-1) << "}";
8081 s.op->newline() << "rcu_read_unlock();";
8082 s.op->newline(-1) << "}";
6846cfc8 8083
3568f1dd
FCE
8084 s.op->newline() << "if (sups->return_p) {";
8085 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 8086 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 8087 s.op->newline() << "#endif";
80b4ad8b
FCE
8088 // NB: PR6829 does not change that we still need to unregister at
8089 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
8090 s.op->newline() << "unregister_uretprobe (& sup->urp);";
8091 s.op->newline(-1) << "} else {";
8092 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 8093 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
8094 s.op->newline() << "#endif";
8095 s.op->newline() << "unregister_uprobe (& sup->up);";
8096 s.op->newline(-1) << "}";
935447c8 8097
6d0f3f0c 8098 s.op->newline() << "sup->spec_index = -1;";
935447c8 8099
3568f1dd
FCE
8100 // XXX: uprobe missed counts?
8101
6d0f3f0c 8102 s.op->newline(-1) << "}";
935447c8 8103
5e112f92 8104 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8105}
8106
2b69faaf
JS
8107
8108void
8109uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8110{
8111 if (probes.empty()) return;
8112 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8113 emit_module_maxuprobes (s);
2ba1736a 8114 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8115
8116 // Write the probe handler.
79af55c3
JS
8117 s.op->newline() << "static int stapiu_probe_handler "
8118 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8119 s.op->newline(1);
2dbbd473
JS
8120
8121 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8122 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8123 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8124 probe_type);
8125
3bff6634 8126 s.op->newline() << "c->uregs = regs;";
e04b5d74 8127 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8128 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8129 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8130
f887a8c9 8131 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8132 s.op->newline() << "return 0;";
8133 s.op->newline(-1) << "}";
8134 s.op->assert_0_indent();
8135
8136 // Index of all the modules for which we need inodes.
8137 map<string, unsigned> module_index;
8138 unsigned module_index_ctr = 0;
8139
8140 // Discover and declare targets for each unique path.
cfcab6c7 8141 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8142 << "stap_inode_uprobe_targets[] = {";
8143 s.op->indent(1);
8144 for (unsigned i=0; i<probes.size(); i++)
8145 {
8146 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8147 const string key = make_pbm_key(p);
8148 if (module_index.find (key) == module_index.end())
2b69faaf 8149 {
cfcab6c7
JS
8150 module_index[key] = module_index_ctr++;
8151 s.op->newline() << "{";
8152 s.op->line() << " .finder={";
b78a0fbb 8153 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8154 if (p->pid != 0)
8155 s.op->line() << " .pid=" << p->pid << ",";
8156
8157 if (p->section == "") // .statement(addr).absolute XXX?
8158 s.op->line() << " .callback=&stapiu_process_found,";
8159 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8160 {
8161 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8162 s.op->line() << " .callback=&stapiu_process_found,";
8163 }
8164 else if (p->section != ".absolute") // ET_DYN
8165 {
8166 if (p->has_library)
8167 s.op->line() << " .procname=\"" << p->path << "\", ";
8168 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8169 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8170 s.op->line() << " .callback=&stapiu_process_munmap,";
8171 }
8172 s.op->line() << " },";
8173 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8174 s.op->line() << " },";
2b69faaf
JS
8175 }
8176 }
8177 s.op->newline(-1) << "};";
8178 s.op->assert_0_indent();
8179
8180 // Declare the actual probes.
3689db05
SC
8181 unsigned pci;
8182 for (pci=0; pci<probes.size(); pci++)
8183 {
8184 // List of perf counters used by each probe
8185 // This list is an index into struct stap_perf_probe,
8186 uprobe_derived_probe *p = probes[pci];
698de6cc 8187 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8188 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8189 for (pcii = p->perf_counter_refs.begin();
8190 pcii != p->perf_counter_refs.end(); pcii++)
8191 {
8192 map<string, pair<string,derived_probe*> >::iterator it;
8193 unsigned i = 0;
8194 // Find the associated perf.counter probe
4fa83377
SC
8195 for (it=s.perf_counters.begin() ;
8196 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8197 if ((*it).second.second == (*pcii))
8198 break;
8199 s.op->line() << lex_cast(i) << ", ";
8200 }
8201 s.op->newline() << "};";
8202 }
8203
cfcab6c7 8204 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8205 << "stap_inode_uprobe_consumers[] = {";
8206 s.op->indent(1);
8207 for (unsigned i=0; i<probes.size(); i++)
8208 {
8209 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8210 unsigned index = module_index[make_pbm_key(p)];
8211 s.op->newline() << "{";
79af55c3
JS
8212 if (p->has_return)
8213 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8214 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8215 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8216 if (p->sdt_semaphore_addr)
8217 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8218 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8219 // XXX: don't bother emit if array is empty
3689db05
SC
8220 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8221 // List of perf counters used by a probe from above
0d049a1d 8222 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8223 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8224 s.op->line() << " },";
2b69faaf
JS
8225 }
8226 s.op->newline(-1) << "};";
8227 s.op->assert_0_indent();
8228}
8229
8230
8231void
8232uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8233{
8234 if (probes.empty()) return;
8235 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8236 // Let stapiu_init() handle reporting errors by setting probe_point
8237 // to NULL.
8238 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8239 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8240 << "stap_inode_uprobe_targets, "
8241 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8242 << "stap_inode_uprobe_consumers, "
8243 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8244}
8245
8246
8247void
8248uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8249{
8250 if (probes.empty()) return;
8251 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8252 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8253 << "stap_inode_uprobe_targets, "
8254 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8255 << "stap_inode_uprobe_consumers, "
8256 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8257}
8258
8259
3a894f7e
JS
8260void
8261uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8262{
8263 if (probes.empty()) return;
8264 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8265 emit_module_maxuprobes (s);
e00f3fb7 8266 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8267
f31a77f5
DS
8268 // Let the dynprobe_derived_probe_group handle outputting targets
8269 // and probes. This allows us to merge different types of probes.
8270 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8271 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8272 {
8273 uprobe_derived_probe *p = probes[i];
e00f3fb7 8274
f31a77f5
DS
8275 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8276 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8277 common_probe_init(p));
3a894f7e 8278 }
874d38bf
JS
8279 // loc2c-generated code assumes pt_regs are available, so use this to make
8280 // sure we always have *something* for it to dereference...
f31a77f5 8281 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8282
3a894f7e
JS
8283 // Write the probe handler.
8284 // NB: not static, so dyninst can find it
8285 s.op->newline() << "int enter_dyninst_uprobe "
8286 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8287 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8288
8289 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8290 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8291 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8292 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8293 probe_type);
8294
874d38bf 8295 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8296 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8297 // XXX: once we have regs, check how dyninst sets the IP
8298 // XXX: the way that dyninst rewrites stuff is probably going to be
8299 // ... very confusing to our backtracer (at least if we stay in process)
8300 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8301 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8302 s.op->newline() << "return 0;";
8303 s.op->newline(-1) << "}";
3debb935 8304 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8305 s.op->assert_0_indent();
8306}
8307
8308
8309void
8310uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8311{
8312 if (probes.empty()) return;
8313
8314 /* stapdyn handles the dirty work via dyninst */
8315 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8316 s.op->newline() << "/* this section left intentionally blank */";
8317}
8318
8319
8320void
8321uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8322{
8323 if (probes.empty()) return;
8324
8325 /* stapdyn handles the dirty work via dyninst */
8326 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8327 s.op->newline() << "/* this section left intentionally blank */";
8328}
8329
8330
2b69faaf
JS
8331void
8332uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8333{
ac3af990 8334 if (s.runtime_usermode_p())
4441e344
JS
8335 emit_module_dyninst_decls (s);
8336 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8337 emit_module_inode_decls (s);
8338 else
8339 emit_module_utrace_decls (s);
8340}
8341
8342
8343void
8344uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8345{
ac3af990 8346 if (s.runtime_usermode_p())
4441e344
JS
8347 emit_module_dyninst_init (s);
8348 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8349 emit_module_inode_init (s);
8350 else
8351 emit_module_utrace_init (s);
8352}
8353
8354
8355void
8356uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8357{
ac3af990 8358 if (s.runtime_usermode_p())
4441e344
JS
8359 emit_module_dyninst_exit (s);
8360 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8361 emit_module_inode_exit (s);
8362 else
8363 emit_module_utrace_exit (s);
8364}
8365
8366
e6fe60e7
AM
8367// ------------------------------------------------------------------------
8368// Kprobe derived probes
8369// ------------------------------------------------------------------------
8370
4627ed58 8371static const string TOK_KPROBE("kprobe");
935447c8 8372
bae55db9 8373struct kprobe_derived_probe: public derived_probe
d0ea46ce 8374{
23dc94f6
DS
8375 kprobe_derived_probe (systemtap_session& sess,
8376 vector<derived_probe *> & results,
8377 probe *base,
bae55db9
JS
8378 probe_point *location,
8379 const string& name,
8380 int64_t stmt_addr,
8381 bool has_return,
8382 bool has_statement,
8383 bool has_maxactive,
b642c901
SC
8384 bool has_path,
8385 bool has_library,
8386 long maxactive_val,
8387 const string& path,
8388 const string& library
bae55db9
JS
8389 );
8390 string symbol_name;
8391 Dwarf_Addr addr;
8392 bool has_return;
8393 bool has_statement;
8394 bool has_maxactive;
b642c901
SC
8395 bool has_path;
8396 bool has_library;
bae55db9 8397 long maxactive_val;
b642c901
SC
8398 string path;
8399 string library;
bae55db9
JS
8400 bool access_var;
8401 void printsig (std::ostream &o) const;
8402 void join_group (systemtap_session& s);
8403};
d0ea46ce 8404
bae55db9
JS
8405struct kprobe_derived_probe_group: public derived_probe_group
8406{
8407private:
8408 multimap<string,kprobe_derived_probe*> probes_by_module;
8409 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8410
bae55db9
JS
8411public:
8412 void enroll (kprobe_derived_probe* probe);
8413 void emit_module_decls (systemtap_session& s);
8414 void emit_module_init (systemtap_session& s);
8415 void emit_module_exit (systemtap_session& s);
8416};
d0ea46ce 8417
23dc94f6
DS
8418struct kprobe_var_expanding_visitor: public var_expanding_visitor
8419{
8420 systemtap_session& sess;
8421 block *add_block;
8422 block *add_call_probe; // synthesized from .return probes with saved $vars
8423 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8424 bool has_return;
23dc94f6 8425
bd5b25e1 8426 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8427 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8428 add_block_tid(false), add_call_probe_tid(false),
8429 has_return(has_return) {}
23dc94f6
DS
8430
8431 void visit_entry_op (entry_op* e);
8432};
8433
8434
8435kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8436 vector<derived_probe *> & results,
8437 probe *base,
e6fe60e7 8438 probe_point *location,
b6371390 8439 const string& name,
e6fe60e7 8440 int64_t stmt_addr,
b6371390
JS
8441 bool has_return,
8442 bool has_statement,
8443 bool has_maxactive,
b642c901
SC
8444 bool has_path,
8445 bool has_library,
8446 long maxactive_val,
8447 const string& path,
8448 const string& library
b6371390 8449 ):
4c5d1300 8450 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 8451 symbol_name (name), addr (stmt_addr),
b6371390 8452 has_return (has_return), has_statement (has_statement),
b642c901
SC
8453 has_maxactive (has_maxactive), has_path (has_path),
8454 has_library (has_library),
8455 maxactive_val (maxactive_val),
8456 path (path), library (library)
e6fe60e7
AM
8457{
8458 this->tok = base->tok;
8459 this->access_var = false;
d0ea46ce 8460
e6fe60e7
AM
8461#ifndef USHRT_MAX
8462#define USHRT_MAX 32767
8463#endif
d0ea46ce 8464
46856d8d
JS
8465 // Expansion of $target variables in the probe body produces an error during
8466 // translate phase, since we're not using debuginfo
d0ea46ce 8467
e6fe60e7 8468 vector<probe_point::component*> comps;
46856d8d 8469 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8470
46856d8d
JS
8471 if (has_statement)
8472 {
9ea68eb9
JS
8473 comps.push_back (new probe_point::component(TOK_STATEMENT,
8474 new literal_number(addr, true)));
46856d8d
JS
8475 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8476 }
8477 else
8478 {
8479 size_t pos = name.find(':');
8480 if (pos != string::npos)
d0ea46ce 8481 {
46856d8d
JS
8482 string module = name.substr(0, pos);
8483 string function = name.substr(pos + 1);
8484 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8485 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8486 }
8487 else
8488 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8489 }
d0ea46ce 8490
b6371390
JS
8491 if (has_return)
8492 comps.push_back (new probe_point::component(TOK_RETURN));
8493 if (has_maxactive)
8494 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8495
bd5b25e1 8496 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8497 v.replace (this->body);
8498
8499 // If during target-variable-expanding the probe, we added a new block
8500 // of code, add it to the start of the probe.
8501 if (v.add_block)
8502 this->body = new block(v.add_block, this->body);
8503
8504 // If when target-variable-expanding the probe, we need to
8505 // synthesize a sibling function-entry probe. We don't go through
8506 // the whole probe derivation business (PR10642) that could lead to
8507 // wildcard/alias resolution, or for that dwarf-induced duplication.
8508 if (v.add_call_probe)
8509 {
8510 assert (has_return);
8511
8512 // We temporarily replace base.
8513 statement* old_body = base->body;
8514 base->body = v.add_call_probe;
8515
8516 derived_probe *entry_handler
8517 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8518 false, has_statement, has_maxactive,
8519 has_path, has_library, maxactive_val,
8520 path, library);
8521 results.push_back (entry_handler);
8522
8523 base->body = old_body;
8524 }
8525
e6fe60e7
AM
8526 this->sole_location()->components = comps;
8527}
d0ea46ce 8528
e6fe60e7
AM
8529void kprobe_derived_probe::printsig (ostream& o) const
8530{
8531 sole_location()->print (o);
8532 o << " /* " << " name = " << symbol_name << "*/";
8533 printsig_nested (o);
8534}
d0ea46ce 8535
e6fe60e7
AM
8536void kprobe_derived_probe::join_group (systemtap_session& s)
8537{
d0ea46ce 8538
e6fe60e7
AM
8539 if (! s.kprobe_derived_probes)
8540 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8541 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8542
e6fe60e7 8543}
d0ea46ce 8544
e6fe60e7
AM
8545void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8546{
8547 probes_by_module.insert (make_pair (p->symbol_name, p));
8548 // probes of same symbol should share single kprobe/kretprobe
8549}
d0ea46ce 8550
e6fe60e7
AM
8551void
8552kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8553{
8554 if (probes_by_module.empty()) return;
d0ea46ce 8555
e6fe60e7 8556 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8557
e6fe60e7
AM
8558 // Warn of misconfigured kernels
8559 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8560 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8561 s.op->newline() << "#endif";
8562 s.op->newline();
d0ea46ce 8563
f07c3b68 8564 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8565 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8566 s.op->newline() << "#endif";
8567
e6fe60e7 8568 // Forward declare the master entry functions
88747011 8569 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8570 s.op->line() << " struct pt_regs *regs);";
88747011 8571 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8572 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8573
e6fe60e7
AM
8574 // Emit an array of kprobe/kretprobe pointers
8575 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8576 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8577 s.op->newline() << "#endif";
d0ea46ce 8578
e6fe60e7 8579 // Emit the actual probe list.
d0ea46ce 8580
e6fe60e7
AM
8581 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8582 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8583 s.op->newline() << "#ifdef __ia64__";
8584 s.op->newline() << "struct kprobe dummy;";
8585 s.op->newline() << "#endif";
8586 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8587 // NB: bss!
d0ea46ce 8588
e6fe60e7
AM
8589 s.op->newline() << "static struct stap_dwarfless_probe {";
8590 s.op->newline(1) << "const unsigned return_p:1;";
8591 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8592 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8593 s.op->newline() << "unsigned registered_p:1;";
8594 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 8595
e6fe60e7
AM
8596 // Function Names are mostly small and uniform enough to justify putting
8597 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 8598
faea5e16
JS
8599 size_t symbol_string_name_max = 0;
8600 size_t symbol_string_name_tot = 0;
e6fe60e7 8601 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 8602 {
e6fe60e7
AM
8603 kprobe_derived_probe* p = it->second;
8604#define DOIT(var,expr) do { \
8605 size_t var##_size = (expr) + 1; \
8606 var##_max = max (var##_max, var##_size); \
8607 var##_tot += var##_size; } while (0)
e6fe60e7
AM
8608 DOIT(symbol_string_name, p->symbol_name.size());
8609#undef DOIT
6270adc1
MH
8610 }
8611
e6fe60e7
AM
8612#define CALCIT(var) \
8613 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 8614
e6fe60e7
AM
8615 CALCIT(symbol_string);
8616#undef CALCIT
6270adc1 8617
bd659351 8618 s.op->newline() << "unsigned long address;";
7c3e97f4 8619 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
8620 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
8621 s.op->indent(1);
6270adc1 8622
e6fe60e7
AM
8623 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
8624 {
8625 kprobe_derived_probe* p = it->second;
8626 s.op->newline() << "{";
8627 if (p->has_return)
8628 s.op->line() << " .return_p=1,";
6270adc1 8629
e6fe60e7
AM
8630 if (p->has_maxactive)
8631 {
8632 s.op->line() << " .maxactive_p=1,";
8633 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
8634 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
8635 }
6270adc1 8636
b350f56b
JS
8637 if (p->locations[0]->optional)
8638 s.op->line() << " .optional_p=1,";
8639
e6fe60e7 8640 if (p->has_statement)
c8d9d15e 8641 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 8642 else
c8d9d15e 8643 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 8644
faea5e16 8645 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 8646 s.op->line() << " },";
935447c8
DS
8647 }
8648
e6fe60e7 8649 s.op->newline(-1) << "};";
5d67b47c 8650
e6fe60e7
AM
8651 // Emit the kprobes callback function
8652 s.op->newline();
88747011 8653 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
8654 s.op->line() << " struct pt_regs *regs) {";
8655 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8656 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8657 // Check that the index is plausible
8658 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8659 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8660 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8661 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8662 s.op->line() << "];";
71db462b 8663 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8664 "stp_probe_type_kprobe");
d9aed31e 8665 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
8666
8667 // Make it look like the IP is set as it wouldn't have been replaced
8668 // by a breakpoint instruction when calling real probe handler. Reset
8669 // IP regs on return, so we don't confuse kprobes. PR10458
8670 s.op->newline() << "{";
8671 s.op->indent(1);
d9aed31e 8672 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8673 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 8674 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8675 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8676 s.op->newline(-1) << "}";
8677
f887a8c9 8678 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8679 s.op->newline() << "return 0;";
8680 s.op->newline(-1) << "}";
935447c8 8681
e6fe60e7
AM
8682 // Same for kretprobes
8683 s.op->newline();
88747011 8684 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
8685 s.op->line() << " struct pt_regs *regs) {";
8686 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 8687
e6fe60e7
AM
8688 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8689 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8690 // Check that the index is plausible
8691 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8692 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8693 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8694 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8695 s.op->line() << "];";
935447c8 8696
71db462b 8697 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8698 "stp_probe_type_kretprobe");
d9aed31e 8699 s.op->newline() << "c->kregs = regs;";
6dceb5c9 8700 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
8701
8702 // Make it look like the IP is set as it wouldn't have been replaced
8703 // by a breakpoint instruction when calling real probe handler. Reset
8704 // IP regs on return, so we don't confuse kprobes. PR10458
8705 s.op->newline() << "{";
8706 s.op->indent(1);
d9aed31e 8707 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8708 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 8709 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8710 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8711 s.op->newline(-1) << "}";
8712
f887a8c9 8713 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8714 s.op->newline() << "return 0;";
8715 s.op->newline(-1) << "}";
bd659351 8716
03a4ec63 8717 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8718 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
8719 s.op->newline() << " struct module *owner,";
8720 s.op->newline() << " unsigned long val) {";
8721 s.op->newline(1) << "int i;";
fc1d2aa2
MW
8722 s.op->newline() << "int *p = (int *) data;";
8723 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
8724 << " && *p > 0; i++) {";
bd659351 8725 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
8726 s.op->newline() << "if (! sdp->address) {";
8727 s.op->indent(1);
8728 s.op->newline() << "const char *colon;";
8729 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
8730 s.op->indent(1);
8731 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
8732 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
8733 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
8734 s.op->newline(1) << "sdp->address = val;";
8735 s.op->newline() << "(*p)--;";
8736 s.op->newline(-1) << "}";
8737 s.op->newline(-1) << "}";
8738 s.op->newline() << "else {";
fc1d2aa2 8739 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 8740 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
8741 s.op->newline() << "(*p)--;";
8742 s.op->newline(-1) << "}";
8c272819
YW
8743 s.op->newline(-1) << "}";
8744 s.op->newline(-1) << "}";
8745 s.op->newline(-1) << "}";
fc1d2aa2 8746 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 8747 s.op->newline(-1) << "}";
03a4ec63 8748 s.op->newline() << "#endif";
935447c8
DS
8749}
8750
e6fe60e7 8751
6270adc1 8752void
e6fe60e7 8753kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 8754{
03a4ec63 8755 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
8756 s.op->newline() << "{";
8757 s.op->newline(1) << "int p = 0;";
8758 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
8759 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8760 s.op->newline() << "if (! sdp->address)";
8761 s.op->newline(1) << "p++;";
8762 s.op->newline(-2) << "}";
8763 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
8764 s.op->newline(-1) << "}";
03a4ec63 8765 s.op->newline() << "#endif";
bd659351 8766
e6fe60e7 8767 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 8768 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 8769 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 8770 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
8771 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
8772
8773 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8774 s.op->newline() << "if (! addr) {";
8775 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
8776 s.op->newline() << "if (!sdp->optional_p)";
8777 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
8778 s.op->newline(-1) << "continue;";
bd659351 8779 s.op->newline(-1) << "}";
03a4ec63
MW
8780 s.op->newline() << "#endif";
8781
26e63673 8782 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 8783 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 8784 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 8785 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8786 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 8787 s.op->newline() << "#endif";
e6fe60e7
AM
8788 s.op->newline() << "if (sdp->maxactive_p) {";
8789 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
8790 s.op->newline(-1) << "} else {";
f07c3b68 8791 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 8792 s.op->newline(-1) << "}";
88747011 8793 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
8794 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
8795 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8796 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 8797 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8798 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 8799 s.op->newline() << "#endif";
c8d9d15e 8800 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
8801 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8802 s.op->newline() << "if (rc == 0) {";
8803 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
8804 s.op->newline() << "if (rc != 0)";
8805 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8806 s.op->newline(-2) << "}";
8807 s.op->newline() << "#else";
8808 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
8809 s.op->newline() << "#endif";
8810 s.op->newline(-1) << "} else {";
8811 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 8812 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 8813 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8814 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 8815 s.op->newline() << "#endif";
88747011 8816 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 8817 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8818 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 8819 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 8820 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8821 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 8822 s.op->newline() << "#endif";
e6fe60e7
AM
8823 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8824 s.op->newline() << "if (rc == 0) {";
8825 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
8826 s.op->newline() << "if (rc != 0)";
8827 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8828 s.op->newline(-2) << "}";
8829 s.op->newline() << "#else";
8830 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
8831 s.op->newline() << "#endif";
8832 s.op->newline(-1) << "}";
8833 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
8834 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 8835 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 8836 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 8837 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
8838 // XXX: shall we increment numskipped?
8839 s.op->newline(-1) << "}";
6270adc1 8840
e6fe60e7
AM
8841 s.op->newline() << "else sdp->registered_p = 1;";
8842 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
8843}
8844
b4be7cbc 8845
e6fe60e7
AM
8846void
8847kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 8848{
e6fe60e7
AM
8849 //Unregister kprobes by batch interfaces.
8850 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
8851 s.op->newline() << "j = 0;";
8852 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8853 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8854 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8855 s.op->newline() << "if (! sdp->registered_p) continue;";
8856 s.op->newline() << "if (!sdp->return_p)";
c9116e99 8857 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 8858 s.op->newline(-2) << "}";
c9116e99 8859 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8860 s.op->newline() << "j = 0;";
8861 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8862 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8863 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8864 s.op->newline() << "if (! sdp->registered_p) continue;";
8865 s.op->newline() << "if (sdp->return_p)";
c9116e99 8866 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 8867 s.op->newline(-2) << "}";
c9116e99 8868 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8869 s.op->newline() << "#ifdef __ia64__";
8870 s.op->newline() << "j = 0;";
8871 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8872 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8873 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8874 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 8875 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 8876 s.op->newline(-1) << "}";
c9116e99 8877 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8878 s.op->newline() << "#endif";
8879 s.op->newline() << "#endif";
3e3bd7b6 8880
e6fe60e7
AM
8881 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8882 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8883 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8884 s.op->newline() << "if (! sdp->registered_p) continue;";
8885 s.op->newline() << "if (sdp->return_p) {";
8886 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8887 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
8888 s.op->newline() << "#endif";
065d5567 8889 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
8890 s.op->newline() << "#ifdef STP_TIMING";
8891 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 8892 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 8893 s.op->newline(-1) << "#endif";
065d5567 8894 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
8895 s.op->newline() << "#ifdef STP_TIMING";
8896 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 8897 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
8898 s.op->newline(-1) << "#endif";
8899 s.op->newline(-1) << "} else {";
8900 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8901 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
8902 s.op->newline() << "#endif";
065d5567 8903 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
8904 s.op->newline() << "#ifdef STP_TIMING";
8905 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 8906 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
8907 s.op->newline(-1) << "#endif";
8908 s.op->newline(-1) << "}";
8909 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
8910 s.op->newline() << "unregister_kprobe (&kp->dummy);";
8911 s.op->newline() << "#endif";
8912 s.op->newline() << "sdp->registered_p = 0;";
8913 s.op->newline(-1) << "}";
f8a968bc
JS
8914}
8915
e6fe60e7 8916struct kprobe_builder: public derived_probe_builder
3c1b3d06 8917{
9fdf787d 8918public:
2a639817 8919 kprobe_builder() {}
9fdf787d 8920
2a639817 8921 void build_no_more (systemtap_session &s) {}
9fdf787d 8922
e6fe60e7
AM
8923 virtual void build(systemtap_session & sess,
8924 probe * base,
8925 probe_point * location,
8926 literal_map_t const & parameters,
8927 vector<derived_probe *> & finished_results);
8928};
3c1b3d06
FCE
8929
8930
79189b84 8931void
05fb3e0c 8932kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
8933 probe * base,
8934 probe_point * location,
8935 literal_map_t const & parameters,
8936 vector<derived_probe *> & finished_results)
79189b84 8937{
e6fe60e7 8938 string function_string_val, module_string_val;
05fb3e0c 8939 string path, library, path_tgt, library_tgt;
b6371390
JS
8940 int64_t statement_num_val = 0, maxactive_val = 0;
8941 bool has_function_str, has_module_str, has_statement_num;
8942 bool has_absolute, has_return, has_maxactive;
b642c901 8943 bool has_path, has_library;
79189b84 8944
b6371390
JS
8945 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
8946 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
8947 has_return = has_null_param (parameters, TOK_RETURN);
8948 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
8949 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
8950 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
8951 has_path = get_param (parameters, TOK_PROCESS, path);
8952 has_library = get_param (parameters, TOK_LIBRARY, library);
8953
8954 if (has_path)
05fb3e0c
WF
8955 {
8956 path = find_executable (path, sess.sysroot, sess.sysenv);
8957 path_tgt = path_remove_sysroot(sess, path);
8958 }
b642c901 8959 if (has_library)
05fb3e0c
WF
8960 {
8961 library = find_executable (library, sess.sysroot, sess.sysenv,
8962 "LD_LIBRARY_PATH");
8963 library_tgt = path_remove_sysroot(sess, library);
8964 }
c57ea854 8965
b6371390 8966 if (has_function_str)
6fb70fb7 8967 {
2a639817 8968 if (has_module_str)
9fdf787d
DS
8969 {
8970 function_string_val = module_string_val + ":" + function_string_val;
8971 derived_probe *dp
23dc94f6
DS
8972 = new kprobe_derived_probe (sess, finished_results, base,
8973 location, function_string_val,
9fdf787d
DS
8974 0, has_return, has_statement_num,
8975 has_maxactive, has_path, has_library,
8976 maxactive_val, path_tgt, library_tgt);
8977 finished_results.push_back (dp);
8978 }
8979 else
8980 {
2a639817
JS
8981 vector<string> matches;
8982
8983 // Simple names can be found directly
8984 if (function_string_val.find_first_of("*?[") == string::npos)
8985 {
8986 if (sess.kernel_functions.count(function_string_val))
8987 matches.push_back(function_string_val);
8988 }
8989 else // Search function name list for matching names
8990 {
8991 for (set<string>::const_iterator it = sess.kernel_functions.begin();
8992 it != sess.kernel_functions.end(); it++)
8993 // fnmatch returns zero for matching.
8994 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
8995 matches.push_back(*it);
8996 }
86758d5f 8997
2a639817
JS
8998 for (vector<string>::const_iterator it = matches.begin();
8999 it != matches.end(); it++)
9fdf787d 9000 {
2a639817
JS
9001 derived_probe *dp
9002 = new kprobe_derived_probe (sess, finished_results, base,
9003 location, *it, 0, has_return,
9004 has_statement_num,
9005 has_maxactive, has_path,
9006 has_library, maxactive_val,
9007 path_tgt, library_tgt);
9008 finished_results.push_back (dp);
9fdf787d
DS
9009 }
9010 }
6fb70fb7 9011 }
e6fe60e7 9012 else
b6371390
JS
9013 {
9014 // assert guru mode for absolute probes
9015 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 9016 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 9017
23dc94f6
DS
9018 finished_results.push_back (new kprobe_derived_probe (sess,
9019 finished_results,
9020 base,
b6371390
JS
9021 location, "",
9022 statement_num_val,
9023 has_return,
9024 has_statement_num,
9025 has_maxactive,
b642c901
SC
9026 has_path,
9027 has_library,
9028 maxactive_val,
05fb3e0c
WF
9029 path_tgt,
9030 library_tgt));
96b030fe 9031 }
79189b84
JS
9032}
9033
23dc94f6
DS
9034
9035void
9036kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
9037{
9038 expression *repl = e;
9039
bd5b25e1
JS
9040 if (has_return)
9041 {
9042 // expand the operand as if it weren't a return probe
9043 has_return = false;
9044 replace (e->operand);
9045 has_return = true;
23dc94f6 9046
bd5b25e1
JS
9047 // XXX it would be nice to use gen_kretprobe_saved_return when
9048 // available, but it requires knowing the types already, which is
9049 // problematic for arbitrary expressons.
9050 repl = gen_mapped_saved_return (sess, e->operand, "entry",
9051 add_block, add_block_tid,
9052 add_call_probe, add_call_probe_tid);
9053 }
23dc94f6
DS
9054 provide (repl);
9055}
9056
9057
dd225250
PS
9058// ------------------------------------------------------------------------
9059// Hardware breakpoint based probes.
9060// ------------------------------------------------------------------------
9061
9062static const string TOK_HWBKPT("data");
9063static const string TOK_HWBKPT_WRITE("write");
9064static const string TOK_HWBKPT_RW("rw");
9065static const string TOK_LENGTH("length");
9066
9067#define HWBKPT_READ 0
9068#define HWBKPT_WRITE 1
9069#define HWBKPT_RW 2
9070struct hwbkpt_derived_probe: public derived_probe
9071{
9072 hwbkpt_derived_probe (probe *base,
9073 probe_point *location,
9074 uint64_t addr,
9075 string symname,
9076 unsigned int len,
9077 bool has_only_read_access,
9078 bool has_only_write_access,
9079 bool has_rw_access
9080 );
9081 Dwarf_Addr hwbkpt_addr;
9082 string symbol_name;
9083 unsigned int hwbkpt_access,hwbkpt_len;
9084
9085 void printsig (std::ostream &o) const;
9086 void join_group (systemtap_session& s);
9087};
9088
9089struct hwbkpt_derived_probe_group: public derived_probe_group
9090{
dd225250 9091private:
dac77b80 9092 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
9093
9094public:
9095 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
9096 void emit_module_decls (systemtap_session& s);
9097 void emit_module_init (systemtap_session& s);
9098 void emit_module_exit (systemtap_session& s);
9099};
9100
9101hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
9102 probe_point *location,
9103 uint64_t addr,
9104 string symname,
9105 unsigned int len,
9106 bool has_only_read_access,
9107 bool has_only_write_access,
822a6a3d 9108 bool):
4c5d1300 9109 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9110 hwbkpt_addr (addr),
9111 symbol_name (symname),
9112 hwbkpt_len (len)
9113{
9114 this->tok = base->tok;
9115
9116 vector<probe_point::component*> comps;
9117 comps.push_back (new probe_point::component(TOK_KERNEL));
9118
9119 if (hwbkpt_addr)
9ea68eb9
JS
9120 comps.push_back (new probe_point::component (TOK_HWBKPT,
9121 new literal_number(hwbkpt_addr, true)));
9122 else if (symbol_name.size())
9123 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9124
9125 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9126
9127 if (has_only_read_access)
9ea68eb9 9128 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9129//TODO add code for comps.push_back for read, since this flag is not for x86
9130
9131 else
9ea68eb9
JS
9132 {
9133 if (has_only_write_access)
9134 {
9135 this->hwbkpt_access = HWBKPT_WRITE ;
9136 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9137 }
9138 else
9139 {
9140 this->hwbkpt_access = HWBKPT_RW ;
9141 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9142 }
9143 }
dd225250
PS
9144
9145 this->sole_location()->components = comps;
9146}
9147
9148void hwbkpt_derived_probe::printsig (ostream& o) const
9149{
9150 sole_location()->print (o);
9151 printsig_nested (o);
9152}
9153
9154void hwbkpt_derived_probe::join_group (systemtap_session& s)
9155{
dac77b80
FCE
9156 if (! s.hwbkpt_derived_probes)
9157 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9158 s.hwbkpt_derived_probes->enroll (this, s);
9159}
9160
9161void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9162{
dac77b80
FCE
9163 hwbkpt_probes.push_back (p);
9164
9165 unsigned max_hwbkpt_probes_by_arch = 0;
9166 if (s.architecture == "i386" || s.architecture == "x86_64")
9167 max_hwbkpt_probes_by_arch = 4;
9168 else if (s.architecture == "s390")
9169 max_hwbkpt_probes_by_arch = 1;
9170
c57ea854 9171 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9172 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9173 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9174}
9175
9176void
9177hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9178{
dac77b80 9179 if (hwbkpt_probes.empty()) return;
dd225250
PS
9180
9181 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9182
9183 s.op->newline() << "#include <linux/perf_event.h>";
9184 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9185 s.op->newline();
9186
9187 // Forward declare the master entry functions
23063de1 9188 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9189 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9190 s.op->line() << " int nmi,";
9191 s.op->line() << " struct perf_sample_data *data,";
9192 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9193 s.op->newline() << "#else";
9194 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9195 s.op->line() << " struct perf_sample_data *data,";
9196 s.op->line() << " struct pt_regs *regs);";
9197 s.op->newline() << "#endif";
79189b84 9198
dd225250
PS
9199 // Emit the actual probe list.
9200
9201 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9202 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9203
9204 s.op->newline() << "static struct perf_event **";
dac77b80 9205 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9206 s.op->newline() << "static struct stap_hwbkpt_probe {";
9207 s.op->newline() << "int registered_p:1;";
43650b10 9208// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9209// registered_p = 1 signifies a probe that got registered successfully
9210
faea5e16 9211 // Symbol Names are mostly small and uniform enough
dd225250 9212 // to justify putting const char*.
dac77b80 9213 s.op->newline() << "const char * const symbol;";
dd225250
PS
9214
9215 s.op->newline() << "const unsigned long address;";
9216 s.op->newline() << "uint8_t atype;";
bb0a4e12 9217 s.op->newline() << "unsigned int len;";
7c3e97f4 9218 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9219 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9220 s.op->indent(1);
9221
dac77b80 9222 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9223 {
dac77b80 9224 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9225 s.op->newline() << "{";
dd225250
PS
9226 if (p->symbol_name.size())
9227 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9228 else
9229 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9230 switch(p->hwbkpt_access){
9231 case HWBKPT_READ:
9232 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9233 break;
dd225250
PS
9234 case HWBKPT_WRITE:
9235 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9236 break;
dd225250
PS
9237 case HWBKPT_RW:
9238 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9239 break;
dd225250
PS
9240 };
9241 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9242 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9243 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9244 s.op->line() << " },";
9245 }
dac77b80 9246 s.op->newline(-1) << "};";
dd225250
PS
9247
9248 // Emit the hwbkpt callback function
9249 s.op->newline() ;
23063de1 9250 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9251 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9252 s.op->line() << " int nmi,";
9253 s.op->line() << " struct perf_sample_data *data,";
9254 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9255 s.op->newline() << "#else";
9256 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9257 s.op->line() << " struct perf_sample_data *data,";
9258 s.op->line() << " struct pt_regs *regs) {";
9259 s.op->newline() << "#endif";
dac77b80
FCE
9260 s.op->newline(1) << "unsigned int i;";
9261 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9262 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9263 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9264 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9265 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) {";
9266 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9267 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9268 "stp_probe_type_hwbkpt");
d9aed31e 9269 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9270 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9271 s.op->newline() << "c->uregs = regs;";
9272 s.op->newline(-1) << "} else {";
9273 s.op->newline(1) << "c->kregs = regs;";
9274 s.op->newline(-1) << "}";
26e63673 9275 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9276 common_probe_entryfn_epilogue (s, true);
dac77b80 9277 s.op->newline(-1) << "}";
dd225250
PS
9278 s.op->newline(-1) << "}";
9279 s.op->newline() << "return 0;";
dac77b80 9280 s.op->newline(-1) << "}";
dd225250
PS
9281}
9282
9283void
9284hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9285{
dac77b80 9286 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9287 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9288 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9289 s.op->newline() << "void *addr = (void *) sdp->address;";
9290 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9291 s.op->newline() << "hw_breakpoint_init(hp);";
9292 s.op->newline() << "if (addr)";
9293 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9294 s.op->newline(-1) << "else { ";
9295 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9296 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9297 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9298 s.op->newline() << "continue;";
9299 s.op->newline(-1) << "}";
9300 s.op->newline(-1) << "}";
9301 s.op->newline() << "hp->bp_type = sdp->atype;";
9302
9303 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9304 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9305 {
9306 s.op->newline() << "switch(sdp->len) {";
9307 s.op->newline() << "case 1:";
9308 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9309 s.op->newline() << "break;";
9310 s.op->newline(-1) << "case 2:";
9311 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9312 s.op->newline() << "break;";
9313 s.op->newline(-1) << "case 3:";
9314 s.op->newline() << "case 4:";
9315 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9316 s.op->newline() << "break;";
9317 s.op->newline(-1) << "case 5:";
9318 s.op->newline() << "case 6:";
9319 s.op->newline() << "case 7:";
9320 s.op->newline() << "case 8:";
9321 s.op->newline() << "default:"; // XXX: could instead reject
9322 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9323 s.op->newline() << "break;";
9324 s.op->newline(-1) << "}";
9325 }
9326 else // other architectures presumed straightforward
9327 s.op->newline() << "hp->bp_len = sdp->len;";
9328
26e63673 9329 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9330 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9331 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9332 s.op->newline() << "#else";
dac77b80 9333 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9334 s.op->newline() << "#endif";
43650b10 9335 s.op->newline() << "rc = 0;";
dac77b80 9336 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9337 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9338 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9339 s.op->newline(-1) << "}";
217ef1f4
WC
9340 s.op->newline() << "if (rc) {";
9341 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9342 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9343 s.op->newline(-1) << "}";
dd225250 9344 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9345 s.op->newline(-1) << "}"; // for loop
9346}
9347
9348void
9349hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9350{
9351 //Unregister hwbkpt probes.
dac77b80 9352 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9353 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9354 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9355 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9356 s.op->newline() << "sdp->registered_p = 0;";
9357 s.op->newline(-1) << "}";
9358}
9359
9360struct hwbkpt_builder: public derived_probe_builder
9361{
9362 hwbkpt_builder() {}
9363 virtual void build(systemtap_session & sess,
9364 probe * base,
9365 probe_point * location,
9366 literal_map_t const & parameters,
9367 vector<derived_probe *> & finished_results);
9368};
9369
9370void
9371hwbkpt_builder::build(systemtap_session & sess,
9372 probe * base,
9373 probe_point * location,
9374 literal_map_t const & parameters,
9375 vector<derived_probe *> & finished_results)
9376{
9377 string symbol_str_val;
9378 int64_t hwbkpt_address, len;
9379 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9380
b47f3a55 9381 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9382 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9383 location->components[0]->tok);
9384 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9385 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9386 location->components[0]->tok);
9387
dd225250
PS
9388 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9389 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9390 has_len = get_param (parameters, TOK_LENGTH, len);
9391 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9392 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9393
9394 if (!has_len)
9395 len = 1;
9396
9397 if (has_addr)
9398 finished_results.push_back (new hwbkpt_derived_probe (base,
9399 location,
9400 hwbkpt_address,
9401 "",len,0,
9402 has_write,
9403 has_rw));
5d8a0aea 9404 else if (has_symbol_str)
dd225250
PS
9405 finished_results.push_back (new hwbkpt_derived_probe (base,
9406 location,
9407 0,
9408 symbol_str_val,len,0,
9409 has_write,
9410 has_rw));
5d8a0aea
FCE
9411 else
9412 assert (0);
dd225250 9413}
342d3f96 9414
0a6f5a3f
JS
9415// ------------------------------------------------------------------------
9416// statically inserted kernel-tracepoint derived probes
9417// ------------------------------------------------------------------------
9418
6fb70fb7 9419struct tracepoint_arg
79189b84 9420{
ad370dcc 9421 string name, c_type, typecast;
dcaa1a65 9422 bool usable, used, isptr;
f8a968bc 9423 Dwarf_Die type_die;
dcaa1a65 9424 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9425};
79189b84 9426
0a6f5a3f
JS
9427struct tracepoint_derived_probe: public derived_probe
9428{
79189b84
JS
9429 tracepoint_derived_probe (systemtap_session& s,
9430 dwflpp& dw, Dwarf_Die& func_die,
9431 const string& tracepoint_name,
9432 probe* base_probe, probe_point* location);
bc9a523d 9433
79189b84 9434 systemtap_session& sess;
6fb70fb7
JS
9435 string tracepoint_name, header;
9436 vector <struct tracepoint_arg> args;
bc9a523d 9437
6fb70fb7 9438 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9439 void getargs (std::list<std::string> &arg_set) const;
79189b84 9440 void join_group (systemtap_session& s);
3e3bd7b6 9441 void print_dupe_stamp(ostream& o);
0a6f5a3f 9442};
79189b84
JS
9443
9444
0a6f5a3f 9445struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9446{
79189b84
JS
9447 void emit_module_decls (systemtap_session& s);
9448 void emit_module_init (systemtap_session& s);
9449 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9450};
79189b84 9451
bc9a523d 9452
f8a968bc
JS
9453struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9454{
9455 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9456 vector <struct tracepoint_arg>& args):
9457 dw (dw), probe_name (probe_name), args (args) {}
9458 dwflpp& dw;
9459 const string& probe_name;
9460 vector <struct tracepoint_arg>& args;
bc9a523d 9461
f8a968bc
JS
9462 void visit_target_symbol (target_symbol* e);
9463 void visit_target_symbol_arg (target_symbol* e);
9464 void visit_target_symbol_context (target_symbol* e);
9465};
79189b84
JS
9466
9467
f8a968bc
JS
9468void
9469tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9470{
cc9001af 9471 string argname = e->sym_name();
75ead1f7 9472
f8a968bc
JS
9473 // search for a tracepoint parameter matching this name
9474 tracepoint_arg *arg = NULL;
9475 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9476 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9477 {
9478 arg = &args[i];
9479 arg->used = true;
9480 break;
9481 }
75ead1f7 9482
f8a968bc
JS
9483 if (arg == NULL)
9484 {
1d0499c2 9485 set<string> vars;
f8a968bc 9486 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
9487 vars.insert("$" + args[i].name);
9488 vars.insert("$$name");
9489 vars.insert("$$parms");
9490 vars.insert("$$vars");
9491 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 9492
f8a968bc
JS
9493 // We hope that this value ends up not being referenced after all, so it
9494 // can be optimized out quietly.
1d0499c2
JL
9495 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
9496 e->name.c_str(), sugs.empty() ? "" :
9497 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
9498 // NB: we use 'alternatives' because we list all
f8a968bc
JS
9499 // NB: we can have multiple errors, since a target variable
9500 // may be expanded in several different contexts:
9501 // trace ("*") { $foo->bar }
f8a968bc 9502 }
75ead1f7 9503
f8a968bc 9504 // make sure we're not dereferencing base types
dc5a09fc 9505 if (!arg->isptr)
d19a9a82 9506 e->assert_no_components("tracepoint", true);
75ead1f7 9507
f8a968bc
JS
9508 // we can only write to dereferenced fields, and only if guru mode is on
9509 bool lvalue = is_active_lvalue(e);
9510 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 9511 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 9512
ad370dcc
JS
9513 // XXX: if a struct/union arg is passed by value, then writing to its fields
9514 // is also meaningless until you dereference past a pointer member. It's
9515 // harder to detect and prevent that though...
75ead1f7 9516
f8a968bc
JS
9517 if (e->components.empty())
9518 {
03c75a4a 9519 if (e->addressof)
dc09353a 9520 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 9521
3e3bd7b6 9522 // Just grab the value from the probe locals
a45664f4
JS
9523 symbol* sym = new symbol;
9524 sym->tok = e->tok;
9525 sym->name = "__tracepoint_arg_" + arg->name;
9526 provide (sym);
f8a968bc
JS
9527 }
9528 else
9529 {
5f36109e
JS
9530 // make a copy of the original as a bare target symbol for the tracepoint
9531 // value, which will be passed into the dwarf dereferencing code
9532 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9533 e2->components.clear();
9534
9535 if (e->components.back().type == target_symbol::comp_pretty_print)
9536 {
9537 if (lvalue)
dc09353a 9538 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9539
d19a9a82 9540 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9541 dpp.expand()->visit (this);
9542 return;
9543 }
9544
1c0be8c7 9545 bool userspace_p = false;
f8a968bc 9546 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9547 + "_" + e->sym_name()
aca66a36 9548 + "_" + lex_cast(tick++));
75ead1f7 9549
1c0be8c7
JS
9550 exp_type type = pe_long;
9551 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 9552
1c0be8c7
JS
9553 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
9554 userspace_p, lvalue, e, e2);
75ead1f7 9555
f8a968bc
JS
9556 if (lvalue)
9557 {
9558 // Provide the functioncall to our parent, so that it can be
9559 // used to substitute for the assignment node immediately above
9560 // us.
9561 assert(!target_symbol_setter_functioncalls.empty());
9562 *(target_symbol_setter_functioncalls.top()) = n;
9563 }
75ead1f7 9564
1c0be8c7
JS
9565 // Revisit the functioncall so arguments can be expanded.
9566 n->visit (this);
f8a968bc 9567 }
75ead1f7
JS
9568}
9569
9570
f8a968bc
JS
9571void
9572tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9573{
03c75a4a 9574 if (e->addressof)
dc09353a 9575 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 9576
f8a968bc 9577 if (is_active_lvalue (e))
dc09353a 9578 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 9579
277c21bc 9580 if (e->name == "$$name")
f8a968bc 9581 {
5f36109e
JS
9582 e->assert_no_components("tracepoint");
9583
bfdaad1e
DS
9584 // Synthesize an embedded expression.
9585 embedded_expr *expr = new embedded_expr;
9586 expr->tok = e->tok;
9587 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 9588 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 9589 provide (expr);
f8a968bc 9590 }
277c21bc 9591 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 9592 {
5f36109e
JS
9593 e->assert_no_components("tracepoint", true);
9594
1c922ad7 9595 print_format* pf = print_format::create(e->tok, "sprintf");
0a6f5a3f 9596
f8a968bc 9597 for (unsigned i = 0; i < args.size(); ++i)
b278033a 9598 {
dcaa1a65
JS
9599 if (!args[i].usable)
9600 continue;
f8a968bc
JS
9601 if (i > 0)
9602 pf->raw_components += " ";
9603 pf->raw_components += args[i].name;
3e3bd7b6 9604 target_symbol *tsym = new target_symbol;
f8a968bc 9605 tsym->tok = e->tok;
277c21bc 9606 tsym->name = "$" + args[i].name;
5f36109e 9607 tsym->components = e->components;
b278033a 9608
f8a968bc
JS
9609 // every variable should always be accessible!
9610 tsym->saved_conversion_error = 0;
8c2f50c0 9611 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
9612 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
9613 {
9614 if (dw.sess.verbose>2)
e26c2f83 9615 for (const semantic_error *c = tsym->saved_conversion_error;
14a97852 9616 c != 0; c = c->chain)
4c5d9906 9617 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
9618 pf->raw_components += "=?";
9619 continue;
9620 }
b278033a 9621
5f36109e
JS
9622 if (!e->components.empty() &&
9623 e->components[0].type == target_symbol::comp_pretty_print)
9624 pf->raw_components += "=%s";
9625 else
9626 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
9627 pf->args.push_back(texp);
9628 }
0a6f5a3f 9629
f8a968bc
JS
9630 pf->components = print_format::string_to_components(pf->raw_components);
9631 provide (pf);
b278033a 9632 }
f8a968bc
JS
9633 else
9634 assert(0); // shouldn't get here
0a6f5a3f
JS
9635}
9636
0a6f5a3f 9637void
f8a968bc 9638tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 9639{
aff5d390 9640 try
c69a87e0 9641 {
bd1fcbad 9642 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 9643
277c21bc 9644 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 9645 visit_target_symbol_context (e);
bd1fcbad 9646
c69a87e0
FCE
9647 else
9648 visit_target_symbol_arg (e);
9649 }
9650 catch (const semantic_error &er)
9651 {
1af1e62d 9652 e->chain (er);
c69a87e0
FCE
9653 provide (e);
9654 }
0a6f5a3f
JS
9655}
9656
9657
79189b84
JS
9658tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
9659 dwflpp& dw, Dwarf_Die& func_die,
9660 const string& tracepoint_name,
9661 probe* base, probe_point* loc):
4c5d1300 9662 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 9663 sess (s), tracepoint_name (tracepoint_name)
56894e91 9664{
79189b84
JS
9665 // create synthetic probe point name; preserve condition
9666 vector<probe_point::component*> comps;
9667 comps.push_back (new probe_point::component (TOK_KERNEL));
9668 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
9669 this->sole_location()->components = comps;
9670
6fb70fb7
JS
9671 // fill out the available arguments in this tracepoint
9672 build_args(dw, func_die);
56894e91 9673
6fb70fb7
JS
9674 // determine which header defined this tracepoint
9675 string decl_file = dwarf_decl_file(&func_die);
b78a0fbb 9676 header = decl_file;
d4393459
FCE
9677
9678#if 0 /* This convention is not enforced. */
6fb70fb7
JS
9679 size_t header_pos = decl_file.rfind("trace/");
9680 if (header_pos == string::npos)
dc09353a 9681 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
9682 + tracepoint_name + "' in '"
9683 + decl_file + "'");
9684 header = decl_file.substr(header_pos);
d4393459 9685#endif
56894e91 9686
6fb70fb7
JS
9687 // tracepoints from FOO_event_types.h should really be included from FOO.h
9688 // XXX can dwarf tell us the include hierarchy? it would be better to
9689 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 9690 // XXX: see also PR9993.
d4393459 9691 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
9692 if (header_pos != string::npos)
9693 header.erase(header_pos, 12);
56894e91 9694
f8a968bc
JS
9695 // Now expand the local variables in the probe body
9696 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 9697 v.replace (this->body);
a45664f4
JS
9698 for (unsigned i = 0; i < args.size(); i++)
9699 if (args[i].used)
9700 {
9701 vardecl* v = new vardecl;
9702 v->name = "__tracepoint_arg_" + args[i].name;
9703 v->tok = this->tok;
58701b78 9704 v->set_arity(0, this->tok);
a45664f4 9705 v->type = pe_long;
69aa668e 9706 v->synthetic = true;
a45664f4
JS
9707 this->locals.push_back (v);
9708 }
56894e91 9709
79189b84 9710 if (sess.verbose > 2)
ce0f6648 9711 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 9712}
dc38c0ae 9713
56894e91 9714
f8a968bc 9715static bool
dcaa1a65 9716resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 9717{
d19a9a82 9718 Dwarf_Die type;
dcaa1a65 9719 switch (dwarf_tag(&arg.type_die))
b20febf3 9720 {
f8a968bc
JS
9721 case DW_TAG_typedef:
9722 case DW_TAG_const_type:
9723 case DW_TAG_volatile_type:
9724 // iterate on the referent type
3d1ad340 9725 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 9726 && resolve_tracepoint_arg_type(arg));
f8a968bc 9727 case DW_TAG_base_type:
a52d2ac0 9728 case DW_TAG_enumeration_type:
f8a968bc 9729 // base types will simply be treated as script longs
dcaa1a65 9730 arg.isptr = false;
f8a968bc
JS
9731 return true;
9732 case DW_TAG_pointer_type:
dcaa1a65
JS
9733 // pointers can be treated as script longs,
9734 // and if we know their type, they can also be dereferenced
d19a9a82
JS
9735 type = arg.type_die;
9736 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
9737 {
9738 // It still might be a non-type, e.g. const void,
9739 // so we need to strip away all qualifiers.
9740 int tag = dwarf_tag(&arg.type_die);
9741 if (tag != DW_TAG_typedef &&
9742 tag != DW_TAG_const_type &&
9743 tag != DW_TAG_volatile_type)
9744 {
9745 arg.isptr = true;
9746 break;
9747 }
9748 }
9749 if (!arg.isptr)
9750 arg.type_die = type;
ad370dcc
JS
9751 arg.typecast = "(intptr_t)";
9752 return true;
9753 case DW_TAG_structure_type:
9754 case DW_TAG_union_type:
9755 // for structs/unions which are passed by value, we turn it into
9756 // a pointer that can be dereferenced.
9757 arg.isptr = true;
9758 arg.typecast = "(intptr_t)&";
dcaa1a65 9759 return true;
f8a968bc
JS
9760 default:
9761 // should we consider other types too?
9762 return false;
b20febf3 9763 }
56894e91
JS
9764}
9765
9766
9767void
822a6a3d 9768tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 9769{
6fb70fb7
JS
9770 Dwarf_Die arg;
9771 if (dwarf_child(&func_die, &arg) == 0)
9772 do
9773 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
9774 {
9775 // build a tracepoint_arg for this parameter
9776 tracepoint_arg tparg;
23d106b9 9777 tparg.name = dwarf_diename(&arg);
56894e91 9778
6fb70fb7 9779 // read the type of this parameter
3d1ad340 9780 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 9781 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 9782 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 9783 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 9784
dcaa1a65 9785 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
9786 args.push_back(tparg);
9787 if (sess.verbose > 4)
a52d2ac0
JS
9788 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
9789 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
9790 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
9791 }
9792 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
9793}
9794
dc38c0ae 9795void
d0bfd2ac 9796tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 9797{
dcaa1a65
JS
9798 for (unsigned i = 0; i < args.size(); ++i)
9799 if (args[i].usable)
d0bfd2ac 9800 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
9801}
9802
79189b84
JS
9803void
9804tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 9805{
79189b84
JS
9806 if (! s.tracepoint_derived_probes)
9807 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
9808 s.tracepoint_derived_probes->enroll (this);
9809}
e38d6504 9810
56894e91 9811
197a4d62 9812void
3e3bd7b6 9813tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 9814{
3e3bd7b6
JS
9815 for (unsigned i = 0; i < args.size(); i++)
9816 if (args[i].used)
9817 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 9818}
56894e91 9819
3e3bd7b6 9820
c9ccb642 9821static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 9822{
3c1b3d06
FCE
9823 vector<string> they_live;
9824 // PR 9993
9825 // XXX: may need this to be configurable
d4393459 9826 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
9827
9828 // PR11649: conditional extra header
9829 // for kvm tracepoints in 2.6.33ish
9830 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
9831 they_live.push_back ("#include <linux/kvm_host.h>");
9832 }
9833
50b72692 9834 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 9835 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
9836 if (s.kernel_source_tree != "")
9837 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
9838 they_live.push_back ("struct xfs_mount;");
9839 they_live.push_back ("struct xfs_inode;");
9840 they_live.push_back ("struct xfs_buf;");
9841 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 9842 they_live.push_back ("struct xfs_trans;");
9e0cd21a 9843 }
d4393459 9844
50b72692 9845 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
9846 they_live.push_back ("struct rpc_task;");
9847 }
b64d65e2
FCE
9848 // RHEL6.3
9849 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
9850 they_live.push_back ("struct rpc_clnt;");
9851 they_live.push_back ("struct rpc_wait_queue;");
9852 }
d4393459
FCE
9853
9854 they_live.push_back ("#include <asm/cputime.h>");
9855
c2cf1b87
FCE
9856 // linux 3.0
9857 they_live.push_back ("struct cpu_workqueue_struct;");
9858
50b72692 9859 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
9860 if (s.kernel_source_tree != "")
9861 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
9862
50b72692
HP
9863 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
9864 they_live.push_back ("struct ext3_reserve_window_node;");
9865
3c1b3d06
FCE
9866 return they_live;
9867}
47dd066d
WC
9868
9869
9870void
79189b84 9871tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 9872{
79189b84
JS
9873 if (probes.empty())
9874 return;
47dd066d 9875
96b030fe
JS
9876 s.op->newline() << "/* ---- tracepoint probes ---- */";
9877 s.op->newline();
79189b84 9878
47dd066d 9879
a4b9c3b3
FCE
9880 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
9881 // to be separately compiled. That's because kernel tracepoint headers sometimes
9882 // conflict. PR13155.
9883
9884 map<string,translator_output*> per_header_aux;
9885 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 9886
6fb70fb7
JS
9887 for (unsigned i = 0; i < probes.size(); ++i)
9888 {
9889 tracepoint_derived_probe *p = probes[i];
75ae2ec9 9890 string header = p->header;
5f73a260 9891
a4b9c3b3
FCE
9892 // We cache the auxiliary output files on a per-header basis. We don't
9893 // need one aux file per tracepoint, only one per tracepoint-header.
9894 translator_output *tpop = per_header_aux[header];
9895 if (tpop == 0)
9896 {
9897 tpop = s.op_create_auxiliary();
9898 per_header_aux[header] = tpop;
9899
9900 // PR9993: Add extra headers to work around undeclared types in individual
9901 // include/trace/foo.h files
9902 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
9903 for (unsigned z=0; z<extra_decls.size(); z++)
9904 tpop->newline() << extra_decls[z] << "\n";
720c435f 9905
a4b9c3b3
FCE
9906 // strip include/ substring, the same way as done in get_tracequery_module()
9907 size_t root_pos = header.rfind("include/");
9908 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443
FCE
9909
9910 tpop->newline() << "#include <linux/tracepoint.h>" << endl;
a4b9c3b3 9911 tpop->newline() << "#include <" << header << ">";
720c435f 9912
a4b9c3b3
FCE
9913 // Starting in 2.6.35, at the same time NOARGS was added, the callback
9914 // always has a void* as the first parameter. PR11599
9915 tpop->newline() << "#ifdef DECLARE_TRACE_NOARGS";
9916 tpop->newline() << "#define STAP_TP_DATA , NULL";
9917 tpop->newline() << "#define STAP_TP_PROTO void *cb_data"
9918 << " __attribute__ ((unused))";
9919 if (!p->args.empty())
9920 tpop->line() << ",";
9921 tpop->newline() << "#else";
9922 tpop->newline() << "#define STAP_TP_DATA";
9923 tpop->newline() << "#define STAP_TP_PROTO";
9924 if (p->args.empty())
9925 tpop->line() << " void";
9926 tpop->newline() << "#endif";
720c435f
JS
9927
9928 tpop->newline() << "#define intptr_t long";
a4b9c3b3
FCE
9929 }
9930
720c435f
JS
9931 // collect the args that are actually in use
9932 vector<const tracepoint_arg*> used_args;
6fb70fb7 9933 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
9934 if (p->args[j].used)
9935 used_args.push_back(&p->args[j]);
9936
a4b9c3b3
FCE
9937 // forward-declare the generated-side tracepoint callback
9938 tpop->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9939 tpop->indent(2);
9940 if (used_args.empty())
9941 tpop->line() << "void";
9942 for (unsigned j = 0; j < used_args.size(); ++j)
6fb70fb7
JS
9943 {
9944 if (j > 0)
a4b9c3b3
FCE
9945 tpop->line() << ", ";
9946 tpop->line() << "int64_t";
6fb70fb7 9947 }
720c435f
JS
9948 tpop->line() << ");";
9949 tpop->indent(-2);
5f73a260 9950
a4b9c3b3
FCE
9951 // define the generated-side tracepoint callback - in the main translator-output
9952 s.op->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9953 s.op->indent(2);
9954 if (used_args.empty())
9955 s.op->newline() << "void";
9956 for (unsigned j = 0; j < used_args.size(); ++j)
a4b9c3b3 9957 {
a4b9c3b3
FCE
9958 if (j > 0)
9959 s.op->line() << ", ";
720c435f 9960 s.op->newline() << "int64_t __tracepoint_arg_" << used_args[j]->name;
6fb70fb7 9961 }
5f73a260
JS
9962 s.op->newline() << ")";
9963 s.op->newline(-2) << "{";
7c3e97f4 9964 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 9965 << common_probe_init (p) << ";";
71db462b 9966 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 9967 "stp_probe_type_tracepoint");
6dceb5c9 9968 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
9969 << lex_cast_qstring (p->tracepoint_name)
9970 << ";";
720c435f
JS
9971 for (unsigned j = 0; j < used_args.size(); ++j)
9972 {
9973 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 9974 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
9975 << " = __tracepoint_arg_" << used_args[j]->name << ";";
9976 }
26e63673 9977 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 9978 common_probe_entryfn_epilogue (s, true);
6fb70fb7 9979 s.op->newline(-1) << "}";
47dd066d 9980
a4b9c3b3 9981 // define the real tracepoint callback function
720c435f 9982 tpop->newline() << "static void enter_tracepoint_probe_" << i << "(";
a4b9c3b3
FCE
9983 tpop->newline(2) << "STAP_TP_PROTO";
9984 for (unsigned j = 0; j < p->args.size(); ++j)
9985 {
9986 if (j > 0)
9987 tpop->line() << ", ";
9988 tpop->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
9989 }
9990 tpop->newline() << ")";
9991 tpop->newline(-2) << "{";
720c435f
JS
9992 tpop->newline(1) << "enter_real_tracepoint_probe_" << i << "(";
9993 tpop->indent(2);
9994 for (unsigned j = 0; j < used_args.size(); ++j)
9995 {
9996 if (j > 0)
9997 tpop->line() << ", ";
9998 tpop->newline() << "(int64_t)" << used_args[j]->typecast
9999 << "__tracepoint_arg_" << used_args[j]->name;
10000 }
10001 tpop->newline() << ");";
10002 tpop->newline(-3) << "}";
a4b9c3b3
FCE
10003
10004
96b030fe 10005 // emit normalized registration functions
720c435f 10006 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 10007 tpop->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 10008 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3 10009 tpop->newline(-1) << "}";
47dd066d 10010
86758d5f
JS
10011 // NB: we're not prepared to deal with unreg failures. However, failures
10012 // can only occur if the tracepoint doesn't exist (yet?), or if we
10013 // weren't even registered. The former should be OKed by the initial
10014 // registration call, and the latter is safe to ignore.
720c435f 10015 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 10016 tpop->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 10017 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3
FCE
10018 tpop->newline(-1) << "}";
10019 tpop->newline();
5f73a260 10020
720c435f
JS
10021 // declare normalized registration functions
10022 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
10023 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 10024
a4b9c3b3 10025 tpop->assert_0_indent();
af304783
DS
10026 }
10027
96b030fe
JS
10028 // emit an array of registration functions for easy init/shutdown
10029 s.op->newline() << "static struct stap_tracepoint_probe {";
10030 s.op->newline(1) << "int (*reg)(void);";
86758d5f 10031 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
10032 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
10033 s.op->indent(1);
10034 for (unsigned i = 0; i < probes.size(); ++i)
10035 {
10036 s.op->newline () << "{";
10037 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
10038 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
10039 s.op->line() << " },";
10040 }
10041 s.op->newline(-1) << "};";
10042 s.op->newline();
47dd066d
WC
10043}
10044
10045
79189b84
JS
10046void
10047tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 10048{
79189b84
JS
10049 if (probes.size () == 0)
10050 return;
47dd066d 10051
79189b84 10052 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
10053 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
10054 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
10055 s.op->newline() << "if (rc) {";
10056 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
10057 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
10058 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
10059 s.op->newline(-1) << "}";
10060 s.op->newline(-1) << "}";
47dd066d 10061
bc9a523d
FCE
10062 // This would be technically proper (on those autoconf-detectable
10063 // kernels that include this function in tracepoint.h), however we
10064 // already make several calls to synchronze_sched() during our
10065 // shutdown processes.
47dd066d 10066
bc9a523d
FCE
10067 // s.op->newline() << "if (rc)";
10068 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
10069 // s.op->indent(-1);
79189b84 10070}
47dd066d
WC
10071
10072
79189b84
JS
10073void
10074tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 10075{
79189b84
JS
10076 if (probes.empty())
10077 return;
47dd066d 10078
96b030fe
JS
10079 s.op->newline() << "/* deregister tracepoint probes */";
10080 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
10081 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
10082 s.op->indent(-1);
47dd066d 10083
bc9a523d 10084 // Not necessary: see above.
47dd066d 10085
bc9a523d 10086 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 10087}
b20febf3 10088
47dd066d 10089
75ead1f7 10090struct tracepoint_query : public base_query
47dd066d 10091{
75ead1f7
JS
10092 tracepoint_query(dwflpp & dw, const string & tracepoint,
10093 probe * base_probe, probe_point * base_loc,
10094 vector<derived_probe *> & results):
10095 base_query(dw, "*"), tracepoint(tracepoint),
10096 base_probe(base_probe), base_loc(base_loc),
10097 results(results) {}
47dd066d 10098
75ead1f7 10099 const string& tracepoint;
47dd066d 10100
75ead1f7
JS
10101 probe * base_probe;
10102 probe_point * base_loc;
10103 vector<derived_probe *> & results;
f982c59b 10104 set<string> probed_names;
47dd066d 10105
75ead1f7
JS
10106 void handle_query_module();
10107 int handle_query_cu(Dwarf_Die * cudie);
10108 int handle_query_func(Dwarf_Die * func);
822a6a3d 10109 void query_library (const char *) {}
576eaefe 10110 void query_plt (const char *entry, size_t addr) {}
b20febf3 10111
75ead1f7
JS
10112 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
10113 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
10114};
47dd066d
WC
10115
10116
10117void
75ead1f7 10118tracepoint_query::handle_query_module()
47dd066d 10119{
75ead1f7 10120 // look for the tracepoints in each CU
337b7c44 10121 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10122}
10123
10124
75ead1f7
JS
10125int
10126tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10127{
75ead1f7 10128 dw.focus_on_cu (cudie);
d906ab9d 10129 dw.mod_info->get_symtab(this);
47dd066d 10130
75ead1f7
JS
10131 // look at each function to see if it's a tracepoint
10132 string function = "stapprobe_" + tracepoint;
10133 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10134}
10135
10136
75ead1f7
JS
10137int
10138tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10139{
75ead1f7 10140 dw.focus_on_function (func);
47dd066d 10141
60d98537 10142 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10143 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10144
10145 // check for duplicates -- sometimes tracepoint headers may be indirectly
10146 // included in more than one of our tracequery modules.
10147 if (!probed_names.insert(tracepoint_instance).second)
10148 return DWARF_CB_OK;
10149
79189b84
JS
10150 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10151 tracepoint_instance,
10152 base_probe, base_loc);
10153 results.push_back (dp);
75ead1f7 10154 return DWARF_CB_OK;
47dd066d
WC
10155}
10156
10157
75ead1f7
JS
10158int
10159tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 10160{
75ead1f7 10161 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 10162 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10163 return q->handle_query_cu(cudie);
47dd066d
WC
10164}
10165
10166
75ead1f7
JS
10167int
10168tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 10169{
75ead1f7 10170 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 10171 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10172 return q->handle_query_func(func);
47dd066d
WC
10173}
10174
10175
0a6f5a3f 10176struct tracepoint_builder: public derived_probe_builder
47dd066d 10177{
0a6f5a3f
JS
10178private:
10179 dwflpp *dw;
10180 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10181 void get_tracequery_modules(systemtap_session& s,
10182 const vector<string>& headers,
10183 vector<string>& modules);
47dd066d 10184
0a6f5a3f 10185public:
47dd066d 10186
0a6f5a3f
JS
10187 tracepoint_builder(): dw(0) {}
10188 ~tracepoint_builder() { delete dw; }
47dd066d 10189
0a6f5a3f
JS
10190 void build_no_more (systemtap_session& s)
10191 {
10192 if (dw && s.verbose > 3)
b530b5b3 10193 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10194 delete dw;
10195 dw = NULL;
435f53a7
FCE
10196
10197 delete_session_module_cache (s);
0a6f5a3f 10198 }
47dd066d 10199
0a6f5a3f
JS
10200 void build(systemtap_session& s,
10201 probe *base, probe_point *location,
10202 literal_map_t const& parameters,
10203 vector<derived_probe*>& finished_results);
10204};
47dd066d 10205
47dd066d 10206
c9ccb642 10207
2a0e62a8 10208// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10209// tracepoint-related header files given. Return the generated or cached
10210// modules[].
10211
10212void
10213tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10214 const vector<string>& headers,
10215 vector<string>& modules)
0a6f5a3f 10216{
c95eddf7 10217 if (s.verbose > 2)
55e50c24 10218 {
ce0f6648 10219 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10220 for (size_t i = 0; i < headers.size(); ++i)
10221 clog << " " << headers[i] << endl;
10222 }
c95eddf7 10223
2a0e62a8
JS
10224 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10225 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10226 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10227 // so we prefer not to repeat this.
10228 vector<string> uncached_headers;
10229 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10230 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10231
10232 // They may be in the cache already.
10233 if (s.use_cache && !s.poison_cache)
10234 for (size_t i=0; i<headers.size(); i++)
10235 {
10236 // see if the cached module exists
2a0e62a8 10237 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10238 if (!tracequery_path.empty() && file_exists(tracequery_path))
10239 {
10240 if (s.verbose > 2)
10241 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10242
c252fca2
JS
10243 // an empty file is a cached failure
10244 if (get_file_size(tracequery_path) > 0)
10245 modules.push_back (tracequery_path);
c9ccb642
FCE
10246 }
10247 else
10248 uncached_headers.push_back(headers[i]);
10249 }
10250 else
10251 uncached_headers = headers;
f982c59b 10252
c9ccb642
FCE
10253 // If we have nothing left to search for, quit
10254 if (uncached_headers.empty()) return;
55e50c24 10255
c9ccb642 10256 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10257
c9ccb642
FCE
10258 // We could query several subsets of headers[] to make this go
10259 // faster, but let's KISS and do one at a time.
10260 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10261 {
c9ccb642
FCE
10262 const string& header = uncached_headers[i];
10263
10264 // create a tracequery source file
10265 ostringstream osrc;
10266
10267 // PR9993: Add extra headers to work around undeclared types in individual
10268 // include/trace/foo.h files
10269 vector<string> short_decls = tracepoint_extra_decls(s, header);
10270
10271 // add each requested tracepoint header
75ae2ec9 10272 size_t root_pos = header.rfind("include/");
832f100d 10273 short_decls.push_back(string("#include <") +
75ae2ec9 10274 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10275 string(">"));
f982c59b 10276
c9ccb642
FCE
10277 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10278 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10279
10280 // the kernel has changed this naming a few times, previously TPPROTO,
10281 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10282 osrc << "#ifndef PARAMS" << endl;
10283 osrc << "#define PARAMS(args...) args" << endl;
10284 osrc << "#endif" << endl;
10285
c9ccb642
FCE
10286 // override DECLARE_TRACE to synthesize probe functions for us
10287 osrc << "#undef DECLARE_TRACE" << endl;
10288 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10289 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10290
c9ccb642
FCE
10291 // 2.6.35 added the NOARGS variant, but it's the same for us
10292 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10293 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10294 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10295
10296 // 2.6.38 added the CONDITION variant, which can also just redirect
10297 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10298 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10299 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10300
c9ccb642
FCE
10301 // older tracepoints used DEFINE_TRACE, so redirect that too
10302 osrc << "#undef DEFINE_TRACE" << endl;
10303 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10304 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10305
c9ccb642
FCE
10306 // add the specified decls/#includes
10307 for (unsigned z=0; z<short_decls.size(); z++)
10308 osrc << "#undef TRACE_INCLUDE_FILE\n"
10309 << "#undef TRACE_INCLUDE_PATH\n"
10310 << short_decls[z] << "\n";
10311
10312 // finish up the module source
10313 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10314
c9ccb642
FCE
10315 // save the source file away
10316 headers_tracequery_src[header] = osrc.str();
55e50c24 10317 }
f982c59b 10318
c9ccb642 10319 // now build them all together
2a0e62a8 10320 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10321
c9ccb642 10322 // now plop them into the cache
b278033a 10323 if (s.use_cache)
c9ccb642
FCE
10324 for (size_t i=0; i<uncached_headers.size(); i++)
10325 {
10326 const string& header = uncached_headers[i];
2a0e62a8
JS
10327 const string& tracequery_obj = tracequery_objs[header];
10328 const string& tracequery_path = headers_cache_obj[header];
10329 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10330 {
2a0e62a8 10331 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10332 modules.push_back (tracequery_path);
10333 }
c252fca2
JS
10334 else
10335 // cache an empty file for failures
10336 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10337 }
f982c59b
JS
10338}
10339
10340
d4393459 10341
f982c59b
JS
10342bool
10343tracepoint_builder::init_dw(systemtap_session& s)
10344{
10345 if (dw != NULL)
10346 return true;
10347
10348 vector<string> tracequery_modules;
55e50c24 10349 vector<string> system_headers;
f982c59b
JS
10350
10351 glob_t trace_glob;
d4393459
FCE
10352
10353 // find kernel_source_tree
10354 if (s.kernel_source_tree == "")
f982c59b 10355 {
d4393459
FCE
10356 unsigned found;
10357 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
10358 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
10359 if (found)
10360 {
10361 Dwarf_Die *cudie = 0;
10362 Dwarf_Addr bias;
10363 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10364 {
e19ebcf7 10365 assert_no_interrupts();
d4393459
FCE
10366 Dwarf_Attribute attr;
10367 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10368 if (name)
d4393459 10369 {
36d65b45
JS
10370 // check that the path actually exists locally before we try to use it
10371 if (file_exists(name))
10372 {
10373 if (s.verbose > 2)
10374 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10375 s.kernel_source_tree = name;
10376 }
10377 else
10378 {
10379 if (s.verbose > 2)
10380 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10381 }
61f1a63b 10382
d4393459
FCE
10383 break; // skip others; modern Kbuild uses same comp_dir for them all
10384 }
10385 }
10386 }
10387 }
10388
10389 // prefixes
10390 vector<string> glob_prefixes;
10391 glob_prefixes.push_back (s.kernel_build_tree);
10392 if (s.kernel_source_tree != "")
10393 glob_prefixes.push_back (s.kernel_source_tree);
10394
10395 // suffixes
10396 vector<string> glob_suffixes;
10397 glob_suffixes.push_back("include/trace/events/*.h");
10398 glob_suffixes.push_back("include/trace/*.h");
10399 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
b1966849 10400 glob_suffixes.push_back("arch/x86/include/asm/trace/*.h");
f89ff3e2 10401 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
ca51c2cd 10402 glob_suffixes.push_back("fs/xfs/xfs_trace*.h");
d4393459
FCE
10403
10404 // compute cartesian product
10405 vector<string> globs;
10406 for (unsigned i=0; i<glob_prefixes.size(); i++)
10407 for (unsigned j=0; j<glob_suffixes.size(); j++)
10408 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10409
8aa43b8d 10410 set<string> duped_headers;
d4393459
FCE
10411 for (unsigned z = 0; z < globs.size(); z++)
10412 {
10413 string glob_str = globs[z];
10414 if (s.verbose > 3)
b530b5b3 10415 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10416
067cc66f
CM
10417 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10418 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10419 throw runtime_error("Error globbing tracepoint");
10420
f982c59b
JS
10421 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10422 {
10423 string header(trace_glob.gl_pathv[i]);
10424
10425 // filter out a few known "internal-only" headers
60d98537
JS
10426 if (endswith(header, "/define_trace.h") ||
10427 endswith(header, "/ftrace.h") ||
10428 endswith(header, "/trace_events.h") ||
10429 endswith(header, "_event_types.h"))
f982c59b
JS
10430 continue;
10431
b1966849
FCE
10432 // With headers now plopped under arch/FOO/include/asm/*,
10433 // the following logic miss some tracepoints.
10434#if 0
8aa43b8d
JS
10435 // skip identical headers from the build and source trees.
10436 size_t root_pos = header.rfind("include/");
10437 if (root_pos != string::npos &&
10438 !duped_headers.insert(header.substr(root_pos + 8)).second)
10439 continue;
b1966849 10440#endif
8aa43b8d 10441
55e50c24 10442 system_headers.push_back(header);
f982c59b
JS
10443 }
10444 globfree(&trace_glob);
10445 }
10446
c9ccb642
FCE
10447 // Build tracequery modules
10448 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 10449
f982c59b
JS
10450 // TODO: consider other sources of tracepoint headers too, like from
10451 // a command-line parameter or some environment or .systemtaprc
47dd066d 10452
59c11f91 10453 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
10454 return true;
10455}
47dd066d 10456
0a6f5a3f
JS
10457void
10458tracepoint_builder::build(systemtap_session& s,
10459 probe *base, probe_point *location,
10460 literal_map_t const& parameters,
10461 vector<derived_probe*>& finished_results)
10462{
10463 if (!init_dw(s))
10464 return;
47dd066d 10465
75ead1f7
JS
10466 string tracepoint;
10467 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 10468
75ead1f7 10469 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
d906ab9d 10470 unsigned results_pre = finished_results.size();
51178501 10471 dw->iterate_over_modules(&query_module, &q);
d906ab9d
JL
10472 unsigned results_post = finished_results.size();
10473
10474 // Did we fail to find a match? Let's suggest something!
10475 if (results_pre == results_post)
10476 {
10477 size_t pos;
10478 string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
10479 while ((pos = sugs.find("stapprobe_")) != string::npos)
10480 sugs.erase(pos, string("stapprobe_").size());
10481 if (!sugs.empty())
ece93f53
JL
10482 throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
10483 "no match (similar tracepoints: %s)",
d906ab9d
JL
10484 sugs.find(',') == string::npos,
10485 sugs.c_str()));
10486 }
47dd066d 10487}
47dd066d 10488
e6fe60e7 10489
b55bc428 10490// ------------------------------------------------------------------------
bd2b1e68 10491// Standard tapset registry.
b55bc428
FCE
10492// ------------------------------------------------------------------------
10493
7a053d3b 10494void
f8220a7b 10495register_standard_tapsets(systemtap_session & s)
b55bc428 10496{
47e0478e 10497 register_tapset_been(s);
93646f4d 10498 register_tapset_itrace(s);
dd0e4fa7 10499 register_tapset_mark(s);
7a212aa8 10500 register_tapset_procfs(s);
912e8c59 10501 register_tapset_timers(s);
8d9609f5 10502 register_tapset_netfilter(s);
b84779a5 10503 register_tapset_utrace(s);
b98a8d73 10504
7a24d422 10505 // dwarf-based kprobe/uprobe parts
c4ce66a1 10506 dwarf_derived_probe::register_patterns(s);
30a279be 10507
888af770
FCE
10508 // XXX: user-space starter set
10509 s.pattern_root->bind_num(TOK_PROCESS)
10510 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10511 ->bind_privilege(pr_all)
888af770
FCE
10512 ->bind(new uprobe_builder ());
10513 s.pattern_root->bind_num(TOK_PROCESS)
10514 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10515 ->bind_privilege(pr_all)
888af770
FCE
10516 ->bind(new uprobe_builder ());
10517
0a6f5a3f
JS
10518 // kernel tracepoint probes
10519 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10520 ->bind(new tracepoint_builder());
10521
e6fe60e7
AM
10522 // Kprobe based probe
10523 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10524 ->bind(new kprobe_builder());
3c57fe1f
JS
10525 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
10526 ->bind(new kprobe_builder());
e6fe60e7
AM
10527 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10528 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
10529 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10530 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
10531 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10532 ->bind(new kprobe_builder());
b6371390
JS
10533 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10534 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10535 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10536 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10537 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10538 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10539 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10540 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10541 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
10542
10543 //Hwbkpt based probe
b47f3a55
FCE
10544 // NB: we formerly registered the probe point types only if the kernel configuration
10545 // allowed it. However, we get better error messages if we allow probes to resolve.
10546 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10547 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10548 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10549 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10550 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10551 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10552 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10553 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10554 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10555 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10556 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10557 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10558 // length supported with address only, not symbol names
83ea76b1
WC
10559
10560 //perf event based probe
4763f713 10561 register_tapset_perf(s);
a29858ef 10562 register_tapset_java(s);
b55bc428 10563}
dc38c0ae
DS
10564
10565
b20febf3
FCE
10566vector<derived_probe_group*>
10567all_session_groups(systemtap_session& s)
dc38c0ae 10568{
b20febf3 10569 vector<derived_probe_group*> g;
912e8c59
JS
10570
10571#define DOONE(x) \
10572 if (s. x##_derived_probes) \
10573 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
10574
10575 // Note that order *is* important here. We want to make sure we
10576 // register (actually run) begin probes before any other probe type
10577 // is run. Similarly, when unregistering probes, we want to
10578 // unregister (actually run) end probes after every other probe type
10579 // has be unregistered. To do the latter,
10580 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
10581 DOONE(be);
10582 DOONE(dwarf);
888af770 10583 DOONE(uprobe);
b20febf3
FCE
10584 DOONE(timer);
10585 DOONE(profile);
10586 DOONE(mark);
0a6f5a3f 10587 DOONE(tracepoint);
e6fe60e7 10588 DOONE(kprobe);
dd225250 10589 DOONE(hwbkpt);
83ea76b1 10590 DOONE(perf);
b20febf3 10591 DOONE(hrtimer);
ce82316f 10592 DOONE(procfs);
8d9609f5 10593 DOONE(netfilter);
935447c8
DS
10594
10595 // Another "order is important" item. We want to make sure we
10596 // "register" the dummy task_finder probe group after all probe
10597 // groups that use the task_finder.
10598 DOONE(utrace);
a96d1db0 10599 DOONE(itrace);
f31a77f5 10600 DOONE(dynprobe);
e7d4410d 10601 DOONE(java);
935447c8 10602 DOONE(task_finder);
b20febf3
FCE
10603#undef DOONE
10604 return g;
46b84a80 10605}
73267b89
JS
10606
10607/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.872333 seconds and 5 git commands to generate.