]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
Fix canonicalize_file_name() leaks
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
1af100fc 2// Copyright (C) 2005-2013 Red Hat Inc.
aa30ccd3 3// Copyright (C) 2005-2007 Intel Corporation.
0b8f6579 4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
56e12059
FCE
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "config.h"
12#include "staptree.h"
13#include "elaborate.h"
b55bc428 14#include "tapsets.h"
93646f4d 15#include "task_finder.h"
f31a77f5 16#include "tapset-dynprobe.h"
56e12059 17#include "translate.h"
dc38c0ae 18#include "session.h"
72dbc915 19#include "util.h"
0a6f5a3f 20#include "buildrun.h"
86bf665e 21#include "dwarf_wrappers.h"
2e67a43b 22#include "auto_free.h"
b278033a 23#include "hash.h"
440f755a 24#include "dwflpp.h"
5f8ca04f 25#include "setupdwfl.h"
6b51ee12 26#include <gelf.h>
22d737e8 27
4d0d9e8a 28#include "sdt_types.h"
bd2b1e68 29
3b579393
FCE
30#include <cstdlib>
31#include <algorithm>
bd2b1e68 32#include <deque>
56e12059 33#include <iostream>
d1bcbe71 34#include <fstream>
bd2b1e68 35#include <map>
ec4373ff 36#include <set>
56e12059 37#include <sstream>
bd2b1e68 38#include <stdexcept>
b55bc428 39#include <vector>
e36387d7 40#include <cstdarg>
29e64872 41#include <cassert>
1969b5bc 42#include <iomanip>
f781f849 43#include <cerrno>
bd2b1e68
GH
44
45extern "C" {
df8fadee 46#include <fcntl.h>
bd2b1e68 47#include <elfutils/libdwfl.h>
7a053d3b 48#include <elfutils/libdw.h>
77de5e9e
GH
49#include <dwarf.h>
50#include <elf.h>
51#include <obstack.h>
b20febf3 52#include <glob.h>
30a279be 53#include <fnmatch.h>
5f0a03a6 54#include <stdio.h>
349dc70e 55#include <sys/types.h>
37001baa 56#include <sys/stat.h>
aaf7ffe8 57#include <math.h>
aff5d390 58#include <regex.h>
37001baa 59#include <unistd.h>
6d5d594e 60#include <wordexp.h>
4b1ad75e
RM
61
62#define __STDC_FORMAT_MACROS
63#include <inttypes.h>
bd2b1e68 64}
77de5e9e 65
56e12059
FCE
66
67using namespace std;
2171f774 68using namespace __gnu_cxx;
56e12059 69
47dd066d 70
b20febf3
FCE
71
72// ------------------------------------------------------------------------
faea5e16
JS
73
74string
75common_probe_init (derived_probe* p)
76{
26e63673
JS
77 assert(p->session_index != (unsigned)-1);
78 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
79}
80
81
b20febf3 82void
71db462b
DS
83common_probe_entryfn_prologue (systemtap_session& s,
84 string statestr, string probe,
85 string probe_type, bool overload_processing)
b20febf3 86{
944c9a7a 87 if (s.runtime_usermode_p())
ac34f2aa
JS
88 {
89 // If session_state() is NULL, then we haven't even initialized shm yet,
90 // and there's *nothing* for the probe to do. (even alibi is in shm)
91 // So failure skips this whole block through the end of the epilogue.
92 s.op->newline() << "if (likely(session_state())) {";
e481ab2e 93 s.op->indent(1);
ac34f2aa
JS
94 }
95
71db462b 96 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 97 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 98 s.op->newline() << "#else";
653e6a9a 99
e481ab2e
JS
100 if (s.runtime_usermode_p())
101 s.op->newline() << "int _stp_saved_errno = errno;";
102
fee09ad5 103 s.op->newline() << "struct context* __restrict__ c = NULL;";
71db462b
DS
104 s.op->newline() << "#if !INTERRUPTIBLE";
105 s.op->newline() << "unsigned long flags;";
106 s.op->newline() << "#endif";
b20febf3 107
f887a8c9 108 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 109 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
110 s.op->newline() << "#endif";
111 if (overload_processing && !s.runtime_usermode_p())
71db462b 112 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 113 else
71db462b 114 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 115
f887a8c9
DS
116 if (! s.runtime_usermode_p())
117 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
118 else
119 {
120 s.op->newline() << "struct timespec timespec_atstart;";
121 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atstart);";
122 }
71db462b 123 s.op->newline() << "#endif";
994aac0e 124
71db462b
DS
125 s.op->newline() << "#if INTERRUPTIBLE";
126 s.op->newline() << "preempt_disable ();";
127 s.op->newline() << "#else";
128 s.op->newline() << "local_irq_save (flags);";
129 s.op->newline() << "#endif";
b20febf3 130
ac3af990 131 if (! s.runtime_usermode_p())
71db462b
DS
132 {
133 // Check for enough free enough stack space
134 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
135 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
136 // XXX: may need porting to platforms where task_struct is not
137 // at bottom of kernel stack NB: see also
138 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 139 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 140 s.op->newline() << "#ifdef STP_TIMING";
065d5567 141 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
142 s.op->newline() << "#endif";
143 s.op->newline() << "goto probe_epilogue;";
144 s.op->newline(-1) << "}";
145 }
c931ec8a 146
065d5567 147 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
148 s.op->newline(1) << "goto probe_epilogue;";
149 s.op->indent(-1);
9a604fac 150
1d0e697d
DS
151 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
152 if (s.runtime_usermode_p())
153 {
154 s.op->newline() << "if (!c) {";
155 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 156 s.op->newline() << "atomic_inc (skipped_count());";
1d0e697d
DS
157 s.op->newline() << "#endif";
158 s.op->newline() << "#ifdef STP_TIMING";
065d5567 159 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
1d0e697d
DS
160 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
161 s.op->newline() << "_stp_warn (\"Skipped %s\\n\", " << probe << "->pp);";
162 s.op->newline() << "#endif";
163 s.op->newline() << "#endif";
164 s.op->newline() << "goto probe_epilogue;";
165 s.op->newline(-1) << "}";
166 }
167
71db462b
DS
168 s.op->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
169 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 170 s.op->newline() << "atomic_inc (skipped_count());";
71db462b
DS
171 s.op->newline() << "#endif";
172 s.op->newline() << "#ifdef STP_TIMING";
065d5567 173 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
71db462b
DS
174 s.op->newline() << "#ifdef DEBUG_REENTRANCY";
175 s.op->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 176 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
177 // NB: There is a conceivable race condition here with reading
178 // c->probe_point, knowing that this other probe is sort of running.
179 // However, in reality, it's interrupted. Plus even if it were able
180 // to somehow start again, and stop before we read c->probe_point,
181 // at least we have that ?: "?" bit in there to avoid a NULL deref.
71db462b
DS
182 s.op->newline() << "#endif";
183 s.op->newline() << "#endif";
184 s.op->newline() << "atomic_dec (& c->busy);";
185 s.op->newline() << "goto probe_epilogue;";
186 s.op->newline(-1) << "}";
187 s.op->newline();
188 s.op->newline() << "c->last_stmt = 0;";
189 s.op->newline() << "c->last_error = 0;";
190 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
191 s.op->newline() << "c->uregs = 0;";
192 s.op->newline() << "c->kregs = 0;";
193 s.op->newline() << "#if defined __ia64__";
194 s.op->newline() << "c->unwaddr = 0;";
195 s.op->newline() << "#endif";
f4d70a33
JS
196 if (s.runtime_usermode_p())
197 s.op->newline() << "c->probe_index = " << probe << "->index;";
71db462b
DS
198 s.op->newline() << "c->probe_point = " << probe << "->pp;";
199 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
200 s.op->newline() << "c->probe_name = " << probe << "->pn;";
201 s.op->newline() << "#endif";
202 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 203 // reset Individual Probe State union
71db462b 204 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 205 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
206 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
207 s.op->newline() << "c->regparm = 0;";
208 s.op->newline() << "#endif";
e0a17418 209
152fa051
LB
210 if(!s.suppress_time_limits){
211 s.op->newline() << "#if INTERRUPTIBLE";
212 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
213 s.op->newline() << "#else";
214 s.op->newline() << "c->actionremaining = MAXACTION;";
215 s.op->newline() << "#endif";
216 }
9915575b
FCE
217 // NB: The following would actually be incorrect.
218 // That's because cycles_sum/cycles_base values are supposed to survive
219 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
220 // cycles), the values will be reset.
221 /*
71db462b
DS
222 s.op->newline() << "#ifdef STP_OVERLOAD";
223 s.op->newline() << "c->cycles_sum = 0;";
224 s.op->newline() << "c->cycles_base = 0;";
225 s.op->newline() << "#endif";
9915575b 226 */
44cfbe25
SM
227
228 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
229 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
230 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
231 s.op->newline() << "#endif";
b20febf3 232}
9a604fac 233
a44a0785 234
b20febf3 235void
f887a8c9
DS
236common_probe_entryfn_epilogue (systemtap_session& s,
237 bool overload_processing)
b20febf3 238{
f887a8c9
DS
239 if (overload_processing && !s.runtime_usermode_p())
240 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 241 else
f887a8c9
DS
242 s.op->newline() << "#ifdef STP_TIMING";
243 s.op->newline() << "{";
244 s.op->indent(1);
245 if (! s.runtime_usermode_p())
246 {
247 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
248 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
249 // fewer, if the hardware counter rolls over really quickly. We
250 // handle 32-bit wraparound here.
251 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
252 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
253 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
254 s.op->indent(-1);
255 }
256 else
257 {
258 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
259 s.op->newline() << "long cycles_elapsed;";
260 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC_RAW, &timespec_atend);";
261 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
262 // 'cycles_elapsed' is really elapsed nanoseconds
263 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
264 }
265
266 s.op->newline() << "#ifdef STP_TIMING";
267 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
268 s.op->newline() << "#endif";
269
270 if (overload_processing && !s.runtime_usermode_p())
271 {
272 s.op->newline() << "#ifdef STP_OVERLOAD";
273 s.op->newline() << "{";
a58d79d0
DS
274 // If the cycle count has wrapped (cycles_atend > cycles_base),
275 // let's go ahead and pretend the interval has been reached.
276 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
277 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
278 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
279 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
280 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
281
282 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
283 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
284 // has overloaded the system and we need to quit.
7baf48e9
FCE
285 // NB: this is not suppressible via --suppress-runtime-errors,
286 // because this is a system safety metric that we cannot trust
287 // unprivileged users to override.
f887a8c9
DS
288 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
289 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
290 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
291 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
292 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
293 s.op->newline(-1) << "}";
294
295 s.op->newline() << "c->cycles_base = cycles_atend;";
296 s.op->newline() << "c->cycles_sum = 0;";
297 s.op->newline(-1) << "}";
298 s.op->newline(-1) << "}";
299 s.op->newline() << "#endif";
a58d79d0 300 }
e57b735a 301
f887a8c9
DS
302 s.op->newline(-1) << "}";
303 s.op->newline() << "#endif";
e57b735a 304
f887a8c9
DS
305 s.op->newline() << "c->probe_point = 0;"; // vacated
306 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
307 s.op->newline() << "c->probe_name = 0;";
308 s.op->newline() << "#endif";
309 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
310
311
f887a8c9
DS
312 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
313 s.op->indent(1);
314 if (s.suppress_handler_errors) // PR 13306
7baf48e9 315 {
065d5567 316 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
317 }
318 else
319 {
f887a8c9
DS
320 s.op->newline() << "if (c->last_stmt != NULL)";
321 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
322 s.op->newline(-1) << "else";
323 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
324 s.op->indent(-1);
065d5567
JS
325 s.op->newline() << "atomic_inc (error_count());";
326 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
327 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
328 s.op->newline() << "_stp_exit ();";
329 s.op->newline(-1) << "}";
7baf48e9
FCE
330 }
331
f887a8c9 332 s.op->newline(-1) << "}";
7baf48e9
FCE
333
334
f887a8c9 335 s.op->newline() << "atomic_dec (&c->busy);";
e57b735a 336
f887a8c9
DS
337 s.op->newline(-1) << "probe_epilogue:"; // context is free
338 s.op->indent(1);
e57b735a 339
8ca891c4
DS
340 // In dyninst mode, we're not done with the context yet, since
341 // _stp_error() still needs a context structure (since the log
342 // buffers are stored there).
343 if (!s.runtime_usermode_p())
344 {
e481ab2e 345 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
8ca891c4 346 }
f887a8c9 347 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
348 {
349 // Check for excessive skip counts.
065d5567
JS
350 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
351 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
352 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
353 s.op->newline(-1) << "}";
7baf48e9 354 }
e57b735a 355
f887a8c9
DS
356 s.op->newline() << "#if INTERRUPTIBLE";
357 s.op->newline() << "preempt_enable_no_resched ();";
358 s.op->newline() << "#else";
359 s.op->newline() << "local_irq_restore (flags);";
360 s.op->newline() << "#endif";
653e6a9a 361
944c9a7a 362 if (s.runtime_usermode_p())
ac34f2aa 363 {
e481ab2e 364 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
ac34f2aa 365 s.op->newline() << "errno = _stp_saved_errno;";
ac34f2aa 366 }
e481ab2e
JS
367
368 s.op->newline() << "#endif // STP_ALIBI";
369
370 if (s.runtime_usermode_p())
371 s.op->newline(-1) << "}";
440f755a 372}
e57b735a 373
e57b735a 374
440f755a 375// ------------------------------------------------------------------------
e57b735a 376
440f755a
JS
377// ------------------------------------------------------------------------
378// Dwarf derived probes. "We apologize for the inconvience."
379// ------------------------------------------------------------------------
e57b735a 380
4627ed58
JS
381static const string TOK_KERNEL("kernel");
382static const string TOK_MODULE("module");
383static const string TOK_FUNCTION("function");
384static const string TOK_INLINE("inline");
385static const string TOK_CALL("call");
4bda987e 386static const string TOK_EXPORTED("exported");
4627ed58
JS
387static const string TOK_RETURN("return");
388static const string TOK_MAXACTIVE("maxactive");
389static const string TOK_STATEMENT("statement");
390static const string TOK_ABSOLUTE("absolute");
391static const string TOK_PROCESS("process");
a794dbeb 392static const string TOK_PROVIDER("provider");
4627ed58
JS
393static const string TOK_MARK("mark");
394static const string TOK_TRACE("trace");
395static const string TOK_LABEL("label");
63b4fd14 396static const string TOK_LIBRARY("library");
576eaefe 397static const string TOK_PLT("plt");
e7d4410d
LB
398static const string TOK_METHOD("method");
399static const string TOK_CLASS("class");;
e57b735a 400
1adf8ef1 401static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 402static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 403
440f755a
JS
404// Can we handle this query with just symbol-table info?
405enum dbinfo_reqt
406{
407 dbr_unknown,
408 dbr_none, // kernel.statement(NUM).absolute
409 dbr_need_symtab, // can get by with symbol table if there's no dwarf
410 dbr_need_dwarf
411};
e57b735a 412
20e4a32c 413
440f755a
JS
414struct base_query; // forward decls
415struct dwarf_query;
416struct dwflpp;
417struct symbol_table;
20e4a32c 418
a781f401 419
440f755a
JS
420struct
421symbol_table
422{
423 module_info *mod_info; // associated module
424 map<string, func_info*> map_by_name;
1c6b77e5
JS
425 multimap<Dwarf_Addr, func_info*> map_by_addr;
426 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
427 typedef pair<iterator_t, iterator_t> range_t;
428#ifdef __powerpc__
429 GElf_Word opd_section;
430#endif
2867a2a1
JS
431 void add_symbol(const char *name, bool weak, bool descriptor,
432 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 433 enum info_status read_symbols(FILE *f, const string& path);
83ca3872 434 enum info_status read_from_elf_file(const string& path,
2713ea24 435 systemtap_session &sess);
83ca3872 436 enum info_status read_from_text_file(const string& path,
2713ea24 437 systemtap_session &sess);
440f755a
JS
438 enum info_status get_from_elf();
439 void prepare_section_rejection(Dwfl_Module *mod);
440 bool reject_section(GElf_Word section);
440f755a
JS
441 void purge_syscall_stubs();
442 func_info *lookup_symbol(const string& name);
443 Dwarf_Addr lookup_symbol_address(const string& name);
444 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 445 func_info *get_first_func();
7a053d3b 446
440f755a
JS
447 symbol_table(module_info *mi) : mod_info(mi) {}
448 ~symbol_table();
449};
77de5e9e 450
440f755a
JS
451static bool null_die(Dwarf_Die *die)
452{
822a6a3d 453 static Dwarf_Die null;
440f755a
JS
454 return (!die || !memcmp(die, &null, sizeof(null)));
455}
c4ce66a1
JS
456
457
7a053d3b 458enum
bd2b1e68 459function_spec_type
7a053d3b 460 {
bd2b1e68
GH
461 function_alone,
462 function_and_file,
7a053d3b 463 function_file_and_line
bd2b1e68
GH
464 };
465
ec4373ff 466
bd2b1e68 467struct dwarf_builder;
f10534c6 468struct dwarf_var_expanding_visitor;
77de5e9e 469
2930abc7 470
b20febf3
FCE
471// XXX: This class is a candidate for subclassing to separate
472// the relocation vs non-relocation variants. Likewise for
473// kprobe vs kretprobe variants.
474
475struct dwarf_derived_probe: public derived_probe
b55bc428 476{
b20febf3
FCE
477 dwarf_derived_probe (const string& function,
478 const string& filename,
479 int line,
480 const string& module,
481 const string& section,
482 Dwarf_Addr dwfl_addr,
2930abc7 483 Dwarf_Addr addr,
b20febf3
FCE
484 dwarf_query & q,
485 Dwarf_Die* scope_die);
20e4a32c 486
b20febf3
FCE
487 string module;
488 string section;
489 Dwarf_Addr addr;
63b4fd14 490 string path;
27dc09b1 491 bool has_process;
2930abc7 492 bool has_return;
c9bad430 493 bool has_maxactive;
63b4fd14 494 bool has_library;
c9bad430 495 long maxactive_val;
4ad95bbc 496 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
497 string user_path;
498 string user_lib;
b95e2b79 499 bool access_vars;
2930abc7 500
af234c40
JS
501 unsigned saved_longs, saved_strings;
502 dwarf_derived_probe* entry_handler;
503
b8da0ad1 504 void printsig (std::ostream &o) const;
6b66b9f7 505 virtual void join_group (systemtap_session& s);
3689db05 506 void emit_probe_local_init(systemtap_session& s, translator_output * o);
d0bfd2ac 507 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 508
42e38653 509 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
510 void print_dupe_stamp(ostream& o);
511
bd2b1e68 512 // Pattern registration helpers.
7a053d3b 513 static void register_statement_variants(match_node * root,
27dc09b1 514 dwarf_builder * dw,
42e38653 515 privilege_t privilege);
fd6602a0 516 static void register_function_variants(match_node * root,
27dc09b1 517 dwarf_builder * dw,
42e38653 518 privilege_t privilege);
440d9b00
DB
519 static void register_function_and_statement_variants(systemtap_session& s,
520 match_node * root,
27dc09b1 521 dwarf_builder * dw,
42e38653 522 privilege_t privilege);
b1615c74
JS
523 static void register_sdt_variants(systemtap_session& s,
524 match_node * root,
525 dwarf_builder * dw);
526 static void register_plt_variants(systemtap_session& s,
527 match_node * root,
528 dwarf_builder * dw);
c4ce66a1 529 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
530
531protected:
532 dwarf_derived_probe(probe *base,
533 probe_point *location,
534 Dwarf_Addr addr,
535 bool has_return):
74fe61bc
LB
536 derived_probe(base, location), addr(addr), has_process(0),
537 has_return(has_return), has_maxactive(0), has_library(0),
538 maxactive_val(0), access_vars(false), saved_longs(0),
539 saved_strings(0), entry_handler(0)
6b66b9f7
JS
540 {}
541
542private:
d0bfd2ac 543 list<string> args;
8c67c337 544 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
545};
546
dc38c0ae 547
6b66b9f7 548struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 549{
6d0f3f0c 550 int pid; // 0 => unrestricted
0973d815 551
6d0f3f0c
FCE
552 uprobe_derived_probe (const string& function,
553 const string& filename,
554 int line,
555 const string& module,
6d0f3f0c
FCE
556 const string& section,
557 Dwarf_Addr dwfl_addr,
558 Dwarf_Addr addr,
559 dwarf_query & q,
6b66b9f7
JS
560 Dwarf_Die* scope_die):
561 dwarf_derived_probe(function, filename, line, module, section,
562 dwfl_addr, addr, q, scope_die), pid(0)
563 {}
6d0f3f0c 564
0973d815
FCE
565 // alternate constructor for process(PID).statement(ADDR).absolute
566 uprobe_derived_probe (probe *base,
567 probe_point *location,
568 int pid,
569 Dwarf_Addr addr,
6b66b9f7
JS
570 bool has_return):
571 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
572 {}
9ace370f 573
6d0f3f0c 574 void join_group (systemtap_session& s);
2865d17a 575
42e38653 576 void emit_privilege_assertion (translator_output*);
8f6d8c2b 577 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
578 void getargs(std::list<std::string> &arg_set) const;
579 void saveargs(int nargs);
580private:
581 list<string> args;
6d0f3f0c
FCE
582};
583
dc38c0ae
DS
584struct dwarf_derived_probe_group: public derived_probe_group
585{
586private:
b20febf3
FCE
587 multimap<string,dwarf_derived_probe*> probes_by_module;
588 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
589
590public:
08b5a50c 591 dwarf_derived_probe_group() {}
b20febf3
FCE
592 void enroll (dwarf_derived_probe* probe);
593 void emit_module_decls (systemtap_session& s);
594 void emit_module_init (systemtap_session& s);
b4be7cbc 595 void emit_module_refresh (systemtap_session& s);
b20febf3 596 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
597};
598
599
20c6c071 600// Helper struct to thread through the dwfl callbacks.
2c384610 601struct base_query
20c6c071 602{
c4ce66a1
JS
603 base_query(dwflpp & dw, literal_map_t const & params);
604 base_query(dwflpp & dw, const string & module_val);
2c384610 605 virtual ~base_query() {}
bd2b1e68 606
5227f1ea 607 systemtap_session & sess;
2c384610 608 dwflpp & dw;
5227f1ea 609
bd2b1e68 610 // Parameter extractors.
86bf665e 611 static bool has_null_param(literal_map_t const & params,
888af770 612 string const & k);
86bf665e 613 static bool get_string_param(literal_map_t const & params,
bd2b1e68 614 string const & k, string & v);
86bf665e 615 static bool get_number_param(literal_map_t const & params,
bd2b1e68 616 string const & k, long & v);
86bf665e 617 static bool get_number_param(literal_map_t const & params,
c239d28c 618 string const & k, Dwarf_Addr & v);
f301a9ff 619 static void query_library_callback (void *object, const char *data);
576eaefe 620 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 621 virtual void query_library (const char *data) = 0;
576eaefe 622 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 623
b55bc428 624
2c384610
DS
625 // Extracted parameters.
626 bool has_kernel;
91af0778
FCE
627 bool has_module;
628 bool has_process;
63b4fd14 629 bool has_library;
576eaefe
SC
630 bool has_plt;
631 bool has_statement;
2c384610 632 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 633 string path; // executable path if module is a .so
576eaefe 634 string plt_val; // has_plt => plt wildcard
2c384610
DS
635
636 virtual void handle_query_module() = 0;
637};
638
639
c4ce66a1 640base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 641 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 642{
91af0778 643 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
644 if (has_kernel)
645 module_val = "kernel";
91af0778
FCE
646
647 has_module = get_string_param (params, TOK_MODULE, module_val);
648 if (has_module)
649 has_process = false;
4baf0e53 650 else
d0a7f5a9 651 {
63b4fd14 652 string library_name;
576eaefe 653 long statement_num_val;
d0a7f5a9 654 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 655 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
656 if ((has_plt = has_null_param (params, TOK_PLT)))
657 plt_val = "*";
658 else has_plt = get_string_param (params, TOK_PLT, plt_val);
18418d34
SC
659 if (has_plt)
660 sess.consult_symtab = true;
576eaefe
SC
661 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
662
84c84ac4 663 if (has_process)
05fb3e0c 664 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
665 if (has_library)
666 {
667 if (! contains_glob_chars (library_name))
668 {
05fb3e0c
WF
669 path = path_remove_sysroot(sess, module_val);
670 module_val = find_executable (library_name, sess.sysroot,
671 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
672 if (module_val.find('/') == string::npos)
673 {
674 // We didn't find library_name so use iterate_over_libraries
675 module_val = path;
676 path = library_name;
677 }
84c84ac4
SC
678 }
679 else
680 path = library_name;
681 }
d0a7f5a9 682 }
91af0778
FCE
683
684 assert (has_kernel || has_process || has_module);
2c384610
DS
685}
686
c4ce66a1 687base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
688 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
689 module_val(module_val)
c4ce66a1
JS
690{
691 // NB: This uses '/' to distinguish between kernel modules and userspace,
692 // which means that userspace modules won't get any PATH searching.
693 if (module_val.find('/') == string::npos)
694 {
695 has_kernel = (module_val == TOK_KERNEL);
696 has_module = !has_kernel;
697 has_process = false;
698 }
699 else
700 {
701 has_kernel = has_module = false;
702 has_process = true;
703 }
704}
705
2c384610 706bool
86bf665e 707base_query::has_null_param(literal_map_t const & params,
2c384610
DS
708 string const & k)
709{
888af770 710 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
711}
712
713
714bool
86bf665e 715base_query::get_string_param(literal_map_t const & params,
2c384610
DS
716 string const & k, string & v)
717{
718 return derived_probe_builder::get_param (params, k, v);
719}
720
721
722bool
86bf665e 723base_query::get_number_param(literal_map_t const & params,
2c384610
DS
724 string const & k, long & v)
725{
726 int64_t value;
727 bool present = derived_probe_builder::get_param (params, k, value);
728 v = (long) value;
729 return present;
730}
731
732
733bool
86bf665e 734base_query::get_number_param(literal_map_t const & params,
2c384610
DS
735 string const & k, Dwarf_Addr & v)
736{
737 int64_t value;
738 bool present = derived_probe_builder::get_param (params, k, value);
739 v = (Dwarf_Addr) value;
740 return present;
741}
742
2c384610
DS
743struct dwarf_query : public base_query
744{
e1278bd4 745 dwarf_query(probe * base_probe,
2c384610
DS
746 probe_point * base_loc,
747 dwflpp & dw,
86bf665e 748 literal_map_t const & params,
b642c901
SC
749 vector<derived_probe *> & results,
750 const string user_path,
751 const string user_lib);
2c384610 752
c4ce66a1 753 vector<derived_probe *> & results;
8f14e444 754 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
755 probe * base_probe;
756 probe_point * base_loc;
b642c901
SC
757 string user_path;
758 string user_lib;
c4ce66a1 759
2cbcfa9c
JL
760 // Used to keep track of which modules were visited during
761 // iterate_over_modules()
762 set<string> visited_modules;
763
2c384610 764 virtual void handle_query_module();
5f0a03a6
JK
765 void query_module_dwarf();
766 void query_module_symtab();
5d5bd369 767 void query_library (const char *data);
576eaefe 768 void query_plt (const char *entry, size_t addr);
2c384610 769
2930abc7
FCE
770 void add_probe_point(string const & funcname,
771 char const * filename,
772 int line,
773 Dwarf_Die *scope_die,
774 Dwarf_Addr addr);
36f9dd1d 775
857bdfd1
JS
776 // Track addresses we've already seen in a given module
777 set<Dwarf_Addr> alias_dupes;
778
7fdd3e2c
JS
779 // Track inlines we've already seen as well
780 // NB: this can't be compared just by entrypc, as inlines can overlap
781 set<inline_instance_info> inline_dupes;
782
2930abc7 783 // Extracted parameters.
7a053d3b 784 string function_val;
20c6c071
GH
785
786 bool has_function_str;
787 bool has_statement_str;
788 bool has_function_num;
789 bool has_statement_num;
7a053d3b
RM
790 string statement_str_val;
791 string function_str_val;
c239d28c
GH
792 Dwarf_Addr statement_num_val;
793 Dwarf_Addr function_num_val;
20c6c071 794
b8da0ad1 795 bool has_call;
4bda987e 796 bool has_exported;
b8da0ad1 797 bool has_inline;
20c6c071
GH
798 bool has_return;
799
c9bad430
DS
800 bool has_maxactive;
801 long maxactive_val;
802
20c6c071
GH
803 bool has_label;
804 string label_val;
805
806 bool has_relative;
807 long relative_val;
808
37ebca01
FCE
809 bool has_absolute;
810
467bea43
SC
811 bool has_mark;
812
5f0a03a6
JK
813 enum dbinfo_reqt dbinfo_reqt;
814 enum dbinfo_reqt assess_dbinfo_reqt();
815
7d6d0afc 816 void parse_function_spec(const string & spec);
20c6c071 817 function_spec_type spec_type;
7d6d0afc 818 vector<string> scopes;
20c6c071
GH
819 string function;
820 string file;
0c8b7d37 821 line_t line_type;
879eb9e9 822 int line[2];
5f0a03a6 823 bool query_done; // Found exact match
20c6c071 824
bd25380d 825 set<string> filtered_srcfiles;
7e1279ea
FCE
826
827 // Map official entrypc -> func_info object
86bf665e
TM
828 inline_instance_map_t filtered_inlines;
829 func_info_map_t filtered_functions;
7e1279ea
FCE
830 bool choose_next_line;
831 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
832
833 void query_module_functions ();
b55bc428
FCE
834};
835
98afd80e 836
435f53a7
FCE
837static void delete_session_module_cache (systemtap_session& s); // forward decl
838
839
98afd80e 840struct dwarf_builder: public derived_probe_builder
b55bc428 841{
665e1256 842 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 843 map <string,dwflpp*> user_dw;
b642c901
SC
844 string user_path;
845 string user_lib;
44ffe90c
JL
846
847 // Holds modules to suggest functions from. NB: aggregates over
848 // recursive calls to build() when deriving globby probes.
849 set <string> modules_seen;
850
ae2552da 851 dwarf_builder() {}
aa30ccd3 852
ae2552da 853 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 854 {
ea14cf67
FCE
855 if (kern_dw[module] == 0)
856 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 857 return kern_dw[module];
707bf35e
JS
858 }
859
860 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
861 {
ea14cf67
FCE
862 if (user_dw[module] == 0)
863 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
864 return user_dw[module];
865 }
7a24d422 866
44ffe90c
JL
867 string suggest_functions(systemtap_session& sess, string func);
868
7a24d422 869 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 870 void dwarf_build_no_more (bool)
aa30ccd3 871 {
435f53a7
FCE
872 delete_map(kern_dw);
873 delete_map(user_dw);
7a24d422
FCE
874 }
875
876 void build_no_more (systemtap_session &s)
877 {
878 dwarf_build_no_more (s.verbose > 3);
435f53a7 879 delete_session_module_cache (s);
aa30ccd3
FCE
880 }
881
e38d6504
RM
882 ~dwarf_builder()
883 {
7a24d422 884 dwarf_build_no_more (false);
c8959a29 885 }
aa30ccd3 886
5227f1ea 887 virtual void build(systemtap_session & sess,
7a053d3b 888 probe * base,
20c6c071 889 probe_point * location,
86bf665e 890 literal_map_t const & parameters,
20c6c071 891 vector<derived_probe *> & finished_results);
b55bc428
FCE
892};
893
5111fc3e 894
e1278bd4 895dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
896 probe_point * base_loc,
897 dwflpp & dw,
86bf665e 898 literal_map_t const & params,
b642c901
SC
899 vector<derived_probe *> & results,
900 const string user_path,
901 const string user_lib)
c4ce66a1 902 : base_query(dw, params), results(results),
b642c901 903 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
904 user_path(user_path), user_lib(user_lib), has_relative(false),
905 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
906{
907 // Reduce the query to more reasonable semantic values (booleans,
908 // extracted strings, numbers, etc).
bd2b1e68
GH
909 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
910 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
911
912 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
913 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
914
0f336e95
SC
915 has_label = get_string_param(params, TOK_LABEL, label_val);
916
b8da0ad1 917 has_call = has_null_param(params, TOK_CALL);
4bda987e 918 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 919 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 920 has_return = has_null_param(params, TOK_RETURN);
c9bad430 921 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 922 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 923 has_mark = false;
37ebca01 924
bd2b1e68 925 if (has_function_str)
7d6d0afc 926 parse_function_spec(function_str_val);
bd2b1e68 927 else if (has_statement_str)
7d6d0afc 928 parse_function_spec(statement_str_val);
0daad364 929
5f0a03a6
JK
930 dbinfo_reqt = assess_dbinfo_reqt();
931 query_done = false;
0daad364
JS
932}
933
934
440f755a
JS
935func_info_map_t *
936get_filtered_functions(dwarf_query *q)
937{
938 return &q->filtered_functions;
939}
940
941
942inline_instance_map_t *
943get_filtered_inlines(dwarf_query *q)
944{
945 return &q->filtered_inlines;
946}
947
948
2c384610 949void
5f0a03a6 950dwarf_query::query_module_dwarf()
2c384610
DS
951{
952 if (has_function_num || has_statement_num)
953 {
954 // If we have module("foo").function(0xbeef) or
955 // module("foo").statement(0xbeef), the address is relative
956 // to the start of the module, so we seek the function
957 // number plus the module's bias.
6b517475
JS
958 Dwarf_Addr addr = has_function_num ?
959 function_num_val : statement_num_val;
08d1d520
MW
960
961 // These are raw addresses, we need to know what the elf_bias
962 // is to feed it to libdwfl based functions.
963 Dwarf_Addr elf_bias;
964 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
965 assert(elf);
966 addr += elf_bias;
6b517475 967 query_addr(addr, this);
2c384610
DS
968 }
969 else
970 {
971 // Otherwise if we have a function("foo") or statement("foo")
972 // specifier, we have to scan over all the CUs looking for
973 // the function(s) in question
974 assert(has_function_str || has_statement_str);
4df79aaf
JS
975
976 // For simple cases, no wildcard and no source:line, we can do a very
977 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
978 if (spec_type == function_alone &&
979 !dw.name_has_wildcard(function) &&
980 !startswith(function, "_Z"))
4df79aaf
JS
981 query_module_functions();
982 else
337b7c44 983 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
984 }
985}
986
5f0a03a6
JK
987static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
988 dwarf_query * q);
989
990void
991dwarf_query::query_module_symtab()
992{
993 // Get the symbol table if it's necessary, sufficient, and not already got.
994 if (dbinfo_reqt == dbr_need_dwarf)
995 return;
996
997 module_info *mi = dw.mod_info;
998 if (dbinfo_reqt == dbr_need_symtab)
999 {
1000 if (mi->symtab_status == info_unknown)
1001 mi->get_symtab(this);
1002 if (mi->symtab_status == info_absent)
1003 return;
1004 }
1005
1006 func_info *fi = NULL;
1007 symbol_table *sym_table = mi->sym_table;
1008
1009 if (has_function_str)
1010 {
1011 // Per dwarf_query::assess_dbinfo_reqt()...
1012 assert(spec_type == function_alone);
1013 if (dw.name_has_wildcard(function_str_val))
1014 {
1015 // Until we augment the blacklist sufficently...
c5810d31 1016 if ((function_str_val.find_first_not_of("*?") == string::npos) && !dw.has_gnu_debugdata())
5f0a03a6
JK
1017 {
1018 // e.g., kernel.function("*")
b530b5b3
LB
1019 cerr << _F("Error: Pattern '%s' matches every single "
1020 "instruction address in the symbol table,\n"
1021 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
1022 return;
1023 }
2e67a43b 1024 symbol_table::iterator_t iter;
1c6b77e5
JS
1025 for (iter = sym_table->map_by_addr.begin();
1026 iter != sym_table->map_by_addr.end();
2e67a43b 1027 ++iter)
5f0a03a6 1028 {
1c6b77e5 1029 fi = iter->second;
5f0a03a6
JK
1030 if (!null_die(&fi->die))
1031 continue; // already handled in query_module_dwarf()
1032 if (dw.function_name_matches_pattern(fi->name, function_str_val))
1033 query_func_info(fi->addr, *fi, this);
1034 }
1035 }
1036 else
1037 {
1038 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1039 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
1040 query_func_info(fi->addr, *fi, this);
1041 }
1042 }
1043 else
1044 {
1045 assert(has_function_num || has_statement_num);
1046 // Find the "function" in which the indicated address resides.
1047 Dwarf_Addr addr =
1048 (has_function_num ? function_num_val : statement_num_val);
576eaefe 1049 if (has_plt)
3d372d6b
SC
1050 {
1051 // Use the raw address from the .plt
1052 fi = sym_table->get_first_func();
1053 fi->addr = addr;
1054 }
1055 else
1056 fi = sym_table->get_func_containing_address(addr);
1057
5f0a03a6
JK
1058 if (!fi)
1059 {
2713ea24
CM
1060 sess.print_warning(_F("address %#" PRIx64 " out of range for module %s",
1061 addr, dw.module_name.c_str()));
1062 return;
5f0a03a6
JK
1063 }
1064 if (!null_die(&fi->die))
1065 {
1066 // addr looks like it's in the compilation unit containing
1067 // the indicated function, but query_module_dwarf() didn't
1068 // match addr to any compilation unit, so addr must be
1069 // above that cu's address range.
2713ea24
CM
1070 sess.print_warning(_F("address %#" PRIx64 " maps to no known compilation unit in module %s",
1071 addr, dw.module_name.c_str()));
5f0a03a6
JK
1072 return;
1073 }
1074 query_func_info(fi->addr, *fi, this);
1075 }
1076}
1077
1078void
1079dwarf_query::handle_query_module()
1080{
1c6b77e5
JS
1081 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
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
5f0a03a6 1094 // Consult the symbol table if we haven't found all we're looking for.
c5810d31
LB
1095 // asm functions can show up in the symbol table but not in dwarf,
1096 // or if we want to check the .gnu_debugdata section
1097 if ((sess.consult_symtab || dw.has_gnu_debugdata()) && !query_done)
5f0a03a6 1098 query_module_symtab();
2cbcfa9c
JL
1099
1100 // Add to list of visited modules
1101 // Use mod_info->name rather than dw.module_name since the former is
1102 // what's actually used in the sess.module_cache->cache map
1103 visited_modules.insert(dw.mod_info->name);
5f0a03a6
JK
1104}
1105
2c384610 1106
7d6d0afc
JS
1107void
1108dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1109{
1d12a9b2
JS
1110 line_type = ABSOLUTE;
1111 line[0] = line[1] = 0;
1112
91699a70 1113 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1114
7d6d0afc 1115 // look for named scopes
91699a70
JS
1116 scope_pos = spec.rfind("::");
1117 if (scope_pos != string::npos)
bd2b1e68 1118 {
91699a70
JS
1119 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1120 scope_pos += 2;
bd2b1e68 1121 }
91699a70
JS
1122 else
1123 scope_pos = 0;
bd2b1e68 1124
7d6d0afc
JS
1125 // look for a source separator
1126 src_pos = spec.find('@', scope_pos);
1127 if (src_pos == string::npos)
bd2b1e68 1128 {
7d6d0afc
JS
1129 function = spec.substr(scope_pos);
1130 spec_type = function_alone;
bd2b1e68 1131 }
7d6d0afc 1132 else
879eb9e9 1133 {
7d6d0afc 1134 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1135
7d6d0afc
JS
1136 // look for a line-number separator
1137 line_pos = spec.find_first_of(":+", src_pos);
1138 if (line_pos == string::npos)
1139 {
1140 file = spec.substr(src_pos + 1);
1141 spec_type = function_and_file;
1142 }
1143 else
1144 {
1145 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1146
1147 // classify the line spec
1148 spec_type = function_file_and_line;
1149 if (spec[line_pos] == '+')
1150 line_type = RELATIVE;
1151 else if (spec[line_pos + 1] == '*' &&
1152 spec.length() == line_pos + 2)
1153 line_type = WILDCARD;
1154 else
1155 line_type = ABSOLUTE;
1156
1157 if (line_type != WILDCARD)
1158 try
1159 {
1160 // try to parse either N or N-M
1161 dash_pos = spec.find('-', line_pos + 1);
1162 if (dash_pos == string::npos)
1163 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1164 else
1165 {
1166 line_type = RANGE;
1167 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1168 dash_pos - line_pos - 1));
1169 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1170 }
1171 }
1172 catch (runtime_error & exn)
1173 {
1174 goto bad;
1175 }
1176 }
bd2b1e68
GH
1177 }
1178
7d6d0afc
JS
1179 if (function.empty() ||
1180 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1181 goto bad;
1182
7d6d0afc 1183 if (sess.verbose > 2)
bd2b1e68 1184 {
b530b5b3
LB
1185 //clog << "parsed '" << spec << "'";
1186 clog << _F("parse '%s'", spec.c_str());
41c262f3 1187
7d6d0afc
JS
1188 if (!scopes.empty())
1189 clog << ", scope '" << scopes[0] << "'";
1190 for (unsigned i = 1; i < scopes.size(); ++i)
1191 clog << "::'" << scopes[i] << "'";
41c262f3 1192
7d6d0afc
JS
1193 clog << ", func '" << function << "'";
1194
1195 if (spec_type != function_alone)
1196 clog << ", file '" << file << "'";
1197
1198 if (spec_type == function_file_and_line)
1199 {
1200 clog << ", line ";
1201 switch (line_type)
1202 {
1203 case ABSOLUTE:
1204 clog << line[0];
1205 break;
1206
1207 case RELATIVE:
1208 clog << "+" << line[0];
1209 break;
1210
1211 case RANGE:
1212 clog << line[0] << " - " << line[1];
1213 break;
1214
1215 case WILDCARD:
1216 clog << "*";
1217 break;
1218 }
1219 }
1220
1221 clog << endl;
bd2b1e68
GH
1222 }
1223
7d6d0afc
JS
1224 return;
1225
1226bad:
b530b5b3 1227 throw semantic_error(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1228 base_probe->tok);
bd2b1e68
GH
1229}
1230
05fb3e0c
WF
1231string path_remove_sysroot(const systemtap_session& sess, const string& path)
1232{
1233 size_t pos;
1234 string retval = path;
1235 if (!sess.sysroot.empty() &&
1236 (pos = retval.find(sess.sysroot)) != string::npos)
1237 retval.replace(pos, sess.sysroot.length(), "/");
1238 return retval;
1239}
bd2b1e68 1240
36f9dd1d 1241void
1ffb8bd1 1242dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1243 const char* filename,
36f9dd1d 1244 int line,
b20febf3 1245 Dwarf_Die* scope_die,
36f9dd1d
FCE
1246 Dwarf_Addr addr)
1247{
b20febf3 1248 string reloc_section; // base section for relocation purposes
27646582 1249 Dwarf_Addr reloc_addr; // relocated
b20febf3 1250 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1251 string funcname = dw_funcname;
36f9dd1d 1252
37ebca01
FCE
1253 assert (! has_absolute); // already handled in dwarf_builder::build()
1254
576eaefe
SC
1255 if (!has_plt)
1256 reloc_addr = dw.relocate_address(addr, reloc_section);
1257 else
1258 {
3d372d6b 1259 // Set the reloc_section but use the plt entry for reloc_addr
576eaefe
SC
1260 dw.relocate_address(addr, reloc_section);
1261 reloc_addr = addr;
1262 }
2930abc7 1263
1ffb8bd1 1264 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1265 const char* linkage_name;
1266 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1267 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1268 funcname = linkage_name;
1269
7f9f3386
FCE
1270 if (sess.verbose > 1)
1271 {
b530b5b3 1272 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1273 if (string(module) == TOK_KERNEL)
b530b5b3 1274 clog << _(" kernel");
91af0778 1275 else if (has_module)
b530b5b3 1276 clog << _(" module=") << module;
91af0778 1277 else if (has_process)
b530b5b3 1278 clog << _(" process=") << module;
b20febf3 1279 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1280 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1281 }
4baf0e53 1282
27646582 1283 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1284 addr, has_return);
b20febf3
FCE
1285 if (sess.verbose > 1)
1286 clog << endl;
7f9f3386 1287
84048984
FCE
1288 if (module == TOK_KERNEL)
1289 {
1290 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1291 reloc_addr = addr - sess.sym_stext;
37ebca01 1292 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1293 }
1294
b20febf3
FCE
1295 if (! bad)
1296 {
1a0dbc5a 1297 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1298
1299 if (has_process)
1300 {
05fb3e0c 1301 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1302 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1303 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1304 *this, scope_die));
1305 }
1306 else
1307 {
1308 assert (has_kernel || has_module);
1309 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1310 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1311 *this, scope_die));
1312 }
b20febf3 1313 }
2930abc7
FCE
1314}
1315
5f0a03a6
JK
1316enum dbinfo_reqt
1317dwarf_query::assess_dbinfo_reqt()
1318{
1319 if (has_absolute)
1320 {
1321 // kernel.statement(NUM).absolute
1322 return dbr_none;
1323 }
1324 if (has_inline)
1325 {
1326 // kernel.function("f").inline or module("m").function("f").inline
1327 return dbr_need_dwarf;
1328 }
1329 if (has_function_str && spec_type == function_alone)
1330 {
1331 // kernel.function("f") or module("m").function("f")
1332 return dbr_need_symtab;
1333 }
1334 if (has_statement_num)
1335 {
1336 // kernel.statement(NUM) or module("m").statement(NUM)
1337 // Technically, all we need is the module offset (or _stext, for
1338 // the kernel). But for that we need either the ELF file or (for
1339 // _stext) the symbol table. In either case, the symbol table
1340 // is available, and that allows us to map the NUM (address)
1341 // to a function, which is goodness.
1342 return dbr_need_symtab;
1343 }
1344 if (has_function_num)
1345 {
1346 // kernel.function(NUM) or module("m").function(NUM)
1347 // Need the symbol table so we can back up from NUM to the
1348 // start of the function.
1349 return dbr_need_symtab;
1350 }
1351 // Symbol table tells us nothing about source files or line numbers.
1352 return dbr_need_dwarf;
1353}
2930abc7
FCE
1354
1355
b8da0ad1
FCE
1356// The critical determining factor when interpreting a pattern
1357// string is, perhaps surprisingly: "presence of a lineno". The
1358// presence of a lineno changes the search strategy completely.
1359//
1360// Compare the two cases:
1361//
1362// 1. {statement,function}(foo@file.c:lineno)
1363// - find the files matching file.c
1364// - in each file, find the functions matching foo
1365// - query the file for line records matching lineno
1366// - iterate over the line records,
1367// - and iterate over the functions,
1368// - if(haspc(function.DIE, line.addr))
1369// - if looking for statements: probe(lineno.addr)
1370// - if looking for functions: probe(function.{entrypc,return,etc.})
1371//
1372// 2. {statement,function}(foo@file.c)
1373// - find the files matching file.c
1374// - in each file, find the functions matching foo
1375// - probe(function.{entrypc,return,etc.})
1376//
1377// Thus the first decision we make is based on the presence of a
1378// lineno, and we enter entirely different sets of callbacks
1379// depending on that decision.
1380//
1381// Note that the first case is a generalization fo the second, in that
1382// we could theoretically search through line records for matching
1383// file names (a "table scan" in rdbms lingo). Luckily, file names
1384// are already cached elsewhere, so we can do an "index scan" as an
1385// optimization.
7e1279ea 1386
bd2b1e68 1387static void
4cd232e4 1388query_statement (string const & func,
20e4a32c 1389 char const * file,
4cd232e4 1390 int line,
bcc12710 1391 Dwarf_Die *scope_die,
20e4a32c 1392 Dwarf_Addr stmt_addr,
4cd232e4 1393 dwarf_query * q)
bd2b1e68 1394{
39bcd429
FCE
1395 try
1396 {
cee35f73 1397 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1398 line, scope_die, stmt_addr);
39bcd429
FCE
1399 }
1400 catch (const semantic_error& e)
1401 {
1402 q->sess.print_error (e);
1403 }
bd2b1e68
GH
1404}
1405
6b517475
JS
1406static void
1407query_addr(Dwarf_Addr addr, dwarf_query *q)
1408{
1409 dwflpp &dw = q->dw;
1410
08d1d520
MW
1411 if (q->sess.verbose > 2)
1412 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1413
1414 // First pick which CU contains this address
1415 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1416 if (!cudie) // address could be wildly out of range
1417 return;
1418 dw.focus_on_cu(cudie);
1419
1420 // Now compensate for the dw bias
1421 addr -= dw.module_bias;
1422
1423 // Per PR5787, we look up the scope die even for
1424 // statement_num's, for blacklist sensitivity and $var
1425 // resolution purposes.
1426
1427 // Find the scopes containing this address
1428 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1429 if (scopes.empty())
1430 return;
1431
1432 // Look for the innermost containing function
1433 Dwarf_Die *fnscope = NULL;
1434 for (size_t i = 0; i < scopes.size(); ++i)
1435 {
1436 int tag = dwarf_tag(&scopes[i]);
1437 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1438 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1439 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1440 {
1441 fnscope = &scopes[i];
1442 break;
1443 }
1444 }
1445 if (!fnscope)
1446 return;
1447 dw.focus_on_function(fnscope);
1448
1449 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1450
1451 const char *file = dwarf_decl_file(fnscope);
1452 int line;
1453 dwarf_decl_line(fnscope, &line);
1454
1455 // Function probes should reset the addr to the function entry
1456 // and possibly perform prologue searching
1457 if (q->has_function_num)
1458 {
1459 dw.die_entrypc(fnscope, &addr);
1460 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1461 (q->sess.prologue_searching || q->has_process)) // PR 6871
1462 {
1463 func_info func;
1464 func.die = *fnscope;
1465 func.name = dw.function_name;
1466 func.decl_file = file;
1467 func.decl_line = line;
1468 func.entrypc = addr;
1469
1470 func_info_map_t funcs(1, func);
1471 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1472 if (q->has_return) // PR13200
1473 {
1474 if (q->sess.verbose > 2)
1475 clog << "ignoring prologue for .return probes" << endl;
1476 }
1477 else
1478 {
1479 if (funcs[0].prologue_end)
1480 addr = funcs[0].prologue_end;
1481 }
6b517475
JS
1482 }
1483 }
1484 else
1485 {
1486 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1487 if (address_line)
1488 {
1489 file = address_line.linesrc();
1490 line = address_line.lineno();
1491 }
1492
1493 // Verify that a raw address matches the beginning of a
1494 // statement. This is a somewhat lame check that the address
1495 // is at the start of an assembly instruction. Mark probes are in the
1496 // middle of a macro and thus not strictly at a statement beginning.
1497 // Guru mode may override this check.
1498 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1499 {
1500 stringstream msg;
2a97f50b 1501 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1502 addr);
6b517475 1503 if (address_line)
2a97f50b 1504 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1505 else
b530b5b3
LB
1506 msg << _F(" (no line info found for '%s', in module '%s')",
1507 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475
JS
1508 if (! q->sess.guru_mode)
1509 throw semantic_error(msg.str());
2713ea24 1510 else
6b517475
JS
1511 q->sess.print_warning(msg.str());
1512 }
1513 }
1514
1515 // Build a probe at this point
1516 query_statement(dw.function_name, file, line, scope, addr, q);
1517}
1518
8096dd7d
JS
1519static void
1520query_label (string const & func,
1521 char const * label,
1522 char const * file,
1523 int line,
1524 Dwarf_Die *scope_die,
1525 Dwarf_Addr stmt_addr,
1526 dwarf_query * q)
1527{
6b517475
JS
1528 assert (q->has_statement_str || q->has_function_str);
1529
8096dd7d
JS
1530 size_t i = q->results.size();
1531
1532 // weed out functions whose decl_file isn't one of
1533 // the source files that we actually care about
6b517475 1534 if (q->spec_type != function_alone &&
8096dd7d
JS
1535 q->filtered_srcfiles.count(file) == 0)
1536 return;
1537
1538 query_statement(func, file, line, scope_die, stmt_addr, q);
1539
c72aa911
JS
1540 // after the fact, insert the label back into the derivation chain
1541 probe_point::component* ppc =
1542 new probe_point::component(TOK_LABEL, new literal_string (label));
1543 for (; i < q->results.size(); ++i)
1544 {
1545 derived_probe* p = q->results[i];
1546 probe_point* pp = new probe_point(*p->locations[0]);
1547 pp->components.push_back (ppc);
1548 p->base = p->base->create_alias(p->locations[0], pp);
1549 }
8096dd7d
JS
1550}
1551
7e1279ea 1552static void
3e961ba6 1553query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1554 dwarf_query * q)
1555{
b6581717 1556 try
7e1279ea 1557 {
8f14e444
FCE
1558 assert (! q->has_return); // checked by caller already
1559 if (q->sess.verbose>2)
b530b5b3
LB
1560 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1561 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1562 query_statement (ii.name, ii.decl_file, ii.decl_line,
1563 &ii.die, ii.entrypc, q);
7e1279ea 1564 }
b6581717 1565 catch (semantic_error &e)
7e1279ea 1566 {
b6581717 1567 q->sess.print_error (e);
7e1279ea
FCE
1568 }
1569}
1570
1571static void
1572query_func_info (Dwarf_Addr entrypc,
bcc12710 1573 func_info & fi,
7e1279ea
FCE
1574 dwarf_query * q)
1575{
b6581717 1576 try
7e1279ea 1577 {
b6581717
GH
1578 if (q->has_return)
1579 {
1580 // NB. dwarf_derived_probe::emit_registrations will emit a
1581 // kretprobe based on the entrypc in this case.
464379bb
FCE
1582 if (fi.prologue_end != 0 && q->has_return) // PR13200
1583 {
1584 if (q->sess.verbose > 2)
1585 clog << "ignoring prologue for .return probes" << endl;
1586 }
20e4a32c 1587 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1588 &fi.die, entrypc, q);
1589 }
1590 else
1591 {
35dc8b04 1592 if (fi.prologue_end != 0)
44f75386 1593 {
44f75386
FCE
1594 query_statement (fi.name, fi.decl_file, fi.decl_line,
1595 &fi.die, fi.prologue_end, q);
1596 }
1597 else
1598 {
1599 query_statement (fi.name, fi.decl_file, fi.decl_line,
1600 &fi.die, entrypc, q);
1601 }
b6581717 1602 }
7e1279ea 1603 }
b6581717 1604 catch (semantic_error &e)
7e1279ea 1605 {
b6581717 1606 q->sess.print_error (e);
7e1279ea
FCE
1607 }
1608}
1609
1610
bd4b874d
SC
1611static void
1612query_srcfile_label (const dwarf_line_t& line, void * arg)
1613{
1614 dwarf_query * q = static_cast<dwarf_query *>(arg);
1615
1616 Dwarf_Addr addr = line.addr();
1617
1618 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1619 i != q->filtered_functions.end(); ++i)
1620 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1621 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1622 q, query_label);
1623
1624 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1625 i != q->filtered_inlines.end(); ++i)
1626 if (q->dw.die_has_pc (i->die, addr))
1627 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1628 q, query_label);
bd4b874d
SC
1629}
1630
7e1279ea 1631static void
86bf665e 1632query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1633{
1634 dwarf_query * q = static_cast<dwarf_query *>(arg);
1635
86bf665e 1636 Dwarf_Addr addr = line.addr();
4cd232e4 1637
86bf665e 1638 int lineno = line.lineno();
847bf07f 1639
86bf665e 1640 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1641 i != q->filtered_functions.end(); ++i)
1642 {
3e961ba6 1643 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1644 {
b0ee93c4 1645 if (q->sess.verbose>3)
b530b5b3 1646 clog << _("function DIE lands on srcfile\n");
4cd232e4 1647 if (q->has_statement_str)
f5958c8f
JS
1648 {
1649 Dwarf_Die scope;
1650 q->dw.inner_die_containing_pc(i->die, addr, scope);
1651 query_statement (i->name, i->decl_file,
1652 lineno, // NB: not q->line !
1653 &scope, addr, q);
1654 }
4cd232e4 1655 else
3e961ba6 1656 query_func_info (i->entrypc, *i, q);
7e1279ea 1657 }
20e4a32c
RM
1658 }
1659
86bf665e 1660 for (inline_instance_map_t::iterator i
897820ca
GH
1661 = q->filtered_inlines.begin();
1662 i != q->filtered_inlines.end(); ++i)
1663 {
3e961ba6 1664 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1665 {
b0ee93c4 1666 if (q->sess.verbose>3)
b530b5b3 1667 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1668 if (q->has_statement_str)
f5958c8f
JS
1669 {
1670 Dwarf_Die scope;
1671 q->dw.inner_die_containing_pc(i->die, addr, scope);
1672 query_statement (i->name, i->decl_file,
d807e0ab
JS
1673 lineno, // NB: not q->line !
1674 &scope, addr, q);
f5958c8f 1675 }
897820ca 1676 else
3e961ba6 1677 query_inline_instance_info (*i, q);
897820ca 1678 }
20e4a32c 1679 }
7e1279ea
FCE
1680}
1681
1682
7fdd3e2c
JS
1683bool
1684inline_instance_info::operator<(const inline_instance_info& other) const
1685{
1686 if (entrypc != other.entrypc)
1687 return entrypc < other.entrypc;
1688
1689 if (decl_line != other.decl_line)
1690 return decl_line < other.decl_line;
1691
1692 int cmp = name.compare(other.name);
1693 if (!cmp)
1694 cmp = strcmp(decl_file, other.decl_file);
1695 return cmp < 0;
1696}
1697
1698
4fa7b22b 1699static int
7e1279ea 1700query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1701{
1702 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475 1703 assert (q->has_statement_str || q->has_function_str);
4bda987e 1704 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1705
39bcd429 1706 try
7a053d3b 1707 {
b0ee93c4 1708 if (q->sess.verbose>2)
b530b5b3 1709 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1710
6b517475
JS
1711 Dwarf_Addr entrypc;
1712 if (q->dw.die_entrypc (die, &entrypc))
1713 {
1714 inline_instance_info inl;
1715 inl.die = *die;
1716 inl.name = q->dw.function_name;
1717 inl.entrypc = entrypc;
1718 q->dw.function_file (&inl.decl_file);
1719 q->dw.function_line (&inl.decl_line);
1720
1721 // make sure that this inline hasn't already
1722 // been matched from a different CU
1723 if (q->inline_dupes.insert(inl).second)
1724 q->filtered_inlines.push_back(inl);
1725 }
7e1279ea
FCE
1726 return DWARF_CB_OK;
1727 }
1728 catch (const semantic_error& e)
1729 {
1730 q->sess.print_error (e);
1731 return DWARF_CB_ABORT;
1732 }
1733}
bb788f9f 1734
7e1279ea 1735static int
2da9cedb 1736query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1737{
2da9cedb 1738 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1739 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1740
bd25380d
JS
1741 // weed out functions whose decl_file isn't one of
1742 // the source files that we actually care about
6b517475 1743 if (q->spec_type != function_alone &&
bd25380d 1744 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1745 return DWARF_CB_OK;
bd25380d 1746
7e1279ea
FCE
1747 try
1748 {
7e1279ea
FCE
1749 q->dw.focus_on_function (func);
1750
7d6d0afc
JS
1751 if (!q->dw.function_scope_matches(q->scopes))
1752 return DWARF_CB_OK;
1753
857bdfd1
JS
1754 // make sure that this function address hasn't
1755 // already been matched under an aliased name
1756 Dwarf_Addr addr;
1757 if (!q->dw.func_is_inline() &&
1758 dwarf_entrypc(func, &addr) == 0 &&
1759 !q->alias_dupes.insert(addr).second)
1760 return DWARF_CB_OK;
1761
4bda987e 1762 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1763 {
4bda987e 1764 if (q->sess.verbose>3)
b530b5b3 1765 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1766 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1767 }
8f14e444
FCE
1768 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1769 {
1770 q->inlined_non_returnable.insert (q->dw.function_name);
1771 }
396afcee 1772 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1773 {
4bda987e
SC
1774 if (q->has_exported && !q->dw.func_is_exported ())
1775 return DWARF_CB_OK;
6b517475 1776 if (q->sess.verbose>2)
b530b5b3 1777 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1778
1779 func_info func;
1780 q->dw.function_die (&func.die);
1781 func.name = q->dw.function_name;
1782 q->dw.function_file (&func.decl_file);
1783 q->dw.function_line (&func.decl_line);
1784
1785 Dwarf_Addr entrypc;
1786 if (q->dw.function_entrypc (&entrypc))
1787 {
1788 func.entrypc = entrypc;
1789 q->filtered_functions.push_back (func);
1790 }
1791 /* else this function is fully inlined, just ignore it */
7e1279ea 1792 }
39bcd429 1793 return DWARF_CB_OK;
bd2b1e68 1794 }
39bcd429 1795 catch (const semantic_error& e)
bd2b1e68 1796 {
39bcd429
FCE
1797 q->sess.print_error (e);
1798 return DWARF_CB_ABORT;
bd2b1e68 1799 }
bd2b1e68
GH
1800}
1801
1802static int
1803query_cu (Dwarf_Die * cudie, void * arg)
1804{
20c6c071 1805 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1806 assert (q->has_statement_str || q->has_function_str);
1807
85007c04 1808 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1809
39bcd429 1810 try
bd2b1e68 1811 {
7e1279ea 1812 q->dw.focus_on_cu (cudie);
b5d77020 1813
b0ee93c4 1814 if (false && q->sess.verbose>2)
b530b5b3
LB
1815 clog << _F("focused on CU '%s', in module '%s'\n",
1816 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1817
6b517475
JS
1818 q->filtered_srcfiles.clear();
1819 q->filtered_functions.clear();
1820 q->filtered_inlines.clear();
1821
1822 // In this path, we find "abstract functions", record
1823 // information about them, and then (depending on lineno
1824 // matching) possibly emit one or more of the function's
1825 // associated addresses. Unfortunately the control of this
1826 // cannot easily be turned inside out.
1827
1828 if (q->spec_type != function_alone)
39bcd429 1829 {
6b517475
JS
1830 // If we have a pattern string with a filename, we need
1831 // to elaborate the srcfile mask in question first.
1832 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1833
1834 // If we have a file pattern and *no* srcfile matches, there's
1835 // no need to look further into this CU, so skip.
1836 if (q->filtered_srcfiles.empty())
1837 return DWARF_CB_OK;
1838 }
e4c58386 1839
6b517475
JS
1840 // Pick up [entrypc, name, DIE] tuples for all the functions
1841 // matching the query, and fill in the prologue endings of them
1842 // all in a single pass.
5898b6e1 1843 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1844 if (rc != DWARF_CB_OK)
1845 q->query_done = true;
1846
1847 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1848 && !q->has_statement_str) // PR 2608
1849 if (! q->filtered_functions.empty())
1850 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1851 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1852 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1853
1854 if (q->spec_type == function_file_and_line)
1855 {
58b070fb 1856 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1857 if (q->has_function_str)
b530b5b3
LB
1858 q->sess.print_warning (_("For probing a particular line, use a "
1859 ".statement() probe, not .function()"),
af2e341f 1860 q->base_probe->tok);
58b070fb 1861
6b517475
JS
1862 // If we have a pattern string with target *line*, we
1863 // have to look at lines in all the matched srcfiles.
1864 void (* callback) (const dwarf_line_t&, void*) =
1865 q->has_label ? query_srcfile_label : query_srcfile_line;
1866 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1867 i != q->filtered_srcfiles.end(); ++i)
1868 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1869 q->line_type, callback, q->function, q);
1870 }
1871 else if (q->has_label)
1872 {
1873 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1874 i != q->filtered_functions.end(); ++i)
1875 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1876 q, query_label);
1877
1878 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1879 i != q->filtered_inlines.end(); ++i)
1880 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1881 q, query_label);
39bcd429 1882 }
6b517475
JS
1883 else
1884 {
1885 // Otherwise, simply probe all resolved functions.
1886 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1887 i != q->filtered_functions.end(); ++i)
1888 query_func_info (i->entrypc, *i, q);
1889
1890 // And all inline instances (if we're not excluding inlines with ".call")
1891 if (! q->has_call)
1892 for (inline_instance_map_t::iterator i
1893 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1894 query_inline_instance_info (*i, q);
1895 }
39bcd429 1896 return DWARF_CB_OK;
bd2b1e68 1897 }
39bcd429 1898 catch (const semantic_error& e)
bd2b1e68 1899 {
39bcd429
FCE
1900 q->sess.print_error (e);
1901 return DWARF_CB_ABORT;
bd2b1e68 1902 }
bd2b1e68
GH
1903}
1904
0ce64fb8 1905
4df79aaf
JS
1906void
1907dwarf_query::query_module_functions ()
1908{
1909 try
1910 {
1911 filtered_srcfiles.clear();
1912 filtered_functions.clear();
1913 filtered_inlines.clear();
1914
1915 // Collect all module functions so we know which CUs are interesting
1916 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1917 if (rc != DWARF_CB_OK)
1918 {
1919 query_done = true;
1920 return;
1921 }
1922
1923 set<void*> used_cus; // by cu->addr
1924 vector<Dwarf_Die> cus;
1925 Dwarf_Die cu_mem;
1926
1927 for (func_info_map_t::iterator i = filtered_functions.begin();
1928 i != filtered_functions.end(); ++i)
1929 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1930 used_cus.insert(cu_mem.addr).second)
1931 cus.push_back(cu_mem);
1932
1933 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1934 i != filtered_inlines.end(); ++i)
1935 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1936 used_cus.insert(cu_mem.addr).second)
1937 cus.push_back(cu_mem);
1938
1939 // Reset the dupes since we didn't actually collect them the first time
1940 alias_dupes.clear();
1941 inline_dupes.clear();
1942
1943 // Run the query again on the individual CUs
1944 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1945 query_cu(&*i, this);
1946 }
1947 catch (const semantic_error& e)
1948 {
1949 sess.print_error (e);
1950 }
1951}
1952
1953
5f0a03a6
JK
1954static void
1955validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1956{
1957 // Validate the machine code in this elf file against the
1958 // session machine. This is important, in case the wrong kind
1959 // of debuginfo is being automagically processed by elfutils.
1960 // While we can tell i686 apart from x86-64, unfortunately
1961 // we can't help confusing i586 vs i686 (both EM_386).
1962
1963 Dwarf_Addr bias;
1964 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1965 // because dwfl_module_getelf can force costly section relocations
1966 // we don't really need, while either will do for this purpose.
1967 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1968 ?: dwfl_module_getelf (mod, &bias));
1969
1970 GElf_Ehdr ehdr_mem;
1971 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1972 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 1973 assert(em);
5f0a03a6
JK
1974 int elf_machine = em->e_machine;
1975 const char* debug_filename = "";
1976 const char* main_filename = "";
1977 (void) dwfl_module_info (mod, NULL, NULL,
1978 NULL, NULL, NULL,
1979 & main_filename,
1980 & debug_filename);
1981 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1982
1983 string expect_machine; // to match sess.machine (i.e., kernel machine)
1984 string expect_machine2;
5f0a03a6 1985
d27e6fd5 1986 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1987 switch (elf_machine)
1988 {
756c9462
FCE
1989 // x86 and ppc are bi-architecture; a 64-bit kernel
1990 // can normally run either 32-bit or 64-bit *userspace*.
1991 case EM_386:
1992 expect_machine = "i?86";
1993 if (! q->has_process) break; // 32-bit kernel/module
1994 /* FALLSTHROUGH */
1995 case EM_X86_64:
1996 expect_machine2 = "x86_64";
1997 break;
1998 case EM_PPC:
756c9462 1999 case EM_PPC64:
5a1c472e 2000 expect_machine = "powerpc";
756c9462 2001 break;
3fe7d888 2002 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2003 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2004 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
2005 // XXX: fill in some more of these
2006 default: expect_machine = "?"; break;
2007 }
2008
2009 if (! debug_filename) debug_filename = main_filename;
2010 if (! debug_filename) debug_filename = name;
2011
756c9462
FCE
2012 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2013 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2014 {
2015 stringstream msg;
b530b5b3
LB
2016 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2017 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2018 sess_machine.c_str(), debug_filename);
5f0a03a6
JK
2019 throw semantic_error(msg.str ());
2020 }
2021
b57082de 2022 if (q->sess.verbose>1)
2a97f50b 2023 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2024 " file %s ELF machine %s|%s (code %d)\n",
2025 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2026 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2027 expect_machine2.c_str(), elf_machine);
5f0a03a6 2028}
1d3a40b6 2029
91af0778
FCE
2030
2031
2032static Dwarf_Addr
2033lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2034{
2035 int syments = dwfl_module_getsymtab(m);
2036 assert(syments);
2037 for (int i = 1; i < syments; ++i)
2038 {
2039 GElf_Sym sym;
2040 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2041 if (name != NULL && strcmp(name, wanted) == 0)
2042 return sym.st_value;
2043 }
2044
2045 return 0;
2046}
2047
2048
2049
bd2b1e68 2050static int
b8da0ad1 2051query_module (Dwfl_Module *mod,
91af0778 2052 void **,
b8da0ad1 2053 const char *name,
6f4c1275 2054 Dwarf_Addr addr,
b8da0ad1 2055 void *arg)
bd2b1e68 2056{
91af0778 2057 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 2058
39bcd429 2059 try
e38d6504 2060 {
91af0778
FCE
2061 module_info* mi = q->sess.module_cache->cache[name];
2062 if (mi == 0)
2063 {
2064 mi = q->sess.module_cache->cache[name] = new module_info(name);
2065
6f4c1275
FCE
2066 mi->mod = mod;
2067 mi->addr = addr;
91af0778 2068
6f4c1275
FCE
2069 const char* debug_filename = "";
2070 const char* main_filename = "";
2071 (void) dwfl_module_info (mod, NULL, NULL,
2072 NULL, NULL, NULL,
2073 & main_filename,
2074 & debug_filename);
2075
ab3ed72d 2076 if (debug_filename || main_filename)
91af0778 2077 {
6f4c1275
FCE
2078 mi->elf_path = debug_filename ?: main_filename;
2079 }
2080 else if (name == TOK_KERNEL)
2081 {
2082 mi->dwarf_status = info_absent;
91af0778 2083 }
91af0778
FCE
2084 }
2085 // OK, enough of that module_info caching business.
2086
5f0a03a6 2087 q->dw.focus_on_module(mod, mi);
d9b516ca 2088
39bcd429
FCE
2089 // If we have enough information in the pattern to skip a module and
2090 // the module does not match that information, return early.
b8da0ad1 2091 if (!q->dw.module_name_matches(q->module_val))
85007c04 2092 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2093
2094 // Don't allow module("*kernel*") type expressions to match the
2095 // elfutils module "kernel", which we refer to in the probe
2096 // point syntax exclusively as "kernel.*".
2097 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2098 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2099
5f0a03a6
JK
2100 if (mod)
2101 validate_module_elf(mod, name, q);
2102 else
91af0778
FCE
2103 assert(q->has_kernel); // and no vmlinux to examine
2104
2105 if (q->sess.verbose>2)
b530b5b3 2106 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2107
2108
2109 // Collect a few kernel addresses. XXX: these belong better
2110 // to the sess.module_info["kernel"] struct.
2111 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2112 {
91af0778
FCE
2113 if (! q->sess.sym_kprobes_text_start)
2114 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2115 if (! q->sess.sym_kprobes_text_end)
2116 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2117 if (! q->sess.sym_stext)
2118 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2119 }
2120
47e226ed
SC
2121 // We either have a wildcard or an unresolved library
2122 if (q->has_library && (contains_glob_chars (q->path)
2123 || q->path.find('/') == string::npos))
84c84ac4
SC
2124 // handle .library(GLOB)
2125 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2126 // .plt is translated to .plt.statement(N). We only want to iterate for the
2127 // .plt case
2128 else if (q->has_plt && ! q->has_statement)
2129 q->dw.iterate_over_plt (q, &q->query_plt_callback);
84c84ac4
SC
2130 else
2131 // search the module for matches of the probe point.
2132 q->handle_query_module();
bb788f9f 2133
b8da0ad1 2134 // If we know that there will be no more matches, abort early.
85007c04 2135 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2136 return DWARF_CB_ABORT;
2137 else
2138 return DWARF_CB_OK;
7a053d3b 2139 }
39bcd429 2140 catch (const semantic_error& e)
bd2b1e68 2141 {
39bcd429
FCE
2142 q->sess.print_error (e);
2143 return DWARF_CB_ABORT;
bd2b1e68 2144 }
bd2b1e68
GH
2145}
2146
35d4ab18 2147
84c84ac4 2148void
5d5bd369 2149base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2150{
2151 base_query *me = (base_query*)q;
5d5bd369 2152 me->query_library (data);
84c84ac4
SC
2153}
2154
2155
2cbcfa9c 2156string
51d6bda3
SC
2157query_one_library (const char *library, dwflpp & dw,
2158 const string user_lib, probe * base_probe, probe_point *base_loc,
2159 vector<derived_probe *> & results)
84c84ac4 2160{
47e226ed 2161 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2162 {
05fb3e0c
WF
2163 string library_path = find_executable (library, "", dw.sess.sysenv,
2164 "LD_LIBRARY_PATH");
84c84ac4
SC
2165 probe_point* specific_loc = new probe_point(*base_loc);
2166 specific_loc->optional = true;
2167 vector<probe_point::component*> derived_comps;
2168
2169 vector<probe_point::component*>::iterator it;
2170 for (it = specific_loc->components.begin();
2171 it != specific_loc->components.end(); ++it)
2172 if ((*it)->functor == TOK_LIBRARY)
2173 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2174 new literal_string(library_path)));
2175 else
2176 derived_comps.push_back(*it);
2177 probe_point* derived_loc = new probe_point(*specific_loc);
2178 derived_loc->components = derived_comps;
8159bf55 2179 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2180 derive_probes(dw.sess, new_base, results);
2181 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2182 clog << _("module=") << library_path << endl;
2183 return library_path;
84c84ac4 2184 }
2cbcfa9c 2185 return "";
84c84ac4
SC
2186}
2187
2188
51d6bda3
SC
2189void
2190dwarf_query::query_library (const char *library)
2191{
2cbcfa9c
JL
2192 string library_path =
2193 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2194 if (!library_path.empty())
2195 visited_modules.insert(library_path);
51d6bda3
SC
2196}
2197
576eaefe
SC
2198struct plt_expanding_visitor: public var_expanding_visitor
2199{
2200 plt_expanding_visitor(const string & entry):
2201 entry (entry)
2202 {
2203 }
2204 const string & entry;
2205
2206 void visit_target_symbol (target_symbol* e);
2207};
2208
2209
2210void
2211base_query::query_plt_callback (void *q, const char *entry, size_t address)
2212{
2213 base_query *me = (base_query*)q;
2214 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2215 me->query_plt (entry, address);
2216}
2217
2218
2219void
2220query_one_plt (const char *entry, long addr, dwflpp & dw,
2221 probe * base_probe, probe_point *base_loc,
2222 vector<derived_probe *> & results)
2223{
2224 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2225 vector<probe_point::component*> derived_comps;
2226
2227 if (dw.sess.verbose > 2)
2228 clog << _F("plt entry=%s\n", entry);
2229
2230 // query_module_symtab requires .plt to recognize that it can set the probe at
2231 // a plt entry so we convert process.plt to process.plt.statement
2232 vector<probe_point::component*>::iterator it;
2233 for (it = specific_loc->components.begin();
2234 it != specific_loc->components.end(); ++it)
2235 if ((*it)->functor == TOK_PLT)
3d372d6b 2236 {
8159bf55
FCE
2237 *it = new probe_point::component(TOK_PLT,
2238 new literal_string(entry));
3d372d6b
SC
2239 derived_comps.push_back(*it);
2240 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2241 new literal_number(addr, true)));
3d372d6b 2242 }
576eaefe
SC
2243 else
2244 derived_comps.push_back(*it);
2245 probe_point* derived_loc = new probe_point(*specific_loc);
2246 derived_loc->components = derived_comps;
02c34e38
FCE
2247 probe *new_base = new probe (new probe (base_probe, specific_loc),
2248 derived_loc);
576eaefe
SC
2249 string e = string(entry);
2250 plt_expanding_visitor pltv (e);
2251 pltv.replace (new_base->body);
2252 derive_probes(dw.sess, new_base, results);
2253}
2254
2255
2256void
2257dwarf_query::query_plt (const char *entry, size_t address)
2258{
2259 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2260}
51d6bda3 2261
435f53a7
FCE
2262// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2263// but the needed declaration for module_cache is not available there.
2264// Nor for that matter in session.cxx. Only in this CU is that field ever
2265// set (in query_module() above), so we clean it up here too.
2266static void
2267delete_session_module_cache (systemtap_session& s)
2268{
2269 if (s.module_cache) {
2270 if (s.verbose > 3)
b530b5b3 2271 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2272 delete s.module_cache;
2273 s.module_cache = 0;
2274 }
2275}
2276
2277
de688825 2278struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2279{
77de5e9e 2280 dwarf_query & q;
bcc12710 2281 Dwarf_Die *scope_die;
77de5e9e 2282 Dwarf_Addr addr;
8c819921 2283 block *add_block;
2260f4e3 2284 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2285 // NB: tids are not always collected in add_block & add_call_probe, because
2286 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2287 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2288 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2289 unsigned saved_longs, saved_strings; // data saved within kretprobes
2290 map<std::string, expression *> return_ts_map;
729455a7 2291 vector<Dwarf_Die> scopes;
3689db05 2292 // probe counter name -> pointer of associated probe
698de6cc 2293 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2294 bool visited;
77de5e9e 2295
de688825 2296 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2297 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2298 add_block_tid(false), add_call_probe_tid(false),
af234c40 2299 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2300 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2301 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2302 void visit_target_symbol_saved_return (target_symbol* e);
2303 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2304 void visit_target_symbol (target_symbol* e);
bd1fcbad 2305 void visit_atvar_op (atvar_op* e);
c24447be 2306 void visit_cast_op (cast_op* e);
8cc799a5 2307 void visit_entry_op (entry_op* e);
3689db05 2308 void visit_perf_op (perf_op* e);
729455a7
JS
2309private:
2310 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2311};
2312
2313
de688825 2314unsigned var_expanding_visitor::tick = 0;
77de5e9e 2315
a50de939 2316
74fe61bc 2317var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2318{
2319 // FIXME: for the time being, by default we only support plain '$foo
2320 // = bar', not '+=' or any other op= variant. This is fixable, but a
2321 // bit ugly.
2322 //
2323 // If derived classes desire to add additional operator support, add
2324 // new operators to this list in the derived class constructor.
2325 valid_ops.insert ("=");
2326}
2327
2328
87214add
JS
2329bool
2330var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2331 expression*& lvalue, expression*& rvalue)
77de5e9e 2332{
e57b735a
GH
2333 // Our job would normally be to require() the left and right sides
2334 // into a new assignment. What we're doing is slightly trickier:
2335 // we're pushing a functioncall** onto a stack, and if our left
2336 // child sets the functioncall* for that value, we're going to
2337 // assume our left child was a target symbol -- transformed into a
2338 // set_target_foo(value) call, and it wants to take our right child
2339 // as the argument "value".
2340 //
2341 // This is why some people claim that languages with
2342 // constructor-decomposing case expressions have a leg up on
2343 // visitors.
2344
2345 functioncall *fcall = NULL;
d9b516ca 2346
a50de939 2347 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2348 const string* old_op = op;
2349 op = &eop;
a50de939 2350
e57b735a 2351 target_symbol_setter_functioncalls.push (&fcall);
87214add 2352 replace (lvalue);
e57b735a 2353 target_symbol_setter_functioncalls.pop ();
87214add
JS
2354 replace (rvalue);
2355
2356 op = old_op;
e57b735a
GH
2357
2358 if (fcall != NULL)
77de5e9e 2359 {
e57b735a
GH
2360 // Our left child is informing us that it was a target variable
2361 // and it has been replaced with a set_target_foo() function
2362 // call; we are going to provide that function call -- with the
2363 // right child spliced in as sole argument -- in place of
de688825 2364 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2365
87214add 2366 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2367 {
2368 // Build up a list of supported operators.
2369 string ops;
2370 std::set<string>::iterator i;
b530b5b3 2371 int valid_ops_size = 0;
a50de939 2372 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2373 {
a50de939 2374 ops += " " + *i + ",";
b530b5b3
LB
2375 valid_ops_size++;
2376 }
a50de939
DS
2377 ops.resize(ops.size() - 1); // chop off the last ','
2378
2379 // Throw the error.
52c2652f 2380 throw semantic_error (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2381 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2382 valid_ops_size, ops.c_str()), tok);
b530b5b3 2383
a50de939 2384 }
e57b735a 2385
87214add
JS
2386 assert (lvalue == fcall);
2387 if (rvalue)
2388 fcall->args.push_back (rvalue);
4ed05b15 2389 provide (fcall);
87214add 2390 return true;
77de5e9e 2391 }
e57b735a 2392 else
87214add
JS
2393 return false;
2394}
2395
2396
2397void
2398var_expanding_visitor::visit_assignment (assignment* e)
2399{
2400 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2401 provide (e);
2402}
2403
2404
2405void
2406var_expanding_visitor::visit_pre_crement (pre_crement* e)
2407{
2408 expression *dummy = NULL;
2409 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2410 provide (e);
2411}
2412
2413
2414void
2415var_expanding_visitor::visit_post_crement (post_crement* e)
2416{
2417 expression *dummy = NULL;
2418 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2419 provide (e);
2420}
2421
2422
2423void
2424var_expanding_visitor::visit_delete_statement (delete_statement* s)
2425{
2426 string fakeop = "delete";
2427 expression *dummy = NULL;
2428 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2429 provide (s);
e57b735a 2430}
d9b516ca 2431
d7f3e0c5 2432
30263a73
FCE
2433void
2434var_expanding_visitor::visit_defined_op (defined_op* e)
2435{
2436 bool resolved = true;
2437
2438 defined_ops.push (e);
2439 try {
2440 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2441 // defined with a target_symbol* operand, a subsidiary call may attempt to
2442 // rewrite it to a general expression* instead, and require<> happily
2443 // casts to/from void*, causing possible memory corruption. We use
2444 // expression* here, being the general case of rewritten $variable.
2445 expression *foo1 = e->operand;
2446 foo1 = require (foo1);
2447
c69a87e0 2448 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2449 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2450 // erroneous resolutions. Some would signal a visit_target_symbol failure
2451 // with an exception, with a set flag within the target_symbol, or nothing
2452 // at all.
30263a73 2453 //
c69a87e0
FCE
2454 // Now, failures always have to be signalled with a
2455 // saved_conversion_error being chained to the target_symbol.
2456 // Successes have to result in an attempted rewrite of the
850bfddd 2457 // target_symbol (via provide()).
780f11ff 2458 //
c69a87e0
FCE
2459 // Edna Mode: "no capes". fche: "no exceptions".
2460
30263a73
FCE
2461 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2462 //
2463 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2464 //
2465 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2466 // dwarf probe to take care of it.
2467 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2468 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2469 //
30263a73
FCE
2470 // utrace: success: rewrites to function; failure: semantic_error
2471 //
850bfddd 2472 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2473
2474 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2475 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2476 resolved = false;
a45664f4 2477 else if (foo2) // unresolved but not marked failing
b7aedf26 2478 {
780f11ff
JS
2479 // There are some visitors that won't touch certain target_symbols,
2480 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2481 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2482 e->operand = foo2;
2483 provide (e);
2484 return;
2485 }
30263a73
FCE
2486 else // resolved, rewritten to some other expression type
2487 resolved = true;
780f11ff 2488 } catch (const semantic_error& e) {
c69a87e0 2489 assert (0); // should not happen
30263a73
FCE
2490 }
2491 defined_ops.pop ();
2492
2493 literal_number* ln = new literal_number (resolved ? 1 : 0);
2494 ln->tok = e->tok;
2495 provide (ln);
2496}
2497
2498
5f36109e
JS
2499struct dwarf_pretty_print
2500{
2501 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2502 const string& local, bool userspace_p,
2503 const target_symbol& e):
d19a9a82
JS
2504 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2505 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2506 {
2507 init_ts (e);
2508 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2509 }
2510
2511 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2512 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2513 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2514 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2515 {
2516 init_ts (e);
2517 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2518 }
2519
2520 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2521 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2522 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2523 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2524 {
2525 init_ts (e);
2526 dw.type_die_for_pointer (type_die, ts, &base_type);
2527 }
2528
2529 functioncall* expand ();
ce83ff57 2530 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2531
2532private:
2533 dwflpp& dw;
2534 target_symbol* ts;
7d11d8c9 2535 bool print_full;
5f36109e
JS
2536 Dwarf_Die base_type;
2537
2538 string local;
2539 vector<Dwarf_Die> scopes;
2540 Dwarf_Addr pc;
2541
2542 expression* pointer;
2543 Dwarf_Die pointer_type;
2544
d19a9a82 2545 const bool userspace_p, deref_p;
5f36109e
JS
2546
2547 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2548 print_format* pf, bool top=false);
600551ca
JS
2549 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2550 print_format* pf);
5f36109e 2551 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2552 print_format* pf);
5f36109e 2553 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2554 print_format* pf, bool top);
5f36109e 2555 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2556 print_format* pf, bool top);
5f36109e 2557 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2558 print_format* pf, bool top);
5f36109e 2559 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2560 print_format* pf, int& count);
bbee5bb8 2561 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2562
2563 void init_ts (const target_symbol& e);
2564 expression* deref (target_symbol* e);
c55ea10d 2565 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2566};
2567
2568
2569void
2570dwarf_pretty_print::init_ts (const target_symbol& e)
2571{
2572 // Work with a new target_symbol so we can modify arguments
2573 ts = new target_symbol (e);
2574
2575 if (ts->addressof)
b530b5b3 2576 throw semantic_error(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2577
2578 if (ts->components.empty() ||
2579 ts->components.back().type != target_symbol::comp_pretty_print)
b530b5b3 2580 throw semantic_error(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2581 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2582 ts->components.pop_back();
2583}
2584
2585
2586functioncall*
2587dwarf_pretty_print::expand ()
2588{
2589 static unsigned tick = 0;
2590
2591 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2592 // try {
2593 // return sprintf("{.foo=...}", (ts)->foo, ...)
2594 // } catch {
2595 // return "ERROR"
2596 // }
5f36109e
JS
2597 // }
2598
2599 // Create the function decl and call.
2600
2601 functiondecl *fdecl = new functiondecl;
2602 fdecl->tok = ts->tok;
2603 fdecl->synthetic = true;
2604 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2605 fdecl->type = pe_string;
2606
2607 functioncall* fcall = new functioncall;
2608 fcall->tok = ts->tok;
2609 fcall->function = fdecl->name;
140be17a 2610 fcall->type = pe_string;
5f36109e
JS
2611
2612 // If there's a <pointer>, replace it with a new var and make that
2613 // the first function argument.
2614 if (pointer)
2615 {
2616 vardecl *v = new vardecl;
2617 v->type = pe_long;
2618 v->name = "pointer";
2619 v->tok = ts->tok;
2620 fdecl->formal_args.push_back (v);
2621 fcall->args.push_back (pointer);
2622
2623 symbol* sym = new symbol;
2624 sym->tok = ts->tok;
2625 sym->name = v->name;
5f36109e
JS
2626 pointer = sym;
2627 }
2628
2629 // For each expression argument, replace it with a function argument.
2630 for (unsigned i = 0; i < ts->components.size(); ++i)
2631 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2632 {
2633 vardecl *v = new vardecl;
2634 v->type = pe_long;
2635 v->name = "index" + lex_cast(i);
2636 v->tok = ts->tok;
2637 fdecl->formal_args.push_back (v);
2638 fcall->args.push_back (ts->components[i].expr_index);
2639
2640 symbol* sym = new symbol;
2641 sym->tok = ts->tok;
2642 sym->name = v->name;
5f36109e
JS
2643 ts->components[i].expr_index = sym;
2644 }
2645
2646 // Create the return sprintf.
2647 token* pf_tok = new token(*ts->tok);
2648 pf_tok->content = "sprintf";
2649 print_format* pf = print_format::create(pf_tok);
2650 return_statement* rs = new return_statement;
2651 rs->tok = ts->tok;
2652 rs->value = pf;
5f36109e
JS
2653
2654 // Recurse into the actual values.
7d11d8c9 2655 recurse (&base_type, ts, pf, true);
5f36109e
JS
2656 pf->components = print_format::string_to_components(pf->raw_components);
2657
7d11d8c9
JS
2658 // Create the try-catch net
2659 try_block* tb = new try_block;
2660 tb->tok = ts->tok;
2661 tb->try_block = rs;
2662 tb->catch_error_var = 0;
2663 return_statement* rs2 = new return_statement;
2664 rs2->tok = ts->tok;
2665 rs2->value = new literal_string ("ERROR");
2666 rs2->value->tok = ts->tok;
2667 tb->catch_block = rs2;
2668 fdecl->body = tb;
2669
f8809d54 2670 fdecl->join (dw.sess);
5f36109e
JS
2671 return fcall;
2672}
2673
2674
2675void
2676dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2677 print_format* pf, bool top)
5f36109e
JS
2678{
2679 Dwarf_Die type;
2680 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2681
2682 switch (dwarf_tag(&type))
2683 {
2684 default:
2685 // XXX need a warning?
2686 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2687 // + ") for " + dwarf_type_name(&type), e->tok);
2688 pf->raw_components.append("?");
2689 break;
2690
2691 case DW_TAG_enumeration_type:
2692 case DW_TAG_base_type:
7d11d8c9 2693 recurse_base (&type, e, pf);
5f36109e
JS
2694 break;
2695
2696 case DW_TAG_array_type:
7d11d8c9 2697 recurse_array (&type, e, pf, top);
5f36109e
JS
2698 break;
2699
2700 case DW_TAG_pointer_type:
2701 case DW_TAG_reference_type:
2702 case DW_TAG_rvalue_reference_type:
7d11d8c9 2703 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2704 break;
2705
2706 case DW_TAG_subroutine_type:
c55ea10d 2707 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2708 break;
2709
2710 case DW_TAG_union_type:
5f36109e
JS
2711 case DW_TAG_structure_type:
2712 case DW_TAG_class_type:
7d11d8c9 2713 recurse_struct (&type, e, pf, top);
5f36109e
JS
2714 break;
2715 }
2716}
2717
2718
600551ca
JS
2719// Bit fields are handled as a special-case combination of recurse() and
2720// recurse_base(), only called from recurse_struct_members(). The main
2721// difference is that the value is always printed numerically, even if the
2722// underlying type is a char.
2723void
2724dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2725 print_format* pf)
2726{
2727 Dwarf_Die type;
2728 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2729
2730 int tag = dwarf_tag(&type);
2731 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2732 {
2733 // XXX need a warning?
2734 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2735 // + ") for " + dwarf_type_name(&type), e->tok);
2736 pf->raw_components.append("?");
2737 return;
2738 }
2739
2740 Dwarf_Attribute attr;
2741 Dwarf_Word encoding = (Dwarf_Word) -1;
2742 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2743 &encoding);
2744 switch (encoding)
2745 {
2746 case DW_ATE_float:
2747 case DW_ATE_complex_float:
2748 // XXX need a warning?
2749 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2750 // + ") for " + dwarf_type_name(&type), e->tok);
2751 pf->raw_components.append("?");
2752 break;
2753
2754 case DW_ATE_unsigned:
2755 case DW_ATE_unsigned_char:
2756 push_deref (pf, "%u", e);
2757 break;
2758
2759 case DW_ATE_signed:
2760 case DW_ATE_signed_char:
2761 default:
2762 push_deref (pf, "%i", e);
2763 break;
2764 }
2765}
2766
2767
5f36109e
JS
2768void
2769dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2770 print_format* pf)
5f36109e
JS
2771{
2772 Dwarf_Attribute attr;
2773 Dwarf_Word encoding = (Dwarf_Word) -1;
2774 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2775 &encoding);
5f36109e
JS
2776 switch (encoding)
2777 {
2778 case DW_ATE_float:
2779 case DW_ATE_complex_float:
2780 // XXX need a warning?
2781 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2782 // + ") for " + dwarf_type_name(type), e->tok);
2783 pf->raw_components.append("?");
5f36109e
JS
2784 break;
2785
6561d8d1 2786 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2787 case DW_ATE_signed_char:
2788 case DW_ATE_unsigned_char:
941101c1
JS
2789 // Use escapes to make sure that non-printable characters
2790 // don't interrupt our stream (especially '\0' values).
2791 push_deref (pf, "'%#c'", e);
5f36109e
JS
2792 break;
2793
2794 case DW_ATE_unsigned:
c55ea10d 2795 push_deref (pf, "%u", e);
5f36109e
JS
2796 break;
2797
600551ca 2798 case DW_ATE_signed:
5f36109e 2799 default:
c55ea10d 2800 push_deref (pf, "%i", e);
5f36109e
JS
2801 break;
2802 }
5f36109e
JS
2803}
2804
2805
2806void
2807dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2808 print_format* pf, bool top)
5f36109e 2809{
7d11d8c9
JS
2810 if (!top && !print_full)
2811 {
2812 pf->raw_components.append("[...]");
2813 return;
2814 }
2815
5f36109e
JS
2816 Dwarf_Die childtype;
2817 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2818
2819 if (print_chars (&childtype, e, pf))
2820 return;
2821
5f36109e
JS
2822 pf->raw_components.append("[");
2823
2824 // We print the array up to the first 5 elements.
2825 // XXX how can we determine the array size?
2826 // ... for now, just print the first element
64cddf39 2827 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2828 unsigned i, size = 1;
64cddf39 2829 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2830 {
2831 if (i > 0)
2832 pf->raw_components.append(", ");
2833 target_symbol* e2 = new target_symbol(*e);
2834 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2835 recurse (&childtype, e2, pf);
5f36109e
JS
2836 }
2837 if (i < size || 1/*XXX until real size is known */)
2838 pf->raw_components.append(", ...");
2839 pf->raw_components.append("]");
2840}
2841
2842
2843void
2844dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2845 print_format* pf, bool top)
5f36109e 2846{
7d11d8c9 2847 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2848 bool void_p = true;
7d11d8c9 2849 Dwarf_Die pointee;
bbee5bb8 2850 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2851 {
2852 try
2853 {
2854 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2855 void_p = false;
2856 }
2857 catch (const semantic_error&) {}
2858 }
2859
2860 if (!void_p)
5f36109e 2861 {
bbee5bb8
JS
2862 if (print_chars (&pointee, e, pf))
2863 return;
2864
2865 if (top)
2866 {
2867 recurse (&pointee, e, pf, top);
2868 return;
2869 }
5f36109e 2870 }
bbee5bb8 2871
c55ea10d 2872 push_deref (pf, "%p", e);
5f36109e
JS
2873}
2874
2875
2876void
2877dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2878 print_format* pf, bool top)
5f36109e 2879{
bdec0e18
JS
2880 if (dwarf_hasattr(type, DW_AT_declaration))
2881 {
a44a7cb5 2882 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2883 if (!resolved)
2884 {
2885 // could be an error, but for now just stub it
2886 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2887 pf->raw_components.append("{...}");
2888 return;
2889 }
2890 type = resolved;
2891 }
2892
5f36109e
JS
2893 int count = 0;
2894 pf->raw_components.append("{");
7d11d8c9
JS
2895 if (top || print_full)
2896 recurse_struct_members (type, e, pf, count);
2897 else
2898 pf->raw_components.append("...");
5f36109e
JS
2899 pf->raw_components.append("}");
2900}
2901
2902
2903void
2904dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2905 print_format* pf, int& count)
5f36109e 2906{
a80f28d8
JS
2907 /* With inheritance, a subclass may mask member names of parent classes, so
2908 * our search among the inheritance tree must be breadth-first rather than
2909 * depth-first (recursive). The type die is still our starting point. When
2910 * we encounter a masked name, just skip it. */
2911 set<string> dupes;
2912 deque<Dwarf_Die> inheritees(1, *type);
2913 for (; !inheritees.empty(); inheritees.pop_front())
2914 {
dee830d9 2915 Dwarf_Die child, childtype, import;
a80f28d8
JS
2916 if (dwarf_child (&inheritees.front(), &child) == 0)
2917 do
2918 {
2919 target_symbol* e2 = e;
5f36109e 2920
a80f28d8
JS
2921 // skip static members
2922 if (dwarf_hasattr(&child, DW_AT_declaration))
2923 continue;
5f36109e 2924
a80f28d8 2925 int tag = dwarf_tag (&child);
5f36109e 2926
dee830d9
MW
2927 /* Pretend imported units contain members by recursing into
2928 struct_member printing with the same count. */
2929 if (tag == DW_TAG_imported_unit
2930 && dwarf_attr_die (&child, DW_AT_import, &import))
2931 recurse_struct_members (&import, e2, pf, count);
2932
a80f28d8
JS
2933 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2934 continue;
5f36109e 2935
a80f28d8 2936 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2937
a80f28d8
JS
2938 if (tag == DW_TAG_inheritance)
2939 {
2940 inheritees.push_back(childtype);
2941 continue;
2942 }
5f36109e 2943
a80f28d8
JS
2944 int childtag = dwarf_tag (&childtype);
2945 const char *member = dwarf_diename (&child);
3a147004 2946
a80f28d8
JS
2947 // "_vptr.foo" members are C++ virtual function tables,
2948 // which (generally?) aren't interesting for users.
2949 if (member && startswith(member, "_vptr."))
2950 continue;
3a147004 2951
a80f28d8
JS
2952 // skip inheritance-masked duplicates
2953 if (member && !dupes.insert(member).second)
2954 continue;
64cddf39 2955
a80f28d8
JS
2956 if (++count > 1)
2957 pf->raw_components.append(", ");
64cddf39 2958
a80f28d8
JS
2959 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2960 if (pf->args.size() >= 32)
2961 {
2962 pf->raw_components.append("...");
2963 break;
2964 }
2965
2966 if (member)
2967 {
2968 pf->raw_components.append(".");
2969 pf->raw_components.append(member);
5f36109e 2970
a80f28d8
JS
2971 e2 = new target_symbol(*e);
2972 e2->components.push_back (target_symbol::component(e->tok, member));
2973 }
2974 else if (childtag == DW_TAG_union_type)
2975 pf->raw_components.append("<union>");
2976 else if (childtag == DW_TAG_structure_type)
2977 pf->raw_components.append("<class>");
2978 else if (childtag == DW_TAG_class_type)
2979 pf->raw_components.append("<struct>");
2980 pf->raw_components.append("=");
600551ca
JS
2981
2982 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
2983 recurse_bitfield (&childtype, e2, pf);
2984 else
2985 recurse (&childtype, e2, pf);
5f36109e 2986 }
a80f28d8
JS
2987 while (dwarf_siblingof (&child, &child) == 0);
2988 }
5f36109e
JS
2989}
2990
2991
bbee5bb8
JS
2992bool
2993dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2994 print_format* pf)
2995{
2996 Dwarf_Die type;
2997 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
2998
2999 Dwarf_Attribute attr;
3000 Dwarf_Word encoding = (Dwarf_Word) -1;
3001 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3002 &encoding);
3003 switch (encoding)
bbee5bb8 3004 {
6561d8d1
JS
3005 case DW_ATE_UTF:
3006 case DW_ATE_signed_char:
3007 case DW_ATE_unsigned_char:
3008 break;
3009 default:
3010 return false;
3011 }
3012
3013 string function = userspace_p ? "user_string2" : "kernel_string2";
3014 Dwarf_Word size = (Dwarf_Word) -1;
3015 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3016 switch (size)
3017 {
3018 case 1:
3019 break;
3020 case 2:
3021 function += "_utf16";
3022 break;
3023 case 4:
3024 function += "_utf32";
3025 break;
3026 default:
3027 return false;
3028 }
3029
3030 if (push_deref (pf, "\"%s\"", e))
3031 {
3032 // steal the last arg for a string access
3033 assert (!pf->args.empty());
3034 functioncall* fcall = new functioncall;
3035 fcall->tok = e->tok;
3036 fcall->function = function;
3037 fcall->args.push_back (pf->args.back());
3038 expression *err_msg = new literal_string ("<unknown>");
3039 err_msg->tok = e->tok;
3040 fcall->args.push_back (err_msg);
3041 pf->args.back() = fcall;
bbee5bb8 3042 }
6561d8d1 3043 return true;
bbee5bb8
JS
3044}
3045
a5ce5211
MW
3046// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3047static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3048 + "#define fetch_register k_fetch_register\n"
3049 + "#define store_register k_store_register\n"
3050 + "#define deref kderef\n"
3051 + "#define store_deref store_kderef\n";
a5ce5211
MW
3052
3053static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3054 + "#define fetch_register u_fetch_register\n"
3055 + "#define store_register u_store_register\n"
3056 + "#define deref uderef\n"
3057 + "#define store_deref store_uderef\n";
a5ce5211
MW
3058
3059#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3060 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3061
3062static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3063 + "#undef fetch_register\n"
3064 + "#undef store_register\n"
3065 + "#undef deref\n"
3066 + "#undef store_deref\n";
bbee5bb8 3067
1c0be8c7
JS
3068static functioncall*
3069synthetic_embedded_deref_call(systemtap_session& session,
3070 const string& function_name,
3071 const string& function_code,
3072 exp_type function_type,
3073 bool userspace_p,
3074 bool lvalue_p,
3075 target_symbol* e,
3076 expression* pointer=NULL)
3077{
3078 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3079 functiondecl *fdecl = new functiondecl;
3080 fdecl->synthetic = true;
3081 fdecl->tok = e->tok;
1c0be8c7
JS
3082 fdecl->name = function_name;
3083 fdecl->type = function_type;
3084
5f36109e
JS
3085 embeddedcode *ec = new embeddedcode;
3086 ec->tok = e->tok;
1c0be8c7
JS
3087 ec->code += "/* unprivileged */";
3088 if (! lvalue_p)
3089 ec->code += "/* pure */";
3090 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3091 ec->code += function_code;
3092 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3093 fdecl->body = ec;
3094
3095 // Synthesize a functioncall.
3096 functioncall* fcall = new functioncall;
3097 fcall->tok = e->tok;
3098 fcall->function = fdecl->name;
1c0be8c7 3099 fcall->type = fdecl->type;
5f36109e 3100
1c0be8c7
JS
3101 // If this code snippet uses a precomputed pointer,
3102 // pass that as the first argument.
5f36109e
JS
3103 if (pointer)
3104 {
5f36109e
JS
3105 vardecl *v = new vardecl;
3106 v->type = pe_long;
3107 v->name = "pointer";
3108 v->tok = e->tok;
3109 fdecl->formal_args.push_back(v);
3110 fcall->args.push_back(pointer);
3111 }
5f36109e 3112
1c0be8c7 3113 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3114 for (unsigned i = 0; i < e->components.size(); ++i)
3115 if (e->components[i].type == target_symbol::comp_expression_array_index)
3116 {
3117 vardecl *v = new vardecl;
3118 v->type = pe_long;
3119 v->name = "index" + lex_cast(i);
3120 v->tok = e->tok;
3121 fdecl->formal_args.push_back(v);
3122 fcall->args.push_back(e->components[i].expr_index);
3123 }
3124
1c0be8c7
JS
3125 // If this code snippet is assigning to an lvalue,
3126 // add a final argument for the rvalue.
3127 if (lvalue_p)
3128 {
3129 // Modify the fdecl so it carries a single pe_long formal
3130 // argument called "value".
5f36109e 3131
1c0be8c7
JS
3132 // FIXME: For the time being we only support setting target
3133 // variables which have base types; these are 'pe_long' in
3134 // stap's type vocabulary. Strings and pointers might be
3135 // reasonable, some day, but not today.
5f36109e 3136
1c0be8c7
JS
3137 vardecl *v = new vardecl;
3138 v->type = pe_long;
3139 v->name = "value";
3140 v->tok = e->tok;
3141 fdecl->formal_args.push_back(v);
3142 // NB: We don't know the value for fcall argument yet.
3143 // (see target_symbol_setter_functioncalls)
3144 }
3145
3146 // Add the synthesized decl to the session, and return the call.
3147 fdecl->join (session);
5f36109e
JS
3148 return fcall;
3149}
3150
1c0be8c7
JS
3151expression*
3152dwarf_pretty_print::deref (target_symbol* e)
3153{
3154 static unsigned tick = 0;
3155
3156 if (!deref_p)
3157 {
3158 assert (pointer && e->components.empty());
3159 return pointer;
3160 }
3161
3162 bool lvalue_p = false;
3163 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3164
3165 string code;
3166 exp_type type = pe_long;
3167 if (pointer)
3168 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3169 else if (!local.empty())
3170 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3171 else
3172 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3173
3174 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3175 userspace_p, lvalue_p, e, pointer);
3176}
3177
5f36109e 3178
c55ea10d
JS
3179bool
3180dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3181 target_symbol* e)
3182{
3183 expression* e2 = NULL;
3184 try
3185 {
3186 e2 = deref (e);
3187 }
3188 catch (const semantic_error&)
3189 {
3190 pf->raw_components.append ("?");
3191 return false;
3192 }
3193 pf->raw_components.append (fmt);
3194 pf->args.push_back (e2);
3195 return true;
3196}
3197
3198
e57b735a 3199void
a7999c82 3200dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3201{
a7999c82
JS
3202 // Get the full name of the target symbol.
3203 stringstream ts_name_stream;
3204 e->print(ts_name_stream);
3205 string ts_name = ts_name_stream.str();
3206
3207 // Check and make sure we haven't already seen this target
3208 // variable in this return probe. If we have, just return our
3209 // last replacement.
af234c40 3210 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3211 if (i != return_ts_map.end())
85ecf79a 3212 {
a7999c82
JS
3213 provide (i->second);
3214 return;
3215 }
85ecf79a 3216
70208613
JS
3217 // Attempt the expansion directly first, so if there's a problem with the
3218 // variable we won't have a bogus entry probe lying around. Like in
3219 // saveargs(), we pretend for a moment that we're not in a .return.
3220 bool saved_has_return = q.has_return;
3221 q.has_return = false;
3222 expression *repl = e;
3223 replace (repl);
3224 q.has_return = saved_has_return;
3225 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3226 if (n && n->saved_conversion_error)
3227 {
3228 provide (repl);
3229 return;
3230 }
3231
af234c40
JS
3232 expression *exp;
3233 if (!q.has_process &&
3234 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3235 exp = gen_kretprobe_saved_return(repl);
af234c40 3236 else
cc9001af 3237 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3238
3239 // Provide the variable to our parent so it can be used as a
3240 // substitute for the target symbol.
3241 provide (exp);
3242
3243 // Remember this replacement since we might be able to reuse
3244 // it later if the same return probe references this target
3245 // symbol again.
3246 return_ts_map[ts_name] = exp;
3247}
3248
4a2970a3 3249static expression*
23dc94f6
DS
3250gen_mapped_saved_return(systemtap_session &sess, expression* e,
3251 const string& name,
3252 block *& add_block, bool& add_block_tid,
3253 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3254{
23dc94f6
DS
3255 static unsigned tick = 0;
3256
a7999c82
JS
3257 // We've got to do several things here to handle target
3258 // variables in return probes.
85ecf79a 3259
a7999c82
JS
3260 // (1) Synthesize two global arrays. One is the cache of the
3261 // target variable and the other contains a thread specific
3262 // nesting level counter. The arrays will look like
3263 // this:
3264 //
23dc94f6
DS
3265 // _entry_tvar_{name}_{num}
3266 // _entry_tvar_{name}_{num}_ctr
a7999c82 3267
23dc94f6 3268 string aname = (string("_entry_tvar_")
cc9001af 3269 + name
aca66a36 3270 + "_" + lex_cast(tick++));
a7999c82
JS
3271 vardecl* vd = new vardecl;
3272 vd->name = aname;
3273 vd->tok = e->tok;
23dc94f6 3274 sess.globals.push_back (vd);
a7999c82
JS
3275
3276 string ctrname = aname + "_ctr";
3277 vd = new vardecl;
3278 vd->name = ctrname;
3279 vd->tok = e->tok;
23dc94f6 3280 sess.globals.push_back (vd);
a7999c82
JS
3281
3282 // (2) Create a new code block we're going to insert at the
3283 // beginning of this probe to get the cached value into a
3284 // temporary variable. We'll replace the target variable
3285 // reference with the temporary variable reference. The code
3286 // will look like this:
3287 //
23dc94f6
DS
3288 // _entry_tvar_tid = tid()
3289 // _entry_tvar_{name}_{num}_tmp
3290 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3291 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3292 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3293 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3294 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3295 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3296
3297 // (2a) Synthesize the tid temporary expression, which will look
3298 // like this:
3299 //
23dc94f6 3300 // _entry_tvar_tid = tid()
a7999c82 3301 symbol* tidsym = new symbol;
23dc94f6 3302 tidsym->name = string("_entry_tvar_tid");
a7999c82 3303 tidsym->tok = e->tok;
85ecf79a 3304
a7999c82
JS
3305 if (add_block == NULL)
3306 {
3307 add_block = new block;
3308 add_block->tok = e->tok;
8cc799a5 3309 }
8c819921 3310
8cc799a5
JS
3311 if (!add_block_tid)
3312 {
a7999c82
JS
3313 // Synthesize a functioncall to grab the thread id.
3314 functioncall* fc = new functioncall;
3315 fc->tok = e->tok;
3316 fc->function = string("tid");
8c819921 3317
23dc94f6 3318 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3319 assignment* a = new assignment;
3320 a->tok = e->tok;
3321 a->op = "=";
a7999c82
JS
3322 a->left = tidsym;
3323 a->right = fc;
8c819921
DS
3324
3325 expr_statement* es = new expr_statement;
3326 es->tok = e->tok;
3327 es->value = a;
8c819921 3328 add_block->statements.push_back (es);
8cc799a5 3329 add_block_tid = true;
a7999c82 3330 }
8c819921 3331
a7999c82
JS
3332 // (2b) Synthesize an array reference and assign it to a
3333 // temporary variable (that we'll use as replacement for the
3334 // target variable reference). It will look like this:
3335 //
23dc94f6
DS
3336 // _entry_tvar_{name}_{num}_tmp
3337 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3338 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3339
3340 arrayindex* ai_tvar_base = new arrayindex;
3341 ai_tvar_base->tok = e->tok;
3342
3343 symbol* sym = new symbol;
3344 sym->name = aname;
3345 sym->tok = e->tok;
3346 ai_tvar_base->base = sym;
3347
3348 ai_tvar_base->indexes.push_back(tidsym);
3349
3350 // We need to create a copy of the array index in its current
3351 // state so we can have 2 variants of it (the original and one
3352 // that post-decrements the second index).
3353 arrayindex* ai_tvar = new arrayindex;
3354 arrayindex* ai_tvar_postdec = new arrayindex;
3355 *ai_tvar = *ai_tvar_base;
3356 *ai_tvar_postdec = *ai_tvar_base;
3357
3358 // Synthesize the
23dc94f6 3359 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3360 // second index into the array.
3361 arrayindex* ai_ctr = new arrayindex;
3362 ai_ctr->tok = e->tok;
3363
3364 sym = new symbol;
3365 sym->name = ctrname;
3366 sym->tok = e->tok;
3367 ai_ctr->base = sym;
3368 ai_ctr->indexes.push_back(tidsym);
3369 ai_tvar->indexes.push_back(ai_ctr);
3370
3371 symbol* tmpsym = new symbol;
3372 tmpsym->name = aname + "_tmp";
3373 tmpsym->tok = e->tok;
3374
3375 assignment* a = new assignment;
3376 a->tok = e->tok;
3377 a->op = "=";
3378 a->left = tmpsym;
3379 a->right = ai_tvar;
3380
3381 expr_statement* es = new expr_statement;
3382 es->tok = e->tok;
3383 es->value = a;
3384
3385 add_block->statements.push_back (es);
3386
3387 // (2c) Add a post-decrement to the second array index and
3388 // delete the array value. It will look like this:
3389 //
23dc94f6
DS
3390 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3391 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3392
3393 post_crement* pc = new post_crement;
3394 pc->tok = e->tok;
3395 pc->op = "--";
3396 pc->operand = ai_ctr;
3397 ai_tvar_postdec->indexes.push_back(pc);
3398
3399 delete_statement* ds = new delete_statement;
3400 ds->tok = e->tok;
3401 ds->value = ai_tvar_postdec;
3402
3403 add_block->statements.push_back (ds);
3404
3405 // (2d) Delete the counter value if it is 0. It will look like
3406 // this:
23dc94f6
DS
3407 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3408 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3409
3410 ds = new delete_statement;
3411 ds->tok = e->tok;
3412 ds->value = ai_ctr;
3413
3414 unary_expression *ue = new unary_expression;
3415 ue->tok = e->tok;
3416 ue->op = "!";
3417 ue->operand = ai_ctr;
3418
3419 if_statement *ifs = new if_statement;
3420 ifs->tok = e->tok;
3421 ifs->condition = ue;
3422 ifs->thenblock = ds;
3423 ifs->elseblock = NULL;
3424
3425 add_block->statements.push_back (ifs);
3426
3427 // (3) We need an entry probe that saves the value for us in the
3428 // global array we created. Create the entry probe, which will
3429 // look like this:
3430 //
2260f4e3 3431 // probe kernel.function("{function}").call {
23dc94f6
DS
3432 // _entry_tvar_tid = tid()
3433 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3434 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3435 // = ${param}
3436 // }
3437
2260f4e3 3438 if (add_call_probe == NULL)
a7999c82 3439 {
2260f4e3
FCE
3440 add_call_probe = new block;
3441 add_call_probe->tok = e->tok;
8cc799a5 3442 }
4baf0e53 3443
8cc799a5
JS
3444 if (!add_call_probe_tid)
3445 {
a7999c82
JS
3446 // Synthesize a functioncall to grab the thread id.
3447 functioncall* fc = new functioncall;
3448 fc->tok = e->tok;
3449 fc->function = string("tid");
4baf0e53 3450
23dc94f6 3451 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3452 assignment* a = new assignment;
8fc05e57
DS
3453 a->tok = e->tok;
3454 a->op = "=";
a7999c82
JS
3455 a->left = tidsym;
3456 a->right = fc;
8fc05e57 3457
a7999c82 3458 expr_statement* es = new expr_statement;
8fc05e57
DS
3459 es->tok = e->tok;
3460 es->value = a;
2260f4e3 3461 add_call_probe = new block(add_call_probe, es);
8cc799a5 3462 add_call_probe_tid = true;
85ecf79a 3463 }
cf2a1f85 3464
a7999c82 3465 // Save the value, like this:
23dc94f6
DS
3466 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3467 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3468 // = ${param}
3469 arrayindex* ai_tvar_preinc = new arrayindex;
3470 *ai_tvar_preinc = *ai_tvar_base;
3471
3472 pre_crement* preinc = new pre_crement;
3473 preinc->tok = e->tok;
3474 preinc->op = "++";
3475 preinc->operand = ai_ctr;
3476 ai_tvar_preinc->indexes.push_back(preinc);
3477
3478 a = new assignment;
3479 a->tok = e->tok;
3480 a->op = "=";
3481 a->left = ai_tvar_preinc;
3482 a->right = e;
3483
3484 es = new expr_statement;
3485 es->tok = e->tok;
3486 es->value = a;
3487
2260f4e3 3488 add_call_probe = new block(add_call_probe, es);
a7999c82 3489
23dc94f6 3490 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3491 // our parent so it can be used as a substitute for the target
3492 // symbol.
3f803f9e 3493 delete ai_tvar_base;
af234c40
JS
3494 return tmpsym;
3495}
a7999c82 3496
af234c40 3497
23dc94f6
DS
3498expression*
3499dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3500 const string& name)
3501{
3502 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3503 add_block_tid, add_call_probe,
3504 add_call_probe_tid);
3505}
3506
3507
af234c40 3508expression*
140be17a 3509dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3510{
3511 // The code for this is simple.
3512 //
3513 // .call:
3514 // _set_kretprobe_long(index, $value)
3515 //
3516 // .return:
3517 // _get_kretprobe_long(index)
3518 //
3519 // (or s/long/string/ for things like $$parms)
3520
3521 unsigned index;
3522 string setfn, getfn;
3523
140be17a
JS
3524 // We need the caller to predetermine the type of the expression!
3525 switch (e->type)
af234c40 3526 {
140be17a 3527 case pe_string:
af234c40
JS
3528 index = saved_strings++;
3529 setfn = "_set_kretprobe_string";
3530 getfn = "_get_kretprobe_string";
140be17a
JS
3531 break;
3532 case pe_long:
af234c40
JS
3533 index = saved_longs++;
3534 setfn = "_set_kretprobe_long";
3535 getfn = "_get_kretprobe_long";
140be17a
JS
3536 break;
3537 default:
b530b5b3 3538 throw semantic_error(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3539 }
3540
3541 // Create the entry code
3542 // _set_kretprobe_{long|string}(index, $value)
3543
3544 if (add_call_probe == NULL)
3545 {
3546 add_call_probe = new block;
3547 add_call_probe->tok = e->tok;
3548 }
3549
3550 functioncall* set_fc = new functioncall;
3551 set_fc->tok = e->tok;
3552 set_fc->function = setfn;
3553 set_fc->args.push_back(new literal_number(index));
3554 set_fc->args.back()->tok = e->tok;
3555 set_fc->args.push_back(e);
3556
3557 expr_statement* set_es = new expr_statement;
3558 set_es->tok = e->tok;
3559 set_es->value = set_fc;
3560
3561 add_call_probe->statements.push_back(set_es);
3562
3563 // Create the return code
3564 // _get_kretprobe_{long|string}(index)
3565
3566 functioncall* get_fc = new functioncall;
3567 get_fc->tok = e->tok;
3568 get_fc->function = getfn;
3569 get_fc->args.push_back(new literal_number(index));
3570 get_fc->args.back()->tok = e->tok;
3571
3572 return get_fc;
a7999c82 3573}
a43ba433 3574
2cb3fe26 3575
a7999c82
JS
3576void
3577dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3578{
9aa8ffce 3579 if (null_die(scope_die))
a7999c82 3580 return;
2cb3fe26 3581
5f36109e
JS
3582 target_symbol *tsym = new target_symbol(*e);
3583
fde50242
JS
3584 bool pretty = (!e->components.empty() &&
3585 e->components[0].type == target_symbol::comp_pretty_print);
3586 string format = pretty ? "=%s" : "=%#x";
a43ba433 3587
a7999c82
JS
3588 // Convert $$parms to sprintf of a list of parms and active local vars
3589 // which we recursively evaluate
a43ba433 3590
a7999c82
JS
3591 // NB: we synthesize a new token here rather than reusing
3592 // e->tok, because print_format::print likes to use
3593 // its tok->content.
5f36109e 3594 token* pf_tok = new token(*e->tok);
a7999c82 3595 pf_tok->type = tok_identifier;
b393f6f2 3596 pf_tok->content = "sprintf";
2cb3fe26 3597
d5e178c1 3598 print_format* pf = print_format::create(pf_tok);
a7999c82 3599
277c21bc 3600 if (q.has_return && (e->name == "$$return"))
a7999c82 3601 {
277c21bc 3602 tsym->name = "$return";
a7999c82
JS
3603
3604 // Ignore any variable that isn't accessible.
3605 tsym->saved_conversion_error = 0;
3606 expression *texp = tsym;
8b095b45 3607 replace (texp); // NB: throws nothing ...
a7999c82 3608 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3609 {
2cb3fe26 3610
a43ba433
FCE
3611 }
3612 else
3613 {
a7999c82 3614 pf->raw_components += "return";
5f36109e 3615 pf->raw_components += format;
a7999c82
JS
3616 pf->args.push_back(texp);
3617 }
3618 }
3619 else
3620 {
3621 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3622 bool first = true;
a7999c82 3623 Dwarf_Die result;
d48bc7eb
JS
3624 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3625 for (unsigned i = 0; i < scopes.size(); ++i)
3626 {
3627 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3628 break; // we don't want file-level variables
3629 if (dwarf_child (&scopes[i], &result) == 0)
3630 do
00cf3709 3631 {
d48bc7eb
JS
3632 switch (dwarf_tag (&result))
3633 {
3634 case DW_TAG_variable:
3635 if (e->name == "$$parms")
3636 continue;
3637 break;
3638 case DW_TAG_formal_parameter:
3639 if (e->name == "$$locals")
3640 continue;
3641 break;
3642
3643 default:
3644 continue;
3645 }
41c262f3 3646
d48bc7eb
JS
3647 const char *diename = dwarf_diename (&result);
3648 if (! diename) continue;
f76427a2 3649
d48bc7eb
JS
3650 if (! first)
3651 pf->raw_components += " ";
3652 pf->raw_components += diename;
fde50242
JS
3653 first = false;
3654
3655 // Write a placeholder for ugly aggregates
3656 Dwarf_Die type;
3657 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3658 {
3659 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3660 switch (dwarf_tag(&type))
3661 {
3662 case DW_TAG_union_type:
3663 case DW_TAG_structure_type:
3664 case DW_TAG_class_type:
3665 pf->raw_components += "={...}";
3666 continue;
3667
3668 case DW_TAG_array_type:
3669 pf->raw_components += "=[...]";
3670 continue;
3671 }
3672 }
345bbb3d 3673
d48bc7eb
JS
3674 tsym->name = "$";
3675 tsym->name += diename;
41c262f3 3676
d48bc7eb
JS
3677 // Ignore any variable that isn't accessible.
3678 tsym->saved_conversion_error = 0;
3679 expression *texp = tsym;
3680 replace (texp); // NB: throws nothing ...
3681 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3682 {
d48bc7eb
JS
3683 if (q.sess.verbose>2)
3684 {
e26c2f83 3685 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb
JS
3686 c != 0;
3687 c = c->chain) {
4c5d9906 3688 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3689 }
3690 }
3691
3692 pf->raw_components += "=?";
a43ba433 3693 }
d48bc7eb
JS
3694 else
3695 {
3696 pf->raw_components += format;
3697 pf->args.push_back(texp);
3698 }
a7999c82 3699 }
d48bc7eb
JS
3700 while (dwarf_siblingof (&result, &result) == 0);
3701 }
a7999c82 3702 }
2cb3fe26 3703
a7999c82 3704 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3705 pf->type = pe_string;
a7999c82
JS
3706 provide (pf);
3707}
3708
2cb3fe26 3709
bd1fcbad
YZ
3710void
3711dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3712{
3713 // Fill in our current module context if needed
3714 if (e->module.empty())
3715 e->module = q.dw.module_name;
3716
3717 if (e->module == q.dw.module_name && e->cu_name.empty())
3718 {
3719 // process like any other local
3720 // e->sym_name() will do the right thing
3721 visit_target_symbol(e);
3722 return;
3723 }
3724
3725 var_expanding_visitor::visit_atvar_op(e);
3726}
3727
3728
a7999c82
JS
3729void
3730dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3731{
bd1fcbad 3732 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3733 visited = true;
30263a73
FCE
3734 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3735 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3736
70208613 3737 try
a7999c82 3738 {
c69a87e0
FCE
3739 bool lvalue = is_active_lvalue(e);
3740 if (lvalue && !q.sess.guru_mode)
b3741c9d 3741 throw semantic_error(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3742
100a540e 3743 // XXX: process $context vars should be writable
70208613 3744
c69a87e0
FCE
3745 // See if we need to generate a new probe to save/access function
3746 // parameters from a return probe. PR 1382.
3747 if (q.has_return
3748 && !defined_being_checked
277c21bc
JS
3749 && e->name != "$return" // not the special return-value variable handled below
3750 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3751 {
3752 if (lvalue)
b530b5b3 3753 throw semantic_error(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3754 visit_target_symbol_saved_return(e);
3755 return;
3756 }
e57b735a 3757
277c21bc
JS
3758 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3759 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3760 {
3761 if (lvalue)
b530b5b3 3762 throw semantic_error(_("cannot write to context variable"), e->tok);
70208613 3763
c69a87e0 3764 if (e->addressof)
b530b5b3 3765 throw semantic_error(_("cannot take address of context variable"), e->tok);
70208613 3766
5f36109e
JS
3767 e->assert_no_components("dwarf", true);
3768
c69a87e0
FCE
3769 visit_target_symbol_context(e);
3770 return;
3771 }
70208613 3772
5f36109e
JS
3773 if (!e->components.empty() &&
3774 e->components.back().type == target_symbol::comp_pretty_print)
3775 {
3776 if (lvalue)
b530b5b3 3777 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3778
277c21bc 3779 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3780 {
3781 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3782 q.has_process, *e);
3783 dpp.expand()->visit(this);
3784 }
3785 else
3786 {
3787 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3788 e->sym_name(),
5f36109e
JS
3789 q.has_process, *e);
3790 dpp.expand()->visit(this);
3791 }
3792 return;
3793 }
3794
1c0be8c7 3795 bool userspace_p = q.has_process;
c69a87e0 3796 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3797 + "_" + e->sym_name()
c69a87e0 3798 + "_" + lex_cast(tick++));
70208613 3799
70208613 3800
1c0be8c7
JS
3801 exp_type type = pe_long;
3802 string code;
277c21bc 3803 if (q.has_return && (e->name == "$return"))
1c0be8c7 3804 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 3805 else
1c0be8c7
JS
3806 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
3807 e, lvalue, type);
70208613 3808
1c0be8c7
JS
3809 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
3810 userspace_p, lvalue, e);
70208613 3811
c69a87e0
FCE
3812 if (lvalue)
3813 {
3814 // Provide the functioncall to our parent, so that it can be
3815 // used to substitute for the assignment node immediately above
3816 // us.
3817 assert(!target_symbol_setter_functioncalls.empty());
3818 *(target_symbol_setter_functioncalls.top()) = n;
3819 }
70208613 3820
1c0be8c7
JS
3821 // Revisit the functioncall so arguments can be expanded.
3822 n->visit (this);
66d284f4
FCE
3823 }
3824 catch (const semantic_error& er)
3825 {
9fab2262
JS
3826 // We suppress this error message, and pass the unresolved
3827 // target_symbol to the next pass. We hope that this value ends
3828 // up not being referenced after all, so it can be optimized out
3829 // quietly.
1af1e62d 3830 e->chain (er);
9fab2262 3831 provide (e);
66d284f4 3832 }
77de5e9e
GH
3833}
3834
3835
c24447be
JS
3836void
3837dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3838{
3839 // Fill in our current module context if needed
3840 if (e->module.empty())
3841 e->module = q.dw.module_name;
3842
3843 var_expanding_visitor::visit_cast_op(e);
3844}
3845
3846
8cc799a5
JS
3847void
3848dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3849{
3850 expression *repl = e;
3851 if (q.has_return)
3852 {
3853 // expand the operand as if it weren't a return probe
3854 q.has_return = false;
3855 replace (e->operand);
3856 q.has_return = true;
3857
3858 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3859 // but it requires knowing the types already, which is problematic for
3860 // arbitrary expressons.
cc9001af 3861 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3862 }
3863 provide (repl);
3864}
3865
3689db05
SC
3866void
3867dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
3868{
3869 token* t = new token;
ace7c23f 3870 string e_lit_val = e->operand->value;
3689db05
SC
3871
3872 t->location = e->tok->location;
3873 t->type = tok_identifier;
3874 t->content = e_lit_val;
3875
3876 add_block = new block;
3877
3878 systemtap_session &s = this->q.sess;
3879 map<string, pair<string,derived_probe*> >::iterator it;
3880 // Find the associated perf.counter probe
3881 for (it=s.perf_counters.begin();
3882 it != s.perf_counters.end();
3883 it++)
3884 if ((*it).first == e_lit_val)
3885 {
3886 // if perf .function("name") omitted, then set it to this process name
3887 if ((*it).second.first.length() == 0)
3888 ((*it).second).first = this->q.user_path;
3889 if (((*it).second).first == this->q.user_path)
3890 break;
3891 }
3892
3893 if (it != s.perf_counters.end())
3894 {
698de6cc 3895 perf_counter_refs.insert((*it).second.second);
3689db05
SC
3896 // __perf_read_N is assigned in the probe prologue
3897 symbol* sym = new symbol;
3898 sym->tok = t;
3899 sym->name = "__perf_read_" + (*it).first;
3900 provide (sym);
3901 }
3902 else
3903 throw semantic_error(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3904}
3905
8cc799a5 3906
729455a7
JS
3907vector<Dwarf_Die>&
3908dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3909{
3910 if (scopes.empty())
3911 {
f25a9197
CM
3912 if(scope_die != NULL)
3913 scopes = q.dw.getscopes(scope_die);
729455a7 3914 if (scopes.empty())
b530b5b3
LB
3915 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3916 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
729455a7
JS
3917 throw semantic_error ("unable to find any scopes containing "
3918 + lex_cast_hex(addr)
3919 + ((scope_die == NULL) ? ""
3920 : (string (" in ")
3921 + (dwarf_diename(scope_die) ?: "<unknown>")
3922 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3923 + ")"))
3924 + " while searching for local '"
cc9001af 3925 + e->sym_name() + "'",
729455a7
JS
3926 e->tok);
3927 }
3928 return scopes;
3929}
3930
3931
5f36109e
JS
3932struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3933{
3934 systemtap_session& s;
3935 dwarf_builder& db;
3936
3937 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3938 s(s), db(db) {}
3939 void visit_cast_op (cast_op* e);
3940 void filter_special_modules(string& module);
3941};
3942
3943
c4ce66a1
JS
3944struct dwarf_cast_query : public base_query
3945{
946e1a48 3946 cast_op& e;
c4ce66a1 3947 const bool lvalue;
5f36109e
JS
3948 const bool userspace_p;
3949 functioncall*& result;
c4ce66a1 3950
5f36109e
JS
3951 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3952 const bool userspace_p, functioncall*& result):
abb41d92 3953 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3954 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3955
3956 void handle_query_module();
822a6a3d 3957 void query_library (const char *) {}
576eaefe 3958 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3959};
3960
3961
c4ce66a1
JS
3962void
3963dwarf_cast_query::handle_query_module()
3964{
5f36109e
JS
3965 static unsigned tick = 0;
3966
3967 if (result)
c4ce66a1
JS
3968 return;
3969
ea1e477a 3970 // look for the type in any CU
a44a7cb5
JS
3971 Dwarf_Die* type_die = NULL;
3972 if (startswith(e.type_name, "class "))
3973 {
3974 // normalize to match dwflpp::global_alias_caching_callback
3975 string struct_name = "struct " + e.type_name.substr(6);
3976 type_die = dw.declaration_resolve_other_cus(struct_name);
3977 }
3978 else
3979 type_die = dw.declaration_resolve_other_cus(e.type_name);
3980
3981 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3982 // just "name". But since we didn't require users to be explicit before, and
3983 // actually sort of discouraged it, we must be flexible now. So if a lookup
3984 // fails with a bare name, try augmenting it.
3985 if (!type_die &&
3986 !startswith(e.type_name, "class ") &&
3987 !startswith(e.type_name, "struct ") &&
3988 !startswith(e.type_name, "union ") &&
3989 !startswith(e.type_name, "enum "))
3990 {
3991 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3992 if (!type_die)
3993 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3994 if (!type_die)
3995 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3996 }
3997
ea1e477a
JS
3998 if (!type_die)
3999 return;
c4ce66a1 4000
5f36109e
JS
4001 string code;
4002 exp_type type = pe_long;
4003
ea1e477a 4004 try
c4ce66a1 4005 {
ea1e477a
JS
4006 Dwarf_Die cu_mem;
4007 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4008
4009 if (!e.components.empty() &&
4010 e.components.back().type == target_symbol::comp_pretty_print)
4011 {
4012 if (lvalue)
b530b5b3 4013 throw semantic_error(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4014
d19a9a82 4015 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4016 result = dpp.expand();
4017 return;
4018 }
4019
4020 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4021 }
4022 catch (const semantic_error& er)
4023 {
4024 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4025 // may be attempted using several different modules:
4026 // @cast(ptr, "type", "module1:module2:...")
4027 e.chain (er);
c4ce66a1 4028 }
c4ce66a1 4029
5f36109e
JS
4030 if (code.empty())
4031 return;
c4ce66a1 4032
5f36109e 4033 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4034 + "_" + e.sym_name()
5f36109e 4035 + "_" + lex_cast(tick++));
c4ce66a1 4036
1c0be8c7
JS
4037 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4038 userspace_p, lvalue, &e, e.operand);
5f36109e 4039}
c4ce66a1
JS
4040
4041
fb0274bc
JS
4042void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4043{
d90053e7 4044 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4045 // for those cases, build a module including that header
d90053e7 4046 if (module[module.size() - 1] == '>' &&
60d98537 4047 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4048 {
4049 string cached_module;
4050 if (s.use_cache)
4051 {
4052 // see if the cached module exists
a2639cb7 4053 cached_module = find_typequery_hash(s, module);
d105f664 4054 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4055 {
4056 int fd = open(cached_module.c_str(), O_RDONLY);
4057 if (fd != -1)
4058 {
4059 if (s.verbose > 2)
b530b5b3
LB
4060 //TRANSLATORS: Here we're using a cached module.
4061 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4062 module = cached_module;
4063 close(fd);
4064 return;
4065 }
4066 }
4067 }
4068
4069 // no cached module, time to make it
d90053e7 4070 if (make_typequery(s, module) == 0)
fb0274bc 4071 {
e16dc041 4072 // try to save typequery in the cache
fb0274bc 4073 if (s.use_cache)
e16dc041 4074 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4075 }
4076 }
4077}
4078
4079
c4ce66a1
JS
4080void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4081{
4082 bool lvalue = is_active_lvalue(e);
4083 if (lvalue && !s.guru_mode)
b3741c9d 4084 throw semantic_error(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4085
4086 if (e->module.empty())
4087 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4088
5f36109e 4089 functioncall* result = NULL;
8b31197b
JS
4090
4091 // split the module string by ':' for alternatives
4092 vector<string> modules;
4093 tokenize(e->module, modules, ":");
b5a0dd41 4094 bool userspace_p=false; // PR10601
5f36109e 4095 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4096 {
8b31197b 4097 string& module = modules[i];
fb0274bc 4098 filter_special_modules(module);
abb41d92 4099
c4ce66a1
JS
4100 // NB: This uses '/' to distinguish between kernel modules and userspace,
4101 // which means that userspace modules won't get any PATH searching.
4102 dwflpp* dw;
707bf35e
JS
4103 try
4104 {
b5a0dd41
FCE
4105 userspace_p=is_user_module (module);
4106 if (! userspace_p)
707bf35e
JS
4107 {
4108 // kernel or kernel module target
ae2552da 4109 dw = db.get_kern_dw(s, module);
707bf35e
JS
4110 }
4111 else
4112 {
05fb3e0c 4113 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4114 dw = db.get_user_dw(s, module);
4115 }
4116 }
4117 catch (const semantic_error& er)
4118 {
4119 /* ignore and go to the next module */
4120 continue;
4121 }
c4ce66a1 4122
5f36109e 4123 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 4124 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 4125 }
abb41d92 4126
5f36109e 4127 if (!result)
c4ce66a1 4128 {
946e1a48
JS
4129 // We pass the unresolved cast_op to the next pass, and hope
4130 // that this value ends up not being referenced after all, so
4131 // it can be optimized out quietly.
c4ce66a1
JS
4132 provide (e);
4133 return;
4134 }
4135
c4ce66a1
JS
4136 if (lvalue)
4137 {
4138 // Provide the functioncall to our parent, so that it can be
4139 // used to substitute for the assignment node immediately above
4140 // us.
4141 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4142 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4143 }
4144
5f36109e 4145 result->visit (this);
77de5e9e
GH
4146}
4147
4148
bd1fcbad
YZ
4149struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4150{
4151 systemtap_session& s;
4152 dwarf_builder& db;
4153
4154 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4155 s(s), db(db) {}
4156 void visit_atvar_op (atvar_op* e);
4157};
4158
4159
4160struct dwarf_atvar_query: public base_query
4161{
4162 atvar_op& e;
4163 const bool userspace_p, lvalue;
4164 functioncall*& result;
4165 unsigned& tick;
4166 const string cu_name_pattern;
4167
4168 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4169 const bool userspace_p, const bool lvalue,
4170 functioncall*& result,
4171 unsigned& tick):
4172 base_query(dw, module), e(e),
4173 userspace_p(userspace_p), lvalue(lvalue), result(result),
4174 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4175
4176 void handle_query_module ();
4177 void query_library (const char *) {}
4178 void query_plt (const char *entry, size_t addr) {}
4179 static int atvar_query_cu (Dwarf_Die *cudie, void *data);
4180};
4181
4182
4183int
4184dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, void * data)
4185{
4186 dwarf_atvar_query * q = static_cast<dwarf_atvar_query *>(data);
4187
4188 if (! q->e.cu_name.empty())
4189 {
4190 const char *die_name = dwarf_diename(cudie);
4191
4192 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4193 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4194 {
4195 return DWARF_CB_OK;
4196 }
4197 }
4198
4199 try
4200 {
4201 vector<Dwarf_Die> scopes(1, *cudie);
4202
4203 q->dw.focus_on_cu (cudie);
4204
4205 if (! q->e.components.empty() &&
4206 q->e.components.back().type == target_symbol::comp_pretty_print)
4207 {
4208 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4209 q->userspace_p, q->e);
4210 q->result = dpp.expand();
4211 return DWARF_CB_ABORT;
4212 }
4213
4214 exp_type type = pe_long;
4215 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4216 &q->e, q->lvalue, type);
4217
4218 if (code.empty())
4219 return DWARF_CB_OK;
4220
4221 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4222 : "_dwarf_tvar_get")
4223 + "_" + q->e.sym_name()
4224 + "_" + lex_cast(q->tick++));
4225
4226 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4227 q->userspace_p, q->lvalue,
4228 &q->e);
4229 }
4230 catch (const semantic_error& er)
4231 {
4232 // Here we suppress the error because we often just have too many
4233 // when scanning all the CUs.
4234 return DWARF_CB_OK;
4235 }
4236
4237 if (q->result) {
4238 return DWARF_CB_ABORT;
4239 }
4240
4241 return DWARF_CB_OK;
4242}
4243
4244
4245void
4246dwarf_atvar_query::handle_query_module ()
4247{
4248
4249 dw.iterate_over_cus(atvar_query_cu, this, false);
4250}
4251
4252
4253void
4254dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4255{
4256 const bool lvalue = is_active_lvalue(e);
4257 if (lvalue && !s.guru_mode)
4258 throw semantic_error(_("write to @var variable not permitted; "
4259 "need stap -g"), e->tok);
4260
4261 if (e->module.empty())
4262 e->module = "kernel";
4263
4264 functioncall* result = NULL;
4265
4266 // split the module string by ':' for alternatives
4267 vector<string> modules;
4268 tokenize(e->module, modules, ":");
4269 bool userspace_p = false;
4270 for (unsigned i = 0; !result && i < modules.size(); ++i)
4271 {
4272 string& module = modules[i];
4273
4274 dwflpp* dw;
4275 try
4276 {
4277 userspace_p = is_user_module(module);
4278 if (!userspace_p)
4279 {
4280 // kernel or kernel module target
4281 dw = db.get_kern_dw(s, module);
4282 }
4283 else
4284 {
4285 module = find_executable(module, "", s.sysenv);
4286 dw = db.get_user_dw(s, module);
4287 }
4288 }
4289 catch (const semantic_error& er)
4290 {
4291 /* ignore and go to the next module */
4292 continue;
4293 }
4294
4295 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
4296 dw->iterate_over_modules(&query_module, &q);
4297
4298 if (result)
4299 {
4300 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4301
4302 if (lvalue)
4303 {
4304 // Provide the functioncall to our parent, so that it can be
4305 // used to substitute for the assignment node immediately above
4306 // us.
4307 assert(!target_symbol_setter_functioncalls.empty());
4308 *(target_symbol_setter_functioncalls.top()) = result;
4309 }
4310
4311 result->visit(this);
4312 return;
4313 }
4314
4315 /* Unable to find the variable in the current module, so we chain
4316 * an error in atvar_op */
4317 semantic_error er(_F("unable to find global '%s' in %s%s%s",
4318 e->sym_name().c_str(), module.c_str(),
4319 e->cu_name.empty() ? "" : _(", in "),
4320 e->cu_name.c_str()));
4321 e->chain (er);
4322 }
4323
4324 provide(e);
4325}
4326
4327
b8da0ad1
FCE
4328void
4329dwarf_derived_probe::printsig (ostream& o) const
4330{
4331 // Instead of just printing the plain locations, we add a PC value
4332 // as a comment as a way of telling e.g. apart multiple inlined
4333 // function instances. This is distinct from the verbose/clog
4334 // output, since this part goes into the cache hash calculations.
4335 sole_location()->print (o);
6d0f3f0c 4336 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4337 printsig_nested (o);
4338}
4339
4340
4341
dc38c0ae 4342void
b20febf3
FCE
4343dwarf_derived_probe::join_group (systemtap_session& s)
4344{
af234c40
JS
4345 // skip probes which are paired entry-handlers
4346 if (!has_return && (saved_longs || saved_strings))
4347 return;
4348
b20febf3
FCE
4349 if (! s.dwarf_derived_probes)
4350 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4351 s.dwarf_derived_probes->enroll (this);
4352}
4353
4354
2b69faaf
JS
4355static bool
4356kernel_supports_inode_uprobes(systemtap_session& s)
4357{
4358 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4359 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4360 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4361 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4362 && s.kernel_config["CONFIG_UPROBES"] == "y");
4363}
4364
4365
3667d615
JS
4366static bool
4367kernel_supports_inode_uretprobes(systemtap_session& s)
4368{
766013af
JS
4369 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4370 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4371 return kernel_supports_inode_uprobes(s) &&
af9e147f 4372 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4373}
4374
4375
5261f7ab
DS
4376void
4377check_process_probe_kernel_support(systemtap_session& s)
4378{
4379 // If we've got utrace, we're good to go.
4380 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4381 return;
4382
8c021542
DS
4383 // We don't have utrace. For process probes that aren't
4384 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4385 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4386 // specific autoconf test for its needs.
8c021542
DS
4387 //
4388 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4389 // approximation.
4390 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4391 return;
4392
d3e959b0
DS
4393 // For uprobes-based process probes, we need the task_finder plus
4394 // the builtin inode-uprobes.
8c021542
DS
4395 if (s.need_uprobes
4396 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4397 && kernel_supports_inode_uprobes(s))
8c021542
DS
4398 return;
4399
4400 throw semantic_error (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4401}
4402
4403
b20febf3
FCE
4404dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4405 const string& filename,
4406 int line,
91af0778 4407 // module & section specify a relocation
b20febf3
FCE
4408 // base for <addr>, unless section==""
4409 // (equivalently module=="kernel")
4410 const string& module,
4411 const string& section,
4412 // NB: dwfl_addr is the virtualized
4413 // address for this symbol.
4414 Dwarf_Addr dwfl_addr,
4415 // addr is the section-offset for
4416 // actual relocation.
4417 Dwarf_Addr addr,
4418 dwarf_query& q,
37ebca01 4419 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4420 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4421 module (module), section (section), addr (addr),
63b4fd14 4422 path (q.path),
27dc09b1 4423 has_process (q.has_process),
c9bad430
DS
4424 has_return (q.has_return),
4425 has_maxactive (q.has_maxactive),
c57ea854 4426 has_library (q.has_library),
6b66b9f7 4427 maxactive_val (q.maxactive_val),
b642c901
SC
4428 user_path (q.user_path),
4429 user_lib (q.user_lib),
af234c40 4430 access_vars(false),
c57ea854 4431 saved_longs(0), saved_strings(0),
af234c40 4432 entry_handler(0)
bd2b1e68 4433{
b642c901
SC
4434 if (user_lib.size() != 0)
4435 has_library = true;
4436
6b66b9f7
JS
4437 if (q.has_process)
4438 {
4439 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4440 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4441 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4442 // by the incoming section value (".absolute" vs. ".dynamic").
4443 // XXX Assert invariants here too?
2b69faaf
JS
4444
4445 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4446 // ditto for userspace runtimes (dyninst)
ac3af990 4447 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4448 section == ".absolute" && addr == dwfl_addr &&
4449 addr >= q.dw.module_start && addr < q.dw.module_end)
4450 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4451 }
4452 else
4453 {
4454 // Assert kernel relocation invariants
4455 if (section == "" && dwfl_addr != addr) // addr should be absolute
ce0f6648 4456 throw semantic_error (_("missing relocation basis"), tok);
6b66b9f7 4457 if (section != "" && dwfl_addr == addr) // addr should be an offset
b530b5b3 4458 throw semantic_error (_("inconsistent relocation address"), tok);
6b66b9f7 4459 }
2930abc7 4460
21beacc9
FCE
4461 // XXX: hack for strange g++/gcc's
4462#ifndef USHRT_MAX
4463#define USHRT_MAX 32767
4464#endif
4465
606fd9c8 4466 // Range limit maxactive() value
6b66b9f7 4467 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
b530b5b3
LB
4468 throw semantic_error (_F("maxactive value out of range [0,%s]",
4469 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4470
de688825 4471 // Expand target variables in the probe body
5f0a03a6 4472 if (!null_die(scope_die))
8fc05e57 4473 {
6b66b9f7 4474 // XXX: user-space deref's for q.has_process!
de688825 4475 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4476 v.replace (this->body);
3689db05
SC
4477
4478 // Propagate perf.counters so we can emit later
4479 this->perf_counter_refs = v.perf_counter_refs;
4480 // Emit local var used to save the perf counter read value
698de6cc 4481 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4482 for (pcii = v.perf_counter_refs.begin();
4483 pcii != v.perf_counter_refs.end(); pcii++)
4484 {
4485 map<string, pair<string,derived_probe*> >::iterator it;
4486 // Find the associated perf counter probe
4487 for (it=q.sess.perf_counters.begin() ;
4488 it != q.sess.perf_counters.end();
4489 it++)
4490 if ((*it).second.second == (*pcii))
4491 break;
4492 vardecl* vd = new vardecl;
4493 vd->name = "__perf_read_" + (*it).first;
4494 vd->tok = this->tok;
4495 vd->set_arity(0, this->tok);
4496 vd->type = pe_long;
4497 vd->synthetic = true;
4498 this->locals.push_back (vd);
4499 }
4500
4501
6b66b9f7
JS
4502 if (!q.has_process)
4503 access_vars = v.visited;
37ebca01
FCE
4504
4505 // If during target-variable-expanding the probe, we added a new block
4506 // of code, add it to the start of the probe.
4507 if (v.add_block)
ba6f838d 4508 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4509
4510 // If when target-variable-expanding the probe, we need to synthesize a
4511 // sibling function-entry probe. We don't go through the whole probe derivation
4512 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4513 // dwarf-induced duplication.
4514 if (v.add_call_probe)
37ebca01 4515 {
2260f4e3
FCE
4516 assert (q.has_return && !q.has_call);
4517
4518 // We temporarily replace q.base_probe.
4519 statement* old_body = q.base_probe->body;
4520 q.base_probe->body = v.add_call_probe;
4521 q.has_return = false;
4522 q.has_call = true;
af234c40 4523
da23eceb 4524 if (q.has_process)
af234c40
JS
4525 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4526 module, section, dwfl_addr,
4527 addr, q, scope_die);
da23eceb 4528 else
af234c40
JS
4529 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4530 module, section, dwfl_addr,
4531 addr, q, scope_die);
4532
4533 saved_longs = entry_handler->saved_longs = v.saved_longs;
4534 saved_strings = entry_handler->saved_strings = v.saved_strings;
4535
4536 q.results.push_back (entry_handler);
2260f4e3
FCE
4537
4538 q.has_return = true;
4539 q.has_call = false;
4540 q.base_probe->body = old_body;
37ebca01 4541 }
f10534c6
WH
4542 // Save the local variables for listing mode
4543 if (q.sess.listing_mode_vars)
8c67c337 4544 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4545 }
37ebca01 4546 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4547
f10534c6 4548 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4549
5d23847d 4550 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4551 // "reverse-engineered" form of the incoming (q.base_loc) probe
4552 // point. This allows a user to see what function / file / line
4553 // number any particular match of the wildcards.
2930abc7 4554
a229fcd7 4555 vector<probe_point::component*> comps;
91af0778
FCE
4556 if (q.has_kernel)
4557 comps.push_back (new probe_point::component(TOK_KERNEL));
4558 else if(q.has_module)
4559 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4560 else if(q.has_process)
4561 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4562 else
4563 assert (0);
b5d77020 4564
db520b00
FCE
4565 string fn_or_stmt;
4566 if (q.has_function_str || q.has_function_num)
4567 fn_or_stmt = "function";
4568 else
4569 fn_or_stmt = "statement";
a229fcd7 4570
b8da0ad1 4571 if (q.has_function_str || q.has_statement_str)
db520b00 4572 {
4cd232e4 4573 string retro_name = funcname;
b20febf3 4574 if (filename != "")
cee35f73 4575 {
fb84c077 4576 retro_name += ("@" + string (filename));
cee35f73 4577 if (line > 0)
aca66a36 4578 retro_name += (":" + lex_cast (line));
cee35f73 4579 }
db520b00
FCE
4580 comps.push_back
4581 (new probe_point::component
4582 (fn_or_stmt, new literal_string (retro_name)));
4583 }
b8da0ad1 4584 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4585 {
4586 Dwarf_Addr retro_addr;
4587 if (q.has_function_num)
4588 retro_addr = q.function_num_val;
4589 else
4590 retro_addr = q.statement_num_val;
db520b00
FCE
4591 comps.push_back (new probe_point::component
4592 (fn_or_stmt,
9ea68eb9 4593 new literal_number(retro_addr, true)));
37ebca01
FCE
4594
4595 if (q.has_absolute)
4596 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4597 }
4598
b8da0ad1
FCE
4599 if (q.has_call)
4600 comps.push_back (new probe_point::component(TOK_CALL));
4bda987e
SC
4601 if (q.has_exported)
4602 comps.push_back (new probe_point::component(TOK_EXPORTED));
b8da0ad1
FCE
4603 if (q.has_inline)
4604 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4605 if (has_return)
b8da0ad1
FCE
4606 comps.push_back (new probe_point::component(TOK_RETURN));
4607 if (has_maxactive)
4608 comps.push_back (new probe_point::component
4609 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4610
5d23847d
FCE
4611 // Overwrite it.
4612 this->sole_location()->components = comps;
2930abc7
FCE
4613}
4614
bd2b1e68 4615
0a98fd42 4616void
8c67c337
JS
4617dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4618 Dwarf_Addr dwfl_addr)
0a98fd42 4619{
9aa8ffce 4620 if (null_die(scope_die))
0a98fd42 4621 return;
0a98fd42 4622
8c67c337 4623 bool verbose = q.sess.verbose > 2;
0a98fd42 4624
8c67c337 4625 if (verbose)
b530b5b3 4626 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4627
8c67c337
JS
4628 if (has_return)
4629 {
4630 /* Only save the return value if it has a type. */
4631 string type_name;
4632 Dwarf_Die type_die;
4633 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4634 dwarf_type_name(&type_die, type_name))
4635 args.push_back("$return:"+type_name);
4636
4637 else if (verbose)
b530b5b3
LB
4638 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4639 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4640 }
d87623a1 4641
0a98fd42 4642 Dwarf_Die arg;
4ef35696
JS
4643 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4644 for (unsigned i = 0; i < scopes.size(); ++i)
4645 {
4646 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4647 break; // we don't want file-level variables
4648 if (dwarf_child (&scopes[i], &arg) == 0)
4649 do
0a98fd42 4650 {
4ef35696
JS
4651 switch (dwarf_tag (&arg))
4652 {
4653 case DW_TAG_variable:
4654 case DW_TAG_formal_parameter:
4655 break;
0a98fd42 4656
4ef35696
JS
4657 default:
4658 continue;
4659 }
0a98fd42 4660
4ef35696
JS
4661 /* Ignore this local if it has no name. */
4662 const char *arg_name = dwarf_diename (&arg);
4663 if (!arg_name)
8c67c337
JS
4664 {
4665 if (verbose)
b530b5b3
LB
4666 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4667 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4668 continue;
4669 }
4ef35696
JS
4670
4671 if (verbose)
b530b5b3
LB
4672 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4673 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4674
4675 /* Ignore this local if it has no location (or not at this PC). */
4676 /* NB: It still may not be directly accessible, e.g. if it is an
4677 * aggregate type, implicit_pointer, etc., but the user can later
4678 * figure out how to access the interesting parts. */
45b02a36
FCE
4679
4680 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4681 * several synthetic
4682 * probe foo { $var }
4683 * probes, testing them for overall resolvability.
4684 */
4685
4ef35696
JS
4686 Dwarf_Attribute attr_mem;
4687 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4688 {
4689 Dwarf_Op *expr;
4690 size_t len;
4691 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4692 {
4693 if (verbose)
b530b5b3
LB
4694 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4695 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4696 continue;
4697 }
4698 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4699 &len, 1) == 1 && len > 0))
4700 {
45b02a36
FCE
4701 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4702 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4703 &len, 1) == 1 && len > 0))) {
4704 if (verbose)
4705 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4706 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4707 continue;
4708 }
4ef35696
JS
4709 }
4710 }
4711
4712 /* Ignore this local if it has no type. */
4713 string type_name;
4714 Dwarf_Die type_die;
4715 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4716 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4717 {
4718 if (verbose)
b530b5b3
LB
4719 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4720 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4721 continue;
4722 }
8c67c337 4723
4ef35696
JS
4724 /* This local looks good -- save it! */
4725 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4726 }
4ef35696
JS
4727 while (dwarf_siblingof (&arg, &arg) == 0);
4728 }
0a98fd42
JS
4729}
4730
4731
4732void
d0bfd2ac 4733dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4734{
d0bfd2ac 4735 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4736}
4737
4738
27dc09b1 4739void
42e38653 4740dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4741{
4742 if (has_process)
4743 {
4744 // These probes are allowed for unprivileged users, but only in the
4745 // context of processes which they own.
4746 emit_process_owner_assertion (o);
4747 return;
4748 }
4749
4750 // Other probes must contain the default assertion which aborts
4751 // if executed by an unprivileged user.
42e38653 4752 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4753}
4754
4755
4756void
4757dwarf_derived_probe::print_dupe_stamp(ostream& o)
4758{
4759 if (has_process)
4760 {
4761 // These probes are allowed for unprivileged users, but only in the
4762 // context of processes which they own.
4763 print_dupe_stamp_unprivileged_process_owner (o);
4764 return;
4765 }
4766
4767 // Other probes must contain the default dupe stamp
4768 derived_probe::print_dupe_stamp (o);
4769}
4770
64211010 4771
7a053d3b 4772void
20c6c071 4773dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4774 dwarf_builder * dw,
42e38653 4775 privilege_t privilege)
bd2b1e68 4776{
27dc09b1 4777 root
42e38653 4778 ->bind_privilege(privilege)
27dc09b1 4779 ->bind(dw);
54efe513
GH
4780}
4781
7a053d3b 4782void
fd6602a0 4783dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4784 dwarf_builder * dw,
42e38653 4785 privilege_t privilege)
2865d17a 4786{
27dc09b1 4787 root
42e38653 4788 ->bind_privilege(privilege)
27dc09b1 4789 ->bind(dw);
27dc09b1 4790 root->bind(TOK_CALL)
42e38653 4791 ->bind_privilege(privilege)
27dc09b1 4792 ->bind(dw);
4bda987e
SC
4793 root->bind(TOK_EXPORTED)
4794 ->bind_privilege(privilege)
4795 ->bind(dw);
27dc09b1 4796 root->bind(TOK_RETURN)
42e38653 4797 ->bind_privilege(privilege)
27dc09b1 4798 ->bind(dw);
1e035395 4799
f6be7c06
DB
4800 // For process probes / uprobes, .maxactive() is unused.
4801 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4802 {
4803 root->bind(TOK_RETURN)
1e035395
FCE
4804 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4805 }
bd2b1e68
GH
4806}
4807
7a053d3b 4808void
27dc09b1 4809dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4810 systemtap_session& s,
27dc09b1
DB
4811 match_node * root,
4812 dwarf_builder * dw,
42e38653 4813 privilege_t privilege
27dc09b1 4814)
bd2b1e68
GH
4815{
4816 // Here we match 4 forms:
4817 //
4818 // .function("foo")
4819 // .function(0xdeadbeef)
4820 // .statement("foo")
4821 // .statement(0xdeadbeef)
4822
440d9b00 4823 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4824 register_function_variants(fv_root, dw, privilege);
7f02ca94 4825 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4826 fv_root->bind(TOK_INLINE)
42e38653 4827 ->bind_privilege(privilege)
440d9b00 4828 ->bind(dw);
7f02ca94
JS
4829 fv_root->bind_str(TOK_LABEL)
4830 ->bind_privilege(privilege)
440d9b00
DB
4831 ->bind(dw);
4832
4833 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 4834 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
4835 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4836 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4837 {
4838 fv_root->bind(TOK_INLINE)
42e38653 4839 ->bind_privilege(privilege)
440d9b00
DB
4840 ->bind(dw);
4841 }
4842
42e38653
DB
4843 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
4844 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
4845}
4846
b1615c74
JS
4847void
4848dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
4849 match_node * root,
4850 dwarf_builder * dw)
4851{
4852 root->bind_str(TOK_MARK)
f66bb29a 4853 ->bind_privilege(pr_all)
b1615c74
JS
4854 ->bind(dw);
4855 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 4856 ->bind_privilege(pr_all)
b1615c74
JS
4857 ->bind(dw);
4858}
4859
4860void
4861dwarf_derived_probe::register_plt_variants(systemtap_session& s,
4862 match_node * root,
4863 dwarf_builder * dw)
4864{
4865 root->bind(TOK_PLT)
f66bb29a 4866 ->bind_privilege(pr_all)
b1615c74
JS
4867 ->bind(dw);
4868 root->bind_str(TOK_PLT)
f66bb29a 4869 ->bind_privilege(pr_all)
b1615c74
JS
4870 ->bind(dw);
4871 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4872 ->bind_privilege(pr_all)
b1615c74
JS
4873 ->bind(dw);
4874 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4875 ->bind_privilege(pr_all)
b1615c74 4876 ->bind(dw);
bd2b1e68
GH
4877}
4878
4879void
c4ce66a1 4880dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4881{
c4ce66a1 4882 match_node* root = s.pattern_root;
bd2b1e68
GH
4883 dwarf_builder *dw = new dwarf_builder();
4884
c4ce66a1
JS
4885 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4886 s.code_filters.push_back(filter);
4887
bd1fcbad
YZ
4888 filter = new dwarf_atvar_expanding_visitor(s, *dw);
4889 s.code_filters.push_back(filter);
4890
73f52eb4
DB
4891 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
4892 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
4893 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4894 ->bind(dw);
2cab6244 4895
7f02ca94
JS
4896 match_node* uprobes[] = {
4897 root->bind(TOK_PROCESS),
4898 root->bind_str(TOK_PROCESS),
4899 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4900 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4901 };
4902 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
4903 {
f66bb29a 4904 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
4905 register_sdt_variants(s, uprobes[i], dw);
4906 register_plt_variants(s, uprobes[i], dw);
4907 }
bd2b1e68
GH
4908}
4909
9020300d 4910void
3689db05
SC
4911dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
4912{
698de6cc 4913 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4914 for (pcii = perf_counter_refs.begin();
4915 pcii != perf_counter_refs.end();
4916 pcii++)
4917 {
4918 map<string, pair<string,derived_probe*> >::iterator it;
4919 // Find the associated perf.counter probe
4920 unsigned i = 0;
4921 for (it=s.perf_counters.begin() ;
4922 it != s.perf_counters.end();
4923 it++, i++)
4924 if ((*it).second.second == (*pcii))
4925 break;
4926 // place the perf counter read so it precedes stp_lock_probe
4927 o->newline() << "l->l___perf_read_" + (*it).first
4928 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
4929 + lex_cast(i) + "))));";
4930 }
4931
b95e2b79
MH
4932 if (access_vars)
4933 {
4934 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4935 o->newline() << "#if defined __ia64__";
d9aed31e 4936 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4937 o->newline() << "#endif";
b95e2b79 4938 }
9020300d 4939}
2930abc7 4940
b20febf3 4941// ------------------------------------------------------------------------
46b84a80
DS
4942
4943void
b20febf3 4944dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4945{
b20febf3 4946 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4947
4948 // XXX: probes put at the same address should all share a
4949 // single kprobe/kretprobe, and have their handlers executed
4950 // sequentially.
b55bc428
FCE
4951}
4952
7a053d3b 4953void
775d51e5 4954dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4955{
b20febf3 4956 if (probes_by_module.empty()) return;
2930abc7 4957
775d51e5
DS
4958 s.op->newline() << "/* ---- dwarf probes ---- */";
4959
4960 // Warn of misconfigured kernels
f41595cc
FCE
4961 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4962 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4963 s.op->newline() << "#endif";
775d51e5 4964 s.op->newline();
f41595cc 4965
f07c3b68 4966 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4967 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4968 s.op->newline() << "#endif";
4969
14cf7e42 4970 // Forward decls
2ba1736a 4971 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 4972
b20febf3
FCE
4973 // Forward declare the master entry functions
4974 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4975 s.op->line() << " struct pt_regs *regs);";
4976 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4977 s.op->line() << " struct pt_regs *regs);";
4978
42cb22bd
MH
4979 // Emit an array of kprobe/kretprobe pointers
4980 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4981 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4982 s.op->newline() << "#endif";
4983
b20febf3 4984 // Emit the actual probe list.
606fd9c8
FCE
4985
4986 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4987 // struct stap_dwarf_probe, but it being initialized data makes it add
4988 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4989 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4990 // NB: bss!
4991
4c2732a1 4992 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4993 s.op->newline(1) << "const unsigned return_p:1;";
4994 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4995 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4996 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4997 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4998
af234c40
JS
4999 // data saved in the kretprobe_instance packet
5000 s.op->newline() << "const unsigned short saved_longs;";
5001 s.op->newline() << "const unsigned short saved_strings;";
5002
faea5e16 5003 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5004 // are small and uniform enough to justify putting char[MAX]'s into
5005 // the array instead of relocated char*'s.
faea5e16
JS
5006 size_t module_name_max = 0, section_name_max = 0;
5007 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5008 size_t all_name_cnt = probes_by_module.size(); // for average
5009 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5010 {
5011 dwarf_derived_probe* p = it->second;
5012#define DOIT(var,expr) do { \
5013 size_t var##_size = (expr) + 1; \
5014 var##_max = max (var##_max, var##_size); \
5015 var##_tot += var##_size; } while (0)
5016 DOIT(module_name, p->module.size());
5017 DOIT(section_name, p->section.size());
606fd9c8
FCE
5018#undef DOIT
5019 }
5020
5021 // Decide whether it's worthwhile to use char[] or char* by comparing
5022 // the amount of average waste (max - avg) to the relocation data size
5023 // (3 native long words).
5024#define CALCIT(var) \
5025 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5026 { \
5027 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5028 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5029 << "[" << var##_name_max << "]" << endl; \
5030 } \
5031 else \
5032 { \
b0986e7a 5033 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5034 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5035 }
5036
5037 CALCIT(module);
5038 CALCIT(section);
e6fe60e7 5039#undef CALCIT
606fd9c8 5040
b0986e7a 5041 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5042 s.op->newline() << "const struct stap_probe * const probe;";
5043 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5044 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5045 s.op->indent(1);
5046
5047 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5048 {
b20febf3
FCE
5049 dwarf_derived_probe* p = it->second;
5050 s.op->newline() << "{";
5051 if (p->has_return)
5052 s.op->line() << " .return_p=1,";
c9bad430 5053 if (p->has_maxactive)
606fd9c8
FCE
5054 {
5055 s.op->line() << " .maxactive_p=1,";
5056 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5057 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5058 }
af234c40
JS
5059 if (p->saved_longs || p->saved_strings)
5060 {
5061 if (p->saved_longs)
5062 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5063 if (p->saved_strings)
5064 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5065 if (p->entry_handler)
c87ae2c1 5066 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5067 }
b350f56b
JS
5068 if (p->locations[0]->optional)
5069 s.op->line() << " .optional_p=1,";
dc38c256 5070 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5071 s.op->line() << " .module=\"" << p->module << "\",";
5072 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5073 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5074 s.op->line() << " },";
2930abc7 5075 }
2930abc7 5076
b20febf3
FCE
5077 s.op->newline(-1) << "};";
5078
5079 // Emit the kprobes callback function
5080 s.op->newline();
5081 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5082 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5083 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5084 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5085 // Check that the index is plausible
5086 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5087 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5088 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5089 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5090 s.op->line() << "];";
71db462b 5091 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5092 "stp_probe_type_kprobe");
d9aed31e 5093 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5094
5095 // Make it look like the IP is set as it wouldn't have been replaced
5096 // by a breakpoint instruction when calling real probe handler. Reset
5097 // IP regs on return, so we don't confuse kprobes. PR10458
5098 s.op->newline() << "{";
5099 s.op->indent(1);
d9aed31e 5100 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5101 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5102 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5103 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5104 s.op->newline(-1) << "}";
5105
f887a8c9 5106 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5107 s.op->newline() << "return 0;";
5108 s.op->newline(-1) << "}";
5109
5110 // Same for kretprobes
5111 s.op->newline();
af234c40
JS
5112 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5113 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5114 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5115
5116 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5117 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5118 // Check that the index is plausible
5119 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5120 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5121 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5122 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5123 s.op->line() << "];";
5124
7c3e97f4 5125 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5126 s.op->newline() << "if (sp) {";
5127 s.op->indent(1);
71db462b 5128 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5129 "stp_probe_type_kretprobe");
d9aed31e 5130 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5131
5132 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5133 s.op->newline() << "c->ips.krp.pi = inst;";
5134 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5135
5136 // Make it look like the IP is set as it wouldn't have been replaced
5137 // by a breakpoint instruction when calling real probe handler. Reset
5138 // IP regs on return, so we don't confuse kprobes. PR10458
5139 s.op->newline() << "{";
d9aed31e 5140 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5141 s.op->newline() << "if (entry)";
5142 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5143 s.op->newline(-1) << "else";
5144 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5145 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5146 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5147 s.op->newline(-1) << "}";
5148
f887a8c9 5149 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5150 s.op->newline(-1) << "}";
b20febf3
FCE
5151 s.op->newline() << "return 0;";
5152 s.op->newline(-1) << "}";
af234c40
JS
5153
5154 s.op->newline();
5155 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5156 s.op->line() << " struct pt_regs *regs) {";
5157 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5158 s.op->newline(-1) << "}";
5159
5160 s.op->newline();
5161 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5162 s.op->line() << " struct pt_regs *regs) {";
5163 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5164 s.op->newline(-1) << "}";
b642c901 5165
14cf7e42 5166 s.op->newline();
20c6c071 5167}
ec4373ff 5168
20c6c071 5169
dc38c0ae 5170void
b20febf3
FCE
5171dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5172{
5173 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5174 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5175 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5176 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5177 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5178 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5179 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5180 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5181 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5182 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5183 s.op->newline(-1) << "} else {";
f07c3b68 5184 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5185 s.op->newline(-1) << "}";
606fd9c8 5186 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5187 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5188 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5189 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5190 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5191 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5192 s.op->newline(-1) << "}";
5193 s.op->newline() << "#endif";
e4cb375f
MH
5194 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5195 s.op->newline() << "#ifdef __ia64__";
5196 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5197 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5198 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5199 s.op->newline() << "if (rc == 0) {";
5200 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5201 s.op->newline() << "if (rc != 0)";
5202 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5203 s.op->newline(-2) << "}";
5204 s.op->newline() << "#else";
606fd9c8 5205 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5206 s.op->newline() << "#endif";
b20febf3 5207 s.op->newline(-1) << "} else {";
e4cb375f 5208 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5209 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5210 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5211 s.op->newline() << "#ifdef __ia64__";
5212 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5213 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5214 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5215 s.op->newline() << "if (rc == 0) {";
5216 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5217 s.op->newline() << "if (rc != 0)";
5218 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5219 s.op->newline(-2) << "}";
5220 s.op->newline() << "#else";
606fd9c8 5221 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5222 s.op->newline() << "#endif";
b20febf3 5223 s.op->newline(-1) << "}";
9063462a
FCE
5224 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5225 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5226 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5227 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5228 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5229 // XXX: shall we increment numskipped?
5230 s.op->newline(-1) << "}";
5231
5232#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5233 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5234 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5235 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5236 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5237 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5238 s.op->newline() << "#ifdef __ia64__";
5239 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5240 s.op->newline() << "#endif";
c48cb0cc
FCE
5241 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5242 // not run for this early-abort case.
5243 s.op->newline(-1) << "}";
5244 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5245 s.op->newline(-1) << "}";
9063462a
FCE
5246#endif
5247
b20febf3
FCE
5248 s.op->newline() << "else sdp->registered_p = 1;";
5249 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5250}
5251
5252
b4be7cbc
FCE
5253void
5254dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5255{
5256 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5257 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5258 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5259 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5260 s.op->newline() << "int rc;";
5261
5262 // new module arrived?
5263 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5264 s.op->newline(1) << "if (sdp->return_p) {";
5265 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5266 s.op->newline() << "if (sdp->maxactive_p) {";
5267 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5268 s.op->newline(-1) << "} else {";
5269 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5270 s.op->newline(-1) << "}";
5271 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5272 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5273 s.op->newline() << "if (sdp->entry_probe) {";
5274 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5275 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5276 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5277 s.op->newline(-1) << "}";
5278 s.op->newline() << "#endif";
5279 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5280 s.op->newline() << "#ifdef __ia64__";
5281 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5282 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5283 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5284 s.op->newline() << "if (rc == 0) {";
5285 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5286 s.op->newline() << "if (rc != 0)";
5287 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5288 s.op->newline(-2) << "}";
5289 s.op->newline() << "#else";
5290 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5291 s.op->newline() << "#endif";
5292 s.op->newline(-1) << "} else {";
5293 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5294 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5295 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5296 s.op->newline() << "#ifdef __ia64__";
5297 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5298 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5299 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5300 s.op->newline() << "if (rc == 0) {";
5301 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5302 s.op->newline() << "if (rc != 0)";
5303 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5304 s.op->newline(-2) << "}";
5305 s.op->newline() << "#else";
5306 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5307 s.op->newline() << "#endif";
5308 s.op->newline(-1) << "}";
5309 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5310
5311 // old module disappeared?
5312 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5313 s.op->newline(1) << "if (sdp->return_p) {";
5314 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5315 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5316 s.op->newline() << "#ifdef STP_TIMING";
5317 s.op->newline() << "if (kp->u.krp.nmissed)";
5318 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5319 s.op->newline(-1) << "#endif";
065d5567 5320 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5321 s.op->newline() << "#ifdef STP_TIMING";
5322 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5323 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5324 s.op->newline(-1) << "#endif";
5325 s.op->newline(-1) << "} else {";
5326 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5327 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5328 s.op->newline() << "#ifdef STP_TIMING";
5329 s.op->newline() << "if (kp->u.kp.nmissed)";
5330 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5331 s.op->newline(-1) << "#endif";
5332 s.op->newline(-1) << "}";
5333 s.op->newline() << "#if defined(__ia64__)";
5334 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5335 s.op->newline() << "#endif";
5336 s.op->newline() << "sdp->registered_p = 0;";
5337 s.op->newline(-1) << "}";
5338
5339 s.op->newline(-1) << "}"; // for loop
5340}
5341
5342
5343
5344
46b84a80 5345void
b20febf3 5346dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5347{
42cb22bd
MH
5348 //Unregister kprobes by batch interfaces.
5349 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5350 s.op->newline() << "j = 0;";
5351 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5352 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5353 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5354 s.op->newline() << "if (! sdp->registered_p) continue;";
5355 s.op->newline() << "if (!sdp->return_p)";
5356 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5357 s.op->newline(-2) << "}";
5358 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5359 s.op->newline() << "j = 0;";
5360 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5361 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5362 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5363 s.op->newline() << "if (! sdp->registered_p) continue;";
5364 s.op->newline() << "if (sdp->return_p)";
5365 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5366 s.op->newline(-2) << "}";
5367 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5368 s.op->newline() << "#ifdef __ia64__";
5369 s.op->newline() << "j = 0;";
5370 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5371 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5372 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5373 s.op->newline() << "if (! sdp->registered_p) continue;";
5374 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5375 s.op->newline(-1) << "}";
5376 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5377 s.op->newline() << "#endif";
42cb22bd
MH
5378 s.op->newline() << "#endif";
5379
b20febf3
FCE
5380 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5381 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5382 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5383 s.op->newline() << "if (! sdp->registered_p) continue;";
5384 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5385 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5386 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5387 s.op->newline() << "#endif";
065d5567 5388 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5389 s.op->newline() << "#ifdef STP_TIMING";
5390 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5391 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5392 s.op->newline(-1) << "#endif";
065d5567 5393 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5394 s.op->newline() << "#ifdef STP_TIMING";
5395 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5396 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
73209876 5397 s.op->newline(-1) << "#endif";
557fb7a8 5398 s.op->newline(-1) << "} else {";
42cb22bd 5399 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5400 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5401 s.op->newline() << "#endif";
065d5567 5402 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5403 s.op->newline() << "#ifdef STP_TIMING";
5404 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5405 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5406 s.op->newline(-1) << "#endif";
b20febf3 5407 s.op->newline(-1) << "}";
e4cb375f
MH
5408 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5409 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5410 s.op->newline() << "#endif";
b20febf3
FCE
5411 s.op->newline() << "sdp->registered_p = 0;";
5412 s.op->newline(-1) << "}";
46b84a80
DS
5413}
5414
272c9036
WF
5415static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5416{
5417 string::size_type pos;
5418 string::size_type lastPos = str.find_first_not_of(" ", 0);
5419 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5420
5421 if (nextAt == string::npos)
5422 {
5423 // PR13934: Assembly probes are not forced to use the N@OP form.
5424 // In this case, N is inferred to be the native word size. Since we
5425 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5426 // then must not put any spaces in arguments, to avoid ambiguity.
5427 tokenize(str, tokens, " ");
5428 return;
5429 }
5430
272c9036
WF
5431 while (lastPos != string::npos)
5432 {
5433 pos = nextAt + 1;
5434 nextAt = str.find("@", pos);
5435 if (nextAt == string::npos)
5436 pos = string::npos;
5437 else
5438 pos = str.rfind(" ", nextAt);
5439
5440 tokens.push_back(str.substr(lastPos, pos - lastPos));
5441 lastPos = str.find_first_not_of(" ", pos);
5442 }
5443}
8aabf152 5444
8aabf152 5445
aff5d390 5446struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5447{
ae1418f0 5448 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
5449 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
5450 int elf_machine,
5451 const string & process_name,
a794dbeb 5452 const string & provider_name,
aff5d390 5453 const string & probe_name,
71e5e13d 5454 stap_sdt_probe_type probe_type,
aff5d390 5455 const string & arg_string,
8aabf152 5456 int ac):
332ba7e7 5457 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
5458 provider_name (provider_name), probe_name (probe_name),
5459 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5460 {
f83336a5
FCE
5461 /* Register name mapping table depends on the elf machine of this particular
5462 probe target process/file, not upon the host. So we can't just
5463 #ifdef _i686_ etc. */
ae1418f0
FCE
5464
5465#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5466 if (elf_machine == EM_X86_64) {
46a94997
SC
5467 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5468 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5469 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5470 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5471 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5472 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5473 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5474 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5475 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5476 DRI ("%sil", 4, QI);
5477 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5478 DRI ("%dil", 5, QI);
5479 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
2c7281e7 5480 DRI ("%bpl", 6, QI);
46a94997 5481 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
2c7281e7 5482 DRI ("%spl", 7, QI);
46a94997
SC
5483 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5484 DRI ("%r8b", 8, QI);
5485 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5486 DRI ("%r9b", 9, QI);
5487 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5488 DRI ("%r10b", 10, QI);
5489 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5490 DRI ("%r11b", 11, QI);
5491 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5492 DRI ("%r12b", 12, QI);
5493 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5494 DRI ("%r13b", 13, QI);
5495 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5496 DRI ("%r14b", 14, QI);
5497 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5498 DRI ("%r15b", 15, QI);
f83336a5 5499 } else if (elf_machine == EM_386) {
46a94997
SC
5500 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5501 DRI ("%ah", 0, QIh);
5502 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5503 DRI ("%ch", 1, QIh);
5504 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5505 DRI ("%dh", 2, QIh);
5506 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5507 DRI ("%bh", 3, QIh);
5508 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5509 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5510 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5511 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5512 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5513 DRI ("%r0", 0, DI);
5514 DRI ("%r1", 1, DI);
5515 DRI ("%r2", 2, DI);
5516 DRI ("%r3", 3, DI);
5517 DRI ("%r4", 4, DI);
5518 DRI ("%r5", 5, DI);
5519 DRI ("%r6", 6, DI);
5520 DRI ("%r7", 7, DI);
5521 DRI ("%r8", 8, DI);
5522 DRI ("%r9", 9, DI);
5523 DRI ("%r10", 10, DI);
5524 DRI ("%r11", 11, DI);
5525 DRI ("%r12", 12, DI);
5526 DRI ("%r13", 13, DI);
5527 DRI ("%r14", 14, DI);
5528 DRI ("%r15", 15, DI);
5529 DRI ("%r16", 16, DI);
5530 DRI ("%r17", 17, DI);
5531 DRI ("%r18", 18, DI);
5532 DRI ("%r19", 19, DI);
5533 DRI ("%r20", 20, DI);
5534 DRI ("%r21", 21, DI);
5535 DRI ("%r22", 22, DI);
5536 DRI ("%r23", 23, DI);
5537 DRI ("%r24", 24, DI);
5538 DRI ("%r25", 25, DI);
5539 DRI ("%r26", 26, DI);
5540 DRI ("%r27", 27, DI);
5541 DRI ("%r28", 28, DI);
5542 DRI ("%r29", 29, DI);
5543 DRI ("%r30", 30, DI);
5544 DRI ("%r31", 31, DI);
8aabf152 5545 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5546 DRI ("0", 0, DI);
5547 DRI ("1", 1, DI);
5548 DRI ("2", 2, DI);
5549 DRI ("3", 3, DI);
5550 DRI ("4", 4, DI);
5551 DRI ("5", 5, DI);
5552 DRI ("6", 6, DI);
5553 DRI ("7", 7, DI);
5554 DRI ("8", 8, DI);
5555 DRI ("9", 9, DI);
5556 DRI ("10", 10, DI);
5557 DRI ("11", 11, DI);
5558 DRI ("12", 12, DI);
5559 DRI ("13", 13, DI);
5560 DRI ("14", 14, DI);
5561 DRI ("15", 15, DI);
5562 DRI ("16", 16, DI);
5563 DRI ("17", 17, DI);
5564 DRI ("18", 18, DI);
5565 DRI ("19", 19, DI);
5566 DRI ("20", 20, DI);
5567 DRI ("21", 21, DI);
5568 DRI ("22", 22, DI);
5569 DRI ("23", 23, DI);
5570 DRI ("24", 24, DI);
5571 DRI ("25", 25, DI);
5572 DRI ("26", 26, DI);
5573 DRI ("27", 27, DI);
5574 DRI ("28", 28, DI);
5575 DRI ("29", 29, DI);
5576 DRI ("30", 30, DI);
5577 DRI ("31", 31, DI);
14900130 5578 } else if (elf_machine == EM_S390) {
46a94997
SC
5579 DRI ("%r0", 0, DI);
5580 DRI ("%r1", 1, DI);
5581 DRI ("%r2", 2, DI);
5582 DRI ("%r3", 3, DI);
5583 DRI ("%r4", 4, DI);
5584 DRI ("%r5", 5, DI);
5585 DRI ("%r6", 6, DI);
5586 DRI ("%r7", 7, DI);
5587 DRI ("%r8", 8, DI);
5588 DRI ("%r9", 9, DI);
5589 DRI ("%r10", 10, DI);
5590 DRI ("%r11", 11, DI);
5591 DRI ("%r12", 12, DI);
5592 DRI ("%r13", 13, DI);
5593 DRI ("%r14", 14, DI);
5594 DRI ("%r15", 15, DI);
272c9036
WF
5595 } else if (elf_machine == EM_ARM) {
5596 DRI ("r0", 0, SI);
5597 DRI ("r1", 1, SI);
5598 DRI ("r2", 2, SI);
5599 DRI ("r3", 3, SI);
5600 DRI ("r4", 4, SI);
5601 DRI ("r5", 5, SI);
5602 DRI ("r6", 6, SI);
5603 DRI ("r7", 7, SI);
5604 DRI ("r8", 8, SI);
5605 DRI ("r9", 9, SI);
669a2feb 5606 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
272c9036
WF
5607 DRI ("fp", 11, SI);
5608 DRI ("ip", 12, SI);
5609 DRI ("sp", 13, SI);
5610 DRI ("lr", 14, SI);
5611 DRI ("pc", 15, SI);
14900130 5612 } else if (arg_count) {
8aabf152 5613 /* permit this case; just fall back to dwarf */
f83336a5 5614 }
ae1418f0 5615#undef DRI
f83336a5 5616
ebbd2b45 5617 need_debug_info = false;
88e39987 5618 if (probe_type == uprobe3_type)
272c9036
WF
5619 {
5620 sdt_v3_tokenize(arg_string, arg_tokens);
5621 assert(arg_count <= 12);
5622 }
88e39987 5623 else
272c9036
WF
5624 {
5625 tokenize(arg_string, arg_tokens, " ");
5626 assert(arg_count <= 10);
5627 }
a8ec7719 5628 }
8aabf152 5629
f83336a5 5630 systemtap_session& session;
332ba7e7 5631 int elf_machine;
aff5d390 5632 const string & process_name;
a794dbeb 5633 const string & provider_name;
aff5d390 5634 const string & probe_name;
71e5e13d 5635 stap_sdt_probe_type probe_type;
8aabf152 5636 unsigned arg_count;
aff5d390 5637 vector<string> arg_tokens;
46a94997 5638 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5639 bool need_debug_info;
aff5d390
SC
5640
5641 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5642 void visit_target_symbol_arg (target_symbol* e);
5643 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5644 void visit_atvar_op (atvar_op* e);
40a0c64e 5645 void visit_cast_op (cast_op* e);
aff5d390
SC
5646};
5647
7a05f484
SC
5648
5649void
6ef331c8 5650sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5651{
6ef331c8 5652 if (e->addressof)
b530b5b3 5653 throw semantic_error(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5654
5655 if (e->name == "$$name")
7a05f484 5656 {
6ef331c8
SC
5657 literal_string *myname = new literal_string (probe_name);
5658 myname->tok = e->tok;
5659 provide(myname);
5660 return;
5661 }
7a05f484 5662
6ef331c8
SC
5663 else if (e->name == "$$provider")
5664 {
5665 literal_string *myname = new literal_string (provider_name);
5666 myname->tok = e->tok;
5667 provide(myname);
5668 return;
5669 }
a794dbeb 5670
6ef331c8
SC
5671 else if (e->name == "$$vars" || e->name == "$$parms")
5672 {
5673 e->assert_no_components("sdt", true);
6ef331c8
SC
5674
5675 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
5676 // NB: we synthesize a new token here rather than reusing
5677 // e->tok, because print_format::print likes to use
5678 // its tok->content.
5679 token* pf_tok = new token(*e->tok);
5680 pf_tok->content = "sprintf";
63ea4244 5681
6ef331c8
SC
5682 print_format* pf = print_format::create(pf_tok);
5683
5684 for (unsigned i = 1; i <= arg_count; ++i)
5685 {
5686 if (i > 1)
5687 pf->raw_components += " ";
5688 target_symbol *tsym = new target_symbol;
5689 tsym->tok = e->tok;
5690 tsym->name = "$arg" + lex_cast(i);
5691 pf->raw_components += tsym->name;
5692 tsym->components = e->components;
5693
8c2f50c0 5694 expression *texp = require<expression> (tsym);
6ef331c8
SC
5695 if (!e->components.empty() &&
5696 e->components[0].type == target_symbol::comp_pretty_print)
5697 pf->raw_components += "=%s";
5698 else
5699 pf->raw_components += "=%#x";
5700 pf->args.push_back(texp);
5701 }
5702
5703 pf->components = print_format::string_to_components(pf->raw_components);
5704 provide (pf);
5705 }
5706 else
5707 assert(0); // shouldn't get here
5708}
5709
5710
5711void
5712sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5713{
5714 try
5715 {
8aabf152 5716 unsigned argno = 0; // the N in $argN
c69a87e0 5717 try
aff5d390 5718 {
5ecaa5a7 5719 if (startswith(e->name, "$arg"))
8aabf152 5720 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5721 }
c69a87e0 5722 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5723 {
8aabf152 5724 argno = 0;
aff5d390 5725 }
5ecaa5a7 5726
8aabf152
FCE
5727 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5728 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5729 {
8aabf152
FCE
5730 // NB: Either
5731 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5732 // 2) uprobe2_type $FOO (no probe args)
5733 // both of which get resolved later.
73d53dd2 5734 // Throw it now, and it might be resolved by DWARF later.
8aabf152 5735 need_debug_info = true;
73d53dd2 5736 throw semantic_error(_("target-symbol requires debuginfo"), e->tok);
aff5d390 5737 }
277c21bc 5738
8aabf152
FCE
5739 assert (arg_tokens.size() >= argno);
5740 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5741
8aabf152
FCE
5742 // Now we try to parse this thing, which is an assembler operand
5743 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5744 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5745 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157
FCE
5746 //
5747 // literal reg reg reg + base+index*size+offset
b874bd52 5748 // indirect offset
8095a157 5749 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S)
b874bd52
SC
5750 // power iN R (R) N(R)
5751 // ia64 N rR [r16]
5752 // s390 N %rR 0(rR) N(r15)
5753 // arm #N rR [rR] [rR, #N]
5754
8aabf152
FCE
5755 expression* argexpr = 0; // filled in in case of successful parse
5756
5757 string percent_regnames;
5758 string regnames;
5759 vector<string> matches;
71e5e13d 5760 long precision;
8aabf152
FCE
5761 int rc;
5762
40fe32e0
SC
5763 // Parse the leading length
5764
5765 if (asmarg.find('@') != string::npos)
5766 {
5767 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5768 asmarg = asmarg.substr(asmarg.find('@')+1);
5769 }
71e5e13d
SC
5770 else
5771 {
5772 // V1/V2 do not have precision field so default to signed long
5773 // V3 asm does not have precision field so default to unsigned long
5774 if (probe_type == uprobe3_type)
5775 precision = sizeof(long); // this is an asm probe
5776 else
5777 precision = -sizeof(long);
5778 }
40fe32e0 5779
8aabf152
FCE
5780 // test for a numeric literal.
5781 // Only accept (signed) decimals throughout. XXX
5782
5783 // PR11821. NB: on powerpc, literals are not prefixed with $,
5784 // so this regex does not match. But that's OK, since without
5785 // -mregnames, we can't tell them apart from register numbers
5786 // anyway. With -mregnames, we could, if gcc somehow
5787 // communicated to us the presence of that option, but alas it
5788 // doesn't. http://gcc.gnu.org/PR44995.
272c9036 5789 rc = regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5790 if (! rc)
5791 {
75a371ce
JS
5792 string sn = matches[0].substr(1);
5793 int64_t n;
5794 try
5795 {
5796 // We have to pay attention to the size & sign, as gcc sometimes
5797 // propagates constants that don't quite match, like a negative
5798 // value to fill an unsigned type.
5799 switch (precision)
5800 {
5801 case -1: n = lex_cast< int8_t>(sn); break;
5802 case 1: n = lex_cast< uint8_t>(sn); break;
5803 case -2: n = lex_cast< int16_t>(sn); break;
5804 case 2: n = lex_cast<uint16_t>(sn); break;
5805 case -4: n = lex_cast< int32_t>(sn); break;
5806 case 4: n = lex_cast<uint32_t>(sn); break;
5807 default:
5808 case -8: n = lex_cast< int64_t>(sn); break;
5809 case 8: n = lex_cast<uint64_t>(sn); break;
5810 }
5811 }
5812 catch (std::runtime_error&)
5813 {
5814 goto not_matched;
5815 }
5816 literal_number* ln = new literal_number(n);
8aabf152
FCE
5817 ln->tok = e->tok;
5818 argexpr = ln;
5819 goto matched;
5820 }
5821
14900130
SC
5822 if (dwarf_regs.empty())
5823 goto not_matched;
d5b83cee 5824
8aabf152
FCE
5825 // Build regex pieces out of the known dwarf_regs. We keep two separate
5826 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5827 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5828 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5829 {
5830 string regname = ri->first;
5831 assert (regname != "");
5832 regnames += string("|")+regname;
5833 if (regname[0]=='%')
5834 percent_regnames += string("|")+regname;
5835 }
5836 // clip off leading |
5837 regnames = regnames.substr(1);
272c9036
WF
5838 if (percent_regnames != "")
5839 percent_regnames = percent_regnames.substr(1);
8aabf152
FCE
5840
5841 // test for REGISTER
5842 // NB: Because PR11821, we must use percent_regnames here.
272c9036 5843 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
9109f487
SC
5844 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5845 else
332ba7e7 5846 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5847 if (! rc)
5848 {
5849 string regname = matches[1];
46a94997
SC
5850 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5851 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5852 {
5853 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5854 string width_adjust;
46a94997 5855 switch (ri->second.second)
19c22e1f 5856 {
892ec39a
SC
5857 case QI: width_adjust = ") & 0xff)"; break;
5858 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5859 case HI:
71e5e13d 5860 // preserve 16 bit register signness
892ec39a
SC
5861 width_adjust = ") & 0xffff)";
5862 if (precision < 0)
55b377f4 5863 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5864 break;
5865 case SI:
5866 // preserve 32 bit register signness
892ec39a
SC
5867 width_adjust = ") & 0xffffffff)";
5868 if (precision < 0)
55b377f4 5869 width_adjust += " << 32 >> 32";
19c22e1f 5870 break;
892ec39a 5871 default: width_adjust = "))";
19c22e1f 5872 }
55b377f4
SC
5873 string type = "";
5874 if (probe_type == uprobe3_type)
5875 type = (precision < 0
5876 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5877 type = type + "((";
8aabf152
FCE
5878 get_arg1->tok = e->tok;
5879 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5880 + string(" ((int64_t)") + type
8aabf152
FCE
5881 + (is_user_module (process_name)
5882 ? string("u_fetch_register(")
5883 : string("k_fetch_register("))
46a94997 5884 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5885 + width_adjust;
8aabf152
FCE
5886 argexpr = get_arg1;
5887 goto matched;
5888 }
5889 // invalid register name, fall through
5890 }
40fe32e0 5891
272c9036 5892 int reg, offset1;
e5b7b83f 5893 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5894 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 5895 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
5896 // On ARM test for [REGISTER, OFFSET]
5897 if (elf_machine == EM_ARM)
5898 {
669a2feb 5899 rc = regexp_match (asmarg, string("^\\[(")+regnames+string(")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$"), matches);
272c9036 5900 reg = 1;
669a2feb 5901 offset1 = 3;
272c9036
WF
5902 }
5903 else
5904 {
5905 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
5906 reg = 4;
5907 offset1 = 1;
5908 }
8aabf152
FCE
5909 if (! rc)
5910 {
e5b7b83f 5911 string regname;
8aabf152 5912 int64_t disp = 0;
272c9036
WF
5913 if (matches[reg].length())
5914 regname = matches[reg];
8095a157
FCE
5915 if (dwarf_regs.find (regname) == dwarf_regs.end())
5916 goto not_matched;
5917
272c9036 5918 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
5919 if (matches[i].length())
5920 try
5921 {
5922 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5923 }
8aabf152
FCE
5924 catch (const runtime_error& f) // unparseable offset
5925 {
5926 goto not_matched; // can't just 'break' out of
5927 // this case or use a sentinel
5928 // value, unfortunately
5929 }
5930
8aabf152 5931 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
5932 embedded_expr *get_arg1 = new embedded_expr;
5933 get_arg1->tok = e->tok;
5934 get_arg1->code = string("/* unprivileged */ /* pure */")
5935 + (is_user_module (process_name)
5936 ? string("u_fetch_register(")
5937 : string("k_fetch_register("))
46a94997 5938 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5939 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5940
8aabf152
FCE
5941 literal_number* inc = new literal_number(disp);
5942 inc->tok = e->tok;
40fe32e0 5943
8aabf152
FCE
5944 binary_expression *be = new binary_expression;
5945 be->tok = e->tok;
5946 be->left = get_arg1;
5947 be->op = "+";
5948 be->right = inc;
40fe32e0 5949
8aabf152 5950 functioncall *fc = new functioncall;
40fe32e0
SC
5951 switch (precision)
5952 {
7f6ce9ab
SC
5953 case 1: case -1:
5954 fc->function = "user_int8"; break;
5955 case 2:
5956 fc->function = "user_uint16"; break;
5957 case -2:
5958 fc->function = "user_int16"; break;
5959 case 4:
5960 fc->function = "user_uint32"; break;
5961 case -4:
5962 fc->function = "user_int32"; break;
5963 case 8: case -8:
5964 fc->function = "user_int64"; break;
40fe32e0
SC
5965 default: fc->function = "user_long";
5966 }
8aabf152
FCE
5967 fc->tok = e->tok;
5968 fc->args.push_back(be);
366af4e7 5969
8aabf152
FCE
5970 argexpr = fc;
5971 goto matched;
5972 }
8095a157
FCE
5973
5974 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
5975 // NB: Despite PR11821, we can use regnames here, since the parentheses
5976 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 5977 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
5978 if (! rc)
5979 {
5980 string baseregname;
5981 string indexregname;
5982 int64_t disp = 0;
5983 short scale = 1;
5984
5985 if (matches[6].length())
5986 try
5987 {
5988 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
5989 // We could verify that scale is one of 1,2,4,8,
5990 // but it doesn't really matter. An erroneous
5991 // address merely results in run-time errors.
8aabf152 5992 }
8095a157
FCE
5993 catch (const runtime_error &f) // unparseable scale
5994 {
5995 goto not_matched;
5996 }
5997
5998 if (matches[4].length())
5999 baseregname = matches[4];
6000 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6001 goto not_matched;
6002
6003 if (matches[5].length())
6004 indexregname = matches[5];
6005 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6006 goto not_matched;
6007
f7719b3d 6008 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
6009 if (matches[i].length())
6010 try
6011 {
6012 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
6013 }
6014 catch (const runtime_error& f) // unparseable offset
6015 {
6016 goto not_matched; // can't just 'break' out of
6017 // this case or use a sentinel
6018 // value, unfortunately
6019 }
6020
6021 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6022
6023 embedded_expr *get_arg1 = new embedded_expr;
6024 string regfn = is_user_module (process_name)
6025 ? string("u_fetch_register")
6026 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
6027
6028 get_arg1->tok = e->tok;
6029 get_arg1->code = string("/* unprivileged */ /* pure */")
6030 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6031 + string("+(")
6032 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6033 + string("*")
6034 + lex_cast(scale)
6035 + string(")");
6036
6037 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6038 literal_number* inc = new literal_number(disp);
6039 inc->tok = e->tok;
6040
6041 binary_expression *be = new binary_expression;
6042 be->tok = e->tok;
6043 be->left = get_arg1;
6044 be->op = "+";
6045 be->right = inc;
6046
6047 functioncall *fc = new functioncall;
6048 switch (precision)
6049 {
6050 case 1: case -1:
6051 fc->function = "user_int8"; break;
6052 case 2:
6053 fc->function = "user_uint16"; break;
6054 case -2:
6055 fc->function = "user_int16"; break;
6056 case 4:
6057 fc->function = "user_uint32"; break;
6058 case -4:
6059 fc->function = "user_int32"; break;
6060 case 8: case -8:
6061 fc->function = "user_int64"; break;
6062 default: fc->function = "user_long";
6063 }
6064 fc->tok = e->tok;
6065 fc->args.push_back(be);
6066
6067 argexpr = fc;
6068 goto matched;
8aabf152
FCE
6069 }
6070
8aabf152
FCE
6071
6072 not_matched:
6073 // The asmarg operand was not recognized. Back down to dwarf.
6074 if (! session.suppress_warnings)
84fef8ee
FCE
6075 {
6076 if (probe_type == UPROBE3_TYPE)
6c9e1946 6077 session.print_warning (_F("Can't parse SDT_V3 operand '%s' [man error::sdt]", asmarg.c_str()), e->tok);
84fef8ee 6078 else // must be *PROBE2; others don't get asm operands
6c9e1946 6079 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s' [man error::sdt]",
84fef8ee
FCE
6080 asmarg.c_str()), e->tok);
6081 }
8aabf152
FCE
6082 assert (argexpr == 0);
6083 need_debug_info = true;
6c9e1946 6084 throw semantic_error(_("SDT asm not understood, requires debuginfo [man error::sdt]"), e->tok);
366af4e7 6085
8aabf152
FCE
6086 matched:
6087 assert (argexpr != 0);
366af4e7
RM
6088
6089 if (session.verbose > 2)
1e41115c 6090 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6091 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6092
aff5d390 6093 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6094 {
6095 if (e->addressof)
b530b5b3 6096 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
6097 provide (argexpr);
6098 return;
6099 }
6100 else // $var->foo
6101 {
6102 cast_op *cast = new cast_op;
6103 cast->name = "@cast";
6104 cast->tok = e->tok;
6105 cast->operand = argexpr;
6106 cast->components = e->components;
6107 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6108 cast->module = process_name;
6109 cast->visit(this);
6110 return;
6111 }
366af4e7 6112
8aabf152 6113 /* NOTREACHED */
aff5d390
SC
6114 }
6115 catch (const semantic_error &er)
6116 {
6117 e->chain (er);
6118 provide (e);
6119 }
6120}
6121
6122
6ef331c8
SC
6123void
6124sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6125{
6126 try
6127 {
49131a6d 6128 assert(e->name.size() > 0
bd1fcbad 6129 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6130
6131 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6132 visit_target_symbol_context (e);
6133 else
6134 visit_target_symbol_arg (e);
6135 }
6136 catch (const semantic_error &er)
6137 {
6138 e->chain (er);
6139 provide (e);
6140 }
6141}
6142
6143
bd1fcbad
YZ
6144void
6145sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6146{
6147 need_debug_info = true;
6148
6149 // Fill in our current module context if needed
6150 if (e->module.empty())
6151 e->module = process_name;
6152
6153 var_expanding_visitor::visit_atvar_op(e);
6154}
6155
6156
40a0c64e
JS
6157void
6158sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6159{
6160 // Fill in our current module context if needed
6161 if (e->module.empty())
6162 e->module = process_name;
6163
6164 var_expanding_visitor::visit_cast_op(e);
6165}
6166
6167
576eaefe
SC
6168void
6169plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6170{
6171 try
6172 {
6173 if (e->name == "$$name")
6174 {
6175 literal_string *myname = new literal_string (entry);
6176 myname->tok = e->tok;
6177 provide(myname);
6178 return;
6179 }
3d69c03f
JS
6180
6181 // variable not found -> throw a semantic error
6182 // (only to be caught right away, but this may be more complex later...)
6183 string alternatives = "$$name";
6184 throw semantic_error(_F("unable to find plt variable '%s' (alternatives: %s)",
6185 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6186 }
6187 catch (const semantic_error &er)
6188 {
6189 e->chain (er);
6190 provide (e);
6191 }
6192}
6193
6194
edce5b67
JS
6195struct sdt_query : public base_query
6196{
6197 sdt_query(probe * base_probe, probe_point * base_loc,
6198 dwflpp & dw, literal_map_t const & params,
51d6bda3 6199 vector<derived_probe *> & results, const string user_lib);
edce5b67 6200
51d6bda3 6201 void query_library (const char *data);
576eaefe 6202 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6203 void handle_query_module();
6204
6205private:
15284963 6206 stap_sdt_probe_type probe_type;
d61ea602 6207 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6208 probe * base_probe;
6209 probe_point * base_loc;
6846cfc8 6210 literal_map_t const & params;
edce5b67 6211 vector<derived_probe *> & results;
a794dbeb
FCE
6212 string pp_mark;
6213 string pp_provider;
51d6bda3 6214 string user_lib;
edce5b67
JS
6215
6216 set<string> probes_handled;
6217
6218 Elf_Data *pdata;
6219 size_t probe_scn_offset;
6220 size_t probe_scn_addr;
aff5d390 6221 uint64_t arg_count;
40fe32e0 6222 GElf_Addr base;
c57ea854 6223 GElf_Addr pc;
aff5d390 6224 string arg_string;
edce5b67 6225 string probe_name;
a794dbeb 6226 string provider_name;
909ab234 6227 GElf_Addr semaphore_load_offset;
79a0ca08 6228 Dwarf_Addr semaphore;
edce5b67
JS
6229
6230 bool init_probe_scn();
6b51ee12 6231 bool get_next_probe();
c57ea854
SC
6232 void iterate_over_probe_entries();
6233 void handle_probe_entry();
edce5b67 6234
40fe32e0
SC
6235 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
6236 void setup_note_probe_entry (int type, const char *data, size_t len);
6237
edce5b67 6238 void convert_probe(probe *base);
4ddb6dd0 6239 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6240 probe* convert_location();
40fe32e0 6241 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6242 bool have_debuginfo_uprobe(bool need_debug_info)
6243 {return probe_type == uprobe1_type
40fe32e0 6244 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6245 && need_debug_info);}
40fe32e0 6246 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6247};
6248
6249
6250sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6251 dwflpp & dw, literal_map_t const & params,
51d6bda3 6252 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6253 base_query(dw, params), probe_type(unknown_probe_type),
6254 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6255 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6256 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6257 semaphore_load_offset(0), semaphore(0)
edce5b67 6258{
a794dbeb
FCE
6259 assert(get_string_param(params, TOK_MARK, pp_mark));
6260 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6261
ef428667
FCE
6262 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6263 // map it to double-underscores.
6264 size_t pos = 0;
6265 while (1) // there may be more than one
6266 {
a794dbeb 6267 size_t i = pp_mark.find("-", pos);
ef428667 6268 if (i == string::npos) break;
a794dbeb 6269 pp_mark.replace (i, 1, "__");
ef428667
FCE
6270 pos = i+1; // resume searching after the inserted __
6271 }
a794dbeb
FCE
6272
6273 // XXX: same for pp_provider?
edce5b67
JS
6274}
6275
6276
6277void
c57ea854 6278sdt_query::handle_probe_entry()
edce5b67 6279{
c57ea854
SC
6280 if (! have_uprobe()
6281 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6282 return;
6283
6284 if (sess.verbose > 3)
c57ea854 6285 {
b530b5b3
LB
6286 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
6287 //TRANSLATORS: is matched to.
6288 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6289 switch (probe_type)
6290 {
6291 case uprobe1_type:
6292 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6293 break;
6294 case uprobe2_type:
6295 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6296 break;
40fe32e0
SC
6297 case uprobe3_type:
6298 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6299 break;
d61ea602
JS
6300 default:
6301 clog << "unknown!" << endl;
6302 break;
c57ea854
SC
6303 }
6304 }
edce5b67 6305
c57ea854
SC
6306 // Extend the derivation chain
6307 probe *new_base = convert_location();
6308 probe_point *new_location = new_base->locations[0];
6309
c57ea854
SC
6310 bool need_debug_info = false;
6311
7d395255
JS
6312 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6313 // or dwfl_module_getelf(...). We only need it for the machine type, which
6314 // should be the same. The bias is used for relocating debuginfoless probes,
6315 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6316 Dwarf_Addr bias;
7d395255 6317 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6318
1cc41cd6
DS
6319 /* Figure out the architecture of this particular ELF file. The
6320 dwarfless register-name mappings depend on it. */
6321 GElf_Ehdr ehdr_mem;
6322 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
6323 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6324 assert(em);
1cc41cd6
DS
6325 int elf_machine = em->e_machine;
6326 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine, module_val,
6327 provider_name, probe_name,
6328 probe_type, arg_string, arg_count);
6329 svv.replace (new_base->body);
6330 need_debug_info = svv.need_debug_info;
c57ea854 6331
1cc41cd6
DS
6332 // XXX: why not derive_probes() in the uprobes case too?
6333 literal_map_t params;
6334 for (unsigned i = 0; i < new_location->components.size(); ++i)
6335 {
6336 probe_point::component *c = new_location->components[i];
6337 params[c->functor] = c->arg;
6338 }
c57ea854 6339
73d53dd2 6340 unsigned prior_results_size = results.size();
1cc41cd6
DS
6341 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6342 q.has_mark = true; // enables mid-statement probing
30263a73 6343
73d53dd2
JS
6344 // V1 probes always need dwarf info
6345 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6
DS
6346 if (have_debuginfo_uprobe(need_debug_info))
6347 dw.iterate_over_modules(&query_module, &q);
73d53dd2
JS
6348
6349 // For V2+ probes, if variable references weren't used or failed (PR14369),
6350 // then try with the more direct approach. Unresolved $vars might still
6351 // cause their own error, but this gives them a chance to be optimized out.
6352 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6353 {
6354 string section;
6355 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6356 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6357 {
6358 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6359 section = ".dynamic";
6360 }
6361 else
6362 section = ".absolute";
edce5b67 6363
1cc41cd6
DS
6364 uprobe_derived_probe* p =
6365 new uprobe_derived_probe ("", "", 0,
6366 path_remove_sysroot(sess,q.module_val),
6367 section,
6368 q.statement_num_val, reloc_addr, q, 0);
6369 p->saveargs (arg_count);
6370 results.push_back (p);
c57ea854 6371 }
487bf4e2 6372 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6373 record_semaphore(results, prior_results_size);
c57ea854 6374}
edce5b67 6375
4ddb6dd0 6376
c57ea854
SC
6377void
6378sdt_query::handle_query_module()
6379{
6380 if (!init_probe_scn())
6381 return;
edce5b67 6382
c57ea854
SC
6383 if (sess.verbose > 3)
6384 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6385
40fe32e0
SC
6386 if (probe_loc == note_section)
6387 {
6388 GElf_Shdr shdr_mem;
6389 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6390
909ab234
JS
6391 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6392 // effects. The 'semaphore_load_offset' accounts for the difference in
6393 // load addresses between text and data, so the semaphore can be
6394 // converted to a file offset if needed.
40fe32e0 6395 if (shdr)
909ab234
JS
6396 {
6397 base = shdr->sh_addr;
6398 GElf_Addr base_offset = shdr->sh_offset;
6399 shdr = dw.get_section (".probes", &shdr_mem);
6400 if (shdr)
6401 semaphore_load_offset =
6402 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6403 }
40fe32e0 6404 else
909ab234
JS
6405 base = semaphore_load_offset = 0;
6406
40fe32e0
SC
6407 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
6408 }
d61ea602 6409 else if (probe_loc == probe_section)
40fe32e0 6410 iterate_over_probe_entries ();
edce5b67
JS
6411}
6412
6413
6414bool
6415sdt_query::init_probe_scn()
6416{
448a86b7 6417 Elf* elf;
edce5b67 6418 GElf_Shdr shdr_mem;
40fe32e0
SC
6419
6420 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6421 if (shdr)
6422 {
6423 probe_loc = note_section;
6424 return true;
6425 }
edce5b67 6426
448a86b7 6427 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6428 if (shdr)
edce5b67 6429 {
fea74777
SC
6430 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6431 probe_scn_offset = 0;
6432 probe_scn_addr = shdr->sh_addr;
6433 assert (pdata != NULL);
6434 if (sess.verbose > 4)
ce0f6648
LB
6435 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6436 << pdata->d_size << endl;
40fe32e0 6437 probe_loc = probe_section;
fea74777 6438 return true;
edce5b67 6439 }
fea74777 6440 else
edce5b67 6441 return false;
edce5b67
JS
6442}
6443
40fe32e0
SC
6444void
6445sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
6446{
6447 sdt_query *me = (sdt_query*)object;
6448 me->setup_note_probe_entry (type, data, len);
6449}
6450
6451
6452void
6453sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
6454{
6455 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
6456 // && !memcmp (data->d_buf + name_off,
6457 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
6458
6459 // probes are in the .note.stapsdt section
6460#define _SDT_NOTE_TYPE 3
6461 if (type != _SDT_NOTE_TYPE)
6462 return;
6463
6464 union
6465 {
6466 Elf64_Addr a64[3];
6467 Elf32_Addr a32[3];
6468 } buf;
6469 Dwarf_Addr bias;
6470 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6471 Elf_Data dst =
6472 {
6473 &buf, ELF_T_ADDR, EV_CURRENT,
6474 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6475 };
6476 assert (dst.d_size <= sizeof buf);
6477
6478 if (len < dst.d_size + 3)
6479 return;
6480
6481 Elf_Data src =
6482 {
6483 (void *) data, ELF_T_ADDR, EV_CURRENT,
6484 dst.d_size, 0, 0
6485 };
6486
6487 if (gelf_xlatetom (elf, &dst, &src,
6488 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6489 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6490
6491 probe_type = uprobe3_type;
6492 const char * provider = data + dst.d_size;
3f803f9e 6493
40fe32e0 6494 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6495 if(name++ == NULL)
6496 return;
6497
6498 const char *args = (const char*)memchr (name, '\0', data + len - name);
6499 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6500 return;
6501
6502 provider_name = provider;
6503 probe_name = name;
6504 arg_string = args;
40fe32e0
SC
6505
6506 // Did we find a matching probe?
6507 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6508 && ((pp_provider == "")
6509 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6510 return;
6511
e9a90eee
JS
6512 // PR13934: Assembly probes are not forced to use the N@OP form.
6513 // If we have '@' then great, else count based on space-delimiters.
6514 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6515 if (!arg_count && !arg_string.empty())
6516 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6517
40fe32e0
SC
6518 GElf_Addr base_ref;
6519 if (gelf_getclass (elf) == ELFCLASS32)
6520 {
6521 pc = buf.a32[0];
6522 base_ref = buf.a32[1];
6523 semaphore = buf.a32[2];
6524 }
6525 else
6526 {
6527 pc = buf.a64[0];
6528 base_ref = buf.a64[1];
6529 semaphore = buf.a64[2];
6530 }
6531
6532 semaphore += base - base_ref;
6533 pc += base - base_ref;
6534
7d395255
JS
6535 // The semaphore also needs the ELF bias added now, so
6536 // record_semaphore can properly relocate it later.
6537 semaphore += bias;
6538
40fe32e0 6539 if (sess.verbose > 4)
b530b5b3 6540 clog << _F(" saw .note.stapsdt %s%s ", probe_name.c_str(), (provider_name != "" ? _(" (provider ")+provider_name+") " : "").c_str()) << "@0x" << hex << pc << dec << endl;
40fe32e0
SC
6541
6542 handle_probe_entry();
6543}
6544
6545
c57ea854
SC
6546void
6547sdt_query::iterate_over_probe_entries()
edce5b67 6548{
c57ea854 6549 // probes are in the .probe section
edce5b67
JS
6550 while (probe_scn_offset < pdata->d_size)
6551 {
aff5d390
SC
6552 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6553 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6554 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6555 if (! have_uprobe())
edce5b67
JS
6556 {
6557 // Unless this is a mangled .probes section, this happens
6558 // because the name of the probe comes first, followed by
6559 // the sentinel.
6560 if (sess.verbose > 5)
b530b5b3 6561 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6562 probe_scn_offset += sizeof(__uint32_t);
6563 continue;
6564 }
aff5d390
SC
6565 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6566 {
6567 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6568 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6569 continue;
6570 }
6571
1cc41cd6 6572 if (probe_type == uprobe1_type)
aff5d390 6573 {
79a0ca08 6574 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6575 return;
79a0ca08 6576 semaphore = 0;
aff5d390 6577 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6578 provider_name = ""; // unknown
1cc41cd6
DS
6579 pc = pbe_v1->arg;
6580 arg_count = 0;
aff5d390
SC
6581 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6582 }
08b5a50c 6583 else if (probe_type == uprobe2_type)
aff5d390 6584 {
79a0ca08 6585 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6586 return;
79a0ca08 6587 semaphore = pbe_v2->semaphore;
aff5d390 6588 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6589 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6590 arg_count = pbe_v2->arg_count;
6591 pc = pbe_v2->pc;
6592 if (pbe_v2->arg_string)
6593 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6594 // skip over pbe_v2, probe_name text and provider text
6595 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6596 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6597 }
edce5b67 6598 if (sess.verbose > 4)
b530b5b3 6599 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6600 << "@0x" << hex << pc << dec << endl;
edce5b67 6601
a794dbeb
FCE
6602 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6603 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6604 handle_probe_entry ();
edce5b67 6605 }
edce5b67
JS
6606}
6607
6608
6846cfc8 6609void
4ddb6dd0 6610sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6611{
a794dbeb
FCE
6612 for (unsigned i=0; i<2; i++) {
6613 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6614 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6615 // XXX: multiple addresses?
6616 if (sess.verbose > 2)
b530b5b3 6617 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6618
79a0ca08
SC
6619 Dwarf_Addr addr;
6620 if (this->semaphore)
6621 addr = this->semaphore;
6622 else
6623 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6624 if (addr)
6625 {
7d395255 6626 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6627 dwfl_module_relocate_address (dw.module, &addr);
6628 // XXX: relocation basis?
909ab234
JS
6629
6630 // Dyninst needs the *file*-based offset for semaphores,
6631 // so subtract the difference in load addresses between .text and .probes
6632 if (dw.sess.runtime_usermode_p())
6633 addr -= semaphore_load_offset;
6634
a794dbeb
FCE
6635 for (unsigned i = start; i < results.size(); ++i)
6636 results[i]->sdt_semaphore_addr = addr;
6637 if (sess.verbose > 2)
b530b5b3 6638 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6639 return;
6640 }
6641 else
6642 if (sess.verbose > 2)
b530b5b3 6643 clog << _(", not found") << endl;
a794dbeb 6644 }
6846cfc8
SC
6645}
6646
6647
edce5b67
JS
6648void
6649sdt_query::convert_probe (probe *base)
6650{
6651 block *b = new block;
6652 b->tok = base->body->tok;
6653
edce5b67
JS
6654 // Generate: if (arg1 != mark("label")) next;
6655 functioncall *fc = new functioncall;
bbafcb1e 6656 fc->function = "ulong_arg";
edce5b67 6657 fc->tok = b->tok;
bbafcb1e 6658 literal_number* num = new literal_number(1);
edce5b67
JS
6659 num->tok = b->tok;
6660 fc->args.push_back(num);
6661
6662 functioncall *fcus = new functioncall;
6663 fcus->function = "user_string";
6664 fcus->type = pe_string;
6665 fcus->tok = b->tok;
6666 fcus->args.push_back(fc);
6667
6668 if_statement *is = new if_statement;
6669 is->thenblock = new next_statement;
6670 is->elseblock = NULL;
6671 is->tok = b->tok;
63ea4244 6672 is->thenblock->tok = b->tok;
edce5b67
JS
6673 comparison *be = new comparison;
6674 be->op = "!=";
6675 be->tok = b->tok;
6676 be->left = fcus;
6677 be->right = new literal_string(probe_name);
63ea4244 6678 be->right->tok = b->tok;
edce5b67
JS
6679 is->condition = be;
6680 b->statements.push_back(is);
6681
6682 // Now replace the body
6683 b->statements.push_back(base->body);
6684 base->body = b;
6685}
6686
6687
c72aa911
JS
6688probe*
6689sdt_query::convert_location ()
edce5b67 6690{
c72aa911 6691 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6692 vector<probe_point::component*> derived_comps;
edce5b67 6693
662539d9
JS
6694 vector<probe_point::component*>::iterator it;
6695 for (it = specific_loc->components.begin();
6696 it != specific_loc->components.end(); ++it)
6697 if ((*it)->functor == TOK_PROCESS)
6698 {
1cc41cd6
DS
6699 // copy the process name
6700 derived_comps.push_back(*it);
662539d9
JS
6701 }
6702 else if ((*it)->functor == TOK_LIBRARY)
6703 {
1cc41cd6
DS
6704 // copy the library name for process probes
6705 derived_comps.push_back(*it);
662539d9
JS
6706 }
6707 else if ((*it)->functor == TOK_PROVIDER)
6708 {
6709 // replace the possibly wildcarded arg with the specific provider name
6710 *it = new probe_point::component(TOK_PROVIDER,
6711 new literal_string(provider_name));
6712 }
6713 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6714 {
6715 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6716 *it = new probe_point::component(TOK_MARK,
6717 new literal_string(probe_name));
a794dbeb 6718
aff5d390
SC
6719 if (sess.verbose > 3)
6720 switch (probe_type)
6721 {
6722 case uprobe1_type:
b530b5b3 6723 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6724 << hex << pc << dec << endl;
6725 break;
6726 case uprobe2_type:
b530b5b3 6727 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6728 << hex << pc << dec << endl;
6729 break;
40fe32e0 6730 case uprobe3_type:
b530b5b3 6731 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6732 << hex << pc << dec << endl;
6733 break;
aff5d390 6734 default:
b530b5b3
LB
6735 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6736 pp_mark.c_str()) << endl;
aff5d390
SC
6737 }
6738
c72aa911
JS
6739 switch (probe_type)
6740 {
aff5d390
SC
6741 case uprobe1_type:
6742 case uprobe2_type:
40fe32e0 6743 case uprobe3_type:
c72aa911 6744 // process("executable").statement(probe_arg)
662539d9
JS
6745 derived_comps.push_back
6746 (new probe_point::component(TOK_STATEMENT,
6747 new literal_number(pc, true)));
c72aa911
JS
6748 break;
6749
a794dbeb 6750 default: // deprecated
c72aa911 6751 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6752 derived_comps.push_back
6753 (new probe_point::component(TOK_FUNCTION,
6754 new literal_string("*")));
6755 derived_comps.push_back
c72aa911 6756 (new probe_point::component(TOK_LABEL,
a794dbeb 6757 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6758 break;
6759 }
6760 }
edce5b67 6761
662539d9
JS
6762 probe_point* derived_loc = new probe_point(*specific_loc);
6763 derived_loc->components = derived_comps;
8159bf55 6764 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
6765}
6766
6767
51d6bda3
SC
6768void
6769sdt_query::query_library (const char *library)
6770{
6771 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6772}
6773
6774
44ffe90c
JL
6775string dwarf_builder::suggest_functions(systemtap_session& sess,
6776 string func)
6777{
6778 // Trim any @ component
6779 size_t pos = func.find('@');
6780 if (pos != string::npos)
6781 func.erase(pos);
6782
6783 if (func.empty() || modules_seen.empty() || sess.module_cache == NULL)
6784 return "";
6785
6786 // We must first aggregate all the functions from the cache
6787 set<string> funcs;
6788 const map<string, module_info*> &cache = sess.module_cache->cache;
6789
6790 for (set<string>::iterator itmod = modules_seen.begin();
6791 itmod != modules_seen.end(); ++itmod)
6792 {
6793 map<string, module_info*>::const_iterator itcache;
6794 if ((itcache = cache.find(*itmod)) != cache.end())
6795 funcs.insert(itcache->second->sym_seen.begin(),
6796 itcache->second->sym_seen.end());
6797 }
6798
6799 if (sess.verbose > 2)
6800 clog << "suggesting from " << funcs.size() << " functions" << endl;
6801
6802 if (funcs.empty())
6803 return "";
6804
6805 // Calculate Levenshtein distance for each symbol
6806
6807 // Sensitivity parameters (open for tweaking)
6808 #define MAXFUNCS 5 // maximum number of funcs to suggest
6809
6810 multimap<unsigned, string> scores;
6811 for (set<string>::iterator it=funcs.begin(); it!=funcs.end(); ++it)
6812 {
6813 unsigned score = levenshtein(func, *it);
6814 scores.insert(make_pair(score, *it));
6815 }
6816
6817 // Print out the top MAXFUNCS funcs
6818 string suggestions; unsigned i = 0;
6819 for (multimap<unsigned, string>::iterator it = scores.begin();
6820 it != scores.end() && i < MAXFUNCS; ++it, i++)
6821 suggestions += it->second + ", ";
6822 if (!suggestions.empty())
6823 suggestions.erase(suggestions.size()-2);
6824
6825 return suggestions;
6826}
6827
20c6c071 6828void
5227f1ea 6829dwarf_builder::build(systemtap_session & sess,
7a053d3b 6830 probe * base,
20c6c071 6831 probe_point * location,
86bf665e 6832 literal_map_t const & parameters,
20c6c071
GH
6833 vector<derived_probe *> & finished_results)
6834{
b20febf3
FCE
6835 // NB: the kernel/user dwlfpp objects are long-lived.
6836 // XXX: but they should be per-session, as this builder object
6837 // may be reused if we try to cross-instrument multiple targets.
84048984 6838
7a24d422 6839 dwflpp* dw = 0;
6d5d594e 6840 literal_map_t filled_parameters = parameters;
7a24d422 6841
7a24d422 6842 string module_name;
ae2552da
FCE
6843 if (has_null_param (parameters, TOK_KERNEL))
6844 {
6845 dw = get_kern_dw(sess, "kernel");
6846 }
6847 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6848 {
c523a015
LB
6849 size_t dash_pos = 0;
6850 while((dash_pos=module_name.find('-'))!=string::npos)
6851 module_name.replace(int(dash_pos),1,"_");
6852 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6853 // NB: glob patterns get expanded later, during the offline
6854 // elfutils module listing.
ae2552da 6855 dw = get_kern_dw(sess, module_name);
b8da0ad1 6856 }
6d5d594e 6857 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6858 {
05fb3e0c 6859 module_name = sess.sysroot + module_name;
6d5d594e
LB
6860 if(has_null_param(filled_parameters, TOK_PROCESS))
6861 {
6862 wordexp_t words;
6863 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6864 if(rc || words.we_wordc <= 0)
6865 throw semantic_error(_("unspecified process probe is invalid without a -c COMMAND"));
05fb3e0c 6866 module_name = sess.sysroot + words.we_wordv[0];
6d5d594e
LB
6867 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6868 // in the case of TOK_MARK we need to modify locations as well
6869 if(location->components[0]->functor==TOK_PROCESS &&
6870 location->components[0]->arg == 0)
6871 location->components[0]->arg = new literal_string(module_name);
6872 wordfree (& words);
6873 }
5750ecc6 6874
37001baa
FCE
6875 // PR6456 process("/bin/*") glob handling
6876 if (contains_glob_chars (module_name))
6877 {
6878 // Expand glob via rewriting the probe-point process("....")
6879 // parameter, asserted to be the first one.
6880
6881 assert (location->components.size() > 0);
6882 assert (location->components[0]->functor == TOK_PROCESS);
6883 assert (location->components[0]->arg);
6884 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6885 assert (lit);
6886
6887 // Evaluate glob here, and call derive_probes recursively with each match.
6888 glob_t the_blob;
6889 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3
LB
6890 if (rc)
6891 throw semantic_error (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 6892 unsigned results_pre = finished_results.size();
37001baa
FCE
6893 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6894 {
e19ebcf7 6895 assert_no_interrupts();
37001baa
FCE
6896
6897 const char* globbed = the_blob.gl_pathv[i];
6898 struct stat st;
6899
6900 if (access (globbed, X_OK) == 0
6901 && stat (globbed, &st) == 0
6902 && S_ISREG (st.st_mode)) // see find_executable()
6903 {
7977a734
FCE
6904 // Need to call canonicalize here, in order to path-expand
6905 // patterns like process("stap*"). Otherwise it may go through
6906 // to the next round of expansion as ("stap"), leading to a $PATH
6907 // search that's not consistent with the glob search already done.
5bca76a8
JS
6908 string canononicalized = resolve_path (globbed);
6909 globbed = canononicalized.c_str();
7977a734 6910
37001baa
FCE
6911 // synthesize a new probe_point, with the glob-expanded string
6912 probe_point *pp = new probe_point (*location);
5750ecc6
FCE
6913 // PR13338: quote results to prevent recursion
6914 string eglobbed = escape_glob_chars (globbed);
6915
6916 if (sess.verbose > 1)
6917 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6918 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 6919 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 6920
37001baa 6921 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6922 new literal_string (eglobbed_tgt));
37001baa
FCE
6923 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6924 pp->components[0] = ppc;
6925
d885563b 6926 probe* new_probe = new probe (base, pp);
7977a734
FCE
6927
6928 // We override "optional = true" here, as if the
6929 // wildcarded probe point was given a "?" suffix.
6930
6931 // This is because wildcard probes will be expected
6932 // by users to apply only to some subset of the
6933 // matching binaries, in the sense of "any", rather
6934 // than "all", sort of similarly how
6935 // module("*").function("...") patterns work.
6936
6937 derive_probes (sess, new_probe, finished_results,
6938 true /* NB: not location->optional */ );
37001baa
FCE
6939 }
6940 }
6941
6942 globfree (& the_blob);
44ffe90c
JL
6943
6944 unsigned results_post = finished_results.size();
6945
6946 // Did we fail to find a function by name? Let's suggest
6947 // something!
6948 string func;
6949 if (results_pre == results_post
6950 && get_param(filled_parameters, TOK_FUNCTION, func)
6951 && !func.empty())
6952 {
6953 if (sess.verbose > 2)
6954 {
6955 clog << "suggesting functions from modules:" << endl;
6956 for (set<string>::const_iterator it = modules_seen.begin();
6957 it != modules_seen.end(); ++it)
6958 {
6959 clog << *it << endl;
6960 }
6961 }
6962 string sugs = suggest_functions(sess, func);
6963 modules_seen.clear();
6964 if (!sugs.empty())
6965 throw semantic_error (_NF("no match (similar function: %s)",
6966 "no match (similar functions: %s)",
6967 sugs.find(',') == string::npos,
6968 sugs.c_str()));
6969 }
6970
37001baa
FCE
6971 return; // avoid falling through
6972 }
6973
5750ecc6
FCE
6974 // PR13338: unquote glob results
6975 module_name = unescape_glob_chars (module_name);
05fb3e0c 6976 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
6977
6978 // if the executable starts with "#!", we look for the interpreter of the script
6979 {
6980 ifstream script_file (user_path.c_str () );
6981
6982 if (script_file.good ())
6983 {
6984 string line;
6985
6986 getline (script_file, line);
6987
6988 if (line.compare (0, 2, "#!") == 0)
6989 {
6990 string path_head = line.substr(2);
6991
6992 // remove white spaces at the beginning of the string
6993 size_t p2 = path_head.find_first_not_of(" \t");
6994
6995 if (p2 != string::npos)
6996 {
6997 string path = path_head.substr(p2);
6998
6999 // remove white spaces at the end of the string
7000 p2 = path.find_last_not_of(" \t\n");
7001 if (string::npos != p2)
7002 path.erase(p2+1);
7003
8e13c1a1
RH
7004 // handle "#!/usr/bin/env" redirect
7005 size_t offset = 0;
7006 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7007 {
7008 offset = sizeof("/bin/env")-1;
7009 }
7010 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7011 {
7012 offset = sizeof("/usr/bin/env")-1;
7013 }
7014
7015 if (offset != 0)
7016 {
7017 size_t p3 = path.find_first_not_of(" \t", offset);
7018
7019 if (p3 != string::npos)
7020 {
7021 string env_path = path.substr(p3);
05fb3e0c
WF
7022 user_path = find_executable (env_path, sess.sysroot,
7023 sess.sysenv);
8e13c1a1
RH
7024 }
7025 }
7026 else
7027 {
05fb3e0c 7028 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7029 }
d1bcbe71
RH
7030
7031 struct stat st;
7032
7033 if (access (user_path.c_str(), X_OK) == 0
7034 && stat (user_path.c_str(), &st) == 0
7035 && S_ISREG (st.st_mode)) // see find_executable()
7036 {
7037 if (sess.verbose > 1)
b530b5b3
LB
7038 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7039 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7040
7041 assert (location->components.size() > 0);
7042 assert (location->components[0]->functor == TOK_PROCESS);
7043 assert (location->components[0]->arg);
7044 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7045 assert (lit);
7046
7047 // synthesize a new probe_point, with the expanded string
7048 probe_point *pp = new probe_point (*location);
05fb3e0c 7049 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7050 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7051 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7052 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7053 pp->components[0] = ppc;
7054
d885563b 7055 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7056
7057 derive_probes (sess, new_probe, finished_results);
7058
7059 script_file.close();
7060 return;
7061 }
7062 }
7063 }
7064 }
7065 script_file.close();
7066 }
7067
47e226ed 7068 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7069 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7070 {
7071 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7072 "LD_LIBRARY_PATH");
7073 if (module_name.find('/') == string::npos)
7074 // We didn't find user_lib so use iterate_over_libraries
7075 module_name = user_path;
7076 }
63b4fd14 7077 else
b642c901 7078 module_name = user_path; // canonicalize it
d0a7f5a9 7079
3667d615 7080 // uretprobes aren't available everywhere
536f1261 7081 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7082 {
3667d615
JS
7083 if (kernel_supports_inode_uprobes(sess) &&
7084 !kernel_supports_inode_uretprobes(sess))
2b69faaf 7085 throw semantic_error
3ffeaf3c 7086 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7087 }
3667d615 7088
f4000852
MW
7089 // There is a similar check in pass 4 (buildrun), but it is
7090 // needed here too to make sure alternatives for optional
7091 // (? or !) process probes are disposed and/or alternatives
7092 // are selected.
3667d615
JS
7093 if (!sess.runtime_usermode_p())
7094 check_process_probe_kernel_support(sess);
e34d5d13 7095
7a24d422
FCE
7096 // user-space target; we use one dwflpp instance per module name
7097 // (= program or shared library)
707bf35e 7098 dw = get_user_dw(sess, module_name);
c8959a29 7099 }
20c6c071 7100
1acfc030
JS
7101 assert(dw);
7102
5896cd05 7103 if (sess.verbose > 3)
b530b5b3 7104 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7105
a794dbeb
FCE
7106 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7107 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7108 {
51d6bda3 7109 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
7110 dw->iterate_over_modules(&query_module, &sdtq);
7111 return;
7a05f484 7112 }
20c6c071 7113
8f14e444 7114 unsigned results_pre = finished_results.size();
6d5d594e 7115 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7116
7117 // XXX: kernel.statement.absolute is a special case that requires no
7118 // dwfl processing. This code should be in a separate builder.
7a24d422 7119 if (q.has_kernel && q.has_absolute)
37ebca01 7120 {
4baf0e53 7121 // assert guru mode for absolute probes
37ebca01
FCE
7122 if (! q.base_probe->privileged)
7123 {
e3bbc038 7124 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7125 q.base_probe->tok);
37ebca01
FCE
7126 }
7127
7128 // For kernel.statement(NUM).absolute probe points, we bypass
7129 // all the debuginfo stuff: We just wire up a
7130 // dwarf_derived_probe right here and now.
4baf0e53 7131 dwarf_derived_probe* p =
b8da0ad1
FCE
7132 new dwarf_derived_probe ("", "", 0, "kernel", "",
7133 q.statement_num_val, q.statement_num_val,
7134 q, 0);
37ebca01 7135 finished_results.push_back (p);
1a0dbc5a 7136 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7137 return;
7138 }
7139
51178501 7140 dw->iterate_over_modules(&query_module, &q);
8f14e444 7141
44ffe90c
JL
7142 // We need to update modules_seen with the modules we've visited
7143 modules_seen.insert(q.visited_modules.begin(),
7144 q.visited_modules.end());
8f14e444
FCE
7145
7146 // PR11553 special processing: .return probes requested, but
7147 // some inlined function instances matched.
7148 unsigned i_n_r = q.inlined_non_returnable.size();
7149 unsigned results_post = finished_results.size();
7150 if (i_n_r > 0)
7151 {
7152 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7153 {
7154 string quicklist;
7155 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7156 it != q.inlined_non_returnable.end();
7157 it++)
7158 {
7159 quicklist += " " + (*it);
7160 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7161 {
7162 quicklist += " ...";
7163 break;
7164 }
7165 }
c57ea854 7166
52c2652f 7167 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7168 "cannot probe .return of %u inlined functions %s",
52c2652f 7169 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7170 // There will be also a "no matches" semantic error generated.
7171 }
7172 if (sess.verbose > 1)
52c2652f
NMA
7173 clog << _NF("skipped .return probe of %u inlined function",
7174 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7175 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7176 {
7177 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7178 it != q.inlined_non_returnable.end();
7179 it++)
7180 clog << (*it) << " ";
7181 clog << endl;
7182 }
7183 } // i_n_r > 0
44ffe90c
JL
7184
7185 // Did we fail to find a function by name? Let's suggest something! We
7186 // need to check for optional because otherwise, we will be suggesting
7187 // things during intermediate results without including all the
7188 // possible functions. For example, process("/usr/bin/*").function
7189 // will go through here for each executable found (all labelled as
7190 // optionals). Similarly for library(glob) probes. TODO: find a
7191 // mechanism to have suggestions for optional probes as well when no
7192 // probes could be derived, e.g. probepoint1?, probepoint2 should
7193 // suggest for both 1 and 2 if both fail to resolve (maybe print as a
7194 // warning?). This may entails detecting the difference between script
7195 // optional probes and probes that are optional in recursive calls.
7196 string func;
7197 if (results_pre == results_post && !location->optional
7198 && get_param(filled_parameters, TOK_FUNCTION, func)
7199 && !func.empty())
7200 {
7201 if (sess.verbose > 2)
7202 {
7203 clog << "suggesting functions from modules:" << endl;
7204 for (set<string>::const_iterator it = modules_seen.begin();
7205 it != modules_seen.end(); ++it)
7206 clog << *it << endl;
7207 }
7208 string sugs = suggest_functions(sess, func);
7209 modules_seen.clear();
7210 if (!sugs.empty())
7211 // Note that this error will not even be printed out if it is
7212 // exactly the same suggestion as a previous throw (since
7213 // print_error() filters out identical errors). Which makes
7214 // sense since it's possible that the user misspelled the same
7215 // function in different probes, in which case the first
7216 // suggestion is sufficient.
7217 throw semantic_error (_NF("no match (similar function: %s)",
7218 "no match (similar functions: %s)",
7219 sugs.find(',') == string::npos,
7220 sugs.c_str()));
7221 }
7222 else if (results_pre != results_post)
7223 // Something was derived so we won't need to suggest something
7224 modules_seen.clear();
5f0a03a6
JK
7225}
7226
7227symbol_table::~symbol_table()
7228{
c9efa5c9 7229 delete_map(map_by_addr);
5f0a03a6
JK
7230}
7231
7232void
2867a2a1 7233symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7234 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7235{
ab91b232
JK
7236#ifdef __powerpc__
7237 // Map ".sys_foo" to "sys_foo".
7238 if (name[0] == '.')
7239 name++;
7240#endif
5f0a03a6
JK
7241 func_info *fi = new func_info();
7242 fi->addr = addr;
7243 fi->name = name;
ab91b232 7244 fi->weak = weak;
2867a2a1 7245 fi->descriptor = descriptor;
5f0a03a6
JK
7246 map_by_name[fi->name] = fi;
7247 // TODO: Use a multimap in case there are multiple static
7248 // functions with the same name?
1c6b77e5 7249 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7250}
7251
7252enum info_status
7253symbol_table::read_symbols(FILE *f, const string& path)
7254{
7255 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
7256 int ret;
2e67a43b
TM
7257 char *name = 0;
7258 char *mod = 0;
5f0a03a6
JK
7259 char type;
7260 unsigned long long addr;
7261 Dwarf_Addr high_addr = 0;
7262 int line = 0;
7263
62a4021d
FCE
7264#if __GLIBC__ >2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)
7265#define MS_FMT "%ms"
7266#else
7267#define MS_FMT "%as"
7268#endif
7269 // %ms (newer than %as) mallocs space for the string and stores its address.
7270 while ((ret = fscanf(f, "%llx %c " MS_FMT " [" MS_FMT, &addr, &type, &name, &mod)) > 0)
5f0a03a6 7271 {
2e67a43b
TM
7272 auto_free free_name(name);
7273 auto_free free_mod(mod);
5f0a03a6
JK
7274 line++;
7275 if (ret < 3)
7276 {
3d372d6b 7277 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 7278 line, path.c_str());
5f0a03a6
JK
7279 // Caller should delete symbol_table object.
7280 return info_absent;
7281 }
2e67a43b 7282 else if (ret > 3)
5f0a03a6
JK
7283 {
7284 // Modules are loaded above the kernel, so if we're getting
7285 // modules, we're done.
2e67a43b 7286 break;
5f0a03a6 7287 }
ab91b232 7288 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 7289 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
7290 }
7291
1c6b77e5 7292 if (map_by_addr.size() < 1)
5f0a03a6 7293 {
3d372d6b 7294 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 7295 path.c_str()) << endl;
5f0a03a6
JK
7296 return info_absent;
7297 }
7298 return info_present;
7299}
7300
7301// NB: This currently unused. We use get_from_elf() instead because
7302// that gives us raw addresses -- which we need for modules -- whereas
7303// nm provides the address relative to the beginning of the section.
7304enum info_status
83ca3872 7305symbol_table::read_from_elf_file(const string &path,
2713ea24 7306 systemtap_session &sess)
5f0a03a6 7307{
58502ae4
JS
7308 vector<string> cmd;
7309 cmd.push_back("/usr/bin/nm");
7310 cmd.push_back("-n");
7311 cmd.push_back("--defined-only");
7312 cmd.push_back("path");
7313
5f0a03a6 7314 FILE *f;
58502ae4
JS
7315 int child_fd;
7316 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
7317 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 7318 {
58502ae4 7319 // nm failures are detected by stap_waitpid
3d372d6b 7320 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 7321 path.c_str(), strerror(errno));
5f0a03a6
JK
7322 return info_absent;
7323 }
7324 enum info_status status = read_symbols(f, path);
58502ae4 7325 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 7326 {
2713ea24
CM
7327 if (status == info_present)
7328 sess.print_warning("nm cannot read symbol table from " + path);
5f0a03a6
JK
7329 return info_absent;
7330 }
7331 return status;
7332}
7333
7334enum info_status
83ca3872 7335symbol_table::read_from_text_file(const string& path,
2713ea24 7336 systemtap_session &sess)
5f0a03a6
JK
7337{
7338 FILE *f = fopen(path.c_str(), "r");
7339 if (!f)
7340 {
2713ea24 7341 sess.print_warning("cannot read symbol table from " + path + " -- " + strerror(errno));
5f0a03a6
JK
7342 return info_absent;
7343 }
7344 enum info_status status = read_symbols(f, path);
7345 (void) fclose(f);
7346 return status;
7347}
7348
46f7b6be 7349void
f98c6346 7350symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7351{
7352#ifdef __powerpc__
7353 /*
7354 * The .opd section contains function descriptors that can look
7355 * just like function entry points. For example, there's a function
7356 * descriptor called "do_exit" that links to the entry point ".do_exit".
7357 * Reject all symbols in .opd.
7358 */
7359 opd_section = SHN_UNDEF;
7360 Dwarf_Addr bias;
7361 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7362 ?: dwfl_module_getelf (mod, &bias));
7363 Elf_Scn* scn = 0;
7364 size_t shstrndx;
7365
7366 if (!elf)
7367 return;
fcc30d6d 7368 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7369 return;
7370 while ((scn = elf_nextscn(elf, scn)) != NULL)
7371 {
7372 GElf_Shdr shdr_mem;
7373 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7374 if (!shdr)
7375 continue;
7376 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7377 if (!strcmp(name, ".opd"))
7378 {
7379 opd_section = elf_ndxscn(scn);
7380 return;
7381 }
7382 }
7383#endif
7384}
7385
7386bool
7387symbol_table::reject_section(GElf_Word section)
7388{
7389 if (section == SHN_UNDEF)
7390 return true;
7391#ifdef __powerpc__
7392 if (section == opd_section)
7393 return true;
7394#endif
7395 return false;
7396}
7397
5f0a03a6
JK
7398enum info_status
7399symbol_table::get_from_elf()
7400{
7401 Dwarf_Addr high_addr = 0;
7402 Dwfl_Module *mod = mod_info->mod;
7403 int syments = dwfl_module_getsymtab(mod);
7404 assert(syments);
46f7b6be 7405 prepare_section_rejection(mod);
5f0a03a6
JK
7406 for (int i = 1; i < syments; ++i)
7407 {
7408 GElf_Sym sym;
ab91b232
JK
7409 GElf_Word section;
7410 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 7411 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7412 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 7413 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
7414 }
7415 return info_present;
7416}
7417
5f0a03a6
JK
7418func_info *
7419symbol_table::get_func_containing_address(Dwarf_Addr addr)
7420{
1c6b77e5
JS
7421 iterator_t iter = map_by_addr.upper_bound(addr);
7422 if (iter == map_by_addr.begin())
5f0a03a6 7423 return NULL;
2e67a43b 7424 else
1c6b77e5 7425 return (--iter)->second;
5f0a03a6
JK
7426}
7427
3d372d6b
SC
7428func_info *
7429symbol_table::get_first_func()
7430{
7431 iterator_t iter = map_by_addr.begin();
7432 return (iter)->second;
7433}
7434
5f0a03a6
JK
7435func_info *
7436symbol_table::lookup_symbol(const string& name)
7437{
7438 map<string, func_info*>::iterator i = map_by_name.find(name);
7439 if (i == map_by_name.end())
7440 return NULL;
7441 return i->second;
7442}
7443
7444Dwarf_Addr
7445symbol_table::lookup_symbol_address(const string& name)
7446{
7447 func_info *fi = lookup_symbol(name);
7448 if (fi)
7449 return fi->addr;
7450 return 0;
7451}
7452
ab91b232
JK
7453// This is the kernel symbol table. The kernel macro cond_syscall creates
7454// a weak symbol for each system call and maps it to sys_ni_syscall.
7455// For system calls not implemented elsewhere, this weak symbol shows up
7456// in the kernel symbol table. Following the precedent of dwarfful stap,
7457// we refuse to consider such symbols. Here we delete them from our
7458// symbol table.
7459// TODO: Consider generalizing this and/or making it part of blacklist
7460// processing.
7461void
7462symbol_table::purge_syscall_stubs()
7463{
7464 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7465 if (stub_addr == 0)
7466 return;
1c6b77e5 7467 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7468 for (iterator_t iter = purge_range.first;
7469 iter != purge_range.second;
1c6b77e5 7470 )
ab91b232 7471 {
1c6b77e5 7472 func_info *fi = iter->second;
2e67a43b 7473 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7474 {
2e67a43b 7475 map_by_name.erase(fi->name);
1c6b77e5 7476 map_by_addr.erase(iter++);
2e67a43b 7477 delete fi;
2e67a43b 7478 }
1c6b77e5
JS
7479 else
7480 iter++;
ab91b232
JK
7481 }
7482}
7483
5f0a03a6
JK
7484void
7485module_info::get_symtab(dwarf_query *q)
7486{
1c6b77e5
JS
7487 if (symtab_status != info_unknown)
7488 return;
7489
5f0a03a6
JK
7490 sym_table = new symbol_table(this);
7491 if (!elf_path.empty())
7492 {
5f0a03a6
JK
7493 symtab_status = sym_table->get_from_elf();
7494 }
7495 else
7496 {
7497 assert(name == TOK_KERNEL);
ab3ed72d
DS
7498 symtab_status = info_absent;
7499 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
7500 }
7501 if (symtab_status == info_absent)
7502 {
7503 delete sym_table;
7504 sym_table = NULL;
7505 return;
7506 }
7507
ab91b232
JK
7508 if (name == TOK_KERNEL)
7509 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7510}
7511
1c6b77e5
JS
7512// update_symtab reconciles data between the elf symbol table and the dwarf
7513// function enumeration. It updates the symbol table entries with the dwarf
7514// die that describes the function, which also signals to query_module_symtab
7515// that a statement probe isn't needed. In return, it also adds aliases to the
7516// function table for names that share the same addr/die.
7517void
7518module_info::update_symtab(cu_function_cache_t *funcs)
7519{
7520 if (!sym_table)
7521 return;
7522
7523 cu_function_cache_t new_funcs;
7524
7525 for (cu_function_cache_t::iterator func = funcs->begin();
7526 func != funcs->end(); func++)
7527 {
6059d7c4
JL
7528 sym_seen.insert(func->first);
7529
1c6b77e5
JS
7530 // optimization: inlines will never be in the symbol table
7531 if (dwarf_func_inline(&func->second) != 0)
7532 continue;
7533
1ffb8bd1
JS
7534 // XXX We may want to make additional efforts to match mangled elf names
7535 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
7536 // missing, so we may also need to try matching by address. See also the
7537 // notes about _Z in dwflpp::iterate_over_functions().
7538
1c6b77e5
JS
7539 func_info *fi = sym_table->lookup_symbol(func->first);
7540 if (!fi)
7541 continue;
7542
7543 // iterate over all functions at the same address
7544 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
7545 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
7546 {
7547 // update this function with the dwarf die
7548 it->second->die = func->second;
7549
7550 // if this function is a new alias, then
7551 // save it to merge into the function cache
7552 if (it->second != fi)
b7478964 7553 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
7554 }
7555 }
7556
7557 // add all discovered aliases back into the function cache
7558 // NB: this won't replace any names that dwarf may have already found
7559 funcs->insert(new_funcs.begin(), new_funcs.end());
7560}
7561
5f0a03a6
JK
7562module_info::~module_info()
7563{
7564 if (sym_table)
7565 delete sym_table;
b55bc428
FCE
7566}
7567
935447c8 7568// ------------------------------------------------------------------------
888af770 7569// user-space probes
935447c8
DS
7570// ------------------------------------------------------------------------
7571
935447c8 7572
888af770 7573struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7574{
89ba3085
FCE
7575private:
7576 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 7577 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
7578 }
7579
cfcab6c7
JS
7580 void emit_module_maxuprobes (systemtap_session& s);
7581
2b69faaf
JS
7582 // Using our own utrace-based uprobes
7583 void emit_module_utrace_decls (systemtap_session& s);
7584 void emit_module_utrace_init (systemtap_session& s);
7585 void emit_module_utrace_exit (systemtap_session& s);
7586
7587 // Using the upstream inode-based uprobes
7588 void emit_module_inode_decls (systemtap_session& s);
7589 void emit_module_inode_init (systemtap_session& s);
7590 void emit_module_inode_exit (systemtap_session& s);
7591
3a894f7e
JS
7592 // Using the dyninst backend (via stapdyn)
7593 void emit_module_dyninst_decls (systemtap_session& s);
7594 void emit_module_dyninst_init (systemtap_session& s);
7595 void emit_module_dyninst_exit (systemtap_session& s);
7596
935447c8 7597public:
888af770 7598 void emit_module_decls (systemtap_session& s);
935447c8
DS
7599 void emit_module_init (systemtap_session& s);
7600 void emit_module_exit (systemtap_session& s);
7601};
7602
7603
888af770
FCE
7604void
7605uprobe_derived_probe::join_group (systemtap_session& s)
7606{
7607 if (! s.uprobe_derived_probes)
7608 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7609 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
7610 if (s.runtime_usermode_p())
7611 enable_dynprobes(s);
7612 else
4441e344 7613 enable_task_finder(s);
a96d1db0 7614
8a03658e 7615 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
7616 // signal staprun to load that module. If we're using the builtin
7617 // inode-uprobes, we still need to know that it is required.
8a03658e 7618 s.need_uprobes = true;
a96d1db0
DN
7619}
7620
888af770 7621
c0f84e7b
SC
7622void
7623uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7624{
7625 dwarf_derived_probe::getargs(arg_set);
7626 arg_set.insert(arg_set.end(), args.begin(), args.end());
7627}
7628
7629
7630void
7631uprobe_derived_probe::saveargs(int nargs)
7632{
7633 for (int i = 1; i <= nargs; i++)
7634 args.push_back("$arg" + lex_cast (i) + ":long");
7635}
7636
7637
2865d17a 7638void
42e38653 7639uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
7640{
7641 // These probes are allowed for unprivileged users, but only in the
7642 // context of processes which they own.
7643 emit_process_owner_assertion (o);
7644}
7645
7646
888af770 7647struct uprobe_builder: public derived_probe_builder
a96d1db0 7648{
888af770 7649 uprobe_builder() {}
2b69faaf 7650 virtual void build(systemtap_session & sess,
a96d1db0
DN
7651 probe * base,
7652 probe_point * location,
86bf665e 7653 literal_map_t const & parameters,
a96d1db0
DN
7654 vector<derived_probe *> & finished_results)
7655 {
888af770 7656 int64_t process, address;
a96d1db0 7657
2b69faaf 7658 if (kernel_supports_inode_uprobes(sess))
3ffeaf3c 7659 throw semantic_error (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 7660
888af770 7661 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7662 (void) b1;
888af770 7663 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7664 (void) b2;
888af770
FCE
7665 bool rr = has_null_param (parameters, TOK_RETURN);
7666 assert (b1 && b2); // by pattern_root construction
a96d1db0 7667
0973d815 7668 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7669 }
7670};
7671
7672
7673void
cfcab6c7 7674uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 7675{
43241c44
FCE
7676 // We'll probably need at least this many:
7677 unsigned minuprobes = probes.size();
7678 // .. but we don't want so many that .bss is inflated (PR10507):
7679 unsigned uprobesize = 64;
7680 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7681 unsigned maxuprobes = maxuprobesmem / uprobesize;
7682
aaf7ffe8
FCE
7683 // Let's choose a value on the geometric middle. This should end up
7684 // between minuprobes and maxuprobes. It's OK if this number turns
7685 // out to be < minuprobes or > maxuprobes. At worst, we get a
7686 // run-time error of one kind (too few: missed uprobe registrations)
7687 // or another (too many: vmalloc errors at module load time).
7688 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7689
6d0f3f0c 7690 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7691 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7692 s.op->newline() << "#endif";
cfcab6c7
JS
7693}
7694
7695
7696void
7697uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
7698{
7699 if (probes.empty()) return;
7700 s.op->newline() << "/* ---- utrace uprobes ---- */";
7701 // If uprobes isn't in the kernel, pull it in from the runtime.
7702
7703 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7704 s.op->newline() << "#include <linux/uprobes.h>";
7705 s.op->newline() << "#else";
2ba1736a 7706 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
7707 s.op->newline() << "#endif";
7708 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7709 s.op->newline() << "#define UPROBES_API_VERSION 1";
7710 s.op->newline() << "#endif";
7711
7712 emit_module_maxuprobes (s);
a96d1db0 7713
cc52276b 7714 // Forward decls
2ba1736a 7715 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 7716
5e112f92
FCE
7717 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7718 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7719 // XXX: consider a slab cache or somesuch for stap_uprobes
7720 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 7721 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7722
89ba3085
FCE
7723 s.op->assert_0_indent();
7724
89ba3085
FCE
7725 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7726 // This means we process probes[] in two passes.
7727 map <string,unsigned> module_index;
7728 unsigned module_index_ctr = 0;
7729
cc52276b
WC
7730 // not const since embedded task_finder_target struct changes
7731 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7732 s.op->indent(1);
7733 for (unsigned i=0; i<probes.size(); i++)
7734 {
7735 uprobe_derived_probe *p = probes[i];
7736 string pbmkey = make_pbm_key (p);
7737 if (module_index.find (pbmkey) == module_index.end())
7738 {
7739 module_index[pbmkey] = module_index_ctr++;
7740
7741 s.op->newline() << "{";
7742 // NB: it's essential that make_pbm_key() use all of and
7743 // only the same fields as we're about to emit.
7744 s.op->line() << " .finder={";
1af100fc 7745 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 7746 if (p->pid != 0)
68910c97
JK
7747 s.op->line() << " .pid=" << p->pid << ",";
7748
7749 if (p->section == "") // .statement(addr).absolute
7750 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7751 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7752 {
7753 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7754 s.op->line() << " .callback=&stap_uprobe_process_found,";
7755 }
68910c97 7756 else if (p->section != ".absolute") // ET_DYN
89ba3085 7757 {
4ad95bbc
SC
7758 if (p->has_library)
7759 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7760 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7761 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7762 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7763 }
89ba3085 7764 s.op->line() << " },";
68910c97
JK
7765 if (p->module != "")
7766 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7767 s.op->line() << " },";
7768 }
c57ea854 7769 else
822a6a3d 7770 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7771 }
7772 s.op->newline(-1) << "};";
7773
7774 s.op->assert_0_indent();
7775
3689db05
SC
7776 unsigned pci;
7777 for (pci=0; pci<probes.size(); pci++)
7778 {
7779 // List of perf counters used by each probe
7780 // This list is an index into struct stap_perf_probe,
7781 uprobe_derived_probe *p = probes[pci];
698de6cc 7782 std::set<derived_probe*>::iterator pcii;
3689db05
SC
7783 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
7784 for (pcii = p->perf_counter_refs.begin();
7785 pcii != p->perf_counter_refs.end(); pcii++)
7786 {
7787 map<string, pair<string,derived_probe*> >::iterator it;
7788 unsigned i = 0;
7789 // Find the associated perf.counter probe
7790 for (it=s.perf_counters.begin() ;
7791 it != s.perf_counters.end(); it++, i++)
7792 if ((*it).second.second == (*pcii))
7793 break;
7794 s.op->line() << lex_cast(i) << ", ";
7795 }
7796 s.op->newline() << "};";
7797 }
7798
cc52276b
WC
7799 // NB: read-only structure
7800 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7801 s.op->indent(1);
888af770
FCE
7802 for (unsigned i =0; i<probes.size(); i++)
7803 {
7804 uprobe_derived_probe* p = probes[i];
7805 s.op->newline() << "{";
89ba3085
FCE
7806 string key = make_pbm_key (p);
7807 unsigned value = module_index[key];
759e1d76
FCE
7808 if (value != 0)
7809 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7810 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7811 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7812
038c38c6 7813 if (p->sdt_semaphore_addr != 0)
63b4fd14 7814 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7815 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 7816
0d049a1d 7817 // XXX: don't bother emit if array is empty
3689db05
SC
7818 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
7819 // List of perf counters used by a probe from above
0d049a1d 7820 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 7821
4ddb6dd0
JS
7822 if (p->has_return)
7823 s.op->line() << " .return_p=1,";
888af770
FCE
7824 s.op->line() << " },";
7825 }
7826 s.op->newline(-1) << "};";
a96d1db0 7827
89ba3085
FCE
7828 s.op->assert_0_indent();
7829
48e685da 7830 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7831 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7832 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7833 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7834 "stp_probe_type_uprobe");
0e090c74 7835 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7836 << "sup->spec_index >= " << probes.size() << ") {";
7837 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7838 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7839 s.op->newline() << "atomic_dec (&c->busy);";
7840 s.op->newline() << "goto probe_epilogue;";
7841 s.op->newline(-1) << "}";
d9aed31e 7842 s.op->newline() << "c->uregs = regs;";
e04b5d74 7843 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7844
7845 // Make it look like the IP is set as it would in the actual user
7846 // task when calling real probe handler. Reset IP regs on return, so
7847 // we don't confuse uprobes. PR10458
7848 s.op->newline() << "{";
7849 s.op->indent(1);
d9aed31e 7850 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7851 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7852 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7853 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7854 s.op->newline(-1) << "}";
7855
f887a8c9 7856 common_probe_entryfn_epilogue (s, true);
888af770 7857 s.op->newline(-1) << "}";
a96d1db0 7858
48e685da 7859 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7860 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7861 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 7862 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 7863 "stp_probe_type_uretprobe");
6dceb5c9 7864 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7865 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7866 << "sup->spec_index >= " << probes.size() << ") {";
7867 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7868 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7869 s.op->newline() << "atomic_dec (&c->busy);";
7870 s.op->newline() << "goto probe_epilogue;";
7871 s.op->newline(-1) << "}";
7872
d9aed31e 7873 s.op->newline() << "c->uregs = regs;";
e04b5d74 7874 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
7875
7876 // Make it look like the IP is set as it would in the actual user
7877 // task when calling real probe handler. Reset IP regs on return, so
7878 // we don't confuse uprobes. PR10458
7879 s.op->newline() << "{";
7880 s.op->indent(1);
d9aed31e 7881 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7882 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7883 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7884 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7885 s.op->newline(-1) << "}";
7886
f887a8c9 7887 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
7888 s.op->newline(-1) << "}";
7889
89ba3085 7890 s.op->newline();
2ba1736a 7891 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 7892 s.op->newline();
888af770 7893}
935447c8
DS
7894
7895
888af770 7896void
2b69faaf 7897uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 7898{
888af770 7899 if (probes.empty()) return;
935447c8 7900
2b69faaf 7901 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 7902
01b05e2e 7903 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
7904 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
7905 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
7906 // NB: we assume the rest of the struct (specificaly, sup->up) is
7907 // initialized to zero. This is so that we can use
7908 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
7909 s.op->newline(-1) << "}";
7910 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 7911
89ba3085
FCE
7912 // Set up the task_finders
7913 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
7914 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 7915 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 7916 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 7917
5e112f92
FCE
7918 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
7919 // finders already registered, since mere registration does not
7920 // cause any utrace or memory allocation actions. That happens only
7921 // later, once the task finder engine starts running. So, for a
7922 // partial initialization requiring unwind, we need do nothing.
7923 s.op->newline() << "if (rc) break;";
a7a68293 7924
888af770
FCE
7925 s.op->newline(-1) << "}";
7926}
d0ea46ce 7927
d0a7f5a9 7928
888af770 7929void
2b69faaf 7930uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
7931{
7932 if (probes.empty()) return;
2b69faaf 7933 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 7934
6d0f3f0c
FCE
7935 // NB: there is no stap_unregister_task_finder_target call;
7936 // important stuff like utrace cleanups are done by
d41d451c
FCE
7937 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7938 //
7939 // This function blocks until all callbacks are completed, so there
7940 // is supposed to be no possibility of any registration-related code starting
7941 // to run in parallel with our shutdown here. So we don't need to protect the
7942 // stap_uprobes[] array with the mutex.
d0a7f5a9 7943
01b05e2e 7944 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7945 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7946 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7947 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7948
8faa1fc5 7949 // PR10655: decrement that ENABLED semaphore
c116c31b 7950 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7951 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7952 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7953 s.op->newline() << "struct task_struct *tsk;";
7954 s.op->newline() << "rcu_read_lock();";
6846cfc8 7955
86229a55
DS
7956 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7957 // that the pid is always in the global namespace, not in any
7958 // private namespace.
8faa1fc5 7959 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7960 // We'd like to call find_task_by_pid_ns() here, but it isn't
7961 // exported. So, we call what it calls...
7962 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7963 s.op->newline() << "#else";
7964 s.op->newline() << " tsk = find_task_by_pid (pid);";
7965 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7966
7967 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7968 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7969 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7970 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7971 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7972 s.op->newline() << "#endif";
3c5b8e2b 7973 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7974 s.op->newline(-1) << "}";
8faa1fc5
FCE
7975 // XXX: need to analyze possibility of race condition
7976 s.op->newline(-1) << "}";
7977 s.op->newline() << "rcu_read_unlock();";
7978 s.op->newline(-1) << "}";
6846cfc8 7979
3568f1dd
FCE
7980 s.op->newline() << "if (sups->return_p) {";
7981 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7982 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 7983 s.op->newline() << "#endif";
80b4ad8b
FCE
7984 // NB: PR6829 does not change that we still need to unregister at
7985 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7986 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7987 s.op->newline(-1) << "} else {";
7988 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7989 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
7990 s.op->newline() << "#endif";
7991 s.op->newline() << "unregister_uprobe (& sup->up);";
7992 s.op->newline(-1) << "}";
935447c8 7993
6d0f3f0c 7994 s.op->newline() << "sup->spec_index = -1;";
935447c8 7995
3568f1dd
FCE
7996 // XXX: uprobe missed counts?
7997
6d0f3f0c 7998 s.op->newline(-1) << "}";
935447c8 7999
5e112f92 8000 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8001}
8002
2b69faaf
JS
8003
8004void
8005uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8006{
8007 if (probes.empty()) return;
8008 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8009 emit_module_maxuprobes (s);
2ba1736a 8010 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8011
8012 // Write the probe handler.
79af55c3
JS
8013 s.op->newline() << "static int stapiu_probe_handler "
8014 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8015 s.op->newline(1);
2dbbd473
JS
8016
8017 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8018 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8019 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8020 probe_type);
8021
3bff6634 8022 s.op->newline() << "c->uregs = regs;";
e04b5d74 8023 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8024 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8025 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8026
f887a8c9 8027 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8028 s.op->newline() << "return 0;";
8029 s.op->newline(-1) << "}";
8030 s.op->assert_0_indent();
8031
8032 // Index of all the modules for which we need inodes.
8033 map<string, unsigned> module_index;
8034 unsigned module_index_ctr = 0;
8035
8036 // Discover and declare targets for each unique path.
cfcab6c7 8037 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8038 << "stap_inode_uprobe_targets[] = {";
8039 s.op->indent(1);
8040 for (unsigned i=0; i<probes.size(); i++)
8041 {
8042 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8043 const string key = make_pbm_key(p);
8044 if (module_index.find (key) == module_index.end())
2b69faaf 8045 {
cfcab6c7
JS
8046 module_index[key] = module_index_ctr++;
8047 s.op->newline() << "{";
8048 s.op->line() << " .finder={";
1af100fc 8049 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8050 if (p->pid != 0)
8051 s.op->line() << " .pid=" << p->pid << ",";
8052
8053 if (p->section == "") // .statement(addr).absolute XXX?
8054 s.op->line() << " .callback=&stapiu_process_found,";
8055 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8056 {
8057 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8058 s.op->line() << " .callback=&stapiu_process_found,";
8059 }
8060 else if (p->section != ".absolute") // ET_DYN
8061 {
8062 if (p->has_library)
8063 s.op->line() << " .procname=\"" << p->path << "\", ";
8064 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8065 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8066 s.op->line() << " .callback=&stapiu_process_munmap,";
8067 }
8068 s.op->line() << " },";
8069 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8070 s.op->line() << " },";
2b69faaf
JS
8071 }
8072 }
8073 s.op->newline(-1) << "};";
8074 s.op->assert_0_indent();
8075
8076 // Declare the actual probes.
3689db05
SC
8077 unsigned pci;
8078 for (pci=0; pci<probes.size(); pci++)
8079 {
8080 // List of perf counters used by each probe
8081 // This list is an index into struct stap_perf_probe,
8082 uprobe_derived_probe *p = probes[pci];
698de6cc 8083 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8084 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8085 for (pcii = p->perf_counter_refs.begin();
8086 pcii != p->perf_counter_refs.end(); pcii++)
8087 {
8088 map<string, pair<string,derived_probe*> >::iterator it;
8089 unsigned i = 0;
8090 // Find the associated perf.counter probe
4fa83377
SC
8091 for (it=s.perf_counters.begin() ;
8092 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8093 if ((*it).second.second == (*pcii))
8094 break;
8095 s.op->line() << lex_cast(i) << ", ";
8096 }
8097 s.op->newline() << "};";
8098 }
8099
cfcab6c7 8100 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8101 << "stap_inode_uprobe_consumers[] = {";
8102 s.op->indent(1);
8103 for (unsigned i=0; i<probes.size(); i++)
8104 {
8105 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8106 unsigned index = module_index[make_pbm_key(p)];
8107 s.op->newline() << "{";
79af55c3
JS
8108 if (p->has_return)
8109 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8110 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8111 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8112 if (p->sdt_semaphore_addr)
8113 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8114 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8115 // XXX: don't bother emit if array is empty
3689db05
SC
8116 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8117 // List of perf counters used by a probe from above
0d049a1d 8118 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8119 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8120 s.op->line() << " },";
2b69faaf
JS
8121 }
8122 s.op->newline(-1) << "};";
8123 s.op->assert_0_indent();
8124}
8125
8126
8127void
8128uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8129{
8130 if (probes.empty()) return;
8131 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8132 // Let stapiu_init() handle reporting errors by setting probe_point
8133 // to NULL.
8134 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8135 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8136 << "stap_inode_uprobe_targets, "
8137 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8138 << "stap_inode_uprobe_consumers, "
8139 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8140}
8141
8142
8143void
8144uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8145{
8146 if (probes.empty()) return;
8147 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8148 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8149 << "stap_inode_uprobe_targets, "
8150 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8151 << "stap_inode_uprobe_consumers, "
8152 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8153}
8154
8155
3a894f7e
JS
8156void
8157uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8158{
8159 if (probes.empty()) return;
8160 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8161 emit_module_maxuprobes (s);
e00f3fb7 8162 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8163
f31a77f5
DS
8164 // Let the dynprobe_derived_probe_group handle outputting targets
8165 // and probes. This allows us to merge different types of probes.
8166 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8167 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8168 {
8169 uprobe_derived_probe *p = probes[i];
e00f3fb7 8170
f31a77f5
DS
8171 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8172 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8173 common_probe_init(p));
3a894f7e 8174 }
874d38bf
JS
8175 // loc2c-generated code assumes pt_regs are available, so use this to make
8176 // sure we always have *something* for it to dereference...
f31a77f5 8177 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8178
3a894f7e
JS
8179 // Write the probe handler.
8180 // NB: not static, so dyninst can find it
8181 s.op->newline() << "int enter_dyninst_uprobe "
8182 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8183 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8184
8185 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8186 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8187 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8188 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8189 probe_type);
8190
874d38bf 8191 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8192 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8193 // XXX: once we have regs, check how dyninst sets the IP
8194 // XXX: the way that dyninst rewrites stuff is probably going to be
8195 // ... very confusing to our backtracer (at least if we stay in process)
8196 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8197 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8198 s.op->newline() << "return 0;";
8199 s.op->newline(-1) << "}";
3debb935 8200 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8201 s.op->assert_0_indent();
8202}
8203
8204
8205void
8206uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8207{
8208 if (probes.empty()) return;
8209
8210 /* stapdyn handles the dirty work via dyninst */
8211 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8212 s.op->newline() << "/* this section left intentionally blank */";
8213}
8214
8215
8216void
8217uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8218{
8219 if (probes.empty()) return;
8220
8221 /* stapdyn handles the dirty work via dyninst */
8222 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8223 s.op->newline() << "/* this section left intentionally blank */";
8224}
8225
8226
2b69faaf
JS
8227void
8228uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8229{
ac3af990 8230 if (s.runtime_usermode_p())
4441e344
JS
8231 emit_module_dyninst_decls (s);
8232 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8233 emit_module_inode_decls (s);
8234 else
8235 emit_module_utrace_decls (s);
8236}
8237
8238
8239void
8240uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8241{
ac3af990 8242 if (s.runtime_usermode_p())
4441e344
JS
8243 emit_module_dyninst_init (s);
8244 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8245 emit_module_inode_init (s);
8246 else
8247 emit_module_utrace_init (s);
8248}
8249
8250
8251void
8252uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8253{
ac3af990 8254 if (s.runtime_usermode_p())
4441e344
JS
8255 emit_module_dyninst_exit (s);
8256 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8257 emit_module_inode_exit (s);
8258 else
8259 emit_module_utrace_exit (s);
8260}
8261
8262
e6fe60e7
AM
8263// ------------------------------------------------------------------------
8264// Kprobe derived probes
8265// ------------------------------------------------------------------------
8266
4627ed58 8267static const string TOK_KPROBE("kprobe");
935447c8 8268
bae55db9 8269struct kprobe_derived_probe: public derived_probe
d0ea46ce 8270{
23dc94f6
DS
8271 kprobe_derived_probe (systemtap_session& sess,
8272 vector<derived_probe *> & results,
8273 probe *base,
bae55db9
JS
8274 probe_point *location,
8275 const string& name,
8276 int64_t stmt_addr,
8277 bool has_return,
8278 bool has_statement,
8279 bool has_maxactive,
b642c901
SC
8280 bool has_path,
8281 bool has_library,
8282 long maxactive_val,
8283 const string& path,
8284 const string& library
bae55db9
JS
8285 );
8286 string symbol_name;
8287 Dwarf_Addr addr;
8288 bool has_return;
8289 bool has_statement;
8290 bool has_maxactive;
b642c901
SC
8291 bool has_path;
8292 bool has_library;
bae55db9 8293 long maxactive_val;
b642c901
SC
8294 string path;
8295 string library;
bae55db9
JS
8296 bool access_var;
8297 void printsig (std::ostream &o) const;
8298 void join_group (systemtap_session& s);
8299};
d0ea46ce 8300
bae55db9
JS
8301struct kprobe_derived_probe_group: public derived_probe_group
8302{
8303private:
8304 multimap<string,kprobe_derived_probe*> probes_by_module;
8305 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8306
bae55db9
JS
8307public:
8308 void enroll (kprobe_derived_probe* probe);
8309 void emit_module_decls (systemtap_session& s);
8310 void emit_module_init (systemtap_session& s);
8311 void emit_module_exit (systemtap_session& s);
8312};
d0ea46ce 8313
23dc94f6
DS
8314struct kprobe_var_expanding_visitor: public var_expanding_visitor
8315{
8316 systemtap_session& sess;
8317 block *add_block;
8318 block *add_call_probe; // synthesized from .return probes with saved $vars
8319 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8320 bool has_return;
23dc94f6 8321
bd5b25e1 8322 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8323 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8324 add_block_tid(false), add_call_probe_tid(false),
8325 has_return(has_return) {}
23dc94f6
DS
8326
8327 void visit_entry_op (entry_op* e);
8328};
8329
8330
8331kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8332 vector<derived_probe *> & results,
8333 probe *base,
e6fe60e7 8334 probe_point *location,
b6371390 8335 const string& name,
e6fe60e7 8336 int64_t stmt_addr,
b6371390
JS
8337 bool has_return,
8338 bool has_statement,
8339 bool has_maxactive,
b642c901
SC
8340 bool has_path,
8341 bool has_library,
8342 long maxactive_val,
8343 const string& path,
8344 const string& library
b6371390 8345 ):
4c5d1300 8346 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 8347 symbol_name (name), addr (stmt_addr),
b6371390 8348 has_return (has_return), has_statement (has_statement),
b642c901
SC
8349 has_maxactive (has_maxactive), has_path (has_path),
8350 has_library (has_library),
8351 maxactive_val (maxactive_val),
8352 path (path), library (library)
e6fe60e7
AM
8353{
8354 this->tok = base->tok;
8355 this->access_var = false;
d0ea46ce 8356
e6fe60e7
AM
8357#ifndef USHRT_MAX
8358#define USHRT_MAX 32767
8359#endif
d0ea46ce 8360
46856d8d
JS
8361 // Expansion of $target variables in the probe body produces an error during
8362 // translate phase, since we're not using debuginfo
d0ea46ce 8363
e6fe60e7 8364 vector<probe_point::component*> comps;
46856d8d 8365 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8366
46856d8d
JS
8367 if (has_statement)
8368 {
9ea68eb9
JS
8369 comps.push_back (new probe_point::component(TOK_STATEMENT,
8370 new literal_number(addr, true)));
46856d8d
JS
8371 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8372 }
8373 else
8374 {
8375 size_t pos = name.find(':');
8376 if (pos != string::npos)
d0ea46ce 8377 {
46856d8d
JS
8378 string module = name.substr(0, pos);
8379 string function = name.substr(pos + 1);
8380 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8381 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8382 }
8383 else
8384 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8385 }
d0ea46ce 8386
b6371390
JS
8387 if (has_return)
8388 comps.push_back (new probe_point::component(TOK_RETURN));
8389 if (has_maxactive)
8390 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8391
bd5b25e1 8392 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8393 v.replace (this->body);
8394
8395 // If during target-variable-expanding the probe, we added a new block
8396 // of code, add it to the start of the probe.
8397 if (v.add_block)
8398 this->body = new block(v.add_block, this->body);
8399
8400 // If when target-variable-expanding the probe, we need to
8401 // synthesize a sibling function-entry probe. We don't go through
8402 // the whole probe derivation business (PR10642) that could lead to
8403 // wildcard/alias resolution, or for that dwarf-induced duplication.
8404 if (v.add_call_probe)
8405 {
8406 assert (has_return);
8407
8408 // We temporarily replace base.
8409 statement* old_body = base->body;
8410 base->body = v.add_call_probe;
8411
8412 derived_probe *entry_handler
8413 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8414 false, has_statement, has_maxactive,
8415 has_path, has_library, maxactive_val,
8416 path, library);
8417 results.push_back (entry_handler);
8418
8419 base->body = old_body;
8420 }
8421
e6fe60e7
AM
8422 this->sole_location()->components = comps;
8423}
d0ea46ce 8424
e6fe60e7
AM
8425void kprobe_derived_probe::printsig (ostream& o) const
8426{
8427 sole_location()->print (o);
8428 o << " /* " << " name = " << symbol_name << "*/";
8429 printsig_nested (o);
8430}
d0ea46ce 8431
e6fe60e7
AM
8432void kprobe_derived_probe::join_group (systemtap_session& s)
8433{
d0ea46ce 8434
e6fe60e7
AM
8435 if (! s.kprobe_derived_probes)
8436 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8437 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8438
e6fe60e7 8439}
d0ea46ce 8440
e6fe60e7
AM
8441void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8442{
8443 probes_by_module.insert (make_pair (p->symbol_name, p));
8444 // probes of same symbol should share single kprobe/kretprobe
8445}
d0ea46ce 8446
e6fe60e7
AM
8447void
8448kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8449{
8450 if (probes_by_module.empty()) return;
d0ea46ce 8451
e6fe60e7 8452 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8453
e6fe60e7
AM
8454 // Warn of misconfigured kernels
8455 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8456 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8457 s.op->newline() << "#endif";
8458 s.op->newline();
d0ea46ce 8459
f07c3b68 8460 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8461 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8462 s.op->newline() << "#endif";
8463
e6fe60e7 8464 // Forward declare the master entry functions
88747011 8465 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8466 s.op->line() << " struct pt_regs *regs);";
88747011 8467 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8468 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8469
e6fe60e7
AM
8470 // Emit an array of kprobe/kretprobe pointers
8471 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8472 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8473 s.op->newline() << "#endif";
d0ea46ce 8474
e6fe60e7 8475 // Emit the actual probe list.
d0ea46ce 8476
e6fe60e7
AM
8477 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8478 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8479 s.op->newline() << "#ifdef __ia64__";
8480 s.op->newline() << "struct kprobe dummy;";
8481 s.op->newline() << "#endif";
8482 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8483 // NB: bss!
d0ea46ce 8484
e6fe60e7
AM
8485 s.op->newline() << "static struct stap_dwarfless_probe {";
8486 s.op->newline(1) << "const unsigned return_p:1;";
8487 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8488 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8489 s.op->newline() << "unsigned registered_p:1;";
8490 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 8491
e6fe60e7
AM
8492 // Function Names are mostly small and uniform enough to justify putting
8493 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 8494
faea5e16
JS
8495 size_t symbol_string_name_max = 0;
8496 size_t symbol_string_name_tot = 0;
e6fe60e7 8497 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 8498 {
e6fe60e7
AM
8499 kprobe_derived_probe* p = it->second;
8500#define DOIT(var,expr) do { \
8501 size_t var##_size = (expr) + 1; \
8502 var##_max = max (var##_max, var##_size); \
8503 var##_tot += var##_size; } while (0)
e6fe60e7
AM
8504 DOIT(symbol_string_name, p->symbol_name.size());
8505#undef DOIT
6270adc1
MH
8506 }
8507
e6fe60e7
AM
8508#define CALCIT(var) \
8509 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 8510
e6fe60e7
AM
8511 CALCIT(symbol_string);
8512#undef CALCIT
6270adc1 8513
bd659351 8514 s.op->newline() << "unsigned long address;";
7c3e97f4 8515 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
8516 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
8517 s.op->indent(1);
6270adc1 8518
e6fe60e7
AM
8519 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
8520 {
8521 kprobe_derived_probe* p = it->second;
8522 s.op->newline() << "{";
8523 if (p->has_return)
8524 s.op->line() << " .return_p=1,";
6270adc1 8525
e6fe60e7
AM
8526 if (p->has_maxactive)
8527 {
8528 s.op->line() << " .maxactive_p=1,";
8529 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
8530 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
8531 }
6270adc1 8532
b350f56b
JS
8533 if (p->locations[0]->optional)
8534 s.op->line() << " .optional_p=1,";
8535
e6fe60e7 8536 if (p->has_statement)
c8d9d15e 8537 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 8538 else
c8d9d15e 8539 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 8540
faea5e16 8541 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 8542 s.op->line() << " },";
935447c8
DS
8543 }
8544
e6fe60e7 8545 s.op->newline(-1) << "};";
5d67b47c 8546
e6fe60e7
AM
8547 // Emit the kprobes callback function
8548 s.op->newline();
88747011 8549 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
8550 s.op->line() << " struct pt_regs *regs) {";
8551 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8552 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8553 // Check that the index is plausible
8554 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8555 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8556 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8557 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8558 s.op->line() << "];";
71db462b 8559 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8560 "stp_probe_type_kprobe");
d9aed31e 8561 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
8562
8563 // Make it look like the IP is set as it wouldn't have been replaced
8564 // by a breakpoint instruction when calling real probe handler. Reset
8565 // IP regs on return, so we don't confuse kprobes. PR10458
8566 s.op->newline() << "{";
8567 s.op->indent(1);
d9aed31e 8568 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8569 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 8570 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8571 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8572 s.op->newline(-1) << "}";
8573
f887a8c9 8574 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8575 s.op->newline() << "return 0;";
8576 s.op->newline(-1) << "}";
935447c8 8577
e6fe60e7
AM
8578 // Same for kretprobes
8579 s.op->newline();
88747011 8580 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
8581 s.op->line() << " struct pt_regs *regs) {";
8582 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 8583
e6fe60e7
AM
8584 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
8585 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
8586 // Check that the index is plausible
8587 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
8588 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
8589 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
8590 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
8591 s.op->line() << "];";
935447c8 8592
71db462b 8593 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 8594 "stp_probe_type_kretprobe");
d9aed31e 8595 s.op->newline() << "c->kregs = regs;";
6dceb5c9 8596 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
8597
8598 // Make it look like the IP is set as it wouldn't have been replaced
8599 // by a breakpoint instruction when calling real probe handler. Reset
8600 // IP regs on return, so we don't confuse kprobes. PR10458
8601 s.op->newline() << "{";
8602 s.op->indent(1);
d9aed31e 8603 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 8604 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 8605 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 8606 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
8607 s.op->newline(-1) << "}";
8608
f887a8c9 8609 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
8610 s.op->newline() << "return 0;";
8611 s.op->newline(-1) << "}";
bd659351 8612
03a4ec63 8613 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8614 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
8615 s.op->newline() << " struct module *owner,";
8616 s.op->newline() << " unsigned long val) {";
8617 s.op->newline(1) << "int i;";
fc1d2aa2
MW
8618 s.op->newline() << "int *p = (int *) data;";
8619 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
8620 << " && *p > 0; i++) {";
bd659351 8621 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
8622 s.op->newline() << "if (! sdp->address) {";
8623 s.op->indent(1);
8624 s.op->newline() << "const char *colon;";
8625 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
8626 s.op->indent(1);
8627 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
8628 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
8629 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
8630 s.op->newline(1) << "sdp->address = val;";
8631 s.op->newline() << "(*p)--;";
8632 s.op->newline(-1) << "}";
8633 s.op->newline(-1) << "}";
8634 s.op->newline() << "else {";
fc1d2aa2 8635 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 8636 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
8637 s.op->newline() << "(*p)--;";
8638 s.op->newline(-1) << "}";
8c272819
YW
8639 s.op->newline(-1) << "}";
8640 s.op->newline(-1) << "}";
8641 s.op->newline(-1) << "}";
fc1d2aa2 8642 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 8643 s.op->newline(-1) << "}";
03a4ec63 8644 s.op->newline() << "#endif";
935447c8
DS
8645}
8646
e6fe60e7 8647
6270adc1 8648void
e6fe60e7 8649kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 8650{
03a4ec63 8651 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
8652 s.op->newline() << "{";
8653 s.op->newline(1) << "int p = 0;";
8654 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
8655 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8656 s.op->newline() << "if (! sdp->address)";
8657 s.op->newline(1) << "p++;";
8658 s.op->newline(-2) << "}";
8659 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
8660 s.op->newline(-1) << "}";
03a4ec63 8661 s.op->newline() << "#endif";
bd659351 8662
e6fe60e7 8663 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 8664 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 8665 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 8666 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
8667 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
8668
8669 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
8670 s.op->newline() << "if (! addr) {";
8671 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
8672 s.op->newline() << "if (!sdp->optional_p)";
8673 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
8674 s.op->newline(-1) << "continue;";
bd659351 8675 s.op->newline(-1) << "}";
03a4ec63
MW
8676 s.op->newline() << "#endif";
8677
26e63673 8678 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 8679 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 8680 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 8681 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8682 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 8683 s.op->newline() << "#endif";
e6fe60e7
AM
8684 s.op->newline() << "if (sdp->maxactive_p) {";
8685 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
8686 s.op->newline(-1) << "} else {";
f07c3b68 8687 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 8688 s.op->newline(-1) << "}";
88747011 8689 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
8690 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
8691 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8692 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 8693 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8694 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 8695 s.op->newline() << "#endif";
c8d9d15e 8696 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
8697 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8698 s.op->newline() << "if (rc == 0) {";
8699 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
8700 s.op->newline() << "if (rc != 0)";
8701 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8702 s.op->newline(-2) << "}";
8703 s.op->newline() << "#else";
8704 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
8705 s.op->newline() << "#endif";
8706 s.op->newline(-1) << "} else {";
8707 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 8708 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 8709 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8710 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 8711 s.op->newline() << "#endif";
88747011 8712 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 8713 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8714 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 8715 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 8716 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8717 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 8718 s.op->newline() << "#endif";
e6fe60e7
AM
8719 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8720 s.op->newline() << "if (rc == 0) {";
8721 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
8722 s.op->newline() << "if (rc != 0)";
8723 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8724 s.op->newline(-2) << "}";
8725 s.op->newline() << "#else";
8726 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
8727 s.op->newline() << "#endif";
8728 s.op->newline(-1) << "}";
8729 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
8730 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 8731 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 8732 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 8733 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
8734 // XXX: shall we increment numskipped?
8735 s.op->newline(-1) << "}";
6270adc1 8736
e6fe60e7
AM
8737 s.op->newline() << "else sdp->registered_p = 1;";
8738 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
8739}
8740
b4be7cbc 8741
e6fe60e7
AM
8742void
8743kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 8744{
e6fe60e7
AM
8745 //Unregister kprobes by batch interfaces.
8746 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
8747 s.op->newline() << "j = 0;";
8748 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8749 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8750 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8751 s.op->newline() << "if (! sdp->registered_p) continue;";
8752 s.op->newline() << "if (!sdp->return_p)";
c9116e99 8753 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 8754 s.op->newline(-2) << "}";
c9116e99 8755 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8756 s.op->newline() << "j = 0;";
8757 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8758 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8759 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8760 s.op->newline() << "if (! sdp->registered_p) continue;";
8761 s.op->newline() << "if (sdp->return_p)";
c9116e99 8762 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 8763 s.op->newline(-2) << "}";
c9116e99 8764 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8765 s.op->newline() << "#ifdef __ia64__";
8766 s.op->newline() << "j = 0;";
8767 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8768 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8769 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8770 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 8771 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 8772 s.op->newline(-1) << "}";
c9116e99 8773 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8774 s.op->newline() << "#endif";
8775 s.op->newline() << "#endif";
3e3bd7b6 8776
e6fe60e7
AM
8777 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8778 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8779 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8780 s.op->newline() << "if (! sdp->registered_p) continue;";
8781 s.op->newline() << "if (sdp->return_p) {";
8782 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8783 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
8784 s.op->newline() << "#endif";
065d5567 8785 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
8786 s.op->newline() << "#ifdef STP_TIMING";
8787 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 8788 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 8789 s.op->newline(-1) << "#endif";
065d5567 8790 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
8791 s.op->newline() << "#ifdef STP_TIMING";
8792 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 8793 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
8794 s.op->newline(-1) << "#endif";
8795 s.op->newline(-1) << "} else {";
8796 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8797 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
8798 s.op->newline() << "#endif";
065d5567 8799 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
8800 s.op->newline() << "#ifdef STP_TIMING";
8801 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 8802 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
8803 s.op->newline(-1) << "#endif";
8804 s.op->newline(-1) << "}";
8805 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
8806 s.op->newline() << "unregister_kprobe (&kp->dummy);";
8807 s.op->newline() << "#endif";
8808 s.op->newline() << "sdp->registered_p = 0;";
8809 s.op->newline(-1) << "}";
f8a968bc
JS
8810}
8811
e6fe60e7 8812struct kprobe_builder: public derived_probe_builder
3c1b3d06 8813{
9fdf787d 8814public:
2a639817 8815 kprobe_builder() {}
9fdf787d 8816
2a639817 8817 void build_no_more (systemtap_session &s) {}
9fdf787d 8818
e6fe60e7
AM
8819 virtual void build(systemtap_session & sess,
8820 probe * base,
8821 probe_point * location,
8822 literal_map_t const & parameters,
8823 vector<derived_probe *> & finished_results);
8824};
3c1b3d06
FCE
8825
8826
79189b84 8827void
05fb3e0c 8828kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
8829 probe * base,
8830 probe_point * location,
8831 literal_map_t const & parameters,
8832 vector<derived_probe *> & finished_results)
79189b84 8833{
e6fe60e7 8834 string function_string_val, module_string_val;
05fb3e0c 8835 string path, library, path_tgt, library_tgt;
b6371390
JS
8836 int64_t statement_num_val = 0, maxactive_val = 0;
8837 bool has_function_str, has_module_str, has_statement_num;
8838 bool has_absolute, has_return, has_maxactive;
b642c901 8839 bool has_path, has_library;
79189b84 8840
b6371390
JS
8841 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
8842 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
8843 has_return = has_null_param (parameters, TOK_RETURN);
8844 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
8845 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
8846 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
8847 has_path = get_param (parameters, TOK_PROCESS, path);
8848 has_library = get_param (parameters, TOK_LIBRARY, library);
8849
8850 if (has_path)
05fb3e0c
WF
8851 {
8852 path = find_executable (path, sess.sysroot, sess.sysenv);
8853 path_tgt = path_remove_sysroot(sess, path);
8854 }
b642c901 8855 if (has_library)
05fb3e0c
WF
8856 {
8857 library = find_executable (library, sess.sysroot, sess.sysenv,
8858 "LD_LIBRARY_PATH");
8859 library_tgt = path_remove_sysroot(sess, library);
8860 }
c57ea854 8861
b6371390 8862 if (has_function_str)
6fb70fb7 8863 {
2a639817 8864 if (has_module_str)
9fdf787d
DS
8865 {
8866 function_string_val = module_string_val + ":" + function_string_val;
8867 derived_probe *dp
23dc94f6
DS
8868 = new kprobe_derived_probe (sess, finished_results, base,
8869 location, function_string_val,
9fdf787d
DS
8870 0, has_return, has_statement_num,
8871 has_maxactive, has_path, has_library,
8872 maxactive_val, path_tgt, library_tgt);
8873 finished_results.push_back (dp);
8874 }
8875 else
8876 {
2a639817
JS
8877 vector<string> matches;
8878
8879 // Simple names can be found directly
8880 if (function_string_val.find_first_of("*?[") == string::npos)
8881 {
8882 if (sess.kernel_functions.count(function_string_val))
8883 matches.push_back(function_string_val);
8884 }
8885 else // Search function name list for matching names
8886 {
8887 for (set<string>::const_iterator it = sess.kernel_functions.begin();
8888 it != sess.kernel_functions.end(); it++)
8889 // fnmatch returns zero for matching.
8890 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
8891 matches.push_back(*it);
8892 }
86758d5f 8893
2a639817
JS
8894 for (vector<string>::const_iterator it = matches.begin();
8895 it != matches.end(); it++)
9fdf787d 8896 {
2a639817
JS
8897 derived_probe *dp
8898 = new kprobe_derived_probe (sess, finished_results, base,
8899 location, *it, 0, has_return,
8900 has_statement_num,
8901 has_maxactive, has_path,
8902 has_library, maxactive_val,
8903 path_tgt, library_tgt);
8904 finished_results.push_back (dp);
9fdf787d
DS
8905 }
8906 }
6fb70fb7 8907 }
e6fe60e7 8908 else
b6371390
JS
8909 {
8910 // assert guru mode for absolute probes
8911 if ( has_statement_num && has_absolute && !base->privileged )
e3bbc038 8912 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 8913
23dc94f6
DS
8914 finished_results.push_back (new kprobe_derived_probe (sess,
8915 finished_results,
8916 base,
b6371390
JS
8917 location, "",
8918 statement_num_val,
8919 has_return,
8920 has_statement_num,
8921 has_maxactive,
b642c901
SC
8922 has_path,
8923 has_library,
8924 maxactive_val,
05fb3e0c
WF
8925 path_tgt,
8926 library_tgt));
96b030fe 8927 }
79189b84
JS
8928}
8929
23dc94f6
DS
8930
8931void
8932kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
8933{
8934 expression *repl = e;
8935
bd5b25e1
JS
8936 if (has_return)
8937 {
8938 // expand the operand as if it weren't a return probe
8939 has_return = false;
8940 replace (e->operand);
8941 has_return = true;
23dc94f6 8942
bd5b25e1
JS
8943 // XXX it would be nice to use gen_kretprobe_saved_return when
8944 // available, but it requires knowing the types already, which is
8945 // problematic for arbitrary expressons.
8946 repl = gen_mapped_saved_return (sess, e->operand, "entry",
8947 add_block, add_block_tid,
8948 add_call_probe, add_call_probe_tid);
8949 }
23dc94f6
DS
8950 provide (repl);
8951}
8952
8953
dd225250
PS
8954// ------------------------------------------------------------------------
8955// Hardware breakpoint based probes.
8956// ------------------------------------------------------------------------
8957
8958static const string TOK_HWBKPT("data");
8959static const string TOK_HWBKPT_WRITE("write");
8960static const string TOK_HWBKPT_RW("rw");
8961static const string TOK_LENGTH("length");
8962
8963#define HWBKPT_READ 0
8964#define HWBKPT_WRITE 1
8965#define HWBKPT_RW 2
8966struct hwbkpt_derived_probe: public derived_probe
8967{
8968 hwbkpt_derived_probe (probe *base,
8969 probe_point *location,
8970 uint64_t addr,
8971 string symname,
8972 unsigned int len,
8973 bool has_only_read_access,
8974 bool has_only_write_access,
8975 bool has_rw_access
8976 );
8977 Dwarf_Addr hwbkpt_addr;
8978 string symbol_name;
8979 unsigned int hwbkpt_access,hwbkpt_len;
8980
8981 void printsig (std::ostream &o) const;
8982 void join_group (systemtap_session& s);
8983};
8984
8985struct hwbkpt_derived_probe_group: public derived_probe_group
8986{
dd225250 8987private:
dac77b80 8988 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
8989
8990public:
8991 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
8992 void emit_module_decls (systemtap_session& s);
8993 void emit_module_init (systemtap_session& s);
8994 void emit_module_exit (systemtap_session& s);
8995};
8996
8997hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
8998 probe_point *location,
8999 uint64_t addr,
9000 string symname,
9001 unsigned int len,
9002 bool has_only_read_access,
9003 bool has_only_write_access,
822a6a3d 9004 bool):
4c5d1300 9005 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9006 hwbkpt_addr (addr),
9007 symbol_name (symname),
9008 hwbkpt_len (len)
9009{
9010 this->tok = base->tok;
9011
9012 vector<probe_point::component*> comps;
9013 comps.push_back (new probe_point::component(TOK_KERNEL));
9014
9015 if (hwbkpt_addr)
9ea68eb9
JS
9016 comps.push_back (new probe_point::component (TOK_HWBKPT,
9017 new literal_number(hwbkpt_addr, true)));
9018 else if (symbol_name.size())
9019 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9020
9021 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9022
9023 if (has_only_read_access)
9ea68eb9 9024 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9025//TODO add code for comps.push_back for read, since this flag is not for x86
9026
9027 else
9ea68eb9
JS
9028 {
9029 if (has_only_write_access)
9030 {
9031 this->hwbkpt_access = HWBKPT_WRITE ;
9032 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9033 }
9034 else
9035 {
9036 this->hwbkpt_access = HWBKPT_RW ;
9037 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9038 }
9039 }
dd225250
PS
9040
9041 this->sole_location()->components = comps;
9042}
9043
9044void hwbkpt_derived_probe::printsig (ostream& o) const
9045{
9046 sole_location()->print (o);
9047 printsig_nested (o);
9048}
9049
9050void hwbkpt_derived_probe::join_group (systemtap_session& s)
9051{
dac77b80
FCE
9052 if (! s.hwbkpt_derived_probes)
9053 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9054 s.hwbkpt_derived_probes->enroll (this, s);
9055}
9056
9057void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9058{
dac77b80
FCE
9059 hwbkpt_probes.push_back (p);
9060
9061 unsigned max_hwbkpt_probes_by_arch = 0;
9062 if (s.architecture == "i386" || s.architecture == "x86_64")
9063 max_hwbkpt_probes_by_arch = 4;
9064 else if (s.architecture == "s390")
9065 max_hwbkpt_probes_by_arch = 1;
9066
c57ea854 9067 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9068 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9069 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9070}
9071
9072void
9073hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9074{
dac77b80 9075 if (hwbkpt_probes.empty()) return;
dd225250
PS
9076
9077 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9078
9079 s.op->newline() << "#include <linux/perf_event.h>";
9080 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9081 s.op->newline();
9082
9083 // Forward declare the master entry functions
23063de1 9084 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9085 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9086 s.op->line() << " int nmi,";
9087 s.op->line() << " struct perf_sample_data *data,";
9088 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9089 s.op->newline() << "#else";
9090 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9091 s.op->line() << " struct perf_sample_data *data,";
9092 s.op->line() << " struct pt_regs *regs);";
9093 s.op->newline() << "#endif";
79189b84 9094
dd225250
PS
9095 // Emit the actual probe list.
9096
9097 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9098 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9099
9100 s.op->newline() << "static struct perf_event **";
dac77b80 9101 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9102 s.op->newline() << "static struct stap_hwbkpt_probe {";
9103 s.op->newline() << "int registered_p:1;";
43650b10 9104// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9105// registered_p = 1 signifies a probe that got registered successfully
9106
faea5e16 9107 // Symbol Names are mostly small and uniform enough
dd225250 9108 // to justify putting const char*.
dac77b80 9109 s.op->newline() << "const char * const symbol;";
dd225250
PS
9110
9111 s.op->newline() << "const unsigned long address;";
9112 s.op->newline() << "uint8_t atype;";
bb0a4e12 9113 s.op->newline() << "unsigned int len;";
7c3e97f4 9114 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9115 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9116 s.op->indent(1);
9117
dac77b80 9118 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9119 {
dac77b80 9120 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9121 s.op->newline() << "{";
dd225250
PS
9122 if (p->symbol_name.size())
9123 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9124 else
9125 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9126 switch(p->hwbkpt_access){
9127 case HWBKPT_READ:
9128 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9129 break;
dd225250
PS
9130 case HWBKPT_WRITE:
9131 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9132 break;
dd225250
PS
9133 case HWBKPT_RW:
9134 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9135 break;
dd225250
PS
9136 };
9137 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9138 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9139 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9140 s.op->line() << " },";
9141 }
dac77b80 9142 s.op->newline(-1) << "};";
dd225250
PS
9143
9144 // Emit the hwbkpt callback function
9145 s.op->newline() ;
23063de1 9146 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9147 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9148 s.op->line() << " int nmi,";
9149 s.op->line() << " struct perf_sample_data *data,";
9150 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9151 s.op->newline() << "#else";
9152 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9153 s.op->line() << " struct perf_sample_data *data,";
9154 s.op->line() << " struct pt_regs *regs) {";
9155 s.op->newline() << "#endif";
dac77b80
FCE
9156 s.op->newline(1) << "unsigned int i;";
9157 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9158 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9159 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9160 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9161 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) {";
9162 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9163 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9164 "stp_probe_type_hwbkpt");
d9aed31e 9165 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9166 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9167 s.op->newline() << "c->uregs = regs;";
9168 s.op->newline(-1) << "} else {";
9169 s.op->newline(1) << "c->kregs = regs;";
9170 s.op->newline(-1) << "}";
26e63673 9171 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9172 common_probe_entryfn_epilogue (s, true);
dac77b80 9173 s.op->newline(-1) << "}";
dd225250
PS
9174 s.op->newline(-1) << "}";
9175 s.op->newline() << "return 0;";
dac77b80 9176 s.op->newline(-1) << "}";
dd225250
PS
9177}
9178
9179void
9180hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9181{
dac77b80 9182 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9183 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9184 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9185 s.op->newline() << "void *addr = (void *) sdp->address;";
9186 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9187 s.op->newline() << "hw_breakpoint_init(hp);";
9188 s.op->newline() << "if (addr)";
9189 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9190 s.op->newline(-1) << "else { ";
9191 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9192 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9193 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9194 s.op->newline() << "continue;";
9195 s.op->newline(-1) << "}";
9196 s.op->newline(-1) << "}";
9197 s.op->newline() << "hp->bp_type = sdp->atype;";
9198
9199 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9200 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9201 {
9202 s.op->newline() << "switch(sdp->len) {";
9203 s.op->newline() << "case 1:";
9204 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9205 s.op->newline() << "break;";
9206 s.op->newline(-1) << "case 2:";
9207 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9208 s.op->newline() << "break;";
9209 s.op->newline(-1) << "case 3:";
9210 s.op->newline() << "case 4:";
9211 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9212 s.op->newline() << "break;";
9213 s.op->newline(-1) << "case 5:";
9214 s.op->newline() << "case 6:";
9215 s.op->newline() << "case 7:";
9216 s.op->newline() << "case 8:";
9217 s.op->newline() << "default:"; // XXX: could instead reject
9218 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9219 s.op->newline() << "break;";
9220 s.op->newline(-1) << "}";
9221 }
9222 else // other architectures presumed straightforward
9223 s.op->newline() << "hp->bp_len = sdp->len;";
9224
26e63673 9225 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9226 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9227 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9228 s.op->newline() << "#else";
dac77b80 9229 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9230 s.op->newline() << "#endif";
43650b10 9231 s.op->newline() << "rc = 0;";
dac77b80 9232 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9233 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9234 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9235 s.op->newline(-1) << "}";
217ef1f4
WC
9236 s.op->newline() << "if (rc) {";
9237 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9238 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9239 s.op->newline(-1) << "}";
dd225250 9240 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9241 s.op->newline(-1) << "}"; // for loop
9242}
9243
9244void
9245hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9246{
9247 //Unregister hwbkpt probes.
dac77b80 9248 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9249 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9250 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9251 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9252 s.op->newline() << "sdp->registered_p = 0;";
9253 s.op->newline(-1) << "}";
9254}
9255
9256struct hwbkpt_builder: public derived_probe_builder
9257{
9258 hwbkpt_builder() {}
9259 virtual void build(systemtap_session & sess,
9260 probe * base,
9261 probe_point * location,
9262 literal_map_t const & parameters,
9263 vector<derived_probe *> & finished_results);
9264};
9265
9266void
9267hwbkpt_builder::build(systemtap_session & sess,
9268 probe * base,
9269 probe_point * location,
9270 literal_map_t const & parameters,
9271 vector<derived_probe *> & finished_results)
9272{
9273 string symbol_str_val;
9274 int64_t hwbkpt_address, len;
9275 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9276
b47f3a55 9277 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
b530b5b3 9278 throw semantic_error (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9279 location->components[0]->tok);
9280 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
b530b5b3 9281 throw semantic_error (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9282 location->components[0]->tok);
9283
dd225250
PS
9284 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9285 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9286 has_len = get_param (parameters, TOK_LENGTH, len);
9287 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9288 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9289
9290 if (!has_len)
9291 len = 1;
9292
9293 if (has_addr)
9294 finished_results.push_back (new hwbkpt_derived_probe (base,
9295 location,
9296 hwbkpt_address,
9297 "",len,0,
9298 has_write,
9299 has_rw));
5d8a0aea 9300 else if (has_symbol_str)
dd225250
PS
9301 finished_results.push_back (new hwbkpt_derived_probe (base,
9302 location,
9303 0,
9304 symbol_str_val,len,0,
9305 has_write,
9306 has_rw));
5d8a0aea
FCE
9307 else
9308 assert (0);
dd225250 9309}
342d3f96 9310
0a6f5a3f
JS
9311// ------------------------------------------------------------------------
9312// statically inserted kernel-tracepoint derived probes
9313// ------------------------------------------------------------------------
9314
6fb70fb7 9315struct tracepoint_arg
79189b84 9316{
ad370dcc 9317 string name, c_type, typecast;
dcaa1a65 9318 bool usable, used, isptr;
f8a968bc 9319 Dwarf_Die type_die;
dcaa1a65 9320 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9321};
79189b84 9322
0a6f5a3f
JS
9323struct tracepoint_derived_probe: public derived_probe
9324{
79189b84
JS
9325 tracepoint_derived_probe (systemtap_session& s,
9326 dwflpp& dw, Dwarf_Die& func_die,
9327 const string& tracepoint_name,
9328 probe* base_probe, probe_point* location);
bc9a523d 9329
79189b84 9330 systemtap_session& sess;
6fb70fb7
JS
9331 string tracepoint_name, header;
9332 vector <struct tracepoint_arg> args;
bc9a523d 9333
6fb70fb7 9334 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9335 void getargs (std::list<std::string> &arg_set) const;
79189b84 9336 void join_group (systemtap_session& s);
3e3bd7b6 9337 void print_dupe_stamp(ostream& o);
0a6f5a3f 9338};
79189b84
JS
9339
9340
0a6f5a3f 9341struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9342{
79189b84
JS
9343 void emit_module_decls (systemtap_session& s);
9344 void emit_module_init (systemtap_session& s);
9345 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9346};
79189b84 9347
bc9a523d 9348
f8a968bc
JS
9349struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9350{
9351 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9352 vector <struct tracepoint_arg>& args):
9353 dw (dw), probe_name (probe_name), args (args) {}
9354 dwflpp& dw;
9355 const string& probe_name;
9356 vector <struct tracepoint_arg>& args;
bc9a523d 9357
f8a968bc
JS
9358 void visit_target_symbol (target_symbol* e);
9359 void visit_target_symbol_arg (target_symbol* e);
9360 void visit_target_symbol_context (target_symbol* e);
9361};
79189b84
JS
9362
9363
f8a968bc
JS
9364void
9365tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9366{
cc9001af 9367 string argname = e->sym_name();
75ead1f7 9368
f8a968bc
JS
9369 // search for a tracepoint parameter matching this name
9370 tracepoint_arg *arg = NULL;
9371 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9372 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9373 {
9374 arg = &args[i];
9375 arg->used = true;
9376 break;
9377 }
75ead1f7 9378
f8a968bc
JS
9379 if (arg == NULL)
9380 {
9381 stringstream alternatives;
9382 for (unsigned i = 0; i < args.size(); ++i)
9383 alternatives << " $" << args[i].name;
046e7190 9384 alternatives << " $$name $$parms $$vars";
75ead1f7 9385
f8a968bc
JS
9386 // We hope that this value ends up not being referenced after all, so it
9387 // can be optimized out quietly.
b530b5b3
LB
9388 throw semantic_error(_F("unable to find tracepoint variable '%s' (alternatives: %s)",
9389 e->name.c_str(), alternatives.str().c_str()), e->tok);
f8a968bc
JS
9390 // NB: we can have multiple errors, since a target variable
9391 // may be expanded in several different contexts:
9392 // trace ("*") { $foo->bar }
f8a968bc 9393 }
75ead1f7 9394
f8a968bc 9395 // make sure we're not dereferencing base types
dc5a09fc 9396 if (!arg->isptr)
d19a9a82 9397 e->assert_no_components("tracepoint", true);
75ead1f7 9398
f8a968bc
JS
9399 // we can only write to dereferenced fields, and only if guru mode is on
9400 bool lvalue = is_active_lvalue(e);
9401 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
b3741c9d 9402 throw semantic_error(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 9403
ad370dcc
JS
9404 // XXX: if a struct/union arg is passed by value, then writing to its fields
9405 // is also meaningless until you dereference past a pointer member. It's
9406 // harder to detect and prevent that though...
75ead1f7 9407
f8a968bc
JS
9408 if (e->components.empty())
9409 {
03c75a4a 9410 if (e->addressof)
b530b5b3 9411 throw semantic_error(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 9412
3e3bd7b6 9413 // Just grab the value from the probe locals
a45664f4
JS
9414 symbol* sym = new symbol;
9415 sym->tok = e->tok;
9416 sym->name = "__tracepoint_arg_" + arg->name;
9417 provide (sym);
f8a968bc
JS
9418 }
9419 else
9420 {
5f36109e
JS
9421 // make a copy of the original as a bare target symbol for the tracepoint
9422 // value, which will be passed into the dwarf dereferencing code
9423 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9424 e2->components.clear();
9425
9426 if (e->components.back().type == target_symbol::comp_pretty_print)
9427 {
9428 if (lvalue)
b530b5b3 9429 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9430
d19a9a82 9431 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9432 dpp.expand()->visit (this);
9433 return;
9434 }
9435
1c0be8c7 9436 bool userspace_p = false;
f8a968bc 9437 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9438 + "_" + e->sym_name()
aca66a36 9439 + "_" + lex_cast(tick++));
75ead1f7 9440
1c0be8c7
JS
9441 exp_type type = pe_long;
9442 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 9443
1c0be8c7
JS
9444 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
9445 userspace_p, lvalue, e, e2);
75ead1f7 9446
f8a968bc
JS
9447 if (lvalue)
9448 {
9449 // Provide the functioncall to our parent, so that it can be
9450 // used to substitute for the assignment node immediately above
9451 // us.
9452 assert(!target_symbol_setter_functioncalls.empty());
9453 *(target_symbol_setter_functioncalls.top()) = n;
9454 }
75ead1f7 9455
1c0be8c7
JS
9456 // Revisit the functioncall so arguments can be expanded.
9457 n->visit (this);
f8a968bc 9458 }
75ead1f7
JS
9459}
9460
9461
f8a968bc
JS
9462void
9463tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9464{
03c75a4a 9465 if (e->addressof)
b530b5b3 9466 throw semantic_error(_("cannot take address of context variable"), e->tok);
03c75a4a 9467
f8a968bc 9468 if (is_active_lvalue (e))
b530b5b3 9469 throw semantic_error(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 9470
277c21bc 9471 if (e->name == "$$name")
f8a968bc 9472 {
5f36109e
JS
9473 e->assert_no_components("tracepoint");
9474
bfdaad1e
DS
9475 // Synthesize an embedded expression.
9476 embedded_expr *expr = new embedded_expr;
9477 expr->tok = e->tok;
9478 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 9479 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 9480 provide (expr);
f8a968bc 9481 }
277c21bc 9482 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 9483 {
5f36109e
JS
9484 e->assert_no_components("tracepoint", true);
9485
f8a968bc
JS
9486 token* pf_tok = new token(*e->tok);
9487 pf_tok->content = "sprintf";
0a6f5a3f 9488
d5e178c1 9489 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 9490
f8a968bc 9491 for (unsigned i = 0; i < args.size(); ++i)
b278033a 9492 {
dcaa1a65
JS
9493 if (!args[i].usable)
9494 continue;
f8a968bc
JS
9495 if (i > 0)
9496 pf->raw_components += " ";
9497 pf->raw_components += args[i].name;
3e3bd7b6 9498 target_symbol *tsym = new target_symbol;
f8a968bc 9499 tsym->tok = e->tok;
277c21bc 9500 tsym->name = "$" + args[i].name;
5f36109e 9501 tsym->components = e->components;
b278033a 9502
f8a968bc
JS
9503 // every variable should always be accessible!
9504 tsym->saved_conversion_error = 0;
8c2f50c0 9505 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
9506 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
9507 {
9508 if (dw.sess.verbose>2)
e26c2f83 9509 for (const semantic_error *c = tsym->saved_conversion_error;
14a97852 9510 c != 0; c = c->chain)
4c5d9906 9511 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
9512 pf->raw_components += "=?";
9513 continue;
9514 }
b278033a 9515
5f36109e
JS
9516 if (!e->components.empty() &&
9517 e->components[0].type == target_symbol::comp_pretty_print)
9518 pf->raw_components += "=%s";
9519 else
9520 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
9521 pf->args.push_back(texp);
9522 }
0a6f5a3f 9523
f8a968bc
JS
9524 pf->components = print_format::string_to_components(pf->raw_components);
9525 provide (pf);
b278033a 9526 }
f8a968bc
JS
9527 else
9528 assert(0); // shouldn't get here
0a6f5a3f
JS
9529}
9530
0a6f5a3f 9531void
f8a968bc 9532tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 9533{
aff5d390 9534 try
c69a87e0 9535 {
bd1fcbad 9536 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 9537
277c21bc 9538 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 9539 visit_target_symbol_context (e);
bd1fcbad 9540
c69a87e0
FCE
9541 else
9542 visit_target_symbol_arg (e);
9543 }
9544 catch (const semantic_error &er)
9545 {
1af1e62d 9546 e->chain (er);
c69a87e0
FCE
9547 provide (e);
9548 }
0a6f5a3f
JS
9549}
9550
9551
79189b84
JS
9552tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
9553 dwflpp& dw, Dwarf_Die& func_die,
9554 const string& tracepoint_name,
9555 probe* base, probe_point* loc):
4c5d1300 9556 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 9557 sess (s), tracepoint_name (tracepoint_name)
56894e91 9558{
79189b84
JS
9559 // create synthetic probe point name; preserve condition
9560 vector<probe_point::component*> comps;
9561 comps.push_back (new probe_point::component (TOK_KERNEL));
9562 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
9563 this->sole_location()->components = comps;
9564
6fb70fb7
JS
9565 // fill out the available arguments in this tracepoint
9566 build_args(dw, func_die);
56894e91 9567
6fb70fb7
JS
9568 // determine which header defined this tracepoint
9569 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
9570 header = decl_file;
9571
9572#if 0 /* This convention is not enforced. */
6fb70fb7
JS
9573 size_t header_pos = decl_file.rfind("trace/");
9574 if (header_pos == string::npos)
9575 throw semantic_error ("cannot parse header location for tracepoint '"
9576 + tracepoint_name + "' in '"
9577 + decl_file + "'");
9578 header = decl_file.substr(header_pos);
d4393459 9579#endif
56894e91 9580
6fb70fb7
JS
9581 // tracepoints from FOO_event_types.h should really be included from FOO.h
9582 // XXX can dwarf tell us the include hierarchy? it would be better to
9583 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 9584 // XXX: see also PR9993.
d4393459 9585 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
9586 if (header_pos != string::npos)
9587 header.erase(header_pos, 12);
56894e91 9588
f8a968bc
JS
9589 // Now expand the local variables in the probe body
9590 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 9591 v.replace (this->body);
a45664f4
JS
9592 for (unsigned i = 0; i < args.size(); i++)
9593 if (args[i].used)
9594 {
9595 vardecl* v = new vardecl;
9596 v->name = "__tracepoint_arg_" + args[i].name;
9597 v->tok = this->tok;
58701b78 9598 v->set_arity(0, this->tok);
a45664f4 9599 v->type = pe_long;
69aa668e 9600 v->synthetic = true;
a45664f4
JS
9601 this->locals.push_back (v);
9602 }
56894e91 9603
79189b84 9604 if (sess.verbose > 2)
ce0f6648 9605 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 9606}
dc38c0ae 9607
56894e91 9608
f8a968bc 9609static bool
dcaa1a65 9610resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 9611{
d19a9a82 9612 Dwarf_Die type;
dcaa1a65 9613 switch (dwarf_tag(&arg.type_die))
b20febf3 9614 {
f8a968bc
JS
9615 case DW_TAG_typedef:
9616 case DW_TAG_const_type:
9617 case DW_TAG_volatile_type:
9618 // iterate on the referent type
3d1ad340 9619 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 9620 && resolve_tracepoint_arg_type(arg));
f8a968bc 9621 case DW_TAG_base_type:
a52d2ac0 9622 case DW_TAG_enumeration_type:
f8a968bc 9623 // base types will simply be treated as script longs
dcaa1a65 9624 arg.isptr = false;
f8a968bc
JS
9625 return true;
9626 case DW_TAG_pointer_type:
dcaa1a65
JS
9627 // pointers can be treated as script longs,
9628 // and if we know their type, they can also be dereferenced
d19a9a82
JS
9629 type = arg.type_die;
9630 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
9631 {
9632 // It still might be a non-type, e.g. const void,
9633 // so we need to strip away all qualifiers.
9634 int tag = dwarf_tag(&arg.type_die);
9635 if (tag != DW_TAG_typedef &&
9636 tag != DW_TAG_const_type &&
9637 tag != DW_TAG_volatile_type)
9638 {
9639 arg.isptr = true;
9640 break;
9641 }
9642 }
9643 if (!arg.isptr)
9644 arg.type_die = type;
ad370dcc
JS
9645 arg.typecast = "(intptr_t)";
9646 return true;
9647 case DW_TAG_structure_type:
9648 case DW_TAG_union_type:
9649 // for structs/unions which are passed by value, we turn it into
9650 // a pointer that can be dereferenced.
9651 arg.isptr = true;
9652 arg.typecast = "(intptr_t)&";
dcaa1a65 9653 return true;
f8a968bc
JS
9654 default:
9655 // should we consider other types too?
9656 return false;
b20febf3 9657 }
56894e91
JS
9658}
9659
9660
9661void
822a6a3d 9662tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 9663{
6fb70fb7
JS
9664 Dwarf_Die arg;
9665 if (dwarf_child(&func_die, &arg) == 0)
9666 do
9667 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
9668 {
9669 // build a tracepoint_arg for this parameter
9670 tracepoint_arg tparg;
23d106b9 9671 tparg.name = dwarf_diename(&arg);
56894e91 9672
6fb70fb7 9673 // read the type of this parameter
3d1ad340 9674 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 9675 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
ce0f6648
LB
9676 throw semantic_error (_F("cannot get type of parameter '%s' of tracepoint '%s'",
9677 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 9678
dcaa1a65 9679 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
9680 args.push_back(tparg);
9681 if (sess.verbose > 4)
a52d2ac0
JS
9682 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
9683 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
9684 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
9685 }
9686 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
9687}
9688
dc38c0ae 9689void
d0bfd2ac 9690tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 9691{
dcaa1a65
JS
9692 for (unsigned i = 0; i < args.size(); ++i)
9693 if (args[i].usable)
d0bfd2ac 9694 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
9695}
9696
79189b84
JS
9697void
9698tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 9699{
79189b84
JS
9700 if (! s.tracepoint_derived_probes)
9701 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
9702 s.tracepoint_derived_probes->enroll (this);
9703}
e38d6504 9704
56894e91 9705
197a4d62 9706void
3e3bd7b6 9707tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 9708{
3e3bd7b6
JS
9709 for (unsigned i = 0; i < args.size(); i++)
9710 if (args[i].used)
9711 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 9712}
56894e91 9713
3e3bd7b6 9714
c9ccb642 9715static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 9716{
3c1b3d06
FCE
9717 vector<string> they_live;
9718 // PR 9993
9719 // XXX: may need this to be configurable
d4393459 9720 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
9721
9722 // PR11649: conditional extra header
9723 // for kvm tracepoints in 2.6.33ish
9724 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
9725 they_live.push_back ("#include <linux/kvm_host.h>");
9726 }
9727
50b72692 9728 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 9729 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
9730 if (s.kernel_source_tree != "")
9731 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
9732 they_live.push_back ("struct xfs_mount;");
9733 they_live.push_back ("struct xfs_inode;");
9734 they_live.push_back ("struct xfs_buf;");
9735 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 9736 they_live.push_back ("struct xfs_trans;");
9e0cd21a 9737 }
d4393459 9738
50b72692 9739 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
9740 they_live.push_back ("struct rpc_task;");
9741 }
b64d65e2
FCE
9742 // RHEL6.3
9743 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
9744 they_live.push_back ("struct rpc_clnt;");
9745 they_live.push_back ("struct rpc_wait_queue;");
9746 }
d4393459
FCE
9747
9748 they_live.push_back ("#include <asm/cputime.h>");
9749
c2cf1b87
FCE
9750 // linux 3.0
9751 they_live.push_back ("struct cpu_workqueue_struct;");
9752
50b72692 9753 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
9754 if (s.kernel_source_tree != "")
9755 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
9756
50b72692
HP
9757 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
9758 they_live.push_back ("struct ext3_reserve_window_node;");
9759
3c1b3d06
FCE
9760 return they_live;
9761}
47dd066d
WC
9762
9763
9764void
79189b84 9765tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 9766{
79189b84
JS
9767 if (probes.empty())
9768 return;
47dd066d 9769
96b030fe
JS
9770 s.op->newline() << "/* ---- tracepoint probes ---- */";
9771 s.op->newline();
79189b84 9772
47dd066d 9773
a4b9c3b3
FCE
9774 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
9775 // to be separately compiled. That's because kernel tracepoint headers sometimes
9776 // conflict. PR13155.
9777
9778 map<string,translator_output*> per_header_aux;
9779 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 9780
6fb70fb7
JS
9781 for (unsigned i = 0; i < probes.size(); ++i)
9782 {
9783 tracepoint_derived_probe *p = probes[i];
75ae2ec9 9784 string header = p->header;
5f73a260 9785
a4b9c3b3
FCE
9786 // We cache the auxiliary output files on a per-header basis. We don't
9787 // need one aux file per tracepoint, only one per tracepoint-header.
9788 translator_output *tpop = per_header_aux[header];
9789 if (tpop == 0)
9790 {
9791 tpop = s.op_create_auxiliary();
9792 per_header_aux[header] = tpop;
9793
9794 // PR9993: Add extra headers to work around undeclared types in individual
9795 // include/trace/foo.h files
9796 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
9797 for (unsigned z=0; z<extra_decls.size(); z++)
9798 tpop->newline() << extra_decls[z] << "\n";
720c435f 9799
a4b9c3b3
FCE
9800 // strip include/ substring, the same way as done in get_tracequery_module()
9801 size_t root_pos = header.rfind("include/");
9802 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443
FCE
9803
9804 tpop->newline() << "#include <linux/tracepoint.h>" << endl;
a4b9c3b3 9805 tpop->newline() << "#include <" << header << ">";
720c435f 9806
a4b9c3b3
FCE
9807 // Starting in 2.6.35, at the same time NOARGS was added, the callback
9808 // always has a void* as the first parameter. PR11599
9809 tpop->newline() << "#ifdef DECLARE_TRACE_NOARGS";
9810 tpop->newline() << "#define STAP_TP_DATA , NULL";
9811 tpop->newline() << "#define STAP_TP_PROTO void *cb_data"
9812 << " __attribute__ ((unused))";
9813 if (!p->args.empty())
9814 tpop->line() << ",";
9815 tpop->newline() << "#else";
9816 tpop->newline() << "#define STAP_TP_DATA";
9817 tpop->newline() << "#define STAP_TP_PROTO";
9818 if (p->args.empty())
9819 tpop->line() << " void";
9820 tpop->newline() << "#endif";
720c435f
JS
9821
9822 tpop->newline() << "#define intptr_t long";
a4b9c3b3
FCE
9823 }
9824
720c435f
JS
9825 // collect the args that are actually in use
9826 vector<const tracepoint_arg*> used_args;
6fb70fb7 9827 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
9828 if (p->args[j].used)
9829 used_args.push_back(&p->args[j]);
9830
a4b9c3b3
FCE
9831 // forward-declare the generated-side tracepoint callback
9832 tpop->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9833 tpop->indent(2);
9834 if (used_args.empty())
9835 tpop->line() << "void";
9836 for (unsigned j = 0; j < used_args.size(); ++j)
6fb70fb7
JS
9837 {
9838 if (j > 0)
a4b9c3b3
FCE
9839 tpop->line() << ", ";
9840 tpop->line() << "int64_t";
6fb70fb7 9841 }
720c435f
JS
9842 tpop->line() << ");";
9843 tpop->indent(-2);
5f73a260 9844
a4b9c3b3
FCE
9845 // define the generated-side tracepoint callback - in the main translator-output
9846 s.op->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9847 s.op->indent(2);
9848 if (used_args.empty())
9849 s.op->newline() << "void";
9850 for (unsigned j = 0; j < used_args.size(); ++j)
a4b9c3b3 9851 {
a4b9c3b3
FCE
9852 if (j > 0)
9853 s.op->line() << ", ";
720c435f 9854 s.op->newline() << "int64_t __tracepoint_arg_" << used_args[j]->name;
6fb70fb7 9855 }
5f73a260
JS
9856 s.op->newline() << ")";
9857 s.op->newline(-2) << "{";
7c3e97f4 9858 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 9859 << common_probe_init (p) << ";";
71db462b 9860 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 9861 "stp_probe_type_tracepoint");
6dceb5c9 9862 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
9863 << lex_cast_qstring (p->tracepoint_name)
9864 << ";";
720c435f
JS
9865 for (unsigned j = 0; j < used_args.size(); ++j)
9866 {
9867 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 9868 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
9869 << " = __tracepoint_arg_" << used_args[j]->name << ";";
9870 }
26e63673 9871 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 9872 common_probe_entryfn_epilogue (s, true);
6fb70fb7 9873 s.op->newline(-1) << "}";
47dd066d 9874
a4b9c3b3 9875 // define the real tracepoint callback function
720c435f 9876 tpop->newline() << "static void enter_tracepoint_probe_" << i << "(";
a4b9c3b3
FCE
9877 tpop->newline(2) << "STAP_TP_PROTO";
9878 for (unsigned j = 0; j < p->args.size(); ++j)
9879 {
9880 if (j > 0)
9881 tpop->line() << ", ";
9882 tpop->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
9883 }
9884 tpop->newline() << ")";
9885 tpop->newline(-2) << "{";
720c435f
JS
9886 tpop->newline(1) << "enter_real_tracepoint_probe_" << i << "(";
9887 tpop->indent(2);
9888 for (unsigned j = 0; j < used_args.size(); ++j)
9889 {
9890 if (j > 0)
9891 tpop->line() << ", ";
9892 tpop->newline() << "(int64_t)" << used_args[j]->typecast
9893 << "__tracepoint_arg_" << used_args[j]->name;
9894 }
9895 tpop->newline() << ");";
9896 tpop->newline(-3) << "}";
a4b9c3b3
FCE
9897
9898
96b030fe 9899 // emit normalized registration functions
720c435f 9900 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9901 tpop->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 9902 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3 9903 tpop->newline(-1) << "}";
47dd066d 9904
86758d5f
JS
9905 // NB: we're not prepared to deal with unreg failures. However, failures
9906 // can only occur if the tracepoint doesn't exist (yet?), or if we
9907 // weren't even registered. The former should be OKed by the initial
9908 // registration call, and the latter is safe to ignore.
720c435f 9909 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9910 tpop->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 9911 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3
FCE
9912 tpop->newline(-1) << "}";
9913 tpop->newline();
5f73a260 9914
720c435f
JS
9915 // declare normalized registration functions
9916 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
9917 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 9918
a4b9c3b3 9919 tpop->assert_0_indent();
af304783
DS
9920 }
9921
96b030fe
JS
9922 // emit an array of registration functions for easy init/shutdown
9923 s.op->newline() << "static struct stap_tracepoint_probe {";
9924 s.op->newline(1) << "int (*reg)(void);";
86758d5f 9925 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
9926 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
9927 s.op->indent(1);
9928 for (unsigned i = 0; i < probes.size(); ++i)
9929 {
9930 s.op->newline () << "{";
9931 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
9932 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
9933 s.op->line() << " },";
9934 }
9935 s.op->newline(-1) << "};";
9936 s.op->newline();
47dd066d
WC
9937}
9938
9939
79189b84
JS
9940void
9941tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 9942{
79189b84
JS
9943 if (probes.size () == 0)
9944 return;
47dd066d 9945
79189b84 9946 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
9947 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
9948 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
9949 s.op->newline() << "if (rc) {";
9950 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
9951 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
9952 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
9953 s.op->newline(-1) << "}";
9954 s.op->newline(-1) << "}";
47dd066d 9955
bc9a523d
FCE
9956 // This would be technically proper (on those autoconf-detectable
9957 // kernels that include this function in tracepoint.h), however we
9958 // already make several calls to synchronze_sched() during our
9959 // shutdown processes.
47dd066d 9960
bc9a523d
FCE
9961 // s.op->newline() << "if (rc)";
9962 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
9963 // s.op->indent(-1);
79189b84 9964}
47dd066d
WC
9965
9966
79189b84
JS
9967void
9968tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 9969{
79189b84
JS
9970 if (probes.empty())
9971 return;
47dd066d 9972
96b030fe
JS
9973 s.op->newline() << "/* deregister tracepoint probes */";
9974 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
9975 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
9976 s.op->indent(-1);
47dd066d 9977
bc9a523d 9978 // Not necessary: see above.
47dd066d 9979
bc9a523d 9980 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 9981}
b20febf3 9982
47dd066d 9983
75ead1f7 9984struct tracepoint_query : public base_query
47dd066d 9985{
75ead1f7
JS
9986 tracepoint_query(dwflpp & dw, const string & tracepoint,
9987 probe * base_probe, probe_point * base_loc,
9988 vector<derived_probe *> & results):
9989 base_query(dw, "*"), tracepoint(tracepoint),
9990 base_probe(base_probe), base_loc(base_loc),
9991 results(results) {}
47dd066d 9992
75ead1f7 9993 const string& tracepoint;
47dd066d 9994
75ead1f7
JS
9995 probe * base_probe;
9996 probe_point * base_loc;
9997 vector<derived_probe *> & results;
f982c59b 9998 set<string> probed_names;
47dd066d 9999
75ead1f7
JS
10000 void handle_query_module();
10001 int handle_query_cu(Dwarf_Die * cudie);
10002 int handle_query_func(Dwarf_Die * func);
822a6a3d 10003 void query_library (const char *) {}
576eaefe 10004 void query_plt (const char *entry, size_t addr) {}
b20febf3 10005
75ead1f7
JS
10006 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
10007 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
10008};
47dd066d
WC
10009
10010
10011void
75ead1f7 10012tracepoint_query::handle_query_module()
47dd066d 10013{
75ead1f7 10014 // look for the tracepoints in each CU
337b7c44 10015 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10016}
10017
10018
75ead1f7
JS
10019int
10020tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10021{
75ead1f7 10022 dw.focus_on_cu (cudie);
47dd066d 10023
75ead1f7
JS
10024 // look at each function to see if it's a tracepoint
10025 string function = "stapprobe_" + tracepoint;
10026 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10027}
10028
10029
75ead1f7
JS
10030int
10031tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10032{
75ead1f7 10033 dw.focus_on_function (func);
47dd066d 10034
60d98537 10035 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10036 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10037
10038 // check for duplicates -- sometimes tracepoint headers may be indirectly
10039 // included in more than one of our tracequery modules.
10040 if (!probed_names.insert(tracepoint_instance).second)
10041 return DWARF_CB_OK;
10042
79189b84
JS
10043 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10044 tracepoint_instance,
10045 base_probe, base_loc);
10046 results.push_back (dp);
75ead1f7 10047 return DWARF_CB_OK;
47dd066d
WC
10048}
10049
10050
75ead1f7
JS
10051int
10052tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 10053{
75ead1f7 10054 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 10055 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10056 return q->handle_query_cu(cudie);
47dd066d
WC
10057}
10058
10059
75ead1f7
JS
10060int
10061tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 10062{
75ead1f7 10063 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 10064 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10065 return q->handle_query_func(func);
47dd066d
WC
10066}
10067
10068
0a6f5a3f 10069struct tracepoint_builder: public derived_probe_builder
47dd066d 10070{
0a6f5a3f
JS
10071private:
10072 dwflpp *dw;
10073 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10074 void get_tracequery_modules(systemtap_session& s,
10075 const vector<string>& headers,
10076 vector<string>& modules);
47dd066d 10077
0a6f5a3f 10078public:
47dd066d 10079
0a6f5a3f
JS
10080 tracepoint_builder(): dw(0) {}
10081 ~tracepoint_builder() { delete dw; }
47dd066d 10082
0a6f5a3f
JS
10083 void build_no_more (systemtap_session& s)
10084 {
10085 if (dw && s.verbose > 3)
b530b5b3 10086 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10087 delete dw;
10088 dw = NULL;
435f53a7
FCE
10089
10090 delete_session_module_cache (s);
0a6f5a3f 10091 }
47dd066d 10092
0a6f5a3f
JS
10093 void build(systemtap_session& s,
10094 probe *base, probe_point *location,
10095 literal_map_t const& parameters,
10096 vector<derived_probe*>& finished_results);
10097};
47dd066d 10098
47dd066d 10099
c9ccb642 10100
2a0e62a8 10101// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10102// tracepoint-related header files given. Return the generated or cached
10103// modules[].
10104
10105void
10106tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10107 const vector<string>& headers,
10108 vector<string>& modules)
0a6f5a3f 10109{
c95eddf7 10110 if (s.verbose > 2)
55e50c24 10111 {
ce0f6648 10112 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10113 for (size_t i = 0; i < headers.size(); ++i)
10114 clog << " " << headers[i] << endl;
10115 }
c95eddf7 10116
2a0e62a8
JS
10117 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10118 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10119 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10120 // so we prefer not to repeat this.
10121 vector<string> uncached_headers;
10122 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10123 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10124
10125 // They may be in the cache already.
10126 if (s.use_cache && !s.poison_cache)
10127 for (size_t i=0; i<headers.size(); i++)
10128 {
10129 // see if the cached module exists
2a0e62a8 10130 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10131 if (!tracequery_path.empty() && file_exists(tracequery_path))
10132 {
10133 if (s.verbose > 2)
10134 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10135
c252fca2
JS
10136 // an empty file is a cached failure
10137 if (get_file_size(tracequery_path) > 0)
10138 modules.push_back (tracequery_path);
c9ccb642
FCE
10139 }
10140 else
10141 uncached_headers.push_back(headers[i]);
10142 }
10143 else
10144 uncached_headers = headers;
f982c59b 10145
c9ccb642
FCE
10146 // If we have nothing left to search for, quit
10147 if (uncached_headers.empty()) return;
55e50c24 10148
c9ccb642 10149 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10150
c9ccb642
FCE
10151 // We could query several subsets of headers[] to make this go
10152 // faster, but let's KISS and do one at a time.
10153 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10154 {
c9ccb642
FCE
10155 const string& header = uncached_headers[i];
10156
10157 // create a tracequery source file
10158 ostringstream osrc;
10159
10160 // PR9993: Add extra headers to work around undeclared types in individual
10161 // include/trace/foo.h files
10162 vector<string> short_decls = tracepoint_extra_decls(s, header);
10163
10164 // add each requested tracepoint header
75ae2ec9 10165 size_t root_pos = header.rfind("include/");
832f100d 10166 short_decls.push_back(string("#include <") +
75ae2ec9 10167 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10168 string(">"));
f982c59b 10169
c9ccb642
FCE
10170 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10171 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10172
10173 // the kernel has changed this naming a few times, previously TPPROTO,
10174 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10175 osrc << "#ifndef PARAMS" << endl;
10176 osrc << "#define PARAMS(args...) args" << endl;
10177 osrc << "#endif" << endl;
10178
c9ccb642
FCE
10179 // override DECLARE_TRACE to synthesize probe functions for us
10180 osrc << "#undef DECLARE_TRACE" << endl;
10181 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10182 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10183
c9ccb642
FCE
10184 // 2.6.35 added the NOARGS variant, but it's the same for us
10185 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10186 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10187 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10188
10189 // 2.6.38 added the CONDITION variant, which can also just redirect
10190 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10191 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10192 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10193
c9ccb642
FCE
10194 // older tracepoints used DEFINE_TRACE, so redirect that too
10195 osrc << "#undef DEFINE_TRACE" << endl;
10196 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10197 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10198
c9ccb642
FCE
10199 // add the specified decls/#includes
10200 for (unsigned z=0; z<short_decls.size(); z++)
10201 osrc << "#undef TRACE_INCLUDE_FILE\n"
10202 << "#undef TRACE_INCLUDE_PATH\n"
10203 << short_decls[z] << "\n";
10204
10205 // finish up the module source
10206 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10207
c9ccb642
FCE
10208 // save the source file away
10209 headers_tracequery_src[header] = osrc.str();
55e50c24 10210 }
f982c59b 10211
c9ccb642 10212 // now build them all together
2a0e62a8 10213 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10214
c9ccb642 10215 // now plop them into the cache
b278033a 10216 if (s.use_cache)
c9ccb642
FCE
10217 for (size_t i=0; i<uncached_headers.size(); i++)
10218 {
10219 const string& header = uncached_headers[i];
2a0e62a8
JS
10220 const string& tracequery_obj = tracequery_objs[header];
10221 const string& tracequery_path = headers_cache_obj[header];
10222 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10223 {
2a0e62a8 10224 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10225 modules.push_back (tracequery_path);
10226 }
c252fca2
JS
10227 else
10228 // cache an empty file for failures
10229 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10230 }
f982c59b
JS
10231}
10232
10233
d4393459 10234
f982c59b
JS
10235bool
10236tracepoint_builder::init_dw(systemtap_session& s)
10237{
10238 if (dw != NULL)
10239 return true;
10240
10241 vector<string> tracequery_modules;
55e50c24 10242 vector<string> system_headers;
f982c59b
JS
10243
10244 glob_t trace_glob;
d4393459
FCE
10245
10246 // find kernel_source_tree
10247 if (s.kernel_source_tree == "")
f982c59b 10248 {
d4393459
FCE
10249 unsigned found;
10250 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
10251 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
10252 if (found)
10253 {
10254 Dwarf_Die *cudie = 0;
10255 Dwarf_Addr bias;
10256 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10257 {
e19ebcf7 10258 assert_no_interrupts();
d4393459
FCE
10259 Dwarf_Attribute attr;
10260 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10261 if (name)
d4393459 10262 {
36d65b45
JS
10263 // check that the path actually exists locally before we try to use it
10264 if (file_exists(name))
10265 {
10266 if (s.verbose > 2)
10267 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10268 s.kernel_source_tree = name;
10269 }
10270 else
10271 {
10272 if (s.verbose > 2)
10273 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10274 }
61f1a63b 10275
d4393459
FCE
10276 break; // skip others; modern Kbuild uses same comp_dir for them all
10277 }
10278 }
10279 }
10280 }
10281
10282 // prefixes
10283 vector<string> glob_prefixes;
10284 glob_prefixes.push_back (s.kernel_build_tree);
10285 if (s.kernel_source_tree != "")
10286 glob_prefixes.push_back (s.kernel_source_tree);
10287
10288 // suffixes
10289 vector<string> glob_suffixes;
10290 glob_suffixes.push_back("include/trace/events/*.h");
10291 glob_suffixes.push_back("include/trace/*.h");
10292 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
b1966849 10293 glob_suffixes.push_back("arch/x86/include/asm/trace/*.h");
f89ff3e2 10294 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
ca51c2cd 10295 glob_suffixes.push_back("fs/xfs/xfs_trace*.h");
d4393459
FCE
10296
10297 // compute cartesian product
10298 vector<string> globs;
10299 for (unsigned i=0; i<glob_prefixes.size(); i++)
10300 for (unsigned j=0; j<glob_suffixes.size(); j++)
10301 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10302
8aa43b8d 10303 set<string> duped_headers;
d4393459
FCE
10304 for (unsigned z = 0; z < globs.size(); z++)
10305 {
10306 string glob_str = globs[z];
10307 if (s.verbose > 3)
b530b5b3 10308 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10309
067cc66f
CM
10310 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10311 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10312 throw runtime_error("Error globbing tracepoint");
10313
f982c59b
JS
10314 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10315 {
10316 string header(trace_glob.gl_pathv[i]);
10317
10318 // filter out a few known "internal-only" headers
60d98537
JS
10319 if (endswith(header, "/define_trace.h") ||
10320 endswith(header, "/ftrace.h") ||
10321 endswith(header, "/trace_events.h") ||
10322 endswith(header, "_event_types.h"))
f982c59b
JS
10323 continue;
10324
b1966849
FCE
10325 // With headers now plopped under arch/FOO/include/asm/*,
10326 // the following logic miss some tracepoints.
10327#if 0
8aa43b8d
JS
10328 // skip identical headers from the build and source trees.
10329 size_t root_pos = header.rfind("include/");
10330 if (root_pos != string::npos &&
10331 !duped_headers.insert(header.substr(root_pos + 8)).second)
10332 continue;
b1966849 10333#endif
8aa43b8d 10334
55e50c24 10335 system_headers.push_back(header);
f982c59b
JS
10336 }
10337 globfree(&trace_glob);
10338 }
10339
c9ccb642
FCE
10340 // Build tracequery modules
10341 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 10342
f982c59b
JS
10343 // TODO: consider other sources of tracepoint headers too, like from
10344 // a command-line parameter or some environment or .systemtaprc
47dd066d 10345
59c11f91 10346 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
10347 return true;
10348}
47dd066d 10349
0a6f5a3f
JS
10350void
10351tracepoint_builder::build(systemtap_session& s,
10352 probe *base, probe_point *location,
10353 literal_map_t const& parameters,
10354 vector<derived_probe*>& finished_results)
10355{
10356 if (!init_dw(s))
10357 return;
47dd066d 10358
75ead1f7
JS
10359 string tracepoint;
10360 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 10361
75ead1f7 10362 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 10363 dw->iterate_over_modules(&query_module, &q);
47dd066d 10364}
47dd066d 10365
e6fe60e7 10366
b55bc428 10367// ------------------------------------------------------------------------
bd2b1e68 10368// Standard tapset registry.
b55bc428
FCE
10369// ------------------------------------------------------------------------
10370
7a053d3b 10371void
f8220a7b 10372register_standard_tapsets(systemtap_session & s)
b55bc428 10373{
47e0478e 10374 register_tapset_been(s);
93646f4d 10375 register_tapset_itrace(s);
dd0e4fa7 10376 register_tapset_mark(s);
7a212aa8 10377 register_tapset_procfs(s);
912e8c59 10378 register_tapset_timers(s);
8d9609f5 10379 register_tapset_netfilter(s);
b84779a5 10380 register_tapset_utrace(s);
b98a8d73 10381
7a24d422 10382 // dwarf-based kprobe/uprobe parts
c4ce66a1 10383 dwarf_derived_probe::register_patterns(s);
30a279be 10384
888af770
FCE
10385 // XXX: user-space starter set
10386 s.pattern_root->bind_num(TOK_PROCESS)
10387 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10388 ->bind_privilege(pr_all)
888af770
FCE
10389 ->bind(new uprobe_builder ());
10390 s.pattern_root->bind_num(TOK_PROCESS)
10391 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10392 ->bind_privilege(pr_all)
888af770
FCE
10393 ->bind(new uprobe_builder ());
10394
0a6f5a3f
JS
10395 // kernel tracepoint probes
10396 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10397 ->bind(new tracepoint_builder());
10398
e6fe60e7
AM
10399 // Kprobe based probe
10400 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10401 ->bind(new kprobe_builder());
3c57fe1f
JS
10402 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
10403 ->bind(new kprobe_builder());
e6fe60e7
AM
10404 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10405 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
10406 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10407 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
10408 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10409 ->bind(new kprobe_builder());
b6371390
JS
10410 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10411 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10412 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10413 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10414 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10415 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10416 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10417 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10418 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
10419
10420 //Hwbkpt based probe
b47f3a55
FCE
10421 // NB: we formerly registered the probe point types only if the kernel configuration
10422 // allowed it. However, we get better error messages if we allow probes to resolve.
10423 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10424 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10425 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10426 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10427 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10428 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10429 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10430 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10431 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10432 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10433 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10434 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10435 // length supported with address only, not symbol names
83ea76b1
WC
10436
10437 //perf event based probe
4763f713 10438 register_tapset_perf(s);
a29858ef 10439 register_tapset_java(s);
b55bc428 10440}
dc38c0ae
DS
10441
10442
b20febf3
FCE
10443vector<derived_probe_group*>
10444all_session_groups(systemtap_session& s)
dc38c0ae 10445{
b20febf3 10446 vector<derived_probe_group*> g;
912e8c59
JS
10447
10448#define DOONE(x) \
10449 if (s. x##_derived_probes) \
10450 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
10451
10452 // Note that order *is* important here. We want to make sure we
10453 // register (actually run) begin probes before any other probe type
10454 // is run. Similarly, when unregistering probes, we want to
10455 // unregister (actually run) end probes after every other probe type
10456 // has be unregistered. To do the latter,
10457 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
10458 DOONE(be);
10459 DOONE(dwarf);
888af770 10460 DOONE(uprobe);
b20febf3
FCE
10461 DOONE(timer);
10462 DOONE(profile);
10463 DOONE(mark);
0a6f5a3f 10464 DOONE(tracepoint);
e6fe60e7 10465 DOONE(kprobe);
dd225250 10466 DOONE(hwbkpt);
83ea76b1 10467 DOONE(perf);
b20febf3 10468 DOONE(hrtimer);
ce82316f 10469 DOONE(procfs);
8d9609f5 10470 DOONE(netfilter);
935447c8
DS
10471
10472 // Another "order is important" item. We want to make sure we
10473 // "register" the dummy task_finder probe group after all probe
10474 // groups that use the task_finder.
10475 DOONE(utrace);
a96d1db0 10476 DOONE(itrace);
f31a77f5 10477 DOONE(dynprobe);
e7d4410d 10478 DOONE(java);
935447c8 10479 DOONE(task_finder);
b20febf3
FCE
10480#undef DOONE
10481 return g;
46b84a80 10482}
73267b89
JS
10483
10484/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.673848 seconds and 5 git commands to generate.