]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
factor out try_parse_arg_register
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
ef36f781 2// Copyright (C) 2005-2014 Red Hat Inc.
aa30ccd3 3// Copyright (C) 2005-2007 Intel Corporation.
0b8f6579 4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
56e12059
FCE
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "config.h"
12#include "staptree.h"
13#include "elaborate.h"
b55bc428 14#include "tapsets.h"
93646f4d 15#include "task_finder.h"
f31a77f5 16#include "tapset-dynprobe.h"
56e12059 17#include "translate.h"
dc38c0ae 18#include "session.h"
72dbc915 19#include "util.h"
0a6f5a3f 20#include "buildrun.h"
86bf665e 21#include "dwarf_wrappers.h"
2e67a43b 22#include "auto_free.h"
b278033a 23#include "hash.h"
440f755a 24#include "dwflpp.h"
5f8ca04f 25#include "setupdwfl.h"
6b51ee12 26#include <gelf.h>
22d737e8 27
4d0d9e8a 28#include "sdt_types.h"
bd2b1e68 29
3b579393
FCE
30#include <cstdlib>
31#include <algorithm>
bd2b1e68 32#include <deque>
56e12059 33#include <iostream>
d1bcbe71 34#include <fstream>
bd2b1e68 35#include <map>
ec4373ff 36#include <set>
56e12059 37#include <sstream>
bd2b1e68 38#include <stdexcept>
b55bc428 39#include <vector>
67959c62 40#include <stack>
e36387d7 41#include <cstdarg>
29e64872 42#include <cassert>
1969b5bc 43#include <iomanip>
f781f849 44#include <cerrno>
bd2b1e68
GH
45
46extern "C" {
df8fadee 47#include <fcntl.h>
bd2b1e68 48#include <elfutils/libdwfl.h>
7a053d3b 49#include <elfutils/libdw.h>
77de5e9e
GH
50#include <dwarf.h>
51#include <elf.h>
52#include <obstack.h>
b20febf3 53#include <glob.h>
30a279be 54#include <fnmatch.h>
5f0a03a6 55#include <stdio.h>
349dc70e 56#include <sys/types.h>
37001baa 57#include <sys/stat.h>
aaf7ffe8 58#include <math.h>
aff5d390 59#include <regex.h>
37001baa 60#include <unistd.h>
4b1ad75e
RM
61
62#define __STDC_FORMAT_MACROS
63#include <inttypes.h>
bd2b1e68 64}
77de5e9e 65
508059f0
MW
66// Old elf.h doesn't know about this machine type.
67#ifndef EM_AARCH64
68#define EM_AARCH64 183
69#endif
70
56e12059
FCE
71
72using namespace std;
2171f774 73using namespace __gnu_cxx;
56e12059 74
47dd066d 75
b20febf3
FCE
76
77// ------------------------------------------------------------------------
faea5e16
JS
78
79string
80common_probe_init (derived_probe* p)
81{
26e63673
JS
82 assert(p->session_index != (unsigned)-1);
83 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
84}
85
86
b20febf3 87void
71db462b
DS
88common_probe_entryfn_prologue (systemtap_session& s,
89 string statestr, string probe,
90 string probe_type, bool overload_processing)
b20febf3 91{
944c9a7a 92 if (s.runtime_usermode_p())
ac34f2aa
JS
93 {
94 // If session_state() is NULL, then we haven't even initialized shm yet,
95 // and there's *nothing* for the probe to do. (even alibi is in shm)
96 // So failure skips this whole block through the end of the epilogue.
97 s.op->newline() << "if (likely(session_state())) {";
e481ab2e 98 s.op->indent(1);
ac34f2aa
JS
99 }
100
71db462b 101 s.op->newline() << "#ifdef STP_ALIBI";
7c3e97f4 102 s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
71db462b 103 s.op->newline() << "#else";
653e6a9a 104
e481ab2e
JS
105 if (s.runtime_usermode_p())
106 s.op->newline() << "int _stp_saved_errno = errno;";
107
fee09ad5 108 s.op->newline() << "struct context* __restrict__ c = NULL;";
71db462b
DS
109 s.op->newline() << "#if !INTERRUPTIBLE";
110 s.op->newline() << "unsigned long flags;";
111 s.op->newline() << "#endif";
b20febf3 112
f887a8c9 113 s.op->newline() << "#ifdef STP_TIMING";
7c3e97f4 114 s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
f887a8c9
DS
115 s.op->newline() << "#endif";
116 if (overload_processing && !s.runtime_usermode_p())
71db462b 117 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 118 else
71db462b 119 s.op->newline() << "#ifdef STP_TIMING";
b20febf3 120
f887a8c9
DS
121 if (! s.runtime_usermode_p())
122 s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
123 else
124 {
125 s.op->newline() << "struct timespec timespec_atstart;";
45639d96 126 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atstart);";
f887a8c9 127 }
71db462b 128 s.op->newline() << "#endif";
994aac0e 129
d2d39de6 130 s.op->newline() << "#if !INTERRUPTIBLE";
71db462b
DS
131 s.op->newline() << "local_irq_save (flags);";
132 s.op->newline() << "#endif";
b20febf3 133
ac3af990 134 if (! s.runtime_usermode_p())
71db462b
DS
135 {
136 // Check for enough free enough stack space
137 s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
138 s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
139 // XXX: may need porting to platforms where task_struct is not
140 // at bottom of kernel stack NB: see also
141 // CONFIG_DEBUG_STACKOVERFLOW
065d5567 142 s.op->newline() << "atomic_inc (skipped_count());";
71db462b 143 s.op->newline() << "#ifdef STP_TIMING";
065d5567 144 s.op->newline() << "atomic_inc (skipped_count_lowstack());";
71db462b
DS
145 s.op->newline() << "#endif";
146 s.op->newline() << "goto probe_epilogue;";
147 s.op->newline(-1) << "}";
148 }
c931ec8a 149
065d5567 150 s.op->newline() << "if (atomic_read (session_state()) != " << statestr << ")";
71db462b
DS
151 s.op->newline(1) << "goto probe_epilogue;";
152 s.op->indent(-1);
9a604fac 153
1d0e697d 154 s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
d2d39de6 155 s.op->newline() << "if (!c) {";
71db462b 156 s.op->newline(1) << "#if !INTERRUPTIBLE";
065d5567 157 s.op->newline() << "atomic_inc (skipped_count());";
71db462b
DS
158 s.op->newline() << "#endif";
159 s.op->newline() << "#ifdef STP_TIMING";
065d5567 160 s.op->newline() << "atomic_inc (skipped_count_reentrant());";
71db462b 161 s.op->newline() << "#endif";
71db462b
DS
162 s.op->newline() << "goto probe_epilogue;";
163 s.op->newline(-1) << "}";
d2d39de6 164
71db462b
DS
165 s.op->newline();
166 s.op->newline() << "c->last_stmt = 0;";
167 s.op->newline() << "c->last_error = 0;";
168 s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
169 s.op->newline() << "c->uregs = 0;";
170 s.op->newline() << "c->kregs = 0;";
171 s.op->newline() << "#if defined __ia64__";
172 s.op->newline() << "c->unwaddr = 0;";
173 s.op->newline() << "#endif";
f4d70a33
JS
174 if (s.runtime_usermode_p())
175 s.op->newline() << "c->probe_index = " << probe << "->index;";
71db462b
DS
176 s.op->newline() << "c->probe_point = " << probe << "->pp;";
177 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
178 s.op->newline() << "c->probe_name = " << probe << "->pn;";
179 s.op->newline() << "#endif";
180 s.op->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9 181 // reset Individual Probe State union
71db462b 182 s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
e04b5d74 183 s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0;";
71db462b
DS
184 s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
185 s.op->newline() << "c->regparm = 0;";
186 s.op->newline() << "#endif";
e0a17418 187
152fa051
LB
188 if(!s.suppress_time_limits){
189 s.op->newline() << "#if INTERRUPTIBLE";
190 s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
191 s.op->newline() << "#else";
192 s.op->newline() << "c->actionremaining = MAXACTION;";
193 s.op->newline() << "#endif";
194 }
9915575b
FCE
195 // NB: The following would actually be incorrect.
196 // That's because cycles_sum/cycles_base values are supposed to survive
197 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
198 // cycles), the values will be reset.
199 /*
71db462b
DS
200 s.op->newline() << "#ifdef STP_OVERLOAD";
201 s.op->newline() << "c->cycles_sum = 0;";
202 s.op->newline() << "c->cycles_base = 0;";
203 s.op->newline() << "#endif";
9915575b 204 */
44cfbe25
SM
205
206 s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
207 s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
208 s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
209 s.op->newline() << "#endif";
b20febf3 210}
9a604fac 211
a44a0785 212
b20febf3 213void
f887a8c9
DS
214common_probe_entryfn_epilogue (systemtap_session& s,
215 bool overload_processing)
b20febf3 216{
f887a8c9
DS
217 if (overload_processing && !s.runtime_usermode_p())
218 s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
a58d79d0 219 else
f887a8c9
DS
220 s.op->newline() << "#ifdef STP_TIMING";
221 s.op->newline() << "{";
222 s.op->indent(1);
223 if (! s.runtime_usermode_p())
224 {
225 s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
226 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
227 // fewer, if the hardware counter rolls over really quickly. We
228 // handle 32-bit wraparound here.
229 s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
230 s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
231 s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
232 s.op->indent(-1);
233 }
234 else
235 {
236 s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
237 s.op->newline() << "long cycles_elapsed;";
45639d96 238 s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, &timespec_atend);";
f887a8c9
DS
239 s.op->newline() << "_stp_timespec_sub(&timespec_atend, &timespec_atstart, &timespec_elapsed);";
240 // 'cycles_elapsed' is really elapsed nanoseconds
241 s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
242 }
243
244 s.op->newline() << "#ifdef STP_TIMING";
245 s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
246 s.op->newline() << "#endif";
247
248 if (overload_processing && !s.runtime_usermode_p())
249 {
250 s.op->newline() << "#ifdef STP_OVERLOAD";
251 s.op->newline() << "{";
a58d79d0
DS
252 // If the cycle count has wrapped (cycles_atend > cycles_base),
253 // let's go ahead and pretend the interval has been reached.
254 // This should reset cycles_base and cycles_sum.
f887a8c9
DS
255 s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
256 s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
257 s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
258 s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
a58d79d0
DS
259
260 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
261 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
262 // has overloaded the system and we need to quit.
7baf48e9
FCE
263 // NB: this is not suppressible via --suppress-runtime-errors,
264 // because this is a system safety metric that we cannot trust
265 // unprivileged users to override.
f887a8c9
DS
266 s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
267 s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
268 s.op->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
065d5567
JS
269 s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
270 s.op->newline() << "atomic_inc (error_count());";
f887a8c9
DS
271 s.op->newline(-1) << "}";
272
273 s.op->newline() << "c->cycles_base = cycles_atend;";
274 s.op->newline() << "c->cycles_sum = 0;";
275 s.op->newline(-1) << "}";
276 s.op->newline(-1) << "}";
277 s.op->newline() << "#endif";
a58d79d0 278 }
e57b735a 279
f887a8c9
DS
280 s.op->newline(-1) << "}";
281 s.op->newline() << "#endif";
e57b735a 282
f887a8c9
DS
283 s.op->newline() << "c->probe_point = 0;"; // vacated
284 s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
285 s.op->newline() << "c->probe_name = 0;";
286 s.op->newline() << "#endif";
287 s.op->newline() << "c->probe_type = 0;";
7baf48e9
FCE
288
289
f887a8c9
DS
290 s.op->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
291 s.op->indent(1);
292 if (s.suppress_handler_errors) // PR 13306
b78a0fbb 293 {
065d5567 294 s.op->newline() << "atomic_inc (error_count());";
7baf48e9
FCE
295 }
296 else
297 {
f887a8c9
DS
298 s.op->newline() << "if (c->last_stmt != NULL)";
299 s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
300 s.op->newline(-1) << "else";
301 s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
302 s.op->indent(-1);
065d5567
JS
303 s.op->newline() << "atomic_inc (error_count());";
304 s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
305 s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
f887a8c9
DS
306 s.op->newline() << "_stp_exit ();";
307 s.op->newline(-1) << "}";
7baf48e9
FCE
308 }
309
f887a8c9 310 s.op->newline(-1) << "}";
7baf48e9
FCE
311
312
f887a8c9
DS
313 s.op->newline(-1) << "probe_epilogue:"; // context is free
314 s.op->indent(1);
e57b735a 315
f887a8c9 316 if (! s.suppress_handler_errors) // PR 13306
7baf48e9
FCE
317 {
318 // Check for excessive skip counts.
065d5567
JS
319 s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
320 s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f887a8c9
DS
321 s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
322 s.op->newline(-1) << "}";
7baf48e9 323 }
e57b735a 324
d2d39de6
JS
325 // We mustn't release the context until after all _stp_error(), so dyninst
326 // mode can still access the log buffers stored therein.
327 s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
328
329 s.op->newline() << "#if !INTERRUPTIBLE";
f887a8c9
DS
330 s.op->newline() << "local_irq_restore (flags);";
331 s.op->newline() << "#endif";
653e6a9a 332
944c9a7a 333 if (s.runtime_usermode_p())
ac34f2aa
JS
334 {
335 s.op->newline() << "errno = _stp_saved_errno;";
ac34f2aa 336 }
e481ab2e
JS
337
338 s.op->newline() << "#endif // STP_ALIBI";
339
340 if (s.runtime_usermode_p())
341 s.op->newline(-1) << "}";
440f755a 342}
e57b735a 343
e57b735a 344
440f755a 345// ------------------------------------------------------------------------
e57b735a 346
440f755a
JS
347// ------------------------------------------------------------------------
348// Dwarf derived probes. "We apologize for the inconvience."
349// ------------------------------------------------------------------------
e57b735a 350
4627ed58
JS
351static const string TOK_KERNEL("kernel");
352static const string TOK_MODULE("module");
353static const string TOK_FUNCTION("function");
354static const string TOK_INLINE("inline");
355static const string TOK_CALL("call");
4bda987e 356static const string TOK_EXPORTED("exported");
4627ed58
JS
357static const string TOK_RETURN("return");
358static const string TOK_MAXACTIVE("maxactive");
359static const string TOK_STATEMENT("statement");
360static const string TOK_ABSOLUTE("absolute");
361static const string TOK_PROCESS("process");
a794dbeb 362static const string TOK_PROVIDER("provider");
4627ed58
JS
363static const string TOK_MARK("mark");
364static const string TOK_TRACE("trace");
365static const string TOK_LABEL("label");
63b4fd14 366static const string TOK_LIBRARY("library");
576eaefe 367static const string TOK_PLT("plt");
e7d4410d
LB
368static const string TOK_METHOD("method");
369static const string TOK_CLASS("class");;
c31add50
JL
370static const string TOK_CALLEE("callee");;
371static const string TOK_CALLEES("callees");;
e57b735a 372
440f755a
JS
373// Can we handle this query with just symbol-table info?
374enum dbinfo_reqt
375{
376 dbr_unknown,
377 dbr_none, // kernel.statement(NUM).absolute
378 dbr_need_symtab, // can get by with symbol table if there's no dwarf
379 dbr_need_dwarf
380};
e57b735a 381
20e4a32c 382
673d0add 383struct dwarf_query; // forward decl
20e4a32c 384
45582cbc
JL
385static int query_cu (Dwarf_Die * cudie, dwarf_query *q);
386static void query_addr(Dwarf_Addr addr, dwarf_query *q);
387static void query_plt_statement(dwarf_query *q);
a781f401 388
440f755a
JS
389struct
390symbol_table
391{
392 module_info *mod_info; // associated module
393 map<string, func_info*> map_by_name;
1c6b77e5 394 multimap<Dwarf_Addr, func_info*> map_by_addr;
2a4acb09
JL
395 map<string, Dwarf_Addr> globals;
396 map<string, Dwarf_Addr> locals;
1c6b77e5 397 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
398 typedef pair<iterator_t, iterator_t> range_t;
399#ifdef __powerpc__
400 GElf_Word opd_section;
401#endif
2867a2a1
JS
402 void add_symbol(const char *name, bool weak, bool descriptor,
403 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a
JS
404 enum info_status get_from_elf();
405 void prepare_section_rejection(Dwfl_Module *mod);
406 bool reject_section(GElf_Word section);
440f755a
JS
407 void purge_syscall_stubs();
408 func_info *lookup_symbol(const string& name);
409 Dwarf_Addr lookup_symbol_address(const string& name);
410 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 411 func_info *get_first_func();
7a053d3b 412
440f755a
JS
413 symbol_table(module_info *mi) : mod_info(mi) {}
414 ~symbol_table();
415};
77de5e9e 416
440f755a
JS
417static bool null_die(Dwarf_Die *die)
418{
822a6a3d 419 static Dwarf_Die null;
440f755a
JS
420 return (!die || !memcmp(die, &null, sizeof(null)));
421}
c4ce66a1
JS
422
423
7a053d3b 424enum
bd2b1e68 425function_spec_type
7a053d3b 426 {
bd2b1e68
GH
427 function_alone,
428 function_and_file,
7a053d3b 429 function_file_and_line
bd2b1e68
GH
430 };
431
ec4373ff 432
bd2b1e68 433struct dwarf_builder;
f10534c6 434struct dwarf_var_expanding_visitor;
77de5e9e 435
2930abc7 436
b20febf3
FCE
437// XXX: This class is a candidate for subclassing to separate
438// the relocation vs non-relocation variants. Likewise for
439// kprobe vs kretprobe variants.
440
441struct dwarf_derived_probe: public derived_probe
b55bc428 442{
b20febf3
FCE
443 dwarf_derived_probe (const string& function,
444 const string& filename,
445 int line,
446 const string& module,
447 const string& section,
448 Dwarf_Addr dwfl_addr,
2930abc7 449 Dwarf_Addr addr,
b20febf3
FCE
450 dwarf_query & q,
451 Dwarf_Die* scope_die);
20e4a32c 452
b20febf3
FCE
453 string module;
454 string section;
455 Dwarf_Addr addr;
63b4fd14 456 string path;
27dc09b1 457 bool has_process;
2930abc7 458 bool has_return;
c9bad430 459 bool has_maxactive;
63b4fd14 460 bool has_library;
c9bad430 461 long maxactive_val;
4ad95bbc 462 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
463 string user_path;
464 string user_lib;
b95e2b79 465 bool access_vars;
2930abc7 466
af234c40
JS
467 unsigned saved_longs, saved_strings;
468 dwarf_derived_probe* entry_handler;
469
b8da0ad1 470 void printsig (std::ostream &o) const;
6b66b9f7 471 virtual void join_group (systemtap_session& s);
3689db05 472 void emit_probe_local_init(systemtap_session& s, translator_output * o);
d0bfd2ac 473 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 474
42e38653 475 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
476 void print_dupe_stamp(ostream& o);
477
bd2b1e68 478 // Pattern registration helpers.
7a053d3b 479 static void register_statement_variants(match_node * root,
27dc09b1 480 dwarf_builder * dw,
42e38653 481 privilege_t privilege);
fd6602a0 482 static void register_function_variants(match_node * root,
27dc09b1 483 dwarf_builder * dw,
42e38653 484 privilege_t privilege);
440d9b00
DB
485 static void register_function_and_statement_variants(systemtap_session& s,
486 match_node * root,
27dc09b1 487 dwarf_builder * dw,
42e38653 488 privilege_t privilege);
b1615c74
JS
489 static void register_sdt_variants(systemtap_session& s,
490 match_node * root,
491 dwarf_builder * dw);
492 static void register_plt_variants(systemtap_session& s,
493 match_node * root,
494 dwarf_builder * dw);
c4ce66a1 495 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
496
497protected:
498 dwarf_derived_probe(probe *base,
499 probe_point *location,
500 Dwarf_Addr addr,
501 bool has_return):
74fe61bc
LB
502 derived_probe(base, location), addr(addr), has_process(0),
503 has_return(has_return), has_maxactive(0), has_library(0),
504 maxactive_val(0), access_vars(false), saved_longs(0),
505 saved_strings(0), entry_handler(0)
6b66b9f7
JS
506 {}
507
508private:
d0bfd2ac 509 list<string> args;
8c67c337 510 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
511};
512
dc38c0ae 513
6b66b9f7 514struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 515{
6d0f3f0c 516 int pid; // 0 => unrestricted
0973d815 517
6d0f3f0c
FCE
518 uprobe_derived_probe (const string& function,
519 const string& filename,
520 int line,
521 const string& module,
6d0f3f0c
FCE
522 const string& section,
523 Dwarf_Addr dwfl_addr,
524 Dwarf_Addr addr,
525 dwarf_query & q,
6b66b9f7
JS
526 Dwarf_Die* scope_die):
527 dwarf_derived_probe(function, filename, line, module, section,
528 dwfl_addr, addr, q, scope_die), pid(0)
529 {}
6d0f3f0c 530
0973d815
FCE
531 // alternate constructor for process(PID).statement(ADDR).absolute
532 uprobe_derived_probe (probe *base,
533 probe_point *location,
534 int pid,
535 Dwarf_Addr addr,
6b66b9f7
JS
536 bool has_return):
537 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
538 {}
9ace370f 539
6d0f3f0c 540 void join_group (systemtap_session& s);
2865d17a 541
42e38653 542 void emit_privilege_assertion (translator_output*);
8f6d8c2b 543 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
544 void getargs(std::list<std::string> &arg_set) const;
545 void saveargs(int nargs);
546private:
547 list<string> args;
6d0f3f0c
FCE
548};
549
dc38c0ae
DS
550struct dwarf_derived_probe_group: public derived_probe_group
551{
552private:
b20febf3
FCE
553 multimap<string,dwarf_derived_probe*> probes_by_module;
554 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
555
556public:
08b5a50c 557 dwarf_derived_probe_group() {}
b20febf3
FCE
558 void enroll (dwarf_derived_probe* probe);
559 void emit_module_decls (systemtap_session& s);
560 void emit_module_init (systemtap_session& s);
b4be7cbc 561 void emit_module_refresh (systemtap_session& s);
b20febf3 562 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
563};
564
565
20c6c071 566// Helper struct to thread through the dwfl callbacks.
2c384610 567struct base_query
20c6c071 568{
c4ce66a1
JS
569 base_query(dwflpp & dw, literal_map_t const & params);
570 base_query(dwflpp & dw, const string & module_val);
2c384610 571 virtual ~base_query() {}
bd2b1e68 572
5227f1ea 573 systemtap_session & sess;
2c384610 574 dwflpp & dw;
5227f1ea 575
070764c0
JL
576 // Used to keep track of which modules were visited during
577 // iterate_over_modules()
578 set<string> visited_modules;
579
bd2b1e68 580 // Parameter extractors.
86bf665e 581 static bool has_null_param(literal_map_t const & params,
888af770 582 string const & k);
86bf665e 583 static bool get_string_param(literal_map_t const & params,
bd2b1e68 584 string const & k, string & v);
86bf665e 585 static bool get_number_param(literal_map_t const & params,
bd2b1e68 586 string const & k, long & v);
86bf665e 587 static bool get_number_param(literal_map_t const & params,
c239d28c 588 string const & k, Dwarf_Addr & v);
bbbc7241 589 static void query_library_callback (base_query *me, const char *data);
45cdb40e 590 static void query_plt_callback (base_query *me, const char *link, size_t addr);
f301a9ff 591 virtual void query_library (const char *data) = 0;
576eaefe 592 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 593
b55bc428 594
2c384610
DS
595 // Extracted parameters.
596 bool has_kernel;
91af0778
FCE
597 bool has_module;
598 bool has_process;
63b4fd14 599 bool has_library;
576eaefe
SC
600 bool has_plt;
601 bool has_statement;
2c384610 602 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 603 string path; // executable path if module is a .so
576eaefe 604 string plt_val; // has_plt => plt wildcard
2c384610
DS
605
606 virtual void handle_query_module() = 0;
607};
608
609
c4ce66a1 610base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 611 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 612{
91af0778 613 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
614 if (has_kernel)
615 module_val = "kernel";
91af0778
FCE
616
617 has_module = get_string_param (params, TOK_MODULE, module_val);
618 if (has_module)
619 has_process = false;
4baf0e53 620 else
d0a7f5a9 621 {
63b4fd14 622 string library_name;
576eaefe 623 long statement_num_val;
d0a7f5a9 624 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 625 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
626 if ((has_plt = has_null_param (params, TOK_PLT)))
627 plt_val = "*";
628 else has_plt = get_string_param (params, TOK_PLT, plt_val);
629 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
630
84c84ac4 631 if (has_process)
05fb3e0c 632 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
633 if (has_library)
634 {
635 if (! contains_glob_chars (library_name))
636 {
05fb3e0c
WF
637 path = path_remove_sysroot(sess, module_val);
638 module_val = find_executable (library_name, sess.sysroot,
639 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
640 if (module_val.find('/') == string::npos)
641 {
642 // We didn't find library_name so use iterate_over_libraries
643 module_val = path;
644 path = library_name;
645 }
84c84ac4
SC
646 }
647 else
648 path = library_name;
649 }
d0a7f5a9 650 }
91af0778
FCE
651
652 assert (has_kernel || has_process || has_module);
2c384610
DS
653}
654
c4ce66a1 655base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
656 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
657 module_val(module_val)
c4ce66a1
JS
658{
659 // NB: This uses '/' to distinguish between kernel modules and userspace,
660 // which means that userspace modules won't get any PATH searching.
661 if (module_val.find('/') == string::npos)
662 {
663 has_kernel = (module_val == TOK_KERNEL);
664 has_module = !has_kernel;
665 has_process = false;
666 }
667 else
668 {
669 has_kernel = has_module = false;
670 has_process = true;
671 }
672}
673
2c384610 674bool
86bf665e 675base_query::has_null_param(literal_map_t const & params,
2c384610
DS
676 string const & k)
677{
888af770 678 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
679}
680
681
682bool
86bf665e 683base_query::get_string_param(literal_map_t const & params,
2c384610
DS
684 string const & k, string & v)
685{
686 return derived_probe_builder::get_param (params, k, v);
687}
688
689
690bool
86bf665e 691base_query::get_number_param(literal_map_t const & params,
2c384610
DS
692 string const & k, long & v)
693{
694 int64_t value;
695 bool present = derived_probe_builder::get_param (params, k, value);
696 v = (long) value;
697 return present;
698}
699
700
701bool
86bf665e 702base_query::get_number_param(literal_map_t const & params,
2c384610
DS
703 string const & k, Dwarf_Addr & v)
704{
705 int64_t value;
706 bool present = derived_probe_builder::get_param (params, k, value);
707 v = (Dwarf_Addr) value;
708 return present;
709}
710
2c384610
DS
711struct dwarf_query : public base_query
712{
e1278bd4 713 dwarf_query(probe * base_probe,
2c384610
DS
714 probe_point * base_loc,
715 dwflpp & dw,
86bf665e 716 literal_map_t const & params,
b642c901
SC
717 vector<derived_probe *> & results,
718 const string user_path,
719 const string user_lib);
2c384610 720
c4ce66a1 721 vector<derived_probe *> & results;
8f14e444 722 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
723 probe * base_probe;
724 probe_point * base_loc;
b642c901
SC
725 string user_path;
726 string user_lib;
c4ce66a1 727
2c384610 728 virtual void handle_query_module();
5f0a03a6
JK
729 void query_module_dwarf();
730 void query_module_symtab();
5d5bd369 731 void query_library (const char *data);
576eaefe 732 void query_plt (const char *entry, size_t addr);
2c384610 733
2930abc7
FCE
734 void add_probe_point(string const & funcname,
735 char const * filename,
736 int line,
737 Dwarf_Die *scope_die,
738 Dwarf_Addr addr);
36f9dd1d 739
857bdfd1
JS
740 // Track addresses we've already seen in a given module
741 set<Dwarf_Addr> alias_dupes;
742
7fdd3e2c
JS
743 // Track inlines we've already seen as well
744 // NB: this can't be compared just by entrypc, as inlines can overlap
745 set<inline_instance_info> inline_dupes;
746
e2941743
JL
747 // Used in .callee[s] probes, when calling iterate_over_callees() (which
748 // provides the actual stack). Retains the addrs of the callers unwind addr
749 // where the callee is found. Specifies multiple callers. E.g. when a callee
750 // at depth 2 is found, callers[1] has the addr of the caller, and callers[0]
751 // has the addr of the caller's caller.
752 stack<Dwarf_Addr> *callers;
753
20c6c071
GH
754 bool has_function_str;
755 bool has_statement_str;
756 bool has_function_num;
757 bool has_statement_num;
7a053d3b
RM
758 string statement_str_val;
759 string function_str_val;
c239d28c
GH
760 Dwarf_Addr statement_num_val;
761 Dwarf_Addr function_num_val;
20c6c071 762
b8da0ad1 763 bool has_call;
4bda987e 764 bool has_exported;
b8da0ad1 765 bool has_inline;
20c6c071
GH
766 bool has_return;
767
c9bad430
DS
768 bool has_maxactive;
769 long maxactive_val;
770
20c6c071
GH
771 bool has_label;
772 string label_val;
773
c31add50
JL
774 bool has_callee;
775 string callee_val;
776
777 bool has_callees_num;
778 long callees_num_val;
779
20c6c071
GH
780 bool has_relative;
781 long relative_val;
782
37ebca01
FCE
783 bool has_absolute;
784
467bea43
SC
785 bool has_mark;
786
5f0a03a6
JK
787 enum dbinfo_reqt dbinfo_reqt;
788 enum dbinfo_reqt assess_dbinfo_reqt();
789
7d6d0afc 790 void parse_function_spec(const string & spec);
20c6c071 791 function_spec_type spec_type;
7d6d0afc 792 vector<string> scopes;
20c6c071
GH
793 string function;
794 string file;
4a81c0d9
JL
795 lineno_t lineno_type;
796 int linenos[2];
5f0a03a6 797 bool query_done; // Found exact match
20c6c071 798
5a617dc6
JL
799 // Holds the prologue end of the current function
800 Dwarf_Addr prologue_end;
801
bd25380d 802 set<string> filtered_srcfiles;
7e1279ea
FCE
803
804 // Map official entrypc -> func_info object
86bf665e
TM
805 inline_instance_map_t filtered_inlines;
806 func_info_map_t filtered_functions;
4df79aaf 807
959ccfed
JL
808 // Helper when we want to iterate over both
809 base_func_info_map_t filtered_all();
810
4df79aaf 811 void query_module_functions ();
e772a6e7
JL
812
813 string final_function_name(const string& final_func,
814 const string& final_file,
815 int final_line);
b55bc428
FCE
816};
817
98afd80e 818
435f53a7
FCE
819static void delete_session_module_cache (systemtap_session& s); // forward decl
820
821
98afd80e 822struct dwarf_builder: public derived_probe_builder
b55bc428 823{
665e1256 824 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 825 map <string,dwflpp*> user_dw;
b642c901
SC
826 string user_path;
827 string user_lib;
44ffe90c
JL
828
829 // Holds modules to suggest functions from. NB: aggregates over
830 // recursive calls to build() when deriving globby probes.
831 set <string> modules_seen;
832
ae2552da 833 dwarf_builder() {}
aa30ccd3 834
ae2552da 835 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 836 {
ea14cf67
FCE
837 if (kern_dw[module] == 0)
838 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 839 return kern_dw[module];
707bf35e
JS
840 }
841
842 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
843 {
ea14cf67
FCE
844 if (user_dw[module] == 0)
845 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
846 return user_dw[module];
847 }
7a24d422
FCE
848
849 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 850 void dwarf_build_no_more (bool)
aa30ccd3 851 {
435f53a7
FCE
852 delete_map(kern_dw);
853 delete_map(user_dw);
7a24d422
FCE
854 }
855
856 void build_no_more (systemtap_session &s)
857 {
858 dwarf_build_no_more (s.verbose > 3);
435f53a7 859 delete_session_module_cache (s);
aa30ccd3
FCE
860 }
861
e38d6504
RM
862 ~dwarf_builder()
863 {
7a24d422 864 dwarf_build_no_more (false);
c8959a29 865 }
aa30ccd3 866
5227f1ea 867 virtual void build(systemtap_session & sess,
7a053d3b 868 probe * base,
20c6c071 869 probe_point * location,
86bf665e 870 literal_map_t const & parameters,
20c6c071 871 vector<derived_probe *> & finished_results);
b55bc428
FCE
872};
873
5111fc3e 874
e1278bd4 875dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
876 probe_point * base_loc,
877 dwflpp & dw,
86bf665e 878 literal_map_t const & params,
b642c901
SC
879 vector<derived_probe *> & results,
880 const string user_path,
881 const string user_lib)
e2941743
JL
882 : base_query(dw, params), results(results), base_probe(base_probe),
883 base_loc(base_loc), user_path(user_path), user_lib(user_lib),
5a617dc6 884 callers(NULL), has_relative(false), relative_val(0), prologue_end(0)
bd2b1e68
GH
885{
886 // Reduce the query to more reasonable semantic values (booleans,
887 // extracted strings, numbers, etc).
bd2b1e68
GH
888 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
889 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
890
891 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
892 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
893
0f336e95 894 has_label = get_string_param(params, TOK_LABEL, label_val);
c31add50
JL
895 has_callee = get_string_param(params, TOK_CALLEE, callee_val);
896 if (has_null_param(params, TOK_CALLEES))
897 { // .callees ==> .callees(1) (also equivalent to .callee("*"))
898 has_callees_num = true;
899 callees_num_val = 1;
900 }
901 else
902 {
903 has_callees_num = get_number_param(params, TOK_CALLEES, callees_num_val);
904 if (has_callees_num && callees_num_val < 1)
905 throw SEMANTIC_ERROR(_(".callees(N) only acceptable for N >= 1"),
906 base_probe->tok);
907 }
0f336e95 908
b8da0ad1 909 has_call = has_null_param(params, TOK_CALL);
4bda987e 910 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 911 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 912 has_return = has_null_param(params, TOK_RETURN);
c9bad430 913 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 914 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 915 has_mark = false;
37ebca01 916
bd2b1e68 917 if (has_function_str)
7d6d0afc 918 parse_function_spec(function_str_val);
bd2b1e68 919 else if (has_statement_str)
7d6d0afc 920 parse_function_spec(statement_str_val);
0daad364 921
5f0a03a6
JK
922 dbinfo_reqt = assess_dbinfo_reqt();
923 query_done = false;
0daad364
JS
924}
925
926
2c384610 927void
5f0a03a6 928dwarf_query::query_module_dwarf()
2c384610
DS
929{
930 if (has_function_num || has_statement_num)
931 {
932 // If we have module("foo").function(0xbeef) or
933 // module("foo").statement(0xbeef), the address is relative
934 // to the start of the module, so we seek the function
935 // number plus the module's bias.
6b517475
JS
936 Dwarf_Addr addr = has_function_num ?
937 function_num_val : statement_num_val;
08d1d520
MW
938
939 // These are raw addresses, we need to know what the elf_bias
940 // is to feed it to libdwfl based functions.
941 Dwarf_Addr elf_bias;
942 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
943 assert(elf);
944 addr += elf_bias;
6b517475 945 query_addr(addr, this);
2c384610
DS
946 }
947 else
948 {
949 // Otherwise if we have a function("foo") or statement("foo")
950 // specifier, we have to scan over all the CUs looking for
951 // the function(s) in question
952 assert(has_function_str || has_statement_str);
4df79aaf
JS
953
954 // For simple cases, no wildcard and no source:line, we can do a very
955 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
956 if (spec_type == function_alone &&
957 !dw.name_has_wildcard(function) &&
958 !startswith(function, "_Z"))
4df79aaf
JS
959 query_module_functions();
960 else
337b7c44 961 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
962 }
963}
964
5f0a03a6
JK
965static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
966 dwarf_query * q);
967
91bb9081
LB
968static void
969query_symtab_func_info (func_info & fi, dwarf_query * q)
970{
971 assert(null_die(&fi.die));
972
973 Dwarf_Addr addr = fi.addr;
974
975 // Now compensate for the dw bias because the addresses come
976 // from dwfl_module_symtab, so fi->addr is NOT a normal dw address.
977 q->dw.get_module_dwarf(false, false);
978 addr -= q->dw.module_bias;
979
980 // If there are already probes in this module, lets not duplicate.
981 // This can come from other weak symbols/aliases or existing
a41f2ad7
JS
982 // matches from Dwarf DIE functions. Try to add this addr to the
983 // collection, and only continue if it was new.
984 if (q->alias_dupes.insert(addr).second)
985 query_func_info(addr, fi, q);
91bb9081
LB
986}
987
5f0a03a6
JK
988void
989dwarf_query::query_module_symtab()
990{
991 // Get the symbol table if it's necessary, sufficient, and not already got.
992 if (dbinfo_reqt == dbr_need_dwarf)
993 return;
994
995 module_info *mi = dw.mod_info;
996 if (dbinfo_reqt == dbr_need_symtab)
997 {
998 if (mi->symtab_status == info_unknown)
5f52fafe 999 mi->get_symtab();
5f0a03a6
JK
1000 if (mi->symtab_status == info_absent)
1001 return;
1002 }
1003
1004 func_info *fi = NULL;
1005 symbol_table *sym_table = mi->sym_table;
1006
1007 if (has_function_str)
1008 {
1009 // Per dwarf_query::assess_dbinfo_reqt()...
1010 assert(spec_type == function_alone);
1011 if (dw.name_has_wildcard(function_str_val))
1012 {
2e67a43b 1013 symbol_table::iterator_t iter;
1c6b77e5
JS
1014 for (iter = sym_table->map_by_addr.begin();
1015 iter != sym_table->map_by_addr.end();
2e67a43b 1016 ++iter)
5f0a03a6 1017 {
1c6b77e5 1018 fi = iter->second;
5f0a03a6
JK
1019 if (!null_die(&fi->die))
1020 continue; // already handled in query_module_dwarf()
1021 if (dw.function_name_matches_pattern(fi->name, function_str_val))
91bb9081 1022 query_symtab_func_info(*fi, this);
5f0a03a6
JK
1023 }
1024 }
1025 else
1026 {
1027 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 1028 if (fi && !fi->descriptor && null_die(&fi->die))
91bb9081 1029 query_symtab_func_info(*fi, this);
5f0a03a6 1030 }
5f0a03a6
JK
1031 }
1032}
1033
1034void
1035dwarf_query::handle_query_module()
1036{
f4faaf86
JS
1037 if (has_plt && has_statement_num)
1038 {
1039 query_plt_statement (this);
1040 return;
1041 }
1042
0035051e 1043 bool report = dbinfo_reqt == dbr_need_dwarf;
1c6b77e5
JS
1044 dw.get_module_dwarf(false, report);
1045
1046 // prebuild the symbol table to resolve aliases
5f52fafe 1047 dw.mod_info->get_symtab();
1c6b77e5 1048
857bdfd1
JS
1049 // reset the dupe-checking for each new module
1050 alias_dupes.clear();
7fdd3e2c 1051 inline_dupes.clear();
857bdfd1 1052
5f0a03a6
JK
1053 if (dw.mod_info->dwarf_status == info_present)
1054 query_module_dwarf();
1c6b77e5 1055
91bb9081
LB
1056 // Consult the symbol table, asm and weak functions can show up
1057 // in the symbol table but not in dwarf and minidebuginfo is
1058 // located in the gnu_debugdata section, alias_dupes checking
1059 // is done before adding any probe points
1060 if (!query_done && !pending_interrupts)
5f0a03a6
JK
1061 query_module_symtab();
1062}
1063
2c384610 1064
7d6d0afc
JS
1065void
1066dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1067{
4a81c0d9
JL
1068 lineno_type = ABSOLUTE;
1069 linenos[0] = linenos[1] = 0;
1d12a9b2 1070
91699a70 1071 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1072
7d6d0afc 1073 // look for named scopes
91699a70
JS
1074 scope_pos = spec.rfind("::");
1075 if (scope_pos != string::npos)
bd2b1e68 1076 {
91699a70
JS
1077 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1078 scope_pos += 2;
bd2b1e68 1079 }
91699a70
JS
1080 else
1081 scope_pos = 0;
bd2b1e68 1082
7d6d0afc
JS
1083 // look for a source separator
1084 src_pos = spec.find('@', scope_pos);
1085 if (src_pos == string::npos)
bd2b1e68 1086 {
7d6d0afc
JS
1087 function = spec.substr(scope_pos);
1088 spec_type = function_alone;
bd2b1e68 1089 }
7d6d0afc 1090 else
879eb9e9 1091 {
7d6d0afc 1092 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1093
7d6d0afc
JS
1094 // look for a line-number separator
1095 line_pos = spec.find_first_of(":+", src_pos);
1096 if (line_pos == string::npos)
1097 {
1098 file = spec.substr(src_pos + 1);
1099 spec_type = function_and_file;
1100 }
1101 else
1102 {
1103 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1104
1105 // classify the line spec
1106 spec_type = function_file_and_line;
1107 if (spec[line_pos] == '+')
4a81c0d9 1108 lineno_type = RELATIVE;
7d6d0afc
JS
1109 else if (spec[line_pos + 1] == '*' &&
1110 spec.length() == line_pos + 2)
4a81c0d9 1111 lineno_type = WILDCARD;
7d6d0afc 1112 else
4a81c0d9 1113 lineno_type = ABSOLUTE;
7d6d0afc 1114
4a81c0d9 1115 if (lineno_type != WILDCARD)
7d6d0afc
JS
1116 try
1117 {
1118 // try to parse either N or N-M
1119 dash_pos = spec.find('-', line_pos + 1);
1120 if (dash_pos == string::npos)
4a81c0d9 1121 linenos[0] = linenos[1] = lex_cast<int>(spec.substr(line_pos + 1));
7d6d0afc
JS
1122 else
1123 {
4a81c0d9
JL
1124 lineno_type = RANGE;
1125 linenos[0] = lex_cast<int>(spec.substr(line_pos + 1,
7d6d0afc 1126 dash_pos - line_pos - 1));
4a81c0d9
JL
1127 linenos[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1128 if (linenos[0] > linenos[1])
1129 throw runtime_error("bad range");
7d6d0afc
JS
1130 }
1131 }
1132 catch (runtime_error & exn)
1133 {
1134 goto bad;
1135 }
1136 }
bd2b1e68
GH
1137 }
1138
7d6d0afc
JS
1139 if (function.empty() ||
1140 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1141 goto bad;
1142
7d6d0afc 1143 if (sess.verbose > 2)
bd2b1e68 1144 {
b530b5b3
LB
1145 //clog << "parsed '" << spec << "'";
1146 clog << _F("parse '%s'", spec.c_str());
41c262f3 1147
7d6d0afc
JS
1148 if (!scopes.empty())
1149 clog << ", scope '" << scopes[0] << "'";
1150 for (unsigned i = 1; i < scopes.size(); ++i)
1151 clog << "::'" << scopes[i] << "'";
41c262f3 1152
7d6d0afc
JS
1153 clog << ", func '" << function << "'";
1154
1155 if (spec_type != function_alone)
1156 clog << ", file '" << file << "'";
1157
1158 if (spec_type == function_file_and_line)
1159 {
1160 clog << ", line ";
4a81c0d9 1161 switch (lineno_type)
7d6d0afc
JS
1162 {
1163 case ABSOLUTE:
4a81c0d9 1164 clog << linenos[0];
7d6d0afc
JS
1165 break;
1166
1167 case RELATIVE:
4a81c0d9 1168 clog << "+" << linenos[0];
7d6d0afc
JS
1169 break;
1170
1171 case RANGE:
4a81c0d9 1172 clog << linenos[0] << " - " << linenos[1];
7d6d0afc
JS
1173 break;
1174
1175 case WILDCARD:
1176 clog << "*";
1177 break;
1178 }
1179 }
1180
1181 clog << endl;
bd2b1e68
GH
1182 }
1183
7d6d0afc
JS
1184 return;
1185
1186bad:
dc09353a 1187 throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1188 base_probe->tok);
bd2b1e68
GH
1189}
1190
05fb3e0c
WF
1191string path_remove_sysroot(const systemtap_session& sess, const string& path)
1192{
1193 size_t pos;
1194 string retval = path;
1195 if (!sess.sysroot.empty() &&
1196 (pos = retval.find(sess.sysroot)) != string::npos)
1197 retval.replace(pos, sess.sysroot.length(), "/");
1198 return retval;
1199}
bd2b1e68 1200
36f9dd1d 1201void
1ffb8bd1 1202dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1203 const char* filename,
36f9dd1d 1204 int line,
b20febf3 1205 Dwarf_Die* scope_die,
36f9dd1d
FCE
1206 Dwarf_Addr addr)
1207{
b20febf3 1208 string reloc_section; // base section for relocation purposes
27646582 1209 Dwarf_Addr reloc_addr; // relocated
b20febf3 1210 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1211 string funcname = dw_funcname;
36f9dd1d 1212
37ebca01
FCE
1213 assert (! has_absolute); // already handled in dwarf_builder::build()
1214
f4faaf86 1215 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1216
1ffb8bd1 1217 // If we originally used the linkage name, then let's call it that way
1ffb8bd1 1218 const char* linkage_name;
91bb9081 1219 if (!null_die(scope_die) && startswith (this->function, "_Z")
f450a7e3 1220 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1221 funcname = linkage_name;
1222
7f9f3386
FCE
1223 if (sess.verbose > 1)
1224 {
b530b5b3 1225 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1226 if (string(module) == TOK_KERNEL)
b530b5b3 1227 clog << _(" kernel");
91af0778 1228 else if (has_module)
b530b5b3 1229 clog << _(" module=") << module;
91af0778 1230 else if (has_process)
b530b5b3 1231 clog << _(" process=") << module;
b20febf3 1232 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1233 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1234 }
4baf0e53 1235
27646582 1236 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1237 addr, has_return);
b20febf3
FCE
1238 if (sess.verbose > 1)
1239 clog << endl;
7f9f3386 1240
84048984
FCE
1241 if (module == TOK_KERNEL)
1242 {
1243 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1244 reloc_addr = addr - sess.sym_stext;
37ebca01 1245 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1246 }
1247
b20febf3
FCE
1248 if (! bad)
1249 {
1a0dbc5a 1250 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1251
1252 if (has_process)
1253 {
05fb3e0c 1254 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1255 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1256 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1257 *this, scope_die));
1258 }
1259 else
1260 {
1261 assert (has_kernel || has_module);
1262 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1263 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1264 *this, scope_die));
1265 }
b20febf3 1266 }
2930abc7
FCE
1267}
1268
5f0a03a6
JK
1269enum dbinfo_reqt
1270dwarf_query::assess_dbinfo_reqt()
1271{
1272 if (has_absolute)
1273 {
1274 // kernel.statement(NUM).absolute
1275 return dbr_none;
1276 }
c31add50 1277 if (has_inline || has_label || has_callee || has_callees_num)
5f0a03a6
JK
1278 {
1279 // kernel.function("f").inline or module("m").function("f").inline
1280 return dbr_need_dwarf;
1281 }
1282 if (has_function_str && spec_type == function_alone)
1283 {
1284 // kernel.function("f") or module("m").function("f")
1285 return dbr_need_symtab;
1286 }
1287 if (has_statement_num)
1288 {
1289 // kernel.statement(NUM) or module("m").statement(NUM)
1290 // Technically, all we need is the module offset (or _stext, for
1291 // the kernel). But for that we need either the ELF file or (for
1292 // _stext) the symbol table. In either case, the symbol table
1293 // is available, and that allows us to map the NUM (address)
1294 // to a function, which is goodness.
1295 return dbr_need_symtab;
1296 }
1297 if (has_function_num)
1298 {
1299 // kernel.function(NUM) or module("m").function(NUM)
1300 // Need the symbol table so we can back up from NUM to the
1301 // start of the function.
1302 return dbr_need_symtab;
1303 }
1304 // Symbol table tells us nothing about source files or line numbers.
1305 return dbr_need_dwarf;
1306}
2930abc7 1307
e772a6e7
JL
1308string
1309dwarf_query::final_function_name(const string& final_func,
1310 const string& final_file,
1311 int final_line)
1312{
1313 string final_name = final_func;
1314 if (final_file != "")
1315 {
1316 final_name += ("@" + final_file);
1317 if (final_line > 0)
1318 final_name += (":" + lex_cast(final_line));
1319 }
1320 return final_name;
1321}
2930abc7 1322
959ccfed
JL
1323base_func_info_map_t
1324dwarf_query::filtered_all(void)
1325{
1326 vector<base_func_info> r;
1327 func_info_map_t::const_iterator f;
1328 for (f = filtered_functions.begin();
1329 f != filtered_functions.end(); ++f)
1330 r.push_back(*f);
1331 inline_instance_map_t::const_iterator i;
1332 for (i = filtered_inlines.begin();
1333 i != filtered_inlines.end(); ++i)
1334 r.push_back(*i);
1335 return r;
1336}
1337
b8da0ad1
FCE
1338// The critical determining factor when interpreting a pattern
1339// string is, perhaps surprisingly: "presence of a lineno". The
1340// presence of a lineno changes the search strategy completely.
1341//
1342// Compare the two cases:
1343//
1344// 1. {statement,function}(foo@file.c:lineno)
1345// - find the files matching file.c
1346// - in each file, find the functions matching foo
1347// - query the file for line records matching lineno
1348// - iterate over the line records,
1349// - and iterate over the functions,
1350// - if(haspc(function.DIE, line.addr))
1351// - if looking for statements: probe(lineno.addr)
1352// - if looking for functions: probe(function.{entrypc,return,etc.})
1353//
1354// 2. {statement,function}(foo@file.c)
1355// - find the files matching file.c
1356// - in each file, find the functions matching foo
1357// - probe(function.{entrypc,return,etc.})
1358//
1359// Thus the first decision we make is based on the presence of a
1360// lineno, and we enter entirely different sets of callbacks
1361// depending on that decision.
1362//
1363// Note that the first case is a generalization fo the second, in that
1364// we could theoretically search through line records for matching
1365// file names (a "table scan" in rdbms lingo). Luckily, file names
1366// are already cached elsewhere, so we can do an "index scan" as an
1367// optimization.
7e1279ea 1368
bd2b1e68 1369static void
4cd232e4 1370query_statement (string const & func,
20e4a32c 1371 char const * file,
4cd232e4 1372 int line,
bcc12710 1373 Dwarf_Die *scope_die,
20e4a32c 1374 Dwarf_Addr stmt_addr,
4cd232e4 1375 dwarf_query * q)
bd2b1e68 1376{
39bcd429
FCE
1377 try
1378 {
cee35f73 1379 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1380 line, scope_die, stmt_addr);
39bcd429
FCE
1381 }
1382 catch (const semantic_error& e)
1383 {
1384 q->sess.print_error (e);
1385 }
bd2b1e68
GH
1386}
1387
6b517475
JS
1388static void
1389query_addr(Dwarf_Addr addr, dwarf_query *q)
1390{
1391 dwflpp &dw = q->dw;
1392
08d1d520
MW
1393 if (q->sess.verbose > 2)
1394 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1395
1396 // First pick which CU contains this address
1397 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1398 if (!cudie) // address could be wildly out of range
1399 return;
1400 dw.focus_on_cu(cudie);
1401
1402 // Now compensate for the dw bias
1403 addr -= dw.module_bias;
1404
1405 // Per PR5787, we look up the scope die even for
1406 // statement_num's, for blacklist sensitivity and $var
1407 // resolution purposes.
1408
1409 // Find the scopes containing this address
1410 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1411 if (scopes.empty())
1412 return;
1413
1414 // Look for the innermost containing function
1415 Dwarf_Die *fnscope = NULL;
1416 for (size_t i = 0; i < scopes.size(); ++i)
1417 {
1418 int tag = dwarf_tag(&scopes[i]);
1419 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1420 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1421 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1422 {
1423 fnscope = &scopes[i];
1424 break;
1425 }
1426 }
1427 if (!fnscope)
1428 return;
1429 dw.focus_on_function(fnscope);
1430
1431 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1432
1433 const char *file = dwarf_decl_file(fnscope);
1434 int line;
1435 dwarf_decl_line(fnscope, &line);
1436
1437 // Function probes should reset the addr to the function entry
1438 // and possibly perform prologue searching
1439 if (q->has_function_num)
1440 {
1bbf3f90
JS
1441 if (!dw.die_entrypc(fnscope, &addr))
1442 return;
6b517475 1443 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
b5b9879f
JL
1444 (q->sess.prologue_searching ||
1445 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
6b517475
JS
1446 {
1447 func_info func;
1448 func.die = *fnscope;
1449 func.name = dw.function_name;
1450 func.decl_file = file;
1451 func.decl_line = line;
1452 func.entrypc = addr;
1453
1454 func_info_map_t funcs(1, func);
1455 dw.resolve_prologue_endings (funcs);
5a617dc6
JL
1456 q->prologue_end = funcs[0].prologue_end;
1457
1458 // PR13200: if it's a .return probe, we need to emit a *retprobe based
1459 // on the entrypc so here we only use prologue_end for non .return
1460 // probes (note however that .return probes still take advantage of
1461 // prologue_end: PR14436)
1462 if (!q->has_return)
1463 addr = funcs[0].prologue_end;
6b517475
JS
1464 }
1465 }
1466 else
1467 {
de797211
JL
1468 Dwarf_Line *address_line = dwarf_getsrc_die(cudie, addr);
1469 Dwarf_Addr address_line_addr = addr;
6b517475
JS
1470 if (address_line)
1471 {
bf5974d6
JL
1472 file = DWARF_LINESRC(address_line);
1473 line = DWARF_LINENO(address_line);
1474 address_line_addr = DWARF_LINEADDR(address_line);
6b517475
JS
1475 }
1476
1477 // Verify that a raw address matches the beginning of a
1478 // statement. This is a somewhat lame check that the address
1479 // is at the start of an assembly instruction. Mark probes are in the
1480 // middle of a macro and thus not strictly at a statement beginning.
1481 // Guru mode may override this check.
de797211 1482 if (!q->has_mark && (!address_line || address_line_addr != addr))
6b517475
JS
1483 {
1484 stringstream msg;
2a97f50b 1485 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1486 addr);
6b517475 1487 if (address_line)
de797211 1488 msg << _F(" (try %#" PRIx64 ")", address_line_addr);
6b517475 1489 else
b530b5b3
LB
1490 msg << _F(" (no line info found for '%s', in module '%s')",
1491 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475 1492 if (! q->sess.guru_mode)
dc09353a 1493 throw SEMANTIC_ERROR(msg.str());
2713ea24 1494 else
6b517475
JS
1495 q->sess.print_warning(msg.str());
1496 }
1497 }
1498
1499 // Build a probe at this point
1500 query_statement(dw.function_name, file, line, scope, addr, q);
1501}
1502
f4faaf86
JS
1503static void
1504query_plt_statement(dwarf_query *q)
1505{
1506 assert (q->has_plt && q->has_statement_num);
1507
1508 Dwarf_Addr addr = q->statement_num_val;
1509 if (q->sess.verbose > 2)
1510 clog << "query_plt_statement 0x" << hex << addr << dec << endl;
1511
1512 // First adjust the raw address to dwfl's elf bias.
1513 Dwarf_Addr elf_bias;
1514 Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
1515 assert(elf);
1516 addr += elf_bias;
1517
1518 // Now compensate for the dw bias
1519 q->dw.get_module_dwarf(false, false);
1520 addr -= q->dw.module_bias;
1521
1522 // Build a probe at this point
1523 query_statement(q->plt_val, NULL, -1, NULL, addr, q);
1524}
1525
8096dd7d
JS
1526static void
1527query_label (string const & func,
1528 char const * label,
1529 char const * file,
1530 int line,
1531 Dwarf_Die *scope_die,
1532 Dwarf_Addr stmt_addr,
1533 dwarf_query * q)
1534{
6b517475
JS
1535 assert (q->has_statement_str || q->has_function_str);
1536
8096dd7d
JS
1537 // weed out functions whose decl_file isn't one of
1538 // the source files that we actually care about
6b517475 1539 if (q->spec_type != function_alone &&
8096dd7d
JS
1540 q->filtered_srcfiles.count(file) == 0)
1541 return;
1542
9891c543
JL
1543 // To help users, we create an intermediate probe point containing the final
1544 // function name, as well as the matched label. See query_callee() for
1545 // something similar, but with more comments.
1546 string canon_func = q->final_function_name(func, file, line);
1547
1548 string module = q->dw.module_name;
1549 if (q->has_process)
1550 module = path_remove_sysroot(q->sess, module);
8096dd7d 1551
9891c543
JL
1552 probe_point *pp = new probe_point(*q->base_loc);
1553 vector<probe_point::component*> pp_comps;
1554 vector<probe_point::component*>::iterator it;
1555 for (it = pp->components.begin(); it != pp->components.end(); ++it)
c72aa911 1556 {
9891c543
JL
1557 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1558 pp_comps.push_back(new probe_point::component((*it)->functor,
1559 new literal_string(module)));
1560 else if ((*it)->functor == TOK_FUNCTION)
1561 pp_comps.push_back(new probe_point::component(TOK_FUNCTION,
1562 new literal_string(canon_func)));
1563 else if ((*it)->functor == TOK_LABEL)
1564 pp_comps.push_back(new probe_point::component(TOK_LABEL,
1565 new literal_string(label)));
1566 else
1567 pp_comps.push_back(*it);
c72aa911 1568 }
9891c543
JL
1569
1570 pp->components = pp_comps;
1571 dwarf_query q_label(*q);
1572 q_label.base_loc = pp;
1573 q_label.base_probe = new probe(q->base_probe, pp);
1574
1575 query_statement(func, file, line, scope_die, stmt_addr, &q_label);
8096dd7d
JS
1576}
1577
67959c62 1578static void
e772a6e7
JL
1579query_callee (base_func_info& callee,
1580 base_func_info& caller,
67959c62
JL
1581 stack<Dwarf_Addr> *callers,
1582 dwarf_query * q)
1583{
1584 assert (q->has_function_str);
e772a6e7
JL
1585 assert (q->has_callee || q->has_callees_num);
1586
1587 // OK, we found a callee for a targeted caller. To help users see the
1588 // derivation, let's add an intermediate probe to the chain. E.g. right now we
1589 // have .function(pattern).callee(pattern) (or .callees) and we want to add as
1590 // the next step .function(caller).callee(callee). This is the step that will
1591 // show up as well when in listing mode.
1592
1593 // To add this intermediate probe, we first create it and then create a new
1594 // dwarf_query with that probe as base.
1595
1596 // Build final names for caller and callee
1597 string canon_caller = q->final_function_name(caller.name, caller.decl_file,
1598 caller.decl_line);
1599 string canon_callee = q->final_function_name(callee.name, callee.decl_file,
1600 callee.decl_line);
1601
1602 // Build the intermediate probe. We replace the function arg with the final
1603 // caller, and the callee arg with the final callee. Also, since the
1604 // process(str) or module(str) currently in the base_loc is still the one the
1605 // user typed in (not necessarily the same as the absolute path we get in the
1606 // sole location), we also replace that (otherwise, function(str).* will
1607 // return a mishmash of absolute and relative paths in listing mode).
1608
1609 string module = q->dw.module_name;
1610 if (q->has_process)
1611 module = path_remove_sysroot(q->sess, module);
1612
1613 probe_point *pp = new probe_point(*q->base_loc);
1614 vector<probe_point::component*> pp_comps;
1615 vector<probe_point::component*>::iterator it;
1616 for (it = pp->components.begin(); it != pp->components.end(); ++it)
1617 {
1618 if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
1619 pp_comps.push_back(new probe_point::component((*it)->functor,
1620 new literal_string(module)));
1621 else if ((*it)->functor == TOK_FUNCTION)
1622 pp_comps.push_back(new probe_point::component(TOK_FUNCTION,
1623 new literal_string(canon_caller)));
1624 else if ((*it)->functor == TOK_CALLEE || (*it)->functor == TOK_CALLEES)
1625 pp_comps.push_back(new probe_point::component(TOK_CALLEE,
1626 new literal_string(canon_callee)));
1627 else
1628 pp_comps.push_back(*it);
1629 }
1630
1631 // Finally create the new probe and the new query (use copy-constructor
1632 // instead of creating from scratch so we don't have to rebuild param map)
1633 pp->components = pp_comps;
1634 dwarf_query q_callee(*q);
1635 q_callee.base_loc = pp;
1636 q_callee.base_probe = new probe(q->base_probe, pp);
1637
1638 // Pass on the callers we'll need to add checks for
1639 q_callee.callers = callers;
1640
1641 query_statement(callee.name, callee.decl_file, callee.decl_line,
1642 &callee.die, callee.entrypc, &q_callee);
67959c62
JL
1643}
1644
7e1279ea 1645static void
3e961ba6 1646query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1647 dwarf_query * q)
1648{
b6581717 1649 try
7e1279ea 1650 {
8f14e444
FCE
1651 assert (! q->has_return); // checked by caller already
1652 if (q->sess.verbose>2)
b530b5b3
LB
1653 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1654 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1655 query_statement (ii.name, ii.decl_file, ii.decl_line,
1656 &ii.die, ii.entrypc, q);
7e1279ea 1657 }
b6581717 1658 catch (semantic_error &e)
7e1279ea 1659 {
b6581717 1660 q->sess.print_error (e);
7e1279ea
FCE
1661 }
1662}
1663
1664static void
1665query_func_info (Dwarf_Addr entrypc,
bcc12710 1666 func_info & fi,
7e1279ea
FCE
1667 dwarf_query * q)
1668{
b6581717 1669 try
7e1279ea 1670 {
5a617dc6
JL
1671 // If it's a .return probe, we need to emit a *retprobe based on the
1672 // entrypc (PR13200). Note however that if prologue_end is valid,
1673 // dwarf_derived_probe will still take advantage of it by creating a new
1674 // probe there if necessary to pick up target vars (PR14436).
1675 if (fi.prologue_end == 0 || q->has_return)
1676 {
170ccf10 1677 q->prologue_end = fi.prologue_end;
5a617dc6
JL
1678 query_statement (fi.name, fi.decl_file, fi.decl_line,
1679 &fi.die, entrypc, q);
1680 }
b6581717 1681 else
5a617dc6 1682 {
5a617dc6
JL
1683 query_statement (fi.name, fi.decl_file, fi.decl_line,
1684 &fi.die, fi.prologue_end, q);
1685 }
7e1279ea 1686 }
b6581717 1687 catch (semantic_error &e)
7e1279ea 1688 {
b6581717 1689 q->sess.print_error (e);
7e1279ea
FCE
1690 }
1691}
1692
1693
bd4b874d 1694static void
de797211 1695query_srcfile_label (Dwarf_Addr addr, int lineno, dwarf_query * q)
bd4b874d 1696{
959ccfed
JL
1697 base_func_info_map_t bfis = q->filtered_all();
1698 base_func_info_map_t::iterator i;
1699 for (i = bfis.begin(); i != bfis.end(); ++i)
f09d0d1e
JS
1700 if (q->dw.die_has_pc (i->die, addr))
1701 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1702 q, query_label);
bd4b874d
SC
1703}
1704
7e1279ea 1705static void
de797211 1706query_srcfile_line (Dwarf_Addr addr, int lineno, dwarf_query * q)
7e1279ea 1707{
8fb810d7
JL
1708 assert (q->has_statement_str || q->has_function_str);
1709 assert (q->spec_type == function_file_and_line);
1710
959ccfed
JL
1711 base_func_info_map_t bfis = q->filtered_all();
1712 base_func_info_map_t::iterator i;
1713 for (i = bfis.begin(); i != bfis.end(); ++i)
897820ca 1714 {
3e961ba6 1715 if (q->dw.die_has_pc (i->die, addr))
959ccfed
JL
1716 {
1717 if (q->sess.verbose>3)
1718 clog << _("filtered DIE lands on srcfile\n");
1719 Dwarf_Die scope;
1720 q->dw.inner_die_containing_pc(i->die, addr, scope);
1721 query_statement (i->name, i->decl_file,
1722 lineno, // NB: not q->line !
1723 &scope, addr, q);
1724 }
20e4a32c 1725 }
7e1279ea
FCE
1726}
1727
7fdd3e2c
JS
1728bool
1729inline_instance_info::operator<(const inline_instance_info& other) const
1730{
1731 if (entrypc != other.entrypc)
1732 return entrypc < other.entrypc;
1733
1734 if (decl_line != other.decl_line)
1735 return decl_line < other.decl_line;
1736
1737 int cmp = name.compare(other.name);
c60517ca
FCE
1738
1739 if (!cmp)
1740 {
1741 assert (decl_file);
1742 assert (other.decl_file);
1743 cmp = strcmp(decl_file, other.decl_file);
1744 }
1745
7fdd3e2c
JS
1746 return cmp < 0;
1747}
1748
1749
4fa7b22b 1750static int
3956fccb 1751query_dwarf_inline_instance (Dwarf_Die * die, dwarf_query * q)
4fa7b22b 1752{
6b517475 1753 assert (q->has_statement_str || q->has_function_str);
4bda987e 1754 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1755
39bcd429 1756 try
7a053d3b 1757 {
b0ee93c4 1758 if (q->sess.verbose>2)
b530b5b3 1759 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1760
6b517475
JS
1761 Dwarf_Addr entrypc;
1762 if (q->dw.die_entrypc (die, &entrypc))
1763 {
1764 inline_instance_info inl;
1765 inl.die = *die;
1766 inl.name = q->dw.function_name;
1767 inl.entrypc = entrypc;
1768 q->dw.function_file (&inl.decl_file);
1769 q->dw.function_line (&inl.decl_line);
1770
1771 // make sure that this inline hasn't already
1772 // been matched from a different CU
1773 if (q->inline_dupes.insert(inl).second)
1774 q->filtered_inlines.push_back(inl);
1775 }
7e1279ea
FCE
1776 return DWARF_CB_OK;
1777 }
1778 catch (const semantic_error& e)
1779 {
1780 q->sess.print_error (e);
1781 return DWARF_CB_ABORT;
1782 }
1783}
bb788f9f 1784
7e1279ea 1785static int
7d007451 1786query_dwarf_func (Dwarf_Die * func, dwarf_query * q)
7e1279ea 1787{
6b517475 1788 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1789
bd25380d
JS
1790 // weed out functions whose decl_file isn't one of
1791 // the source files that we actually care about
6b517475 1792 if (q->spec_type != function_alone &&
bd25380d 1793 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1794 return DWARF_CB_OK;
bd25380d 1795
7e1279ea
FCE
1796 try
1797 {
7e1279ea
FCE
1798 q->dw.focus_on_function (func);
1799
7d6d0afc
JS
1800 if (!q->dw.function_scope_matches(q->scopes))
1801 return DWARF_CB_OK;
1802
857bdfd1
JS
1803 // make sure that this function address hasn't
1804 // already been matched under an aliased name
1805 Dwarf_Addr addr;
1806 if (!q->dw.func_is_inline() &&
1807 dwarf_entrypc(func, &addr) == 0 &&
1808 !q->alias_dupes.insert(addr).second)
1809 return DWARF_CB_OK;
1810
4bda987e 1811 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1812 {
4bda987e 1813 if (q->sess.verbose>3)
b530b5b3 1814 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1815 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1816 }
8f14e444
FCE
1817 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1818 {
1819 q->inlined_non_returnable.insert (q->dw.function_name);
1820 }
396afcee 1821 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1822 {
4bda987e
SC
1823 if (q->has_exported && !q->dw.func_is_exported ())
1824 return DWARF_CB_OK;
6b517475 1825 if (q->sess.verbose>2)
b530b5b3 1826 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1827
1828 func_info func;
1829 q->dw.function_die (&func.die);
1830 func.name = q->dw.function_name;
1831 q->dw.function_file (&func.decl_file);
1832 q->dw.function_line (&func.decl_line);
1833
1834 Dwarf_Addr entrypc;
1835 if (q->dw.function_entrypc (&entrypc))
1836 {
1837 func.entrypc = entrypc;
1838 q->filtered_functions.push_back (func);
1839 }
1840 /* else this function is fully inlined, just ignore it */
7e1279ea 1841 }
39bcd429 1842 return DWARF_CB_OK;
bd2b1e68 1843 }
39bcd429 1844 catch (const semantic_error& e)
bd2b1e68 1845 {
39bcd429
FCE
1846 q->sess.print_error (e);
1847 return DWARF_CB_ABORT;
bd2b1e68 1848 }
bd2b1e68
GH
1849}
1850
1851static int
5c378838 1852query_cu (Dwarf_Die * cudie, dwarf_query * q)
bd2b1e68 1853{
6b517475
JS
1854 assert (q->has_statement_str || q->has_function_str);
1855
85007c04 1856 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1857
39bcd429 1858 try
bd2b1e68 1859 {
7e1279ea 1860 q->dw.focus_on_cu (cudie);
b5d77020 1861
b0ee93c4 1862 if (false && q->sess.verbose>2)
b530b5b3
LB
1863 clog << _F("focused on CU '%s', in module '%s'\n",
1864 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1865
6b517475
JS
1866 q->filtered_srcfiles.clear();
1867 q->filtered_functions.clear();
1868 q->filtered_inlines.clear();
1869
1870 // In this path, we find "abstract functions", record
1871 // information about them, and then (depending on lineno
1872 // matching) possibly emit one or more of the function's
1873 // associated addresses. Unfortunately the control of this
1874 // cannot easily be turned inside out.
1875
1876 if (q->spec_type != function_alone)
39bcd429 1877 {
6b517475
JS
1878 // If we have a pattern string with a filename, we need
1879 // to elaborate the srcfile mask in question first.
1880 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1881
1882 // If we have a file pattern and *no* srcfile matches, there's
1883 // no need to look further into this CU, so skip.
1884 if (q->filtered_srcfiles.empty())
1885 return DWARF_CB_OK;
1886 }
e4c58386 1887
6b517475
JS
1888 // Pick up [entrypc, name, DIE] tuples for all the functions
1889 // matching the query, and fill in the prologue endings of them
1890 // all in a single pass.
5898b6e1 1891 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1892 if (rc != DWARF_CB_OK)
1893 q->query_done = true;
1894
277a2b96
JL
1895 if (!q->filtered_functions.empty() &&
1896 !q->has_statement_str && // PR 2608
1897 (q->sess.prologue_searching ||
1898 (q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
1899 q->dw.resolve_prologue_endings (q->filtered_functions);
6b517475
JS
1900
1901 if (q->spec_type == function_file_and_line)
1902 {
58b070fb 1903 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1904 if (q->has_function_str)
b530b5b3 1905 q->sess.print_warning (_("For probing a particular line, use a "
b78a0fbb 1906 ".statement() probe, not .function()"),
af2e341f 1907 q->base_probe->tok);
58b070fb 1908
de797211 1909 void (* callback) (Dwarf_Addr, int, dwarf_query*) =
6b517475 1910 q->has_label ? query_srcfile_label : query_srcfile_line;
516e1e2c
JL
1911
1912 base_func_info_map_t bfis = q->filtered_all();
1913
1914 set<string>::const_iterator srcfile;
1915 for (srcfile = q->filtered_srcfiles.begin();
1916 srcfile != q->filtered_srcfiles.end(); ++srcfile)
1917 q->dw.iterate_over_srcfile_lines(srcfile->c_str(), q->linenos,
1918 q->lineno_type, bfis, callback, q);
6b517475
JS
1919 }
1920 else if (q->has_label)
1921 {
959ccfed
JL
1922 base_func_info_map_t bfis = q->filtered_all();
1923 base_func_info_map_t::iterator i;
1924 for (i = bfis.begin(); i != bfis.end(); ++i)
6b517475
JS
1925 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1926 q, query_label);
39bcd429 1927 }
67959c62
JL
1928 else if (q->has_callee || q->has_callees_num)
1929 {
1930 // .callee(str) --> str, .callees[(N)] --> "*"
1931 string callee_val = q->has_callee ? q->callee_val : "*";
1932 long callees_num_val = q->has_callees_num ? q->callees_num_val : 1;
1933
1934 // NB: We filter functions that do not match the file here rather than
1935 // in query_callee because we only want the filtering to apply to the
1936 // first level, not to callees that are recursed into if
1937 // callees_num_val > 1.
959ccfed
JL
1938 base_func_info_map_t bfis = q->filtered_all();
1939 base_func_info_map_t::iterator i;
1940 for (i = bfis.begin(); i != bfis.end(); ++i)
67959c62
JL
1941 {
1942 if (q->spec_type != function_alone &&
1943 q->filtered_srcfiles.count(i->decl_file) == 0)
1944 continue;
1945 q->dw.iterate_over_callees (&i->die, callee_val,
1946 callees_num_val,
e772a6e7 1947 q, query_callee, *i);
67959c62
JL
1948 }
1949 }
6b517475
JS
1950 else
1951 {
1952 // Otherwise, simply probe all resolved functions.
1953 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1954 i != q->filtered_functions.end(); ++i)
1955 query_func_info (i->entrypc, *i, q);
1956
1957 // And all inline instances (if we're not excluding inlines with ".call")
1958 if (! q->has_call)
1959 for (inline_instance_map_t::iterator i
1960 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1961 query_inline_instance_info (*i, q);
e772a6e7 1962 }
39bcd429 1963 return DWARF_CB_OK;
bd2b1e68 1964 }
39bcd429 1965 catch (const semantic_error& e)
bd2b1e68 1966 {
39bcd429
FCE
1967 q->sess.print_error (e);
1968 return DWARF_CB_ABORT;
bd2b1e68 1969 }
bd2b1e68
GH
1970}
1971
0ce64fb8 1972
4df79aaf
JS
1973void
1974dwarf_query::query_module_functions ()
1975{
1976 try
1977 {
1978 filtered_srcfiles.clear();
1979 filtered_functions.clear();
1980 filtered_inlines.clear();
1981
1982 // Collect all module functions so we know which CUs are interesting
1983 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1984 if (rc != DWARF_CB_OK)
1985 {
1986 query_done = true;
1987 return;
1988 }
1989
1990 set<void*> used_cus; // by cu->addr
1991 vector<Dwarf_Die> cus;
1992 Dwarf_Die cu_mem;
1993
959ccfed
JL
1994 base_func_info_map_t bfis = filtered_all();
1995 base_func_info_map_t::iterator i;
1996 for (i = bfis.begin(); i != bfis.end(); ++i)
4df79aaf
JS
1997 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1998 used_cus.insert(cu_mem.addr).second)
1999 cus.push_back(cu_mem);
2000
2001 // Reset the dupes since we didn't actually collect them the first time
2002 alias_dupes.clear();
2003 inline_dupes.clear();
2004
2005 // Run the query again on the individual CUs
91bb9081
LB
2006 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i){
2007 rc = query_cu(&*i, this);
2008 if (rc != DWARF_CB_OK)
2009 {
2010 query_done = true;
2011 return;
2012 }
2013 }
4df79aaf
JS
2014 }
2015 catch (const semantic_error& e)
2016 {
2017 sess.print_error (e);
2018 }
2019}
2020
2021
5f0a03a6
JK
2022static void
2023validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
2024{
2025 // Validate the machine code in this elf file against the
2026 // session machine. This is important, in case the wrong kind
2027 // of debuginfo is being automagically processed by elfutils.
2028 // While we can tell i686 apart from x86-64, unfortunately
2029 // we can't help confusing i586 vs i686 (both EM_386).
2030
2031 Dwarf_Addr bias;
2032 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
2033 // because dwfl_module_getelf can force costly section relocations
2034 // we don't really need, while either will do for this purpose.
2035 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
2036 ?: dwfl_module_getelf (mod, &bias));
2037
2038 GElf_Ehdr ehdr_mem;
2039 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 2040 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 2041 assert(em);
5f0a03a6
JK
2042 int elf_machine = em->e_machine;
2043 const char* debug_filename = "";
2044 const char* main_filename = "";
2045 (void) dwfl_module_info (mod, NULL, NULL,
2046 NULL, NULL, NULL,
2047 & main_filename,
2048 & debug_filename);
2049 const string& sess_machine = q->sess.architecture;
756c9462
FCE
2050
2051 string expect_machine; // to match sess.machine (i.e., kernel machine)
2052 string expect_machine2;
5f0a03a6 2053
d27e6fd5 2054 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
2055 switch (elf_machine)
2056 {
756c9462
FCE
2057 // x86 and ppc are bi-architecture; a 64-bit kernel
2058 // can normally run either 32-bit or 64-bit *userspace*.
2059 case EM_386:
2060 expect_machine = "i?86";
2061 if (! q->has_process) break; // 32-bit kernel/module
2062 /* FALLSTHROUGH */
2063 case EM_X86_64:
2064 expect_machine2 = "x86_64";
2065 break;
2066 case EM_PPC:
756c9462 2067 case EM_PPC64:
5a1c472e 2068 expect_machine = "powerpc";
756c9462 2069 break;
3fe7d888 2070 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 2071 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 2072 case EM_ARM: expect_machine = "arm*"; break;
86aae990 2073 case EM_AARCH64: expect_machine = "arm64"; break;
5f0a03a6
JK
2074 // XXX: fill in some more of these
2075 default: expect_machine = "?"; break;
2076 }
2077
2078 if (! debug_filename) debug_filename = main_filename;
2079 if (! debug_filename) debug_filename = name;
2080
756c9462
FCE
2081 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
2082 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
2083 {
2084 stringstream msg;
b530b5b3
LB
2085 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
2086 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
2087 sess_machine.c_str(), debug_filename);
dc09353a 2088 throw SEMANTIC_ERROR(msg.str ());
5f0a03a6
JK
2089 }
2090
b57082de 2091 if (q->sess.verbose>1)
b78a0fbb 2092 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
2093 " file %s ELF machine %s|%s (code %d)\n",
2094 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
2095 q->dw.module_bias, debug_filename, expect_machine.c_str(),
2096 expect_machine2.c_str(), elf_machine);
5f0a03a6 2097}
1d3a40b6 2098
91af0778
FCE
2099
2100
2101static Dwarf_Addr
2102lookup_symbol_address (Dwfl_Module *m, const char* wanted)
2103{
2104 int syments = dwfl_module_getsymtab(m);
2105 assert(syments);
2106 for (int i = 1; i < syments; ++i)
2107 {
2108 GElf_Sym sym;
2109 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
2110 if (name != NULL && strcmp(name, wanted) == 0)
2111 return sym.st_value;
2112 }
2113
2114 return 0;
2115}
2116
2117
2118
bd2b1e68 2119static int
b8da0ad1 2120query_module (Dwfl_Module *mod,
91af0778 2121 void **,
b8da0ad1 2122 const char *name,
6f4c1275 2123 Dwarf_Addr addr,
06de3a04 2124 base_query *q)
bd2b1e68 2125{
39bcd429 2126 try
e38d6504 2127 {
91af0778
FCE
2128 module_info* mi = q->sess.module_cache->cache[name];
2129 if (mi == 0)
2130 {
2131 mi = q->sess.module_cache->cache[name] = new module_info(name);
2132
6f4c1275
FCE
2133 mi->mod = mod;
2134 mi->addr = addr;
91af0778 2135
6f4c1275
FCE
2136 const char* debug_filename = "";
2137 const char* main_filename = "";
2138 (void) dwfl_module_info (mod, NULL, NULL,
2139 NULL, NULL, NULL,
2140 & main_filename,
2141 & debug_filename);
2142
ab3ed72d 2143 if (debug_filename || main_filename)
91af0778 2144 {
6f4c1275
FCE
2145 mi->elf_path = debug_filename ?: main_filename;
2146 }
2147 else if (name == TOK_KERNEL)
2148 {
2149 mi->dwarf_status = info_absent;
91af0778 2150 }
91af0778
FCE
2151 }
2152 // OK, enough of that module_info caching business.
2153
5f0a03a6 2154 q->dw.focus_on_module(mod, mi);
d9b516ca 2155
39bcd429
FCE
2156 // If we have enough information in the pattern to skip a module and
2157 // the module does not match that information, return early.
b8da0ad1 2158 if (!q->dw.module_name_matches(q->module_val))
85007c04 2159 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2160
2161 // Don't allow module("*kernel*") type expressions to match the
2162 // elfutils module "kernel", which we refer to in the probe
2163 // point syntax exclusively as "kernel.*".
2164 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2165 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2166
5f0a03a6
JK
2167 if (mod)
2168 validate_module_elf(mod, name, q);
2169 else
91af0778
FCE
2170 assert(q->has_kernel); // and no vmlinux to examine
2171
2172 if (q->sess.verbose>2)
b530b5b3 2173 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2174
2175
2176 // Collect a few kernel addresses. XXX: these belong better
2177 // to the sess.module_info["kernel"] struct.
2178 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2179 {
91af0778
FCE
2180 if (! q->sess.sym_kprobes_text_start)
2181 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2182 if (! q->sess.sym_kprobes_text_end)
2183 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2184 if (! q->sess.sym_stext)
2185 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2186 }
2187
47e226ed
SC
2188 // We either have a wildcard or an unresolved library
2189 if (q->has_library && (contains_glob_chars (q->path)
2190 || q->path.find('/') == string::npos))
84c84ac4
SC
2191 // handle .library(GLOB)
2192 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2193 // .plt is translated to .plt.statement(N). We only want to iterate for the
2194 // .plt case
2195 else if (q->has_plt && ! q->has_statement)
070764c0
JL
2196 {
2197 q->dw.iterate_over_plt (q, &q->query_plt_callback);
2198 q->visited_modules.insert(name);
2199 }
84c84ac4 2200 else
070764c0
JL
2201 {
2202 // search the module for matches of the probe point.
2203 q->handle_query_module();
2204 q->visited_modules.insert(name);
2205 }
bb788f9f 2206
b8da0ad1 2207 // If we know that there will be no more matches, abort early.
85007c04 2208 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2209 return DWARF_CB_ABORT;
2210 else
2211 return DWARF_CB_OK;
7a053d3b 2212 }
39bcd429 2213 catch (const semantic_error& e)
bd2b1e68 2214 {
39bcd429
FCE
2215 q->sess.print_error (e);
2216 return DWARF_CB_ABORT;
bd2b1e68 2217 }
bd2b1e68
GH
2218}
2219
35d4ab18 2220
84c84ac4 2221void
bbbc7241 2222base_query::query_library_callback (base_query *me, const char *data)
84c84ac4 2223{
5d5bd369 2224 me->query_library (data);
84c84ac4
SC
2225}
2226
2227
2cbcfa9c 2228string
51d6bda3
SC
2229query_one_library (const char *library, dwflpp & dw,
2230 const string user_lib, probe * base_probe, probe_point *base_loc,
2231 vector<derived_probe *> & results)
84c84ac4 2232{
47e226ed 2233 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2234 {
05fb3e0c
WF
2235 string library_path = find_executable (library, "", dw.sess.sysenv,
2236 "LD_LIBRARY_PATH");
84c84ac4
SC
2237 probe_point* specific_loc = new probe_point(*base_loc);
2238 specific_loc->optional = true;
ef0943df 2239 specific_loc->from_glob = true;
84c84ac4
SC
2240 vector<probe_point::component*> derived_comps;
2241
5d25dfb6
JL
2242 // Create new probe point for the matching library. This is what will be
2243 // shown in listing mode. Also replace the process(str) with the real
2244 // absolute path rather than keeping what the user typed in.
84c84ac4
SC
2245 vector<probe_point::component*>::iterator it;
2246 for (it = specific_loc->components.begin();
2247 it != specific_loc->components.end(); ++it)
5d25dfb6
JL
2248 if ((*it)->functor == TOK_PROCESS)
2249 derived_comps.push_back(new probe_point::component(TOK_PROCESS,
2250 new literal_string(path_remove_sysroot(dw.sess, dw.module_name))));
2251 else if ((*it)->functor == TOK_LIBRARY)
84c84ac4
SC
2252 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2253 new literal_string(library_path)));
2254 else
2255 derived_comps.push_back(*it);
2256 probe_point* derived_loc = new probe_point(*specific_loc);
2257 derived_loc->components = derived_comps;
8159bf55 2258 probe *new_base = new probe (new probe (base_probe, specific_loc), derived_loc);
51d6bda3
SC
2259 derive_probes(dw.sess, new_base, results);
2260 if (dw.sess.verbose > 2)
2cbcfa9c
JL
2261 clog << _("module=") << library_path << endl;
2262 return library_path;
84c84ac4 2263 }
2cbcfa9c 2264 return "";
84c84ac4
SC
2265}
2266
2267
51d6bda3
SC
2268void
2269dwarf_query::query_library (const char *library)
2270{
2cbcfa9c
JL
2271 string library_path =
2272 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2273 if (!library_path.empty())
2274 visited_modules.insert(library_path);
51d6bda3
SC
2275}
2276
576eaefe
SC
2277struct plt_expanding_visitor: public var_expanding_visitor
2278{
2279 plt_expanding_visitor(const string & entry):
2280 entry (entry)
2281 {
2282 }
2283 const string & entry;
2284
2285 void visit_target_symbol (target_symbol* e);
2286};
2287
2288
2289void
45cdb40e 2290base_query::query_plt_callback (base_query *me, const char *entry, size_t address)
576eaefe 2291{
576eaefe
SC
2292 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2293 me->query_plt (entry, address);
7f4964f1 2294 me->dw.mod_info->plt_funcs.insert(entry);
576eaefe
SC
2295}
2296
2297
2298void
2299query_one_plt (const char *entry, long addr, dwflpp & dw,
2300 probe * base_probe, probe_point *base_loc,
2301 vector<derived_probe *> & results)
2302{
2303 probe_point* specific_loc = new probe_point(*base_loc);
576eaefe
SC
2304 vector<probe_point::component*> derived_comps;
2305
2306 if (dw.sess.verbose > 2)
2307 clog << _F("plt entry=%s\n", entry);
2308
576eaefe
SC
2309 vector<probe_point::component*>::iterator it;
2310 for (it = specific_loc->components.begin();
2311 it != specific_loc->components.end(); ++it)
2312 if ((*it)->functor == TOK_PLT)
3d372d6b 2313 {
8159bf55
FCE
2314 *it = new probe_point::component(TOK_PLT,
2315 new literal_string(entry));
3d372d6b
SC
2316 derived_comps.push_back(*it);
2317 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
ac7c8669 2318 new literal_number(addr, true)));
3d372d6b 2319 }
576eaefe
SC
2320 else
2321 derived_comps.push_back(*it);
2322 probe_point* derived_loc = new probe_point(*specific_loc);
2323 derived_loc->components = derived_comps;
02c34e38
FCE
2324 probe *new_base = new probe (new probe (base_probe, specific_loc),
2325 derived_loc);
576eaefe
SC
2326 string e = string(entry);
2327 plt_expanding_visitor pltv (e);
2328 pltv.replace (new_base->body);
2329 derive_probes(dw.sess, new_base, results);
2330}
2331
2332
2333void
2334dwarf_query::query_plt (const char *entry, size_t address)
2335{
2336 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2337}
51d6bda3 2338
435f53a7
FCE
2339// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2340// but the needed declaration for module_cache is not available there.
2341// Nor for that matter in session.cxx. Only in this CU is that field ever
2342// set (in query_module() above), so we clean it up here too.
2343static void
2344delete_session_module_cache (systemtap_session& s)
2345{
2346 if (s.module_cache) {
2347 if (s.verbose > 3)
b530b5b3 2348 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2349 delete s.module_cache;
2350 s.module_cache = 0;
2351 }
2352}
2353
2354
de688825 2355struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2356{
77de5e9e 2357 dwarf_query & q;
bcc12710 2358 Dwarf_Die *scope_die;
77de5e9e 2359 Dwarf_Addr addr;
8c819921 2360 block *add_block;
2260f4e3 2361 block *add_call_probe; // synthesized from .return probes with saved $vars
1630966a
JS
2362 // NB: tids are not always collected in add_block & add_call_probe, because
2363 // gen_kretprobe_saved_return doesn't need them. Thus we need these extra
2364 // *_tid bools for gen_mapped_saved_return to tell what's there.
8cc799a5 2365 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2366 unsigned saved_longs, saved_strings; // data saved within kretprobes
2367 map<std::string, expression *> return_ts_map;
729455a7 2368 vector<Dwarf_Die> scopes;
3689db05 2369 // probe counter name -> pointer of associated probe
698de6cc 2370 std::set<derived_probe*> perf_counter_refs;
b95e2b79 2371 bool visited;
77de5e9e 2372
de688825 2373 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2374 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2375 add_block_tid(false), add_call_probe_tid(false),
af234c40 2376 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2377 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2378 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2379 void visit_target_symbol_saved_return (target_symbol* e);
2380 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2381 void visit_target_symbol (target_symbol* e);
bd1fcbad 2382 void visit_atvar_op (atvar_op* e);
c24447be 2383 void visit_cast_op (cast_op* e);
8cc799a5 2384 void visit_entry_op (entry_op* e);
3689db05 2385 void visit_perf_op (perf_op* e);
729455a7
JS
2386private:
2387 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2388};
2389
2390
de688825 2391unsigned var_expanding_visitor::tick = 0;
77de5e9e 2392
a50de939 2393
74fe61bc 2394var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2395{
2396 // FIXME: for the time being, by default we only support plain '$foo
2397 // = bar', not '+=' or any other op= variant. This is fixable, but a
2398 // bit ugly.
2399 //
2400 // If derived classes desire to add additional operator support, add
2401 // new operators to this list in the derived class constructor.
2402 valid_ops.insert ("=");
2403}
2404
2405
87214add
JS
2406bool
2407var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2408 expression*& lvalue, expression*& rvalue)
77de5e9e 2409{
e57b735a
GH
2410 // Our job would normally be to require() the left and right sides
2411 // into a new assignment. What we're doing is slightly trickier:
2412 // we're pushing a functioncall** onto a stack, and if our left
2413 // child sets the functioncall* for that value, we're going to
2414 // assume our left child was a target symbol -- transformed into a
2415 // set_target_foo(value) call, and it wants to take our right child
2416 // as the argument "value".
2417 //
2418 // This is why some people claim that languages with
2419 // constructor-decomposing case expressions have a leg up on
2420 // visitors.
2421
2422 functioncall *fcall = NULL;
d9b516ca 2423
a50de939 2424 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2425 const string* old_op = op;
2426 op = &eop;
a50de939 2427
e57b735a 2428 target_symbol_setter_functioncalls.push (&fcall);
87214add 2429 replace (lvalue);
e57b735a 2430 target_symbol_setter_functioncalls.pop ();
87214add
JS
2431 replace (rvalue);
2432
2433 op = old_op;
e57b735a
GH
2434
2435 if (fcall != NULL)
77de5e9e 2436 {
e57b735a
GH
2437 // Our left child is informing us that it was a target variable
2438 // and it has been replaced with a set_target_foo() function
2439 // call; we are going to provide that function call -- with the
2440 // right child spliced in as sole argument -- in place of
de688825 2441 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2442
87214add 2443 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2444 {
2445 // Build up a list of supported operators.
2446 string ops;
2447 std::set<string>::iterator i;
b530b5b3 2448 int valid_ops_size = 0;
a50de939 2449 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2450 {
a50de939 2451 ops += " " + *i + ",";
b530b5b3
LB
2452 valid_ops_size++;
2453 }
a50de939
DS
2454 ops.resize(ops.size() - 1); // chop off the last ','
2455
2456 // Throw the error.
dc09353a 2457 throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
1e41115c 2458 "Only the following assign operators are implemented on target variables: %s",
52c2652f 2459 valid_ops_size, ops.c_str()), tok);
b530b5b3 2460
a50de939 2461 }
e57b735a 2462
87214add
JS
2463 assert (lvalue == fcall);
2464 if (rvalue)
2465 fcall->args.push_back (rvalue);
4ed05b15 2466 provide (fcall);
87214add 2467 return true;
77de5e9e 2468 }
e57b735a 2469 else
87214add
JS
2470 return false;
2471}
2472
2473
2474void
2475var_expanding_visitor::visit_assignment (assignment* e)
2476{
2477 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2478 provide (e);
2479}
2480
2481
2482void
2483var_expanding_visitor::visit_pre_crement (pre_crement* e)
2484{
2485 expression *dummy = NULL;
2486 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2487 provide (e);
2488}
2489
2490
2491void
2492var_expanding_visitor::visit_post_crement (post_crement* e)
2493{
2494 expression *dummy = NULL;
2495 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2496 provide (e);
2497}
2498
2499
2500void
2501var_expanding_visitor::visit_delete_statement (delete_statement* s)
2502{
2503 string fakeop = "delete";
2504 expression *dummy = NULL;
2505 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2506 provide (s);
e57b735a 2507}
d9b516ca 2508
d7f3e0c5 2509
30263a73
FCE
2510void
2511var_expanding_visitor::visit_defined_op (defined_op* e)
2512{
2513 bool resolved = true;
2514
2515 defined_ops.push (e);
2516 try {
2517 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2518 // defined with a target_symbol* operand, a subsidiary call may attempt to
2519 // rewrite it to a general expression* instead, and require<> happily
2520 // casts to/from void*, causing possible memory corruption. We use
2521 // expression* here, being the general case of rewritten $variable.
2522 expression *foo1 = e->operand;
2523 foo1 = require (foo1);
2524
c69a87e0 2525 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2526 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2527 // erroneous resolutions. Some would signal a visit_target_symbol failure
2528 // with an exception, with a set flag within the target_symbol, or nothing
2529 // at all.
30263a73 2530 //
c69a87e0
FCE
2531 // Now, failures always have to be signalled with a
2532 // saved_conversion_error being chained to the target_symbol.
2533 // Successes have to result in an attempted rewrite of the
850bfddd 2534 // target_symbol (via provide()).
780f11ff 2535 //
c69a87e0
FCE
2536 // Edna Mode: "no capes". fche: "no exceptions".
2537
30263a73
FCE
2538 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2539 //
2540 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2541 //
2542 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2543 // dwarf probe to take care of it.
2544 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2545 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2546 //
30263a73
FCE
2547 // utrace: success: rewrites to function; failure: semantic_error
2548 //
850bfddd 2549 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2550
2551 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2552 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2553 resolved = false;
a45664f4 2554 else if (foo2) // unresolved but not marked failing
b7aedf26 2555 {
780f11ff
JS
2556 // There are some visitors that won't touch certain target_symbols,
2557 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2558 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2559 e->operand = foo2;
2560 provide (e);
2561 return;
2562 }
30263a73
FCE
2563 else // resolved, rewritten to some other expression type
2564 resolved = true;
780f11ff 2565 } catch (const semantic_error& e) {
c69a87e0 2566 assert (0); // should not happen
30263a73
FCE
2567 }
2568 defined_ops.pop ();
2569
2570 literal_number* ln = new literal_number (resolved ? 1 : 0);
2571 ln->tok = e->tok;
2572 provide (ln);
2573}
2574
2575
5f36109e
JS
2576struct dwarf_pretty_print
2577{
2578 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2579 const string& local, bool userspace_p,
2580 const target_symbol& e):
d19a9a82
JS
2581 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2582 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2583 {
2584 init_ts (e);
2585 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2586 }
2587
2588 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2589 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2590 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2591 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2592 {
2593 init_ts (e);
2594 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2595 }
2596
2597 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2598 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2599 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2600 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2601 {
2602 init_ts (e);
2603 dw.type_die_for_pointer (type_die, ts, &base_type);
2604 }
2605
2606 functioncall* expand ();
ce83ff57 2607 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2608
2609private:
2610 dwflpp& dw;
2611 target_symbol* ts;
7d11d8c9 2612 bool print_full;
5f36109e
JS
2613 Dwarf_Die base_type;
2614
2615 string local;
2616 vector<Dwarf_Die> scopes;
2617 Dwarf_Addr pc;
2618
2619 expression* pointer;
2620 Dwarf_Die pointer_type;
2621
d19a9a82 2622 const bool userspace_p, deref_p;
5f36109e
JS
2623
2624 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2625 print_format* pf, bool top=false);
600551ca
JS
2626 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2627 print_format* pf);
5f36109e 2628 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2629 print_format* pf);
5f36109e 2630 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2631 print_format* pf, bool top);
5f36109e 2632 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2633 print_format* pf, bool top);
5f36109e 2634 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2635 print_format* pf, bool top);
5f36109e 2636 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2637 print_format* pf, int& count);
bbee5bb8 2638 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2639
2640 void init_ts (const target_symbol& e);
2641 expression* deref (target_symbol* e);
c55ea10d 2642 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2643};
2644
2645
2646void
2647dwarf_pretty_print::init_ts (const target_symbol& e)
2648{
2649 // Work with a new target_symbol so we can modify arguments
2650 ts = new target_symbol (e);
2651
2652 if (ts->addressof)
dc09353a 2653 throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2654
2655 if (ts->components.empty() ||
2656 ts->components.back().type != target_symbol::comp_pretty_print)
dc09353a 2657 throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2658 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2659 ts->components.pop_back();
2660}
2661
2662
2663functioncall*
2664dwarf_pretty_print::expand ()
2665{
2666 static unsigned tick = 0;
2667
2668 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2669 // try {
2670 // return sprintf("{.foo=...}", (ts)->foo, ...)
2671 // } catch {
2672 // return "ERROR"
2673 // }
5f36109e
JS
2674 // }
2675
2676 // Create the function decl and call.
2677
2678 functiondecl *fdecl = new functiondecl;
2679 fdecl->tok = ts->tok;
2680 fdecl->synthetic = true;
2681 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2682 fdecl->type = pe_string;
2683
2684 functioncall* fcall = new functioncall;
2685 fcall->tok = ts->tok;
2686 fcall->function = fdecl->name;
140be17a 2687 fcall->type = pe_string;
5f36109e
JS
2688
2689 // If there's a <pointer>, replace it with a new var and make that
2690 // the first function argument.
2691 if (pointer)
2692 {
2693 vardecl *v = new vardecl;
2694 v->type = pe_long;
2695 v->name = "pointer";
2696 v->tok = ts->tok;
2697 fdecl->formal_args.push_back (v);
2698 fcall->args.push_back (pointer);
2699
2700 symbol* sym = new symbol;
2701 sym->tok = ts->tok;
2702 sym->name = v->name;
5f36109e
JS
2703 pointer = sym;
2704 }
2705
2706 // For each expression argument, replace it with a function argument.
2707 for (unsigned i = 0; i < ts->components.size(); ++i)
2708 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2709 {
2710 vardecl *v = new vardecl;
2711 v->type = pe_long;
2712 v->name = "index" + lex_cast(i);
2713 v->tok = ts->tok;
2714 fdecl->formal_args.push_back (v);
2715 fcall->args.push_back (ts->components[i].expr_index);
2716
2717 symbol* sym = new symbol;
2718 sym->tok = ts->tok;
2719 sym->name = v->name;
5f36109e
JS
2720 ts->components[i].expr_index = sym;
2721 }
2722
2723 // Create the return sprintf.
1c922ad7 2724 print_format* pf = print_format::create(ts->tok, "sprintf");
5f36109e
JS
2725 return_statement* rs = new return_statement;
2726 rs->tok = ts->tok;
2727 rs->value = pf;
5f36109e
JS
2728
2729 // Recurse into the actual values.
7d11d8c9 2730 recurse (&base_type, ts, pf, true);
5f36109e
JS
2731 pf->components = print_format::string_to_components(pf->raw_components);
2732
7d11d8c9
JS
2733 // Create the try-catch net
2734 try_block* tb = new try_block;
2735 tb->tok = ts->tok;
2736 tb->try_block = rs;
2737 tb->catch_error_var = 0;
2738 return_statement* rs2 = new return_statement;
2739 rs2->tok = ts->tok;
2740 rs2->value = new literal_string ("ERROR");
2741 rs2->value->tok = ts->tok;
2742 tb->catch_block = rs2;
2743 fdecl->body = tb;
2744
f8809d54 2745 fdecl->join (dw.sess);
5f36109e
JS
2746 return fcall;
2747}
2748
2749
2750void
2751dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2752 print_format* pf, bool top)
5f36109e
JS
2753{
2754 Dwarf_Die type;
2755 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2756
2757 switch (dwarf_tag(&type))
2758 {
2759 default:
2760 // XXX need a warning?
2761 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2762 // + ") for " + dwarf_type_name(&type), e->tok);
2763 pf->raw_components.append("?");
2764 break;
2765
2766 case DW_TAG_enumeration_type:
2767 case DW_TAG_base_type:
7d11d8c9 2768 recurse_base (&type, e, pf);
5f36109e
JS
2769 break;
2770
2771 case DW_TAG_array_type:
7d11d8c9 2772 recurse_array (&type, e, pf, top);
5f36109e
JS
2773 break;
2774
2775 case DW_TAG_pointer_type:
2776 case DW_TAG_reference_type:
2777 case DW_TAG_rvalue_reference_type:
7d11d8c9 2778 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2779 break;
2780
2781 case DW_TAG_subroutine_type:
c55ea10d 2782 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2783 break;
2784
2785 case DW_TAG_union_type:
5f36109e
JS
2786 case DW_TAG_structure_type:
2787 case DW_TAG_class_type:
7d11d8c9 2788 recurse_struct (&type, e, pf, top);
5f36109e
JS
2789 break;
2790 }
2791}
2792
2793
600551ca
JS
2794// Bit fields are handled as a special-case combination of recurse() and
2795// recurse_base(), only called from recurse_struct_members(). The main
2796// difference is that the value is always printed numerically, even if the
2797// underlying type is a char.
2798void
2799dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2800 print_format* pf)
2801{
2802 Dwarf_Die type;
2803 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2804
2805 int tag = dwarf_tag(&type);
2806 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2807 {
2808 // XXX need a warning?
2809 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2810 // + ") for " + dwarf_type_name(&type), e->tok);
2811 pf->raw_components.append("?");
2812 return;
2813 }
2814
2815 Dwarf_Attribute attr;
2816 Dwarf_Word encoding = (Dwarf_Word) -1;
2817 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2818 &encoding);
2819 switch (encoding)
2820 {
2821 case DW_ATE_float:
2822 case DW_ATE_complex_float:
2823 // XXX need a warning?
2824 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2825 // + ") for " + dwarf_type_name(&type), e->tok);
2826 pf->raw_components.append("?");
2827 break;
2828
2829 case DW_ATE_unsigned:
2830 case DW_ATE_unsigned_char:
2831 push_deref (pf, "%u", e);
2832 break;
2833
2834 case DW_ATE_signed:
2835 case DW_ATE_signed_char:
2836 default:
2837 push_deref (pf, "%i", e);
2838 break;
2839 }
2840}
2841
2842
5f36109e
JS
2843void
2844dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2845 print_format* pf)
5f36109e
JS
2846{
2847 Dwarf_Attribute attr;
2848 Dwarf_Word encoding = (Dwarf_Word) -1;
2849 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2850 &encoding);
5f36109e
JS
2851 switch (encoding)
2852 {
2853 case DW_ATE_float:
2854 case DW_ATE_complex_float:
2855 // XXX need a warning?
2856 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2857 // + ") for " + dwarf_type_name(type), e->tok);
2858 pf->raw_components.append("?");
5f36109e
JS
2859 break;
2860
6561d8d1 2861 case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
5f36109e
JS
2862 case DW_ATE_signed_char:
2863 case DW_ATE_unsigned_char:
941101c1
JS
2864 // Use escapes to make sure that non-printable characters
2865 // don't interrupt our stream (especially '\0' values).
2866 push_deref (pf, "'%#c'", e);
5f36109e
JS
2867 break;
2868
2869 case DW_ATE_unsigned:
c55ea10d 2870 push_deref (pf, "%u", e);
5f36109e
JS
2871 break;
2872
600551ca 2873 case DW_ATE_signed:
5f36109e 2874 default:
c55ea10d 2875 push_deref (pf, "%i", e);
5f36109e
JS
2876 break;
2877 }
5f36109e
JS
2878}
2879
2880
2881void
2882dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2883 print_format* pf, bool top)
5f36109e 2884{
7d11d8c9
JS
2885 if (!top && !print_full)
2886 {
2887 pf->raw_components.append("[...]");
2888 return;
2889 }
2890
5f36109e
JS
2891 Dwarf_Die childtype;
2892 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2893
2894 if (print_chars (&childtype, e, pf))
2895 return;
2896
5f36109e
JS
2897 pf->raw_components.append("[");
2898
2899 // We print the array up to the first 5 elements.
2900 // XXX how can we determine the array size?
2901 // ... for now, just print the first element
64cddf39 2902 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2903 unsigned i, size = 1;
64cddf39 2904 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2905 {
2906 if (i > 0)
2907 pf->raw_components.append(", ");
2908 target_symbol* e2 = new target_symbol(*e);
2909 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2910 recurse (&childtype, e2, pf);
5f36109e
JS
2911 }
2912 if (i < size || 1/*XXX until real size is known */)
2913 pf->raw_components.append(", ...");
2914 pf->raw_components.append("]");
2915}
2916
2917
2918void
2919dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2920 print_format* pf, bool top)
5f36109e 2921{
7d11d8c9 2922 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2923 bool void_p = true;
7d11d8c9 2924 Dwarf_Die pointee;
bbee5bb8 2925 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2926 {
2927 try
2928 {
2929 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2930 void_p = false;
2931 }
2932 catch (const semantic_error&) {}
2933 }
2934
2935 if (!void_p)
5f36109e 2936 {
bbee5bb8
JS
2937 if (print_chars (&pointee, e, pf))
2938 return;
2939
2940 if (top)
2941 {
2942 recurse (&pointee, e, pf, top);
2943 return;
2944 }
5f36109e 2945 }
bbee5bb8 2946
c55ea10d 2947 push_deref (pf, "%p", e);
5f36109e
JS
2948}
2949
2950
2951void
2952dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2953 print_format* pf, bool top)
5f36109e 2954{
bdec0e18
JS
2955 if (dwarf_hasattr(type, DW_AT_declaration))
2956 {
a44a7cb5 2957 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2958 if (!resolved)
2959 {
2960 // could be an error, but for now just stub it
2961 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2962 pf->raw_components.append("{...}");
2963 return;
2964 }
2965 type = resolved;
2966 }
2967
5f36109e
JS
2968 int count = 0;
2969 pf->raw_components.append("{");
7d11d8c9
JS
2970 if (top || print_full)
2971 recurse_struct_members (type, e, pf, count);
2972 else
2973 pf->raw_components.append("...");
5f36109e
JS
2974 pf->raw_components.append("}");
2975}
2976
2977
2978void
2979dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2980 print_format* pf, int& count)
5f36109e 2981{
a80f28d8
JS
2982 /* With inheritance, a subclass may mask member names of parent classes, so
2983 * our search among the inheritance tree must be breadth-first rather than
2984 * depth-first (recursive). The type die is still our starting point. When
2985 * we encounter a masked name, just skip it. */
2986 set<string> dupes;
2987 deque<Dwarf_Die> inheritees(1, *type);
2988 for (; !inheritees.empty(); inheritees.pop_front())
2989 {
dee830d9 2990 Dwarf_Die child, childtype, import;
a80f28d8
JS
2991 if (dwarf_child (&inheritees.front(), &child) == 0)
2992 do
2993 {
2994 target_symbol* e2 = e;
5f36109e 2995
a80f28d8
JS
2996 // skip static members
2997 if (dwarf_hasattr(&child, DW_AT_declaration))
2998 continue;
5f36109e 2999
a80f28d8 3000 int tag = dwarf_tag (&child);
5f36109e 3001
dee830d9
MW
3002 /* Pretend imported units contain members by recursing into
3003 struct_member printing with the same count. */
3004 if (tag == DW_TAG_imported_unit
3005 && dwarf_attr_die (&child, DW_AT_import, &import))
3006 recurse_struct_members (&import, e2, pf, count);
3007
a80f28d8
JS
3008 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
3009 continue;
5f36109e 3010
a80f28d8 3011 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 3012
a80f28d8
JS
3013 if (tag == DW_TAG_inheritance)
3014 {
3015 inheritees.push_back(childtype);
3016 continue;
3017 }
5f36109e 3018
a80f28d8
JS
3019 int childtag = dwarf_tag (&childtype);
3020 const char *member = dwarf_diename (&child);
3a147004 3021
a80f28d8
JS
3022 // "_vptr.foo" members are C++ virtual function tables,
3023 // which (generally?) aren't interesting for users.
3024 if (member && startswith(member, "_vptr."))
3025 continue;
3a147004 3026
a80f28d8
JS
3027 // skip inheritance-masked duplicates
3028 if (member && !dupes.insert(member).second)
3029 continue;
64cddf39 3030
a80f28d8
JS
3031 if (++count > 1)
3032 pf->raw_components.append(", ");
64cddf39 3033
a80f28d8
JS
3034 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
3035 if (pf->args.size() >= 32)
3036 {
3037 pf->raw_components.append("...");
3038 break;
3039 }
3040
3041 if (member)
3042 {
3043 pf->raw_components.append(".");
3044 pf->raw_components.append(member);
5f36109e 3045
a80f28d8
JS
3046 e2 = new target_symbol(*e);
3047 e2->components.push_back (target_symbol::component(e->tok, member));
3048 }
3049 else if (childtag == DW_TAG_union_type)
3050 pf->raw_components.append("<union>");
3051 else if (childtag == DW_TAG_structure_type)
3052 pf->raw_components.append("<class>");
3053 else if (childtag == DW_TAG_class_type)
3054 pf->raw_components.append("<struct>");
3055 pf->raw_components.append("=");
600551ca
JS
3056
3057 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
3058 recurse_bitfield (&childtype, e2, pf);
3059 else
3060 recurse (&childtype, e2, pf);
5f36109e 3061 }
a80f28d8
JS
3062 while (dwarf_siblingof (&child, &child) == 0);
3063 }
5f36109e
JS
3064}
3065
3066
bbee5bb8
JS
3067bool
3068dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
3069 print_format* pf)
3070{
3071 Dwarf_Die type;
3072 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
6561d8d1
JS
3073
3074 Dwarf_Attribute attr;
3075 Dwarf_Word encoding = (Dwarf_Word) -1;
3076 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
3077 &encoding);
3078 switch (encoding)
bbee5bb8 3079 {
6561d8d1
JS
3080 case DW_ATE_UTF:
3081 case DW_ATE_signed_char:
3082 case DW_ATE_unsigned_char:
3083 break;
3084 default:
3085 return false;
3086 }
3087
3088 string function = userspace_p ? "user_string2" : "kernel_string2";
3089 Dwarf_Word size = (Dwarf_Word) -1;
3090 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
3091 switch (size)
3092 {
3093 case 1:
3094 break;
3095 case 2:
3096 function += "_utf16";
3097 break;
3098 case 4:
3099 function += "_utf32";
3100 break;
3101 default:
3102 return false;
3103 }
3104
3105 if (push_deref (pf, "\"%s\"", e))
3106 {
3107 // steal the last arg for a string access
3108 assert (!pf->args.empty());
3109 functioncall* fcall = new functioncall;
3110 fcall->tok = e->tok;
3111 fcall->function = function;
3112 fcall->args.push_back (pf->args.back());
3113 expression *err_msg = new literal_string ("<unknown>");
3114 err_msg->tok = e->tok;
3115 fcall->args.push_back (err_msg);
3116 pf->args.back() = fcall;
bbee5bb8 3117 }
6561d8d1 3118 return true;
bbee5bb8
JS
3119}
3120
a5ce5211
MW
3121// PR10601: adapt to kernel-vs-userspace loc2c-runtime
3122static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
3123 + "#define fetch_register k_fetch_register\n"
3124 + "#define store_register k_store_register\n"
3125 + "#define deref kderef\n"
3126 + "#define store_deref store_kderef\n";
a5ce5211
MW
3127
3128static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
3129 + "#define fetch_register u_fetch_register\n"
3130 + "#define store_register u_store_register\n"
3131 + "#define deref uderef\n"
3132 + "#define store_deref store_uderef\n";
a5ce5211
MW
3133
3134#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 3135 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
3136
3137static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
3138 + "#undef fetch_register\n"
3139 + "#undef store_register\n"
3140 + "#undef deref\n"
3141 + "#undef store_deref\n";
bbee5bb8 3142
1c0be8c7
JS
3143static functioncall*
3144synthetic_embedded_deref_call(systemtap_session& session,
3145 const string& function_name,
3146 const string& function_code,
3147 exp_type function_type,
3148 bool userspace_p,
3149 bool lvalue_p,
3150 target_symbol* e,
3151 expression* pointer=NULL)
3152{
3153 // Synthesize a functiondecl for the given embedded code string.
5f36109e
JS
3154 functiondecl *fdecl = new functiondecl;
3155 fdecl->synthetic = true;
3156 fdecl->tok = e->tok;
1c0be8c7
JS
3157 fdecl->name = function_name;
3158 fdecl->type = function_type;
3159
5f36109e
JS
3160 embeddedcode *ec = new embeddedcode;
3161 ec->tok = e->tok;
1c0be8c7
JS
3162 ec->code += "/* unprivileged */";
3163 if (! lvalue_p)
3164 ec->code += "/* pure */";
3165 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
3166 ec->code += function_code;
3167 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e
JS
3168 fdecl->body = ec;
3169
3170 // Synthesize a functioncall.
3171 functioncall* fcall = new functioncall;
3172 fcall->tok = e->tok;
3173 fcall->function = fdecl->name;
1c0be8c7 3174 fcall->type = fdecl->type;
5f36109e 3175
1c0be8c7
JS
3176 // If this code snippet uses a precomputed pointer,
3177 // pass that as the first argument.
5f36109e
JS
3178 if (pointer)
3179 {
5f36109e
JS
3180 vardecl *v = new vardecl;
3181 v->type = pe_long;
3182 v->name = "pointer";
3183 v->tok = e->tok;
3184 fdecl->formal_args.push_back(v);
3185 fcall->args.push_back(pointer);
3186 }
5f36109e 3187
1c0be8c7 3188 // Any non-literal indexes need to be passed as arguments too.
5f36109e
JS
3189 for (unsigned i = 0; i < e->components.size(); ++i)
3190 if (e->components[i].type == target_symbol::comp_expression_array_index)
3191 {
3192 vardecl *v = new vardecl;
3193 v->type = pe_long;
3194 v->name = "index" + lex_cast(i);
3195 v->tok = e->tok;
3196 fdecl->formal_args.push_back(v);
3197 fcall->args.push_back(e->components[i].expr_index);
3198 }
3199
1c0be8c7
JS
3200 // If this code snippet is assigning to an lvalue,
3201 // add a final argument for the rvalue.
3202 if (lvalue_p)
3203 {
3204 // Modify the fdecl so it carries a single pe_long formal
3205 // argument called "value".
5f36109e 3206
1c0be8c7
JS
3207 // FIXME: For the time being we only support setting target
3208 // variables which have base types; these are 'pe_long' in
3209 // stap's type vocabulary. Strings and pointers might be
3210 // reasonable, some day, but not today.
5f36109e 3211
1c0be8c7
JS
3212 vardecl *v = new vardecl;
3213 v->type = pe_long;
3214 v->name = "value";
3215 v->tok = e->tok;
3216 fdecl->formal_args.push_back(v);
3217 // NB: We don't know the value for fcall argument yet.
3218 // (see target_symbol_setter_functioncalls)
3219 }
3220
3221 // Add the synthesized decl to the session, and return the call.
3222 fdecl->join (session);
5f36109e
JS
3223 return fcall;
3224}
3225
1c0be8c7
JS
3226expression*
3227dwarf_pretty_print::deref (target_symbol* e)
3228{
3229 static unsigned tick = 0;
3230
3231 if (!deref_p)
3232 {
3233 assert (pointer && e->components.empty());
3234 return pointer;
3235 }
3236
3237 bool lvalue_p = false;
3238 string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
3239
3240 string code;
3241 exp_type type = pe_long;
3242 if (pointer)
3243 code = dw.literal_stmt_for_pointer (&pointer_type, e, false, type);
3244 else if (!local.empty())
3245 code = dw.literal_stmt_for_local (scopes, pc, local, e, false, type);
3246 else
3247 code = dw.literal_stmt_for_return (&scopes[0], pc, e, false, type);
3248
3249 return synthetic_embedded_deref_call(dw.sess, name, code, type,
3250 userspace_p, lvalue_p, e, pointer);
3251}
3252
5f36109e 3253
c55ea10d
JS
3254bool
3255dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3256 target_symbol* e)
3257{
3258 expression* e2 = NULL;
3259 try
3260 {
3261 e2 = deref (e);
3262 }
3263 catch (const semantic_error&)
3264 {
3265 pf->raw_components.append ("?");
3266 return false;
3267 }
3268 pf->raw_components.append (fmt);
3269 pf->args.push_back (e2);
3270 return true;
3271}
3272
3273
e57b735a 3274void
a7999c82 3275dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3276{
a7999c82
JS
3277 // Get the full name of the target symbol.
3278 stringstream ts_name_stream;
3279 e->print(ts_name_stream);
3280 string ts_name = ts_name_stream.str();
3281
3282 // Check and make sure we haven't already seen this target
3283 // variable in this return probe. If we have, just return our
3284 // last replacement.
af234c40 3285 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3286 if (i != return_ts_map.end())
85ecf79a 3287 {
a7999c82
JS
3288 provide (i->second);
3289 return;
3290 }
85ecf79a 3291
70208613
JS
3292 // Attempt the expansion directly first, so if there's a problem with the
3293 // variable we won't have a bogus entry probe lying around. Like in
3294 // saveargs(), we pretend for a moment that we're not in a .return.
3295 bool saved_has_return = q.has_return;
3296 q.has_return = false;
3297 expression *repl = e;
3298 replace (repl);
3299 q.has_return = saved_has_return;
3300 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3301 if (n && n->saved_conversion_error)
3302 {
3303 provide (repl);
3304 return;
3305 }
3306
af234c40
JS
3307 expression *exp;
3308 if (!q.has_process &&
3309 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3310 exp = gen_kretprobe_saved_return(repl);
af234c40 3311 else
cc9001af 3312 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3313
3314 // Provide the variable to our parent so it can be used as a
3315 // substitute for the target symbol.
3316 provide (exp);
3317
3318 // Remember this replacement since we might be able to reuse
3319 // it later if the same return probe references this target
3320 // symbol again.
3321 return_ts_map[ts_name] = exp;
3322}
3323
4a2970a3 3324static expression*
23dc94f6
DS
3325gen_mapped_saved_return(systemtap_session &sess, expression* e,
3326 const string& name,
3327 block *& add_block, bool& add_block_tid,
3328 block *& add_call_probe, bool& add_call_probe_tid)
af234c40 3329{
23dc94f6
DS
3330 static unsigned tick = 0;
3331
a7999c82
JS
3332 // We've got to do several things here to handle target
3333 // variables in return probes.
85ecf79a 3334
a7999c82
JS
3335 // (1) Synthesize two global arrays. One is the cache of the
3336 // target variable and the other contains a thread specific
3337 // nesting level counter. The arrays will look like
3338 // this:
3339 //
23dc94f6
DS
3340 // _entry_tvar_{name}_{num}
3341 // _entry_tvar_{name}_{num}_ctr
a7999c82 3342
23dc94f6 3343 string aname = (string("_entry_tvar_")
cc9001af 3344 + name
aca66a36 3345 + "_" + lex_cast(tick++));
a7999c82
JS
3346 vardecl* vd = new vardecl;
3347 vd->name = aname;
3348 vd->tok = e->tok;
23dc94f6 3349 sess.globals.push_back (vd);
a7999c82
JS
3350
3351 string ctrname = aname + "_ctr";
3352 vd = new vardecl;
3353 vd->name = ctrname;
3354 vd->tok = e->tok;
23dc94f6 3355 sess.globals.push_back (vd);
a7999c82
JS
3356
3357 // (2) Create a new code block we're going to insert at the
3358 // beginning of this probe to get the cached value into a
3359 // temporary variable. We'll replace the target variable
3360 // reference with the temporary variable reference. The code
3361 // will look like this:
3362 //
23dc94f6
DS
3363 // _entry_tvar_tid = tid()
3364 // _entry_tvar_{name}_{num}_tmp
3365 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3366 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
3367 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3368 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
3369 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3370 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3371
3372 // (2a) Synthesize the tid temporary expression, which will look
3373 // like this:
3374 //
23dc94f6 3375 // _entry_tvar_tid = tid()
a7999c82 3376 symbol* tidsym = new symbol;
23dc94f6 3377 tidsym->name = string("_entry_tvar_tid");
a7999c82 3378 tidsym->tok = e->tok;
85ecf79a 3379
a7999c82
JS
3380 if (add_block == NULL)
3381 {
3382 add_block = new block;
3383 add_block->tok = e->tok;
8cc799a5 3384 }
8c819921 3385
8cc799a5
JS
3386 if (!add_block_tid)
3387 {
a7999c82
JS
3388 // Synthesize a functioncall to grab the thread id.
3389 functioncall* fc = new functioncall;
3390 fc->tok = e->tok;
3391 fc->function = string("tid");
8c819921 3392
23dc94f6 3393 // Assign the tid to '_entry_tvar_tid'.
8c819921
DS
3394 assignment* a = new assignment;
3395 a->tok = e->tok;
3396 a->op = "=";
a7999c82
JS
3397 a->left = tidsym;
3398 a->right = fc;
8c819921
DS
3399
3400 expr_statement* es = new expr_statement;
3401 es->tok = e->tok;
3402 es->value = a;
8c819921 3403 add_block->statements.push_back (es);
8cc799a5 3404 add_block_tid = true;
a7999c82 3405 }
8c819921 3406
a7999c82
JS
3407 // (2b) Synthesize an array reference and assign it to a
3408 // temporary variable (that we'll use as replacement for the
3409 // target variable reference). It will look like this:
3410 //
23dc94f6
DS
3411 // _entry_tvar_{name}_{num}_tmp
3412 // = _entry_tvar_{name}_{num}[_entry_tvar_tid,
3413 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3414
3415 arrayindex* ai_tvar_base = new arrayindex;
3416 ai_tvar_base->tok = e->tok;
3417
3418 symbol* sym = new symbol;
3419 sym->name = aname;
3420 sym->tok = e->tok;
3421 ai_tvar_base->base = sym;
3422
3423 ai_tvar_base->indexes.push_back(tidsym);
3424
3425 // We need to create a copy of the array index in its current
3426 // state so we can have 2 variants of it (the original and one
3427 // that post-decrements the second index).
3428 arrayindex* ai_tvar = new arrayindex;
3429 arrayindex* ai_tvar_postdec = new arrayindex;
3430 *ai_tvar = *ai_tvar_base;
3431 *ai_tvar_postdec = *ai_tvar_base;
3432
3433 // Synthesize the
23dc94f6 3434 // "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
a7999c82
JS
3435 // second index into the array.
3436 arrayindex* ai_ctr = new arrayindex;
3437 ai_ctr->tok = e->tok;
3438
3439 sym = new symbol;
3440 sym->name = ctrname;
3441 sym->tok = e->tok;
3442 ai_ctr->base = sym;
3443 ai_ctr->indexes.push_back(tidsym);
3444 ai_tvar->indexes.push_back(ai_ctr);
3445
3446 symbol* tmpsym = new symbol;
3447 tmpsym->name = aname + "_tmp";
3448 tmpsym->tok = e->tok;
3449
3450 assignment* a = new assignment;
3451 a->tok = e->tok;
3452 a->op = "=";
3453 a->left = tmpsym;
3454 a->right = ai_tvar;
3455
3456 expr_statement* es = new expr_statement;
3457 es->tok = e->tok;
3458 es->value = a;
3459
3460 add_block->statements.push_back (es);
3461
3462 // (2c) Add a post-decrement to the second array index and
3463 // delete the array value. It will look like this:
3464 //
23dc94f6
DS
3465 // delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
3466 // _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
a7999c82
JS
3467
3468 post_crement* pc = new post_crement;
3469 pc->tok = e->tok;
3470 pc->op = "--";
3471 pc->operand = ai_ctr;
3472 ai_tvar_postdec->indexes.push_back(pc);
3473
3474 delete_statement* ds = new delete_statement;
3475 ds->tok = e->tok;
3476 ds->value = ai_tvar_postdec;
3477
3478 add_block->statements.push_back (ds);
3479
3480 // (2d) Delete the counter value if it is 0. It will look like
3481 // this:
23dc94f6
DS
3482 // if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
3483 // delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
a7999c82
JS
3484
3485 ds = new delete_statement;
3486 ds->tok = e->tok;
3487 ds->value = ai_ctr;
3488
3489 unary_expression *ue = new unary_expression;
3490 ue->tok = e->tok;
3491 ue->op = "!";
3492 ue->operand = ai_ctr;
3493
3494 if_statement *ifs = new if_statement;
3495 ifs->tok = e->tok;
3496 ifs->condition = ue;
3497 ifs->thenblock = ds;
3498 ifs->elseblock = NULL;
3499
3500 add_block->statements.push_back (ifs);
3501
3502 // (3) We need an entry probe that saves the value for us in the
3503 // global array we created. Create the entry probe, which will
3504 // look like this:
3505 //
2260f4e3 3506 // probe kernel.function("{function}").call {
23dc94f6
DS
3507 // _entry_tvar_tid = tid()
3508 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3509 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3510 // = ${param}
3511 // }
3512
2260f4e3 3513 if (add_call_probe == NULL)
a7999c82 3514 {
2260f4e3
FCE
3515 add_call_probe = new block;
3516 add_call_probe->tok = e->tok;
8cc799a5 3517 }
4baf0e53 3518
8cc799a5
JS
3519 if (!add_call_probe_tid)
3520 {
a7999c82
JS
3521 // Synthesize a functioncall to grab the thread id.
3522 functioncall* fc = new functioncall;
3523 fc->tok = e->tok;
3524 fc->function = string("tid");
4baf0e53 3525
23dc94f6 3526 // Assign the tid to '_entry_tvar_tid'.
a7999c82 3527 assignment* a = new assignment;
8fc05e57
DS
3528 a->tok = e->tok;
3529 a->op = "=";
a7999c82
JS
3530 a->left = tidsym;
3531 a->right = fc;
8fc05e57 3532
a7999c82 3533 expr_statement* es = new expr_statement;
8fc05e57
DS
3534 es->tok = e->tok;
3535 es->value = a;
2260f4e3 3536 add_call_probe = new block(add_call_probe, es);
8cc799a5 3537 add_call_probe_tid = true;
85ecf79a 3538 }
cf2a1f85 3539
a7999c82 3540 // Save the value, like this:
23dc94f6
DS
3541 // _entry_tvar_{name}_{num}[_entry_tvar_tid,
3542 // ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
a7999c82
JS
3543 // = ${param}
3544 arrayindex* ai_tvar_preinc = new arrayindex;
3545 *ai_tvar_preinc = *ai_tvar_base;
3546
3547 pre_crement* preinc = new pre_crement;
3548 preinc->tok = e->tok;
3549 preinc->op = "++";
3550 preinc->operand = ai_ctr;
3551 ai_tvar_preinc->indexes.push_back(preinc);
3552
3553 a = new assignment;
3554 a->tok = e->tok;
3555 a->op = "=";
3556 a->left = ai_tvar_preinc;
3557 a->right = e;
3558
3559 es = new expr_statement;
3560 es->tok = e->tok;
3561 es->value = a;
3562
2260f4e3 3563 add_call_probe = new block(add_call_probe, es);
a7999c82 3564
23dc94f6 3565 // (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
a7999c82
JS
3566 // our parent so it can be used as a substitute for the target
3567 // symbol.
3f803f9e 3568 delete ai_tvar_base;
af234c40
JS
3569 return tmpsym;
3570}
a7999c82 3571
af234c40 3572
23dc94f6
DS
3573expression*
3574dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
3575 const string& name)
3576{
3577 return ::gen_mapped_saved_return(q.sess, e, name, add_block,
3578 add_block_tid, add_call_probe,
3579 add_call_probe_tid);
3580}
3581
3582
af234c40 3583expression*
140be17a 3584dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3585{
3586 // The code for this is simple.
3587 //
3588 // .call:
3589 // _set_kretprobe_long(index, $value)
3590 //
3591 // .return:
3592 // _get_kretprobe_long(index)
3593 //
3594 // (or s/long/string/ for things like $$parms)
3595
3596 unsigned index;
3597 string setfn, getfn;
3598
140be17a
JS
3599 // We need the caller to predetermine the type of the expression!
3600 switch (e->type)
af234c40 3601 {
140be17a 3602 case pe_string:
af234c40
JS
3603 index = saved_strings++;
3604 setfn = "_set_kretprobe_string";
3605 getfn = "_get_kretprobe_string";
140be17a
JS
3606 break;
3607 case pe_long:
af234c40
JS
3608 index = saved_longs++;
3609 setfn = "_set_kretprobe_long";
3610 getfn = "_get_kretprobe_long";
140be17a
JS
3611 break;
3612 default:
dc09353a 3613 throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3614 }
3615
3616 // Create the entry code
3617 // _set_kretprobe_{long|string}(index, $value)
3618
3619 if (add_call_probe == NULL)
3620 {
3621 add_call_probe = new block;
3622 add_call_probe->tok = e->tok;
3623 }
3624
3625 functioncall* set_fc = new functioncall;
3626 set_fc->tok = e->tok;
3627 set_fc->function = setfn;
3628 set_fc->args.push_back(new literal_number(index));
3629 set_fc->args.back()->tok = e->tok;
3630 set_fc->args.push_back(e);
3631
3632 expr_statement* set_es = new expr_statement;
3633 set_es->tok = e->tok;
3634 set_es->value = set_fc;
3635
3636 add_call_probe->statements.push_back(set_es);
3637
3638 // Create the return code
3639 // _get_kretprobe_{long|string}(index)
3640
3641 functioncall* get_fc = new functioncall;
3642 get_fc->tok = e->tok;
3643 get_fc->function = getfn;
3644 get_fc->args.push_back(new literal_number(index));
3645 get_fc->args.back()->tok = e->tok;
3646
3647 return get_fc;
a7999c82 3648}
a43ba433 3649
2cb3fe26 3650
a7999c82
JS
3651void
3652dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3653{
b78a0fbb 3654 if (null_die(scope_die)) {
04c8e51b
JL
3655 literal_string *empty = new literal_string("");
3656 empty->tok = e->tok;
3657 provide(empty);
a7999c82 3658 return;
b78a0fbb 3659 }
2cb3fe26 3660
5f36109e
JS
3661 target_symbol *tsym = new target_symbol(*e);
3662
fde50242
JS
3663 bool pretty = (!e->components.empty() &&
3664 e->components[0].type == target_symbol::comp_pretty_print);
3665 string format = pretty ? "=%s" : "=%#x";
a43ba433 3666
a7999c82
JS
3667 // Convert $$parms to sprintf of a list of parms and active local vars
3668 // which we recursively evaluate
a43ba433 3669
1c922ad7 3670 print_format* pf = print_format::create(e->tok, "sprintf");
a7999c82 3671
277c21bc 3672 if (q.has_return && (e->name == "$$return"))
a7999c82 3673 {
277c21bc 3674 tsym->name = "$return";
a7999c82
JS
3675
3676 // Ignore any variable that isn't accessible.
3677 tsym->saved_conversion_error = 0;
3678 expression *texp = tsym;
8b095b45 3679 replace (texp); // NB: throws nothing ...
a7999c82 3680 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3681 {
2cb3fe26 3682
a43ba433
FCE
3683 }
3684 else
3685 {
a7999c82 3686 pf->raw_components += "return";
5f36109e 3687 pf->raw_components += format;
a7999c82
JS
3688 pf->args.push_back(texp);
3689 }
3690 }
3691 else
3692 {
3693 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3694 bool first = true;
a7999c82 3695 Dwarf_Die result;
d48bc7eb
JS
3696 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3697 for (unsigned i = 0; i < scopes.size(); ++i)
3698 {
3699 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3700 break; // we don't want file-level variables
3701 if (dwarf_child (&scopes[i], &result) == 0)
3702 do
00cf3709 3703 {
d48bc7eb
JS
3704 switch (dwarf_tag (&result))
3705 {
3706 case DW_TAG_variable:
3707 if (e->name == "$$parms")
3708 continue;
3709 break;
3710 case DW_TAG_formal_parameter:
3711 if (e->name == "$$locals")
3712 continue;
3713 break;
3714
3715 default:
3716 continue;
3717 }
41c262f3 3718
d48bc7eb
JS
3719 const char *diename = dwarf_diename (&result);
3720 if (! diename) continue;
f76427a2 3721
d48bc7eb
JS
3722 if (! first)
3723 pf->raw_components += " ";
3724 pf->raw_components += diename;
fde50242
JS
3725 first = false;
3726
3727 // Write a placeholder for ugly aggregates
3728 Dwarf_Die type;
3729 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3730 {
3731 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3732 switch (dwarf_tag(&type))
3733 {
3734 case DW_TAG_union_type:
3735 case DW_TAG_structure_type:
3736 case DW_TAG_class_type:
3737 pf->raw_components += "={...}";
3738 continue;
3739
3740 case DW_TAG_array_type:
3741 pf->raw_components += "=[...]";
3742 continue;
3743 }
3744 }
345bbb3d 3745
d48bc7eb
JS
3746 tsym->name = "$";
3747 tsym->name += diename;
41c262f3 3748
d48bc7eb
JS
3749 // Ignore any variable that isn't accessible.
3750 tsym->saved_conversion_error = 0;
3751 expression *texp = tsym;
3752 replace (texp); // NB: throws nothing ...
3753 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3754 {
d48bc7eb
JS
3755 if (q.sess.verbose>2)
3756 {
e26c2f83 3757 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb 3758 c != 0;
c081af73 3759 c = c->get_chain()) {
4c5d9906 3760 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
d48bc7eb
JS
3761 }
3762 }
3763
3764 pf->raw_components += "=?";
a43ba433 3765 }
d48bc7eb
JS
3766 else
3767 {
3768 pf->raw_components += format;
3769 pf->args.push_back(texp);
3770 }
a7999c82 3771 }
d48bc7eb
JS
3772 while (dwarf_siblingof (&result, &result) == 0);
3773 }
a7999c82 3774 }
2cb3fe26 3775
a7999c82 3776 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3777 pf->type = pe_string;
a7999c82
JS
3778 provide (pf);
3779}
3780
2cb3fe26 3781
bd1fcbad
YZ
3782void
3783dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
3784{
3785 // Fill in our current module context if needed
3786 if (e->module.empty())
3787 e->module = q.dw.module_name;
3788
3789 if (e->module == q.dw.module_name && e->cu_name.empty())
3790 {
3791 // process like any other local
3792 // e->sym_name() will do the right thing
3793 visit_target_symbol(e);
3794 return;
3795 }
3796
3797 var_expanding_visitor::visit_atvar_op(e);
3798}
3799
3800
a7999c82
JS
3801void
3802dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3803{
bd1fcbad 3804 assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
a7999c82 3805 visited = true;
30263a73
FCE
3806 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3807 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3808
70208613 3809 try
a7999c82 3810 {
c69a87e0
FCE
3811 bool lvalue = is_active_lvalue(e);
3812 if (lvalue && !q.sess.guru_mode)
dc09353a 3813 throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3814
100a540e 3815 // XXX: process $context vars should be writable
70208613 3816
c69a87e0
FCE
3817 // See if we need to generate a new probe to save/access function
3818 // parameters from a return probe. PR 1382.
3819 if (q.has_return
3820 && !defined_being_checked
277c21bc
JS
3821 && e->name != "$return" // not the special return-value variable handled below
3822 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3823 {
3824 if (lvalue)
dc09353a 3825 throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3826 visit_target_symbol_saved_return(e);
3827 return;
3828 }
e57b735a 3829
277c21bc
JS
3830 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3831 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3832 {
3833 if (lvalue)
dc09353a 3834 throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
70208613 3835
c69a87e0 3836 if (e->addressof)
dc09353a 3837 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
70208613 3838
5f36109e
JS
3839 e->assert_no_components("dwarf", true);
3840
c69a87e0
FCE
3841 visit_target_symbol_context(e);
3842 return;
3843 }
70208613 3844
04c8e51b
JL
3845 // Everything else (pretty-printed vars, and context vars) require a
3846 // scope_die in which to search for them. If we don't have that, just
3847 // leave it unresolved; we'll produce an error later on.
3848 if (null_die(scope_die))
3849 {
3850 provide(e);
3851 return;
3852 }
3853
5f36109e
JS
3854 if (!e->components.empty() &&
3855 e->components.back().type == target_symbol::comp_pretty_print)
3856 {
3857 if (lvalue)
dc09353a 3858 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3859
277c21bc 3860 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3861 {
3862 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3863 q.has_process, *e);
3864 dpp.expand()->visit(this);
3865 }
3866 else
3867 {
3868 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3869 e->sym_name(),
5f36109e
JS
3870 q.has_process, *e);
3871 dpp.expand()->visit(this);
3872 }
3873 return;
3874 }
3875
1c0be8c7 3876 bool userspace_p = q.has_process;
c69a87e0 3877 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3878 + "_" + e->sym_name()
c69a87e0 3879 + "_" + lex_cast(tick++));
70208613 3880
70208613 3881
1c0be8c7
JS
3882 exp_type type = pe_long;
3883 string code;
277c21bc 3884 if (q.has_return && (e->name == "$return"))
1c0be8c7 3885 code = q.dw.literal_stmt_for_return (scope_die, addr, e, lvalue, type);
e19fda4e 3886 else
1c0be8c7
JS
3887 code = q.dw.literal_stmt_for_local (getscopes(e), addr, e->sym_name(),
3888 e, lvalue, type);
70208613 3889
1c0be8c7
JS
3890 functioncall* n = synthetic_embedded_deref_call(q.sess, fname, code, type,
3891 userspace_p, lvalue, e);
70208613 3892
c69a87e0
FCE
3893 if (lvalue)
3894 {
3895 // Provide the functioncall to our parent, so that it can be
3896 // used to substitute for the assignment node immediately above
3897 // us.
3898 assert(!target_symbol_setter_functioncalls.empty());
3899 *(target_symbol_setter_functioncalls.top()) = n;
3900 }
70208613 3901
1c0be8c7
JS
3902 // Revisit the functioncall so arguments can be expanded.
3903 n->visit (this);
66d284f4
FCE
3904 }
3905 catch (const semantic_error& er)
3906 {
9fab2262
JS
3907 // We suppress this error message, and pass the unresolved
3908 // target_symbol to the next pass. We hope that this value ends
3909 // up not being referenced after all, so it can be optimized out
3910 // quietly.
1af1e62d 3911 e->chain (er);
9fab2262 3912 provide (e);
66d284f4 3913 }
77de5e9e
GH
3914}
3915
3916
c24447be
JS
3917void
3918dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3919{
3920 // Fill in our current module context if needed
3921 if (e->module.empty())
3922 e->module = q.dw.module_name;
3923
3924 var_expanding_visitor::visit_cast_op(e);
3925}
3926
3927
8cc799a5
JS
3928void
3929dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3930{
3931 expression *repl = e;
3932 if (q.has_return)
3933 {
3934 // expand the operand as if it weren't a return probe
3935 q.has_return = false;
3936 replace (e->operand);
3937 q.has_return = true;
3938
3939 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3940 // but it requires knowing the types already, which is problematic for
3941 // arbitrary expressons.
cc9001af 3942 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3943 }
3944 provide (repl);
3945}
3946
3689db05
SC
3947void
3948dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
3949{
ace7c23f 3950 string e_lit_val = e->operand->value;
b78a0fbb 3951
3689db05 3952 add_block = new block;
9eaaceaa 3953 add_block->tok = e->tok;
3689db05
SC
3954
3955 systemtap_session &s = this->q.sess;
3956 map<string, pair<string,derived_probe*> >::iterator it;
3957 // Find the associated perf.counter probe
3958 for (it=s.perf_counters.begin();
3959 it != s.perf_counters.end();
3960 it++)
3961 if ((*it).first == e_lit_val)
3962 {
3963 // if perf .function("name") omitted, then set it to this process name
3964 if ((*it).second.first.length() == 0)
3965 ((*it).second).first = this->q.user_path;
3966 if (((*it).second).first == this->q.user_path)
3967 break;
3968 }
3969
3970 if (it != s.perf_counters.end())
3971 {
698de6cc 3972 perf_counter_refs.insert((*it).second.second);
3689db05
SC
3973 // __perf_read_N is assigned in the probe prologue
3974 symbol* sym = new symbol;
4653caf1 3975 sym->tok = e->tok;
3689db05
SC
3976 sym->name = "__perf_read_" + (*it).first;
3977 provide (sym);
3978 }
3979 else
dc09353a 3980 throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
3689db05
SC
3981}
3982
8cc799a5 3983
729455a7
JS
3984vector<Dwarf_Die>&
3985dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3986{
3987 if (scopes.empty())
3988 {
04c8e51b 3989 if(!null_die(scope_die))
f25a9197 3990 scopes = q.dw.getscopes(scope_die);
729455a7 3991 if (scopes.empty())
b530b5b3
LB
3992 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3993 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
dc09353a 3994 throw SEMANTIC_ERROR ("unable to find any scopes containing "
729455a7 3995 + lex_cast_hex(addr)
04c8e51b 3996 + (null_die(scope_die) ? ""
729455a7
JS
3997 : (string (" in ")
3998 + (dwarf_diename(scope_die) ?: "<unknown>")
3999 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
4000 + ")"))
4001 + " while searching for local '"
cc9001af 4002 + e->sym_name() + "'",
729455a7
JS
4003 e->tok);
4004 }
4005 return scopes;
4006}
4007
4008
5f36109e
JS
4009struct dwarf_cast_expanding_visitor: public var_expanding_visitor
4010{
4011 systemtap_session& s;
4012 dwarf_builder& db;
4013
4014 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4015 s(s), db(db) {}
4016 void visit_cast_op (cast_op* e);
4017 void filter_special_modules(string& module);
4018};
4019
4020
c4ce66a1
JS
4021struct dwarf_cast_query : public base_query
4022{
946e1a48 4023 cast_op& e;
c4ce66a1 4024 const bool lvalue;
5f36109e
JS
4025 const bool userspace_p;
4026 functioncall*& result;
c4ce66a1 4027
5f36109e
JS
4028 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
4029 const bool userspace_p, functioncall*& result):
abb41d92 4030 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 4031 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
4032
4033 void handle_query_module();
822a6a3d 4034 void query_library (const char *) {}
576eaefe 4035 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
4036};
4037
4038
c4ce66a1
JS
4039void
4040dwarf_cast_query::handle_query_module()
4041{
5f36109e
JS
4042 static unsigned tick = 0;
4043
4044 if (result)
c4ce66a1
JS
4045 return;
4046
ea1e477a 4047 // look for the type in any CU
a44a7cb5
JS
4048 Dwarf_Die* type_die = NULL;
4049 if (startswith(e.type_name, "class "))
4050 {
4051 // normalize to match dwflpp::global_alias_caching_callback
4052 string struct_name = "struct " + e.type_name.substr(6);
4053 type_die = dw.declaration_resolve_other_cus(struct_name);
4054 }
4055 else
4056 type_die = dw.declaration_resolve_other_cus(e.type_name);
4057
4058 // NB: We now index the types as "struct name"/"union name"/etc. instead of
4059 // just "name". But since we didn't require users to be explicit before, and
4060 // actually sort of discouraged it, we must be flexible now. So if a lookup
4061 // fails with a bare name, try augmenting it.
4062 if (!type_die &&
4063 !startswith(e.type_name, "class ") &&
4064 !startswith(e.type_name, "struct ") &&
4065 !startswith(e.type_name, "union ") &&
4066 !startswith(e.type_name, "enum "))
4067 {
4068 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
4069 if (!type_die)
4070 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
4071 if (!type_die)
4072 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
4073 }
4074
ea1e477a
JS
4075 if (!type_die)
4076 return;
c4ce66a1 4077
5f36109e
JS
4078 string code;
4079 exp_type type = pe_long;
4080
ea1e477a 4081 try
c4ce66a1 4082 {
ea1e477a
JS
4083 Dwarf_Die cu_mem;
4084 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
4085
4086 if (!e.components.empty() &&
4087 e.components.back().type == target_symbol::comp_pretty_print)
4088 {
4089 if (lvalue)
dc09353a 4090 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 4091
d19a9a82 4092 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
4093 result = dpp.expand();
4094 return;
4095 }
4096
4097 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
4098 }
4099 catch (const semantic_error& er)
4100 {
4101 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
4102 // may be attempted using several different modules:
4103 // @cast(ptr, "type", "module1:module2:...")
4104 e.chain (er);
c4ce66a1 4105 }
c4ce66a1 4106
5f36109e
JS
4107 if (code.empty())
4108 return;
c4ce66a1 4109
5f36109e 4110 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 4111 + "_" + e.sym_name()
5f36109e 4112 + "_" + lex_cast(tick++));
c4ce66a1 4113
1c0be8c7
JS
4114 result = synthetic_embedded_deref_call(dw.sess, fname, code, type,
4115 userspace_p, lvalue, &e, e.operand);
5f36109e 4116}
c4ce66a1
JS
4117
4118
fb0274bc
JS
4119void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
4120{
d90053e7 4121 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 4122 // for those cases, build a module including that header
d90053e7 4123 if (module[module.size() - 1] == '>' &&
60d98537 4124 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
4125 {
4126 string cached_module;
4127 if (s.use_cache)
4128 {
4129 // see if the cached module exists
a2639cb7 4130 cached_module = find_typequery_hash(s, module);
d105f664 4131 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
4132 {
4133 int fd = open(cached_module.c_str(), O_RDONLY);
4134 if (fd != -1)
4135 {
4136 if (s.verbose > 2)
b530b5b3
LB
4137 //TRANSLATORS: Here we're using a cached module.
4138 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
4139 module = cached_module;
4140 close(fd);
4141 return;
4142 }
4143 }
4144 }
4145
4146 // no cached module, time to make it
d90053e7 4147 if (make_typequery(s, module) == 0)
fb0274bc 4148 {
e16dc041 4149 // try to save typequery in the cache
fb0274bc 4150 if (s.use_cache)
e16dc041 4151 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4152 }
4153 }
4154}
4155
4156
c4ce66a1
JS
4157void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4158{
4159 bool lvalue = is_active_lvalue(e);
4160 if (lvalue && !s.guru_mode)
dc09353a 4161 throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4162
4163 if (e->module.empty())
4164 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4165
5f36109e 4166 functioncall* result = NULL;
8b31197b
JS
4167
4168 // split the module string by ':' for alternatives
4169 vector<string> modules;
4170 tokenize(e->module, modules, ":");
b5a0dd41 4171 bool userspace_p=false; // PR10601
5f36109e 4172 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4173 {
8b31197b 4174 string& module = modules[i];
fb0274bc 4175 filter_special_modules(module);
abb41d92 4176
c4ce66a1
JS
4177 // NB: This uses '/' to distinguish between kernel modules and userspace,
4178 // which means that userspace modules won't get any PATH searching.
4179 dwflpp* dw;
707bf35e
JS
4180 try
4181 {
b5a0dd41
FCE
4182 userspace_p=is_user_module (module);
4183 if (! userspace_p)
707bf35e
JS
4184 {
4185 // kernel or kernel module target
ae2552da 4186 dw = db.get_kern_dw(s, module);
707bf35e
JS
4187 }
4188 else
4189 {
05fb3e0c 4190 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4191 dw = db.get_user_dw(s, module);
4192 }
4193 }
4194 catch (const semantic_error& er)
4195 {
4196 /* ignore and go to the next module */
4197 continue;
4198 }
c4ce66a1 4199
5f36109e 4200 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
06de3a04 4201 dw->iterate_over_modules<base_query>(&query_module, &q);
c4ce66a1 4202 }
abb41d92 4203
5f36109e 4204 if (!result)
c4ce66a1 4205 {
946e1a48
JS
4206 // We pass the unresolved cast_op to the next pass, and hope
4207 // that this value ends up not being referenced after all, so
4208 // it can be optimized out quietly.
c4ce66a1
JS
4209 provide (e);
4210 return;
4211 }
4212
c4ce66a1
JS
4213 if (lvalue)
4214 {
4215 // Provide the functioncall to our parent, so that it can be
4216 // used to substitute for the assignment node immediately above
4217 // us.
4218 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4219 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4220 }
4221
5f36109e 4222 result->visit (this);
77de5e9e
GH
4223}
4224
4225
bd1fcbad
YZ
4226struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
4227{
4228 systemtap_session& s;
4229 dwarf_builder& db;
4230
4231 dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
4232 s(s), db(db) {}
4233 void visit_atvar_op (atvar_op* e);
4234};
4235
4236
4237struct dwarf_atvar_query: public base_query
4238{
4239 atvar_op& e;
4240 const bool userspace_p, lvalue;
4241 functioncall*& result;
4242 unsigned& tick;
4243 const string cu_name_pattern;
4244
4245 dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
4246 const bool userspace_p, const bool lvalue,
4247 functioncall*& result,
4248 unsigned& tick):
4249 base_query(dw, module), e(e),
4250 userspace_p(userspace_p), lvalue(lvalue), result(result),
4251 tick(tick), cu_name_pattern(string("*/") + e.cu_name) {}
4252
4253 void handle_query_module ();
4254 void query_library (const char *) {}
4255 void query_plt (const char *entry, size_t addr) {}
5c378838 4256 static int atvar_query_cu (Dwarf_Die *cudie, dwarf_atvar_query *q);
bd1fcbad
YZ
4257};
4258
4259
4260int
5c378838 4261dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, dwarf_atvar_query *q)
bd1fcbad 4262{
bd1fcbad
YZ
4263 if (! q->e.cu_name.empty())
4264 {
c60517ca 4265 const char *die_name = dwarf_diename(cudie) ?: "";
bd1fcbad
YZ
4266 if (strcmp(die_name, q->e.cu_name.c_str()) != 0 // Perfect match
4267 && fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
4268 {
4269 return DWARF_CB_OK;
4270 }
4271 }
4272
4273 try
4274 {
4275 vector<Dwarf_Die> scopes(1, *cudie);
4276
4277 q->dw.focus_on_cu (cudie);
4278
4279 if (! q->e.components.empty() &&
4280 q->e.components.back().type == target_symbol::comp_pretty_print)
4281 {
4282 dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
4283 q->userspace_p, q->e);
4284 q->result = dpp.expand();
4285 return DWARF_CB_ABORT;
4286 }
4287
4288 exp_type type = pe_long;
4289 string code = q->dw.literal_stmt_for_local (scopes, 0, q->e.sym_name(),
4290 &q->e, q->lvalue, type);
4291
4292 if (code.empty())
4293 return DWARF_CB_OK;
4294
4295 string fname = (string(q->lvalue ? "_dwarf_tvar_set"
4296 : "_dwarf_tvar_get")
4297 + "_" + q->e.sym_name()
4298 + "_" + lex_cast(q->tick++));
4299
4300 q->result = synthetic_embedded_deref_call (q->sess, fname, code, type,
4301 q->userspace_p, q->lvalue,
4302 &q->e);
4303 }
4304 catch (const semantic_error& er)
4305 {
4306 // Here we suppress the error because we often just have too many
4307 // when scanning all the CUs.
4308 return DWARF_CB_OK;
4309 }
4310
4311 if (q->result) {
4312 return DWARF_CB_ABORT;
4313 }
4314
4315 return DWARF_CB_OK;
4316}
4317
4318
4319void
4320dwarf_atvar_query::handle_query_module ()
4321{
4322
4323 dw.iterate_over_cus(atvar_query_cu, this, false);
4324}
4325
4326
4327void
4328dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
4329{
4330 const bool lvalue = is_active_lvalue(e);
4331 if (lvalue && !s.guru_mode)
dc09353a 4332 throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
bd1fcbad
YZ
4333 "need stap -g"), e->tok);
4334
4335 if (e->module.empty())
4336 e->module = "kernel";
4337
4338 functioncall* result = NULL;
4339
4340 // split the module string by ':' for alternatives
4341 vector<string> modules;
4342 tokenize(e->module, modules, ":");
4343 bool userspace_p = false;
4344 for (unsigned i = 0; !result && i < modules.size(); ++i)
4345 {
4346 string& module = modules[i];
4347
4348 dwflpp* dw;
4349 try
4350 {
4351 userspace_p = is_user_module(module);
4352 if (!userspace_p)
4353 {
4354 // kernel or kernel module target
4355 dw = db.get_kern_dw(s, module);
4356 }
4357 else
4358 {
4359 module = find_executable(module, "", s.sysenv);
4360 dw = db.get_user_dw(s, module);
4361 }
4362 }
4363 catch (const semantic_error& er)
4364 {
4365 /* ignore and go to the next module */
4366 continue;
4367 }
4368
4369 dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
06de3a04 4370 dw->iterate_over_modules<base_query>(&query_module, &q);
bd1fcbad
YZ
4371
4372 if (result)
4373 {
4374 s.unwindsym_modules.insert(module);
bd1fcbad
YZ
4375
4376 if (lvalue)
4377 {
4378 // Provide the functioncall to our parent, so that it can be
4379 // used to substitute for the assignment node immediately above
4380 // us.
4381 assert(!target_symbol_setter_functioncalls.empty());
4382 *(target_symbol_setter_functioncalls.top()) = result;
4383 }
4384
4385 result->visit(this);
4386 return;
4387 }
4388
4389 /* Unable to find the variable in the current module, so we chain
4390 * an error in atvar_op */
dc09353a 4391 semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
bd1fcbad
YZ
4392 e->sym_name().c_str(), module.c_str(),
4393 e->cu_name.empty() ? "" : _(", in "),
4394 e->cu_name.c_str()));
4395 e->chain (er);
4396 }
4397
4398 provide(e);
4399}
4400
4401
b8da0ad1
FCE
4402void
4403dwarf_derived_probe::printsig (ostream& o) const
4404{
4405 // Instead of just printing the plain locations, we add a PC value
4406 // as a comment as a way of telling e.g. apart multiple inlined
4407 // function instances. This is distinct from the verbose/clog
4408 // output, since this part goes into the cache hash calculations.
4409 sole_location()->print (o);
6d0f3f0c 4410 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4411 printsig_nested (o);
4412}
4413
4414
4415
dc38c0ae 4416void
b20febf3
FCE
4417dwarf_derived_probe::join_group (systemtap_session& s)
4418{
af234c40
JS
4419 // skip probes which are paired entry-handlers
4420 if (!has_return && (saved_longs || saved_strings))
4421 return;
4422
b20febf3
FCE
4423 if (! s.dwarf_derived_probes)
4424 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4425 s.dwarf_derived_probes->enroll (this);
4426}
4427
4428
2b69faaf
JS
4429static bool
4430kernel_supports_inode_uprobes(systemtap_session& s)
4431{
4432 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4433 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4434 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4435 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4436 && s.kernel_config["CONFIG_UPROBES"] == "y");
4437}
4438
4439
3667d615
JS
4440static bool
4441kernel_supports_inode_uretprobes(systemtap_session& s)
4442{
766013af
JS
4443 // We need inode-uprobes first, then look for a sign of uretprobes. The only
4444 // non-static function at present is arch_uretprobe_hijack_return_addr.
3667d615 4445 return kernel_supports_inode_uprobes(s) &&
af9e147f 4446 (s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
3667d615
JS
4447}
4448
4449
5261f7ab
DS
4450void
4451check_process_probe_kernel_support(systemtap_session& s)
4452{
4453 // If we've got utrace, we're good to go.
4454 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4455 return;
4456
8c021542
DS
4457 // We don't have utrace. For process probes that aren't
4458 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4459 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4460 // specific autoconf test for its needs.
8c021542
DS
4461 //
4462 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4463 // approximation.
4464 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4465 return;
4466
d3e959b0
DS
4467 // For uprobes-based process probes, we need the task_finder plus
4468 // the builtin inode-uprobes.
8c021542
DS
4469 if (s.need_uprobes
4470 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4471 && kernel_supports_inode_uprobes(s))
8c021542
DS
4472 return;
4473
dc09353a 4474 throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4475}
4476
4477
b20febf3
FCE
4478dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4479 const string& filename,
4480 int line,
91af0778 4481 // module & section specify a relocation
b20febf3
FCE
4482 // base for <addr>, unless section==""
4483 // (equivalently module=="kernel")
4484 const string& module,
4485 const string& section,
4486 // NB: dwfl_addr is the virtualized
4487 // address for this symbol.
4488 Dwarf_Addr dwfl_addr,
4489 // addr is the section-offset for
4490 // actual relocation.
4491 Dwarf_Addr addr,
4492 dwarf_query& q,
37ebca01 4493 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4494 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4495 module (module), section (section), addr (addr),
63b4fd14 4496 path (q.path),
27dc09b1 4497 has_process (q.has_process),
c9bad430
DS
4498 has_return (q.has_return),
4499 has_maxactive (q.has_maxactive),
c57ea854 4500 has_library (q.has_library),
6b66b9f7 4501 maxactive_val (q.maxactive_val),
b642c901
SC
4502 user_path (q.user_path),
4503 user_lib (q.user_lib),
af234c40 4504 access_vars(false),
c57ea854 4505 saved_longs(0), saved_strings(0),
af234c40 4506 entry_handler(0)
bd2b1e68 4507{
b642c901
SC
4508 if (user_lib.size() != 0)
4509 has_library = true;
4510
6b66b9f7
JS
4511 if (q.has_process)
4512 {
4513 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4514 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4515 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4516 // by the incoming section value (".absolute" vs. ".dynamic").
4517 // XXX Assert invariants here too?
2b69faaf
JS
4518
4519 // inode-uprobes needs an offset rather than an absolute VM address.
4441e344 4520 // ditto for userspace runtimes (dyninst)
ac3af990 4521 if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
2b69faaf
JS
4522 section == ".absolute" && addr == dwfl_addr &&
4523 addr >= q.dw.module_start && addr < q.dw.module_end)
4524 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4525 }
4526 else
4527 {
4528 // Assert kernel relocation invariants
4529 if (section == "" && dwfl_addr != addr) // addr should be absolute
dc09353a 4530 throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
6b66b9f7 4531 if (section != "" && dwfl_addr == addr) // addr should be an offset
dc09353a 4532 throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
6b66b9f7 4533 }
2930abc7 4534
21beacc9
FCE
4535 // XXX: hack for strange g++/gcc's
4536#ifndef USHRT_MAX
4537#define USHRT_MAX 32767
4538#endif
4539
606fd9c8 4540 // Range limit maxactive() value
6b66b9f7 4541 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
dc09353a 4542 throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
b530b5b3 4543 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4544
a7696882
JL
4545 // Expand target variables in the probe body. Even if the scope_die is
4546 // invalid, we still want to expand things such as $$vars/$$parms/etc...
4547 // (PR15999, PR16473). Access to specific context vars e.g. $argc will not be
4548 // expanded and will produce an error during the typeresolution_info pass.
8fc05e57 4549 {
6b66b9f7 4550 // XXX: user-space deref's for q.has_process!
5a617dc6
JL
4551
4552 // PR14436: if we're expanding target variables in the probe body of a
4553 // .return probe, we need to make the expansion at the postprologue addr
4554 // instead (if any), which is then also the spot where the entry handler
4555 // probe is placed. (Note that at this point, a nonzero prologue_end
4556 // implies that it should be used, i.e. code is unoptimized).
4557 Dwarf_Addr handler_dwfl_addr = dwfl_addr;
4558 if (q.prologue_end != 0 && q.has_return)
4559 {
4560 handler_dwfl_addr = q.prologue_end;
4561 if (q.sess.verbose > 2)
4562 clog << _F("expanding .return vars at prologue_end (0x%s) "
4563 "rather than entrypc (0x%s)\n",
4564 lex_cast_hex(handler_dwfl_addr).c_str(),
4565 lex_cast_hex(dwfl_addr).c_str());
4566 }
4567 dwarf_var_expanding_visitor v (q, scope_die, handler_dwfl_addr);
8b095b45 4568 v.replace (this->body);
3689db05
SC
4569
4570 // Propagate perf.counters so we can emit later
4571 this->perf_counter_refs = v.perf_counter_refs;
4572 // Emit local var used to save the perf counter read value
698de6cc 4573 std::set<derived_probe*>::iterator pcii;
3689db05
SC
4574 for (pcii = v.perf_counter_refs.begin();
4575 pcii != v.perf_counter_refs.end(); pcii++)
4576 {
4577 map<string, pair<string,derived_probe*> >::iterator it;
4578 // Find the associated perf counter probe
4579 for (it=q.sess.perf_counters.begin() ;
4580 it != q.sess.perf_counters.end();
4581 it++)
4582 if ((*it).second.second == (*pcii))
4583 break;
4584 vardecl* vd = new vardecl;
4585 vd->name = "__perf_read_" + (*it).first;
4586 vd->tok = this->tok;
4587 vd->set_arity(0, this->tok);
4588 vd->type = pe_long;
4589 vd->synthetic = true;
4590 this->locals.push_back (vd);
4591 }
4592
4593
6b66b9f7
JS
4594 if (!q.has_process)
4595 access_vars = v.visited;
37ebca01
FCE
4596
4597 // If during target-variable-expanding the probe, we added a new block
4598 // of code, add it to the start of the probe.
4599 if (v.add_block)
ba6f838d 4600 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4601
4602 // If when target-variable-expanding the probe, we need to synthesize a
4603 // sibling function-entry probe. We don't go through the whole probe derivation
4604 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4605 // dwarf-induced duplication.
4606 if (v.add_call_probe)
37ebca01 4607 {
2260f4e3
FCE
4608 assert (q.has_return && !q.has_call);
4609
4610 // We temporarily replace q.base_probe.
4611 statement* old_body = q.base_probe->body;
4612 q.base_probe->body = v.add_call_probe;
4613 q.has_return = false;
4614 q.has_call = true;
af234c40 4615
da23eceb 4616 if (q.has_process)
5a617dc6
JL
4617 {
4618 // Place handler probe at the same addr as where the vars were
4619 // expanded (which may not be the same addr as the one for the
4620 // main retprobe, PR14436).
4621 Dwarf_Addr handler_addr = addr;
4622 if (handler_dwfl_addr != dwfl_addr)
4623 // adjust section offset by prologue_end-entrypc
4624 handler_addr += handler_dwfl_addr - dwfl_addr;
4625 entry_handler = new uprobe_derived_probe (funcname, filename,
4626 line, module, section,
4627 handler_dwfl_addr,
4628 handler_addr, q,
4629 scope_die);
4630 }
da23eceb 4631 else
af234c40
JS
4632 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4633 module, section, dwfl_addr,
4634 addr, q, scope_die);
4635
4636 saved_longs = entry_handler->saved_longs = v.saved_longs;
4637 saved_strings = entry_handler->saved_strings = v.saved_strings;
4638
4639 q.results.push_back (entry_handler);
2260f4e3
FCE
4640
4641 q.has_return = true;
4642 q.has_call = false;
4643 q.base_probe->body = old_body;
37ebca01 4644 }
a7696882
JL
4645 // Save the local variables for listing mode. If the scope_die is null,
4646 // local vars aren't accessible, so no need to invoke saveargs (PR10820).
bba368c5
JL
4647 if (!null_die(scope_die) &&
4648 q.sess.dump_mode == systemtap_session::dump_matched_probes_vars)
4649 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4650 }
0a98fd42 4651
5d23847d 4652 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4653 // "reverse-engineered" form of the incoming (q.base_loc) probe
4654 // point. This allows a user to see what function / file / line
4655 // number any particular match of the wildcards.
919debfc
JL
4656
4657 vector<probe_point::component*> comps;
4658 if (q.has_kernel)
4659 comps.push_back (new probe_point::component(TOK_KERNEL));
4660 else if(q.has_module)
4661 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4662 else if(q.has_process)
4663 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4664 else
4665 assert (0);
4666
4667 string fn_or_stmt;
4668 if (q.has_function_str || q.has_function_num)
e772a6e7 4669 fn_or_stmt = TOK_FUNCTION;
919debfc 4670 else
e772a6e7 4671 fn_or_stmt = TOK_STATEMENT;
919debfc
JL
4672
4673 if (q.has_function_str || q.has_statement_str)
4674 {
e772a6e7 4675 string retro_name = q.final_function_name(funcname, filename, line);
919debfc
JL
4676 comps.push_back
4677 (new probe_point::component
4678 (fn_or_stmt, new literal_string (retro_name)));
4679 }
4680 else if (q.has_function_num || q.has_statement_num)
4681 {
4682 Dwarf_Addr retro_addr;
4683 if (q.has_function_num)
4684 retro_addr = q.function_num_val;
4685 else
4686 retro_addr = q.statement_num_val;
4687 comps.push_back (new probe_point::component
4688 (fn_or_stmt,
4689 new literal_number(retro_addr, true)));
4690
4691 if (q.has_absolute)
4692 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
4693 }
4694
4695 if (q.has_call)
4696 comps.push_back (new probe_point::component(TOK_CALL));
4697 if (q.has_exported)
4698 comps.push_back (new probe_point::component(TOK_EXPORTED));
4699 if (q.has_inline)
4700 comps.push_back (new probe_point::component(TOK_INLINE));
4701 if (has_return)
4702 comps.push_back (new probe_point::component(TOK_RETURN));
4703 if (has_maxactive)
4704 comps.push_back (new probe_point::component
4705 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
4706
4707 // Overwrite it.
4708 this->sole_location()->components = comps;
e2941743
JL
4709
4710 // if it's a .callee[s[(N)]] call, add checks to the probe body so that the
4711 // user body is only 'triggered' when called from q.callers[N-1], which
4712 // itself is called from q.callers[N-2], etc... I.E.
4713 // callees(N) --> N elements in q.callers --> N checks against [u]stack(0..N-1)
4714 if ((q.has_callee || q.has_callees_num) && q.callers && !q.callers->empty())
4715 {
4716 if (q.sess.verbose > 2)
7761da8b 4717 clog << _F("adding caller checks for callee %s\n", funcname.c_str());
e2941743
JL
4718
4719 // Copy the stack and empty it out
4720 stack<Dwarf_Addr> callers(*q.callers);
4721 for (unsigned level = 1; !callers.empty(); level++,
4722 callers.pop())
4723 {
4724 Dwarf_Addr caller = callers.top();
4725
4726 // We first need to make the caller addr relocatable
4727 string caller_section;
4728 Dwarf_Addr caller_reloc;
4729 if (module == TOK_KERNEL)
4730 { // allow for relocatable kernel (see also add_probe_point())
4731 caller_reloc = caller - q.sess.sym_stext;
4732 caller_section = "_stext";
4733 }
4734 else
4735 caller_reloc = q.dw.relocate_address(caller,
4736 caller_section);
4737
4738 if (q.sess.verbose > 2)
7761da8b
JL
4739 clog << _F("adding caller check [u]stack(%d) == reloc(0x%s)\n",
4740 level, lex_cast_hex(caller_reloc).c_str());
e2941743
JL
4741
4742 // We want to add a statement like this:
6211aed9 4743 // if (!_caller_match(user, mod, sec, addr)) next;
e2941743
JL
4744 // Something similar is done in semantic_pass_conditions()
4745
4746 functioncall* check = new functioncall();
4747 check->tok = this->tok;
6211aed9 4748 check->function = "_caller_match";
e2941743
JL
4749 check->args.push_back(new literal_number(q.has_process));
4750 check->args[0]->tok = this->tok;
4751 check->args.push_back(new literal_number(level));
4752 check->args[1]->tok = this->tok;
4753 check->args.push_back(new literal_string(module));
4754 check->args[2]->tok = this->tok;
4755 check->args.push_back(new literal_string(caller_section));
4756 check->args[3]->tok = this->tok;
4757 check->args.push_back(new literal_number(caller_reloc, true /* hex */));
4758 check->args[4]->tok = this->tok;
4759
4760 unary_expression* notexp = new unary_expression();
4761 notexp->tok = this->tok;
4762 notexp->op = "!";
4763 notexp->operand = check;
4764
4765 if_statement* ifs = new if_statement();
4766 ifs->tok = this->tok;
4767 ifs->thenblock = new next_statement();
4768 ifs->thenblock->tok = this->tok;
4769 ifs->elseblock = NULL;
4770 ifs->condition = notexp;
4771
4772 this->body = new block(ifs, this->body);
4773 }
4774 }
2930abc7
FCE
4775}
4776
bd2b1e68 4777
0a98fd42 4778void
8c67c337
JS
4779dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4780 Dwarf_Addr dwfl_addr)
0a98fd42 4781{
9aa8ffce 4782 if (null_die(scope_die))
0a98fd42 4783 return;
0a98fd42 4784
8c67c337 4785 bool verbose = q.sess.verbose > 2;
0a98fd42 4786
8c67c337 4787 if (verbose)
b530b5b3 4788 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4789
8c67c337
JS
4790 if (has_return)
4791 {
4792 /* Only save the return value if it has a type. */
4793 string type_name;
4794 Dwarf_Die type_die;
4795 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4796 dwarf_type_name(&type_die, type_name))
4797 args.push_back("$return:"+type_name);
4798
4799 else if (verbose)
b530b5b3
LB
4800 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4801 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4802 }
d87623a1 4803
0a98fd42 4804 Dwarf_Die arg;
4ef35696
JS
4805 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4806 for (unsigned i = 0; i < scopes.size(); ++i)
4807 {
4808 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4809 break; // we don't want file-level variables
4810 if (dwarf_child (&scopes[i], &arg) == 0)
4811 do
0a98fd42 4812 {
4ef35696
JS
4813 switch (dwarf_tag (&arg))
4814 {
4815 case DW_TAG_variable:
4816 case DW_TAG_formal_parameter:
4817 break;
0a98fd42 4818
4ef35696
JS
4819 default:
4820 continue;
4821 }
0a98fd42 4822
4ef35696
JS
4823 /* Ignore this local if it has no name. */
4824 const char *arg_name = dwarf_diename (&arg);
4825 if (!arg_name)
8c67c337
JS
4826 {
4827 if (verbose)
b530b5b3
LB
4828 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4829 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4830 continue;
4831 }
4ef35696
JS
4832
4833 if (verbose)
b530b5b3
LB
4834 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4835 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4836
4837 /* Ignore this local if it has no location (or not at this PC). */
4838 /* NB: It still may not be directly accessible, e.g. if it is an
4839 * aggregate type, implicit_pointer, etc., but the user can later
4840 * figure out how to access the interesting parts. */
45b02a36
FCE
4841
4842 /* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
4843 * several synthetic
4844 * probe foo { $var }
4845 * probes, testing them for overall resolvability.
4846 */
4847
4ef35696
JS
4848 Dwarf_Attribute attr_mem;
4849 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4850 {
4851 Dwarf_Op *expr;
4852 size_t len;
4853 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4854 {
4855 if (verbose)
b530b5b3
LB
4856 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4857 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4858 continue;
4859 }
4860 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4861 &len, 1) == 1 && len > 0))
4862 {
45b02a36
FCE
4863 Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
4864 if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
4865 &len, 1) == 1 && len > 0))) {
4866 if (verbose)
4867 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4868 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4869 continue;
4870 }
4ef35696
JS
4871 }
4872 }
4873
4874 /* Ignore this local if it has no type. */
4875 string type_name;
4876 Dwarf_Die type_die;
4877 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4878 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4879 {
4880 if (verbose)
b530b5b3
LB
4881 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4882 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4883 continue;
4884 }
8c67c337 4885
4ef35696
JS
4886 /* This local looks good -- save it! */
4887 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4888 }
4ef35696
JS
4889 while (dwarf_siblingof (&arg, &arg) == 0);
4890 }
0a98fd42
JS
4891}
4892
4893
4894void
d0bfd2ac 4895dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4896{
d0bfd2ac 4897 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4898}
4899
4900
27dc09b1 4901void
42e38653 4902dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4903{
4904 if (has_process)
4905 {
4906 // These probes are allowed for unprivileged users, but only in the
4907 // context of processes which they own.
4908 emit_process_owner_assertion (o);
4909 return;
4910 }
4911
4912 // Other probes must contain the default assertion which aborts
4913 // if executed by an unprivileged user.
42e38653 4914 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4915}
4916
4917
4918void
4919dwarf_derived_probe::print_dupe_stamp(ostream& o)
4920{
4921 if (has_process)
4922 {
4923 // These probes are allowed for unprivileged users, but only in the
4924 // context of processes which they own.
4925 print_dupe_stamp_unprivileged_process_owner (o);
4926 return;
4927 }
4928
4929 // Other probes must contain the default dupe stamp
4930 derived_probe::print_dupe_stamp (o);
4931}
4932
64211010 4933
7a053d3b 4934void
20c6c071 4935dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4936 dwarf_builder * dw,
42e38653 4937 privilege_t privilege)
bd2b1e68 4938{
27dc09b1 4939 root
42e38653 4940 ->bind_privilege(privilege)
27dc09b1 4941 ->bind(dw);
54efe513
GH
4942}
4943
7a053d3b 4944void
fd6602a0 4945dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4946 dwarf_builder * dw,
42e38653 4947 privilege_t privilege)
2865d17a 4948{
27dc09b1 4949 root
42e38653 4950 ->bind_privilege(privilege)
27dc09b1 4951 ->bind(dw);
27dc09b1 4952 root->bind(TOK_CALL)
42e38653 4953 ->bind_privilege(privilege)
27dc09b1 4954 ->bind(dw);
4bda987e
SC
4955 root->bind(TOK_EXPORTED)
4956 ->bind_privilege(privilege)
4957 ->bind(dw);
27dc09b1 4958 root->bind(TOK_RETURN)
42e38653 4959 ->bind_privilege(privilege)
27dc09b1 4960 ->bind(dw);
1e035395 4961
f6be7c06
DB
4962 // For process probes / uprobes, .maxactive() is unused.
4963 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4964 {
4965 root->bind(TOK_RETURN)
1e035395
FCE
4966 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4967 }
bd2b1e68
GH
4968}
4969
7a053d3b 4970void
27dc09b1 4971dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4972 systemtap_session& s,
27dc09b1
DB
4973 match_node * root,
4974 dwarf_builder * dw,
42e38653 4975 privilege_t privilege
27dc09b1 4976)
bd2b1e68
GH
4977{
4978 // Here we match 4 forms:
4979 //
4980 // .function("foo")
4981 // .function(0xdeadbeef)
4982 // .statement("foo")
4983 // .statement(0xdeadbeef)
4984
440d9b00 4985 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4986 register_function_variants(fv_root, dw, privilege);
7f02ca94 4987 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4988 fv_root->bind(TOK_INLINE)
42e38653 4989 ->bind_privilege(privilege)
440d9b00 4990 ->bind(dw);
7f02ca94
JS
4991 fv_root->bind_str(TOK_LABEL)
4992 ->bind_privilege(privilege)
440d9b00 4993 ->bind(dw);
c31add50
JL
4994 fv_root->bind_str(TOK_CALLEE)
4995 ->bind_privilege(privilege)
4996 ->bind(dw);
4997 fv_root->bind(TOK_CALLEES)
4998 ->bind_privilege(privilege)
4999 ->bind(dw);
5000 fv_root->bind_num(TOK_CALLEES)
5001 ->bind_privilege(privilege)
5002 ->bind(dw);
440d9b00
DB
5003
5004 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 5005 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
5006 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
5007 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
5008 {
5009 fv_root->bind(TOK_INLINE)
42e38653 5010 ->bind_privilege(privilege)
440d9b00
DB
5011 ->bind(dw);
5012 }
5013
42e38653
DB
5014 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
5015 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
5016}
5017
b1615c74
JS
5018void
5019dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
5020 match_node * root,
5021 dwarf_builder * dw)
5022{
5023 root->bind_str(TOK_MARK)
f66bb29a 5024 ->bind_privilege(pr_all)
b1615c74
JS
5025 ->bind(dw);
5026 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 5027 ->bind_privilege(pr_all)
b1615c74
JS
5028 ->bind(dw);
5029}
5030
5031void
5032dwarf_derived_probe::register_plt_variants(systemtap_session& s,
5033 match_node * root,
5034 dwarf_builder * dw)
5035{
5036 root->bind(TOK_PLT)
f66bb29a 5037 ->bind_privilege(pr_all)
b1615c74
JS
5038 ->bind(dw);
5039 root->bind_str(TOK_PLT)
f66bb29a 5040 ->bind_privilege(pr_all)
b1615c74
JS
5041 ->bind(dw);
5042 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5043 ->bind_privilege(pr_all)
b1615c74
JS
5044 ->bind(dw);
5045 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 5046 ->bind_privilege(pr_all)
b1615c74 5047 ->bind(dw);
bd2b1e68
GH
5048}
5049
5050void
c4ce66a1 5051dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 5052{
c4ce66a1 5053 match_node* root = s.pattern_root;
bd2b1e68
GH
5054 dwarf_builder *dw = new dwarf_builder();
5055
c4ce66a1
JS
5056 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
5057 s.code_filters.push_back(filter);
5058
bd1fcbad
YZ
5059 filter = new dwarf_atvar_expanding_visitor(s, *dw);
5060 s.code_filters.push_back(filter);
5061
73f52eb4
DB
5062 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
5063 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
5064 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
5065 ->bind(dw);
2cab6244 5066
7f02ca94
JS
5067 match_node* uprobes[] = {
5068 root->bind(TOK_PROCESS),
5069 root->bind_str(TOK_PROCESS),
5070 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5071 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
5072 };
5073 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
5074 {
f66bb29a 5075 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
5076 register_sdt_variants(s, uprobes[i], dw);
5077 register_plt_variants(s, uprobes[i], dw);
5078 }
bd2b1e68
GH
5079}
5080
9020300d 5081void
3689db05
SC
5082dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
5083{
698de6cc 5084 std::set<derived_probe*>::iterator pcii;
3689db05
SC
5085 for (pcii = perf_counter_refs.begin();
5086 pcii != perf_counter_refs.end();
5087 pcii++)
5088 {
5089 map<string, pair<string,derived_probe*> >::iterator it;
5090 // Find the associated perf.counter probe
5091 unsigned i = 0;
5092 for (it=s.perf_counters.begin() ;
5093 it != s.perf_counters.end();
5094 it++, i++)
5095 if ((*it).second.second == (*pcii))
5096 break;
5097 // place the perf counter read so it precedes stp_lock_probe
5098 o->newline() << "l->l___perf_read_" + (*it).first
5099 + " = (((int64_t) (_stp_perf_read(smp_processor_id(),"
5100 + lex_cast(i) + "))));";
5101 }
b78a0fbb 5102
b95e2b79
MH
5103 if (access_vars)
5104 {
5105 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 5106 o->newline() << "#if defined __ia64__";
d9aed31e 5107 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 5108 o->newline() << "#endif";
b95e2b79 5109 }
9020300d 5110}
2930abc7 5111
b20febf3 5112// ------------------------------------------------------------------------
46b84a80
DS
5113
5114void
b20febf3 5115dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 5116{
b20febf3 5117 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
5118
5119 // XXX: probes put at the same address should all share a
5120 // single kprobe/kretprobe, and have their handlers executed
5121 // sequentially.
b55bc428
FCE
5122}
5123
7a053d3b 5124void
775d51e5 5125dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 5126{
b20febf3 5127 if (probes_by_module.empty()) return;
2930abc7 5128
775d51e5
DS
5129 s.op->newline() << "/* ---- dwarf probes ---- */";
5130
5131 // Warn of misconfigured kernels
f41595cc
FCE
5132 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
5133 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
5134 s.op->newline() << "#endif";
775d51e5 5135 s.op->newline();
f41595cc 5136
f07c3b68 5137 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 5138 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
5139 s.op->newline() << "#endif";
5140
14cf7e42 5141 // Forward decls
2ba1736a 5142 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 5143
b20febf3
FCE
5144 // Forward declare the master entry functions
5145 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5146 s.op->line() << " struct pt_regs *regs);";
5147 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5148 s.op->line() << " struct pt_regs *regs);";
5149
42cb22bd
MH
5150 // Emit an array of kprobe/kretprobe pointers
5151 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5152 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
5153 s.op->newline() << "#endif";
5154
b20febf3 5155 // Emit the actual probe list.
606fd9c8
FCE
5156
5157 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
5158 // struct stap_dwarf_probe, but it being initialized data makes it add
5159 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 5160 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
5161 // NB: bss!
5162
4c2732a1 5163 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
5164 s.op->newline(1) << "const unsigned return_p:1;";
5165 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 5166 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 5167 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 5168 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 5169
af234c40
JS
5170 // data saved in the kretprobe_instance packet
5171 s.op->newline() << "const unsigned short saved_longs;";
5172 s.op->newline() << "const unsigned short saved_strings;";
5173
faea5e16 5174 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
5175 // are small and uniform enough to justify putting char[MAX]'s into
5176 // the array instead of relocated char*'s.
faea5e16
JS
5177 size_t module_name_max = 0, section_name_max = 0;
5178 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
5179 size_t all_name_cnt = probes_by_module.size(); // for average
5180 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
5181 {
5182 dwarf_derived_probe* p = it->second;
5183#define DOIT(var,expr) do { \
5184 size_t var##_size = (expr) + 1; \
5185 var##_max = max (var##_max, var##_size); \
5186 var##_tot += var##_size; } while (0)
5187 DOIT(module_name, p->module.size());
5188 DOIT(section_name, p->section.size());
606fd9c8
FCE
5189#undef DOIT
5190 }
5191
5192 // Decide whether it's worthwhile to use char[] or char* by comparing
5193 // the amount of average waste (max - avg) to the relocation data size
5194 // (3 native long words).
5195#define CALCIT(var) \
5196 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
5197 { \
5198 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
5199 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
5200 << "[" << var##_name_max << "]" << endl; \
5201 } \
5202 else \
5203 { \
b0986e7a 5204 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
5205 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
5206 }
5207
5208 CALCIT(module);
5209 CALCIT(section);
e6fe60e7 5210#undef CALCIT
606fd9c8 5211
b0986e7a 5212 s.op->newline() << "const unsigned long address;";
7c3e97f4
JS
5213 s.op->newline() << "const struct stap_probe * const probe;";
5214 s.op->newline() << "const struct stap_probe * const entry_probe;";
b20febf3
FCE
5215 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
5216 s.op->indent(1);
5217
5218 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 5219 {
b20febf3
FCE
5220 dwarf_derived_probe* p = it->second;
5221 s.op->newline() << "{";
5222 if (p->has_return)
5223 s.op->line() << " .return_p=1,";
c9bad430 5224 if (p->has_maxactive)
606fd9c8
FCE
5225 {
5226 s.op->line() << " .maxactive_p=1,";
5227 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
5228 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
5229 }
af234c40
JS
5230 if (p->saved_longs || p->saved_strings)
5231 {
5232 if (p->saved_longs)
5233 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
5234 if (p->saved_strings)
5235 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
5236 if (p->entry_handler)
c87ae2c1 5237 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 5238 }
b350f56b
JS
5239 if (p->locations[0]->optional)
5240 s.op->line() << " .optional_p=1,";
dc38c256 5241 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
5242 s.op->line() << " .module=\"" << p->module << "\",";
5243 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 5244 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 5245 s.op->line() << " },";
2930abc7 5246 }
2930abc7 5247
b20febf3
FCE
5248 s.op->newline(-1) << "};";
5249
5250 // Emit the kprobes callback function
5251 s.op->newline();
5252 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
5253 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
5254 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
5255 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
5256 // Check that the index is plausible
5257 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5258 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5259 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5260 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5261 s.op->line() << "];";
71db462b 5262 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 5263 "stp_probe_type_kprobe");
d9aed31e 5264 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
5265
5266 // Make it look like the IP is set as it wouldn't have been replaced
5267 // by a breakpoint instruction when calling real probe handler. Reset
5268 // IP regs on return, so we don't confuse kprobes. PR10458
5269 s.op->newline() << "{";
5270 s.op->indent(1);
d9aed31e 5271 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 5272 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 5273 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 5274 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5275 s.op->newline(-1) << "}";
5276
f887a8c9 5277 common_probe_entryfn_epilogue (s, true);
b20febf3
FCE
5278 s.op->newline() << "return 0;";
5279 s.op->newline(-1) << "}";
5280
5281 // Same for kretprobes
5282 s.op->newline();
af234c40
JS
5283 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
5284 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 5285 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
5286
5287 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 5288 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
5289 // Check that the index is plausible
5290 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
5291 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
5292 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
5293 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
5294 s.op->line() << "];";
5295
7c3e97f4 5296 s.op->newline() << "const struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
c87ae2c1
JS
5297 s.op->newline() << "if (sp) {";
5298 s.op->indent(1);
71db462b 5299 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sp",
cda141c2 5300 "stp_probe_type_kretprobe");
d9aed31e 5301 s.op->newline() << "c->kregs = regs;";
af234c40
JS
5302
5303 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
5304 s.op->newline() << "c->ips.krp.pi = inst;";
5305 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
5306
5307 // Make it look like the IP is set as it wouldn't have been replaced
5308 // by a breakpoint instruction when calling real probe handler. Reset
5309 // IP regs on return, so we don't confuse kprobes. PR10458
5310 s.op->newline() << "{";
d9aed31e 5311 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
5312 s.op->newline() << "if (entry)";
5313 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
5314 s.op->newline(-1) << "else";
5315 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
5316 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 5317 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
5318 s.op->newline(-1) << "}";
5319
f887a8c9 5320 common_probe_entryfn_epilogue (s, true);
c87ae2c1 5321 s.op->newline(-1) << "}";
b20febf3
FCE
5322 s.op->newline() << "return 0;";
5323 s.op->newline(-1) << "}";
af234c40
JS
5324
5325 s.op->newline();
5326 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
5327 s.op->line() << " struct pt_regs *regs) {";
5328 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
5329 s.op->newline(-1) << "}";
5330
5331 s.op->newline();
5332 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
5333 s.op->line() << " struct pt_regs *regs) {";
5334 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
5335 s.op->newline(-1) << "}";
b642c901 5336
14cf7e42 5337 s.op->newline();
20c6c071 5338}
ec4373ff 5339
20c6c071 5340
dc38c0ae 5341void
b20febf3
FCE
5342dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
5343{
5344 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5345 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5346 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 5347 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 5348 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 5349 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 5350 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 5351 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 5352 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 5353 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 5354 s.op->newline(-1) << "} else {";
f07c3b68 5355 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 5356 s.op->newline(-1) << "}";
606fd9c8 5357 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 5358 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 5359 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
5360 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5361 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5362 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5363 s.op->newline(-1) << "}";
5364 s.op->newline() << "#endif";
e4cb375f
MH
5365 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5366 s.op->newline() << "#ifdef __ia64__";
5367 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5368 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5369 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5370 s.op->newline() << "if (rc == 0) {";
5371 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5372 s.op->newline() << "if (rc != 0)";
5373 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5374 s.op->newline(-2) << "}";
5375 s.op->newline() << "#else";
606fd9c8 5376 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 5377 s.op->newline() << "#endif";
b20febf3 5378 s.op->newline(-1) << "} else {";
e4cb375f 5379 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
5380 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5381 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
5382 s.op->newline() << "#ifdef __ia64__";
5383 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5384 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5385 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5386 s.op->newline() << "if (rc == 0) {";
5387 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5388 s.op->newline() << "if (rc != 0)";
5389 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5390 s.op->newline(-2) << "}";
5391 s.op->newline() << "#else";
606fd9c8 5392 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 5393 s.op->newline() << "#endif";
b20febf3 5394 s.op->newline(-1) << "}";
9063462a
FCE
5395 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
5396 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 5397 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 5398 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 5399 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
5400 // XXX: shall we increment numskipped?
5401 s.op->newline(-1) << "}";
5402
5403#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 5404 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 5405 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
5406 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
5407 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
5408 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
5409 s.op->newline() << "#ifdef __ia64__";
5410 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
5411 s.op->newline() << "#endif";
c48cb0cc
FCE
5412 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
5413 // not run for this early-abort case.
5414 s.op->newline(-1) << "}";
5415 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 5416 s.op->newline(-1) << "}";
9063462a
FCE
5417#endif
5418
b20febf3
FCE
5419 s.op->newline() << "else sdp->registered_p = 1;";
5420 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
5421}
5422
5423
b4be7cbc
FCE
5424void
5425dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
5426{
5427 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5428 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5429 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5430 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
5431 s.op->newline() << "int rc;";
5432
5433 // new module arrived?
5434 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
5435 s.op->newline(1) << "if (sdp->return_p) {";
5436 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
5437 s.op->newline() << "if (sdp->maxactive_p) {";
5438 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
5439 s.op->newline(-1) << "} else {";
5440 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
5441 s.op->newline(-1) << "}";
5442 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
5443 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
5444 s.op->newline() << "if (sdp->entry_probe) {";
5445 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
5446 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
5447 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
5448 s.op->newline(-1) << "}";
5449 s.op->newline() << "#endif";
5450 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5451 s.op->newline() << "#ifdef __ia64__";
5452 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
5453 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5454 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5455 s.op->newline() << "if (rc == 0) {";
5456 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
5457 s.op->newline() << "if (rc != 0)";
5458 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5459 s.op->newline(-2) << "}";
5460 s.op->newline() << "#else";
5461 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
5462 s.op->newline() << "#endif";
5463 s.op->newline(-1) << "} else {";
5464 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
5465 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
5466 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
5467 s.op->newline() << "#ifdef __ia64__";
5468 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
5469 s.op->newline() << "kp->dummy.pre_handler = NULL;";
5470 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
5471 s.op->newline() << "if (rc == 0) {";
5472 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
5473 s.op->newline() << "if (rc != 0)";
5474 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
5475 s.op->newline(-2) << "}";
5476 s.op->newline() << "#else";
5477 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
5478 s.op->newline() << "#endif";
5479 s.op->newline(-1) << "}";
5480 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
5481
5482 // old module disappeared?
5483 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
5484 s.op->newline(1) << "if (sdp->return_p) {";
5485 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
065d5567 5486 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
b4be7cbc
FCE
5487 s.op->newline() << "#ifdef STP_TIMING";
5488 s.op->newline() << "if (kp->u.krp.nmissed)";
5489 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5490 s.op->newline(-1) << "#endif";
065d5567 5491 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5492 s.op->newline() << "#ifdef STP_TIMING";
5493 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5494 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5495 s.op->newline(-1) << "#endif";
5496 s.op->newline(-1) << "} else {";
5497 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
065d5567 5498 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
b4be7cbc
FCE
5499 s.op->newline() << "#ifdef STP_TIMING";
5500 s.op->newline() << "if (kp->u.kp.nmissed)";
5501 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5502 s.op->newline(-1) << "#endif";
5503 s.op->newline(-1) << "}";
5504 s.op->newline() << "#if defined(__ia64__)";
5505 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5506 s.op->newline() << "#endif";
5507 s.op->newline() << "sdp->registered_p = 0;";
5508 s.op->newline(-1) << "}";
5509
5510 s.op->newline(-1) << "}"; // for loop
5511}
5512
5513
5514
5515
46b84a80 5516void
b20febf3 5517dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5518{
42cb22bd
MH
5519 //Unregister kprobes by batch interfaces.
5520 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5521 s.op->newline() << "j = 0;";
5522 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5523 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5524 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5525 s.op->newline() << "if (! sdp->registered_p) continue;";
5526 s.op->newline() << "if (!sdp->return_p)";
5527 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5528 s.op->newline(-2) << "}";
5529 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5530 s.op->newline() << "j = 0;";
5531 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5532 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5533 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5534 s.op->newline() << "if (! sdp->registered_p) continue;";
5535 s.op->newline() << "if (sdp->return_p)";
5536 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5537 s.op->newline(-2) << "}";
5538 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5539 s.op->newline() << "#ifdef __ia64__";
5540 s.op->newline() << "j = 0;";
5541 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5542 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5543 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5544 s.op->newline() << "if (! sdp->registered_p) continue;";
5545 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5546 s.op->newline(-1) << "}";
5547 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5548 s.op->newline() << "#endif";
42cb22bd
MH
5549 s.op->newline() << "#endif";
5550
b20febf3
FCE
5551 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5552 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5553 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5554 s.op->newline() << "if (! sdp->registered_p) continue;";
5555 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5556 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5557 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5558 s.op->newline() << "#endif";
065d5567 5559 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
73209876
FCE
5560 s.op->newline() << "#ifdef STP_TIMING";
5561 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5562 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5563 s.op->newline(-1) << "#endif";
065d5567 5564 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
73209876
FCE
5565 s.op->newline() << "#ifdef STP_TIMING";
5566 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5567 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 5568 s.op->newline(-1) << "#endif";
557fb7a8 5569 s.op->newline(-1) << "} else {";
42cb22bd 5570 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5571 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5572 s.op->newline() << "#endif";
065d5567 5573 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
73209876
FCE
5574 s.op->newline() << "#ifdef STP_TIMING";
5575 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5576 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5577 s.op->newline(-1) << "#endif";
b20febf3 5578 s.op->newline(-1) << "}";
e4cb375f
MH
5579 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5580 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5581 s.op->newline() << "#endif";
b20febf3
FCE
5582 s.op->newline() << "sdp->registered_p = 0;";
5583 s.op->newline(-1) << "}";
46b84a80
DS
5584}
5585
272c9036
WF
5586static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5587{
5588 string::size_type pos;
5589 string::size_type lastPos = str.find_first_not_of(" ", 0);
5590 string::size_type nextAt = str.find("@", lastPos);
e9a90eee
JS
5591
5592 if (nextAt == string::npos)
5593 {
5594 // PR13934: Assembly probes are not forced to use the N@OP form.
5595 // In this case, N is inferred to be the native word size. Since we
5596 // don't have a nice delimiter, just split it on spaces. SDT-asm authors
5597 // then must not put any spaces in arguments, to avoid ambiguity.
5598 tokenize(str, tokens, " ");
5599 return;
5600 }
5601
272c9036
WF
5602 while (lastPos != string::npos)
5603 {
5604 pos = nextAt + 1;
5605 nextAt = str.find("@", pos);
5606 if (nextAt == string::npos)
5607 pos = string::npos;
5608 else
5609 pos = str.rfind(" ", nextAt);
5610
5611 tokens.push_back(str.substr(lastPos, pos - lastPos));
5612 lastPos = str.find_first_not_of(" ", pos);
5613 }
5614}
8aabf152 5615
8aabf152 5616
aff5d390 5617struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5618{
ae1418f0 5619 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5 5620 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
b8688ee6 5621 dwflpp& dw,
f83336a5
FCE
5622 int elf_machine,
5623 const string & process_name,
a794dbeb 5624 const string & provider_name,
aff5d390 5625 const string & probe_name,
71e5e13d 5626 stap_sdt_probe_type probe_type,
aff5d390 5627 const string & arg_string,
8aabf152 5628 int ac):
b8688ee6
JL
5629 session (s), dw (dw), elf_machine (elf_machine),
5630 process_name (process_name), provider_name (provider_name),
5631 probe_name (probe_name), probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5632 {
2e6d617a 5633 build_dwarf_registers();
f83336a5 5634
ebbd2b45 5635 need_debug_info = false;
88e39987 5636 if (probe_type == uprobe3_type)
272c9036
WF
5637 {
5638 sdt_v3_tokenize(arg_string, arg_tokens);
5639 assert(arg_count <= 12);
5640 }
88e39987 5641 else
272c9036
WF
5642 {
5643 tokenize(arg_string, arg_tokens, " ");
5644 assert(arg_count <= 10);
5645 }
a8ec7719 5646 }
8aabf152 5647
f83336a5 5648 systemtap_session& session;
b8688ee6 5649 dwflpp& dw;
332ba7e7 5650 int elf_machine;
aff5d390 5651 const string & process_name;
a794dbeb 5652 const string & provider_name;
aff5d390 5653 const string & probe_name;
71e5e13d 5654 stap_sdt_probe_type probe_type;
8aabf152 5655 unsigned arg_count;
aff5d390 5656 vector<string> arg_tokens;
2e6d617a 5657
46a94997 5658 map<string, pair<unsigned,int> > dwarf_regs;
2e6d617a
JL
5659 string regnames;
5660 string percent_regnames;
5661
ebbd2b45 5662 bool need_debug_info;
aff5d390 5663
2e6d617a 5664 void build_dwarf_registers();
aff5d390 5665 void visit_target_symbol (target_symbol* e);
03c45fcb 5666 unsigned get_target_symbol_argno_and_validate (target_symbol* e);
ac074daf 5667 long parse_out_arg_precision(string& asmarg);
0fbf6fb8
JL
5668 expression* try_parse_arg_literal (target_symbol *e,
5669 const string& asmarg,
5670 long precision);
95b78bc9
JL
5671 expression* try_parse_arg_register (target_symbol *e,
5672 const string& asmarg,
5673 long precision);
6ef331c8
SC
5674 void visit_target_symbol_arg (target_symbol* e);
5675 void visit_target_symbol_context (target_symbol* e);
bd1fcbad 5676 void visit_atvar_op (atvar_op* e);
40a0c64e 5677 void visit_cast_op (cast_op* e);
aff5d390
SC
5678};
5679
2e6d617a
JL
5680void
5681sdt_uprobe_var_expanding_visitor::build_dwarf_registers ()
5682{
5683 /* Register name mapping table depends on the elf machine of this particular
5684 probe target process/file, not upon the host. So we can't just
5685 #ifdef _i686_ etc. */
5686
5687#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
5688 if (elf_machine == EM_X86_64) {
5689 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5690 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5691 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5692 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5693 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5694 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5695 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5696 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5697 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5698 DRI ("%sil", 4, QI);
5699 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5700 DRI ("%dil", 5, QI);
5701 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5702 DRI ("%bpl", 6, QI);
5703 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5704 DRI ("%spl", 7, QI);
5705 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5706 DRI ("%r8b", 8, QI);
5707 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5708 DRI ("%r9b", 9, QI);
5709 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5710 DRI ("%r10b", 10, QI);
5711 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5712 DRI ("%r11b", 11, QI);
5713 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5714 DRI ("%r12b", 12, QI);
5715 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5716 DRI ("%r13b", 13, QI);
5717 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5718 DRI ("%r14b", 14, QI);
5719 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5720 DRI ("%r15b", 15, QI);
5721 DRI ("%rip", 16, DI); DRI ("%eip", 16, SI); DRI ("%ip", 16, HI);
5722 } else if (elf_machine == EM_386) {
5723 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5724 DRI ("%ah", 0, QIh);
5725 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5726 DRI ("%ch", 1, QIh);
5727 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5728 DRI ("%dh", 2, QIh);
5729 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5730 DRI ("%bh", 3, QIh);
5731 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5732 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5733 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5734 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
5735 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
5736 DRI ("%r0", 0, DI);
5737 DRI ("%r1", 1, DI);
5738 DRI ("%r2", 2, DI);
5739 DRI ("%r3", 3, DI);
5740 DRI ("%r4", 4, DI);
5741 DRI ("%r5", 5, DI);
5742 DRI ("%r6", 6, DI);
5743 DRI ("%r7", 7, DI);
5744 DRI ("%r8", 8, DI);
5745 DRI ("%r9", 9, DI);
5746 DRI ("%r10", 10, DI);
5747 DRI ("%r11", 11, DI);
5748 DRI ("%r12", 12, DI);
5749 DRI ("%r13", 13, DI);
5750 DRI ("%r14", 14, DI);
5751 DRI ("%r15", 15, DI);
5752 DRI ("%r16", 16, DI);
5753 DRI ("%r17", 17, DI);
5754 DRI ("%r18", 18, DI);
5755 DRI ("%r19", 19, DI);
5756 DRI ("%r20", 20, DI);
5757 DRI ("%r21", 21, DI);
5758 DRI ("%r22", 22, DI);
5759 DRI ("%r23", 23, DI);
5760 DRI ("%r24", 24, DI);
5761 DRI ("%r25", 25, DI);
5762 DRI ("%r26", 26, DI);
5763 DRI ("%r27", 27, DI);
5764 DRI ("%r28", 28, DI);
5765 DRI ("%r29", 29, DI);
5766 DRI ("%r30", 30, DI);
5767 DRI ("%r31", 31, DI);
5768 // PR11821: unadorned register "names" without -mregnames
5769 DRI ("0", 0, DI);
5770 DRI ("1", 1, DI);
5771 DRI ("2", 2, DI);
5772 DRI ("3", 3, DI);
5773 DRI ("4", 4, DI);
5774 DRI ("5", 5, DI);
5775 DRI ("6", 6, DI);
5776 DRI ("7", 7, DI);
5777 DRI ("8", 8, DI);
5778 DRI ("9", 9, DI);
5779 DRI ("10", 10, DI);
5780 DRI ("11", 11, DI);
5781 DRI ("12", 12, DI);
5782 DRI ("13", 13, DI);
5783 DRI ("14", 14, DI);
5784 DRI ("15", 15, DI);
5785 DRI ("16", 16, DI);
5786 DRI ("17", 17, DI);
5787 DRI ("18", 18, DI);
5788 DRI ("19", 19, DI);
5789 DRI ("20", 20, DI);
5790 DRI ("21", 21, DI);
5791 DRI ("22", 22, DI);
5792 DRI ("23", 23, DI);
5793 DRI ("24", 24, DI);
5794 DRI ("25", 25, DI);
5795 DRI ("26", 26, DI);
5796 DRI ("27", 27, DI);
5797 DRI ("28", 28, DI);
5798 DRI ("29", 29, DI);
5799 DRI ("30", 30, DI);
5800 DRI ("31", 31, DI);
5801 } else if (elf_machine == EM_S390) {
5802 DRI ("%r0", 0, DI);
5803 DRI ("%r1", 1, DI);
5804 DRI ("%r2", 2, DI);
5805 DRI ("%r3", 3, DI);
5806 DRI ("%r4", 4, DI);
5807 DRI ("%r5", 5, DI);
5808 DRI ("%r6", 6, DI);
5809 DRI ("%r7", 7, DI);
5810 DRI ("%r8", 8, DI);
5811 DRI ("%r9", 9, DI);
5812 DRI ("%r10", 10, DI);
5813 DRI ("%r11", 11, DI);
5814 DRI ("%r12", 12, DI);
5815 DRI ("%r13", 13, DI);
5816 DRI ("%r14", 14, DI);
5817 DRI ("%r15", 15, DI);
5818 } else if (elf_machine == EM_ARM) {
5819 DRI ("r0", 0, SI);
5820 DRI ("r1", 1, SI);
5821 DRI ("r2", 2, SI);
5822 DRI ("r3", 3, SI);
5823 DRI ("r4", 4, SI);
5824 DRI ("r5", 5, SI);
5825 DRI ("r6", 6, SI);
5826 DRI ("r7", 7, SI);
5827 DRI ("r8", 8, SI);
5828 DRI ("r9", 9, SI);
5829 DRI ("r10", 10, SI); DRI ("sl", 10, SI);
5830 DRI ("fp", 11, SI);
5831 DRI ("ip", 12, SI);
5832 DRI ("sp", 13, SI);
5833 DRI ("lr", 14, SI);
5834 DRI ("pc", 15, SI);
5835 } else if (elf_machine == EM_AARCH64) {
5836 DRI ("x0", 0, DI); DRI ("w0", 0, SI);
5837 DRI ("x1", 1, DI); DRI ("w1", 1, SI);
5838 DRI ("x2", 2, DI); DRI ("w2", 2, SI);
5839 DRI ("x3", 3, DI); DRI ("w3", 3, SI);
5840 DRI ("x4", 4, DI); DRI ("w4", 4, SI);
5841 DRI ("x5", 5, DI); DRI ("w5", 5, SI);
5842 DRI ("x6", 6, DI); DRI ("w6", 6, SI);
5843 DRI ("x7", 7, DI); DRI ("w7", 7, SI);
5844 DRI ("x8", 8, DI); DRI ("w8", 8, SI);
5845 DRI ("x9", 9, DI); DRI ("w9", 9, SI);
5846 DRI ("x10", 10, DI); DRI ("w10", 10, SI);
5847 DRI ("x11", 11, DI); DRI ("w11", 11, SI);
5848 DRI ("x12", 12, DI); DRI ("w12", 12, SI);
5849 DRI ("x13", 13, DI); DRI ("w13", 13, SI);
5850 DRI ("x14", 14, DI); DRI ("w14", 14, SI);
5851 DRI ("x15", 15, DI); DRI ("w15", 15, SI);
5852 DRI ("x16", 16, DI); DRI ("w16", 16, SI);
5853 DRI ("x17", 17, DI); DRI ("w17", 17, SI);
5854 DRI ("x18", 18, DI); DRI ("w18", 18, SI);
5855 DRI ("x19", 19, DI); DRI ("w19", 19, SI);
5856 DRI ("x20", 20, DI); DRI ("w20", 20, SI);
5857 DRI ("x21", 21, DI); DRI ("w21", 21, SI);
5858 DRI ("x22", 22, DI); DRI ("w22", 22, SI);
5859 DRI ("x23", 23, DI); DRI ("w23", 23, SI);
5860 DRI ("x24", 24, DI); DRI ("w24", 24, SI);
5861 DRI ("x25", 25, DI); DRI ("w25", 25, SI);
5862 DRI ("x26", 26, DI); DRI ("w26", 26, SI);
5863 DRI ("x27", 27, DI); DRI ("w27", 27, SI);
5864 DRI ("x28", 28, DI); DRI ("w28", 28, SI);
5865 DRI ("x29", 29, DI); DRI ("w29", 29, SI);
5866 DRI ("x30", 30, DI); DRI ("w30", 30, SI);
5867 DRI ("sp", 31, DI);
5868 } else if (arg_count) {
5869 /* permit this case; just fall back to dwarf */
5870 }
5871#undef DRI
5872
5873 // Build regex pieces out of the known dwarf_regs. We keep two separate
5874 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5875 // and ones with no prefix (and thus only usable in unambiguous contexts).
5876 map<string,pair<unsigned,int> >::const_iterator ri;
5877 for (ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
5878 {
5879 string regname = ri->first;
5880 assert (regname != "");
5881 regnames += string("|")+regname;
5882 if (regname[0]=='%')
5883 percent_regnames += string("|")+regname;
5884 }
5885
5886 // clip off leading |
5887 if (regnames != "")
5888 regnames = regnames.substr(1);
5889 if (percent_regnames != "")
5890 percent_regnames = percent_regnames.substr(1);
5891}
7a05f484
SC
5892
5893void
6ef331c8 5894sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5895{
6ef331c8 5896 if (e->addressof)
dc09353a 5897 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5898
5899 if (e->name == "$$name")
7a05f484 5900 {
6ef331c8
SC
5901 literal_string *myname = new literal_string (probe_name);
5902 myname->tok = e->tok;
5903 provide(myname);
5904 return;
5905 }
7a05f484 5906
6ef331c8
SC
5907 else if (e->name == "$$provider")
5908 {
5909 literal_string *myname = new literal_string (provider_name);
5910 myname->tok = e->tok;
5911 provide(myname);
5912 return;
5913 }
a794dbeb 5914
6ef331c8
SC
5915 else if (e->name == "$$vars" || e->name == "$$parms")
5916 {
5917 e->assert_no_components("sdt", true);
6ef331c8
SC
5918
5919 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
63ea4244 5920
1c922ad7 5921 print_format* pf = print_format::create(e->tok, "sprintf");
6ef331c8
SC
5922
5923 for (unsigned i = 1; i <= arg_count; ++i)
5924 {
5925 if (i > 1)
5926 pf->raw_components += " ";
5927 target_symbol *tsym = new target_symbol;
5928 tsym->tok = e->tok;
5929 tsym->name = "$arg" + lex_cast(i);
5930 pf->raw_components += tsym->name;
5931 tsym->components = e->components;
5932
8c2f50c0 5933 expression *texp = require<expression> (tsym);
6ef331c8
SC
5934 if (!e->components.empty() &&
5935 e->components[0].type == target_symbol::comp_pretty_print)
5936 pf->raw_components += "=%s";
5937 else
5938 pf->raw_components += "=%#x";
5939 pf->args.push_back(texp);
5940 }
5941
5942 pf->components = print_format::string_to_components(pf->raw_components);
5943 provide (pf);
5944 }
5945 else
5946 assert(0); // shouldn't get here
5947}
5948
03c45fcb
JL
5949unsigned
5950sdt_uprobe_var_expanding_visitor::get_target_symbol_argno_and_validate (target_symbol *e)
5951{
5952 // parsing
5953 unsigned argno = 0;
5954 if (startswith(e->name, "$arg"))
5955 {
5956 try
5957 {
5958 argno = lex_cast<unsigned>(e->name.substr(4));
5959 }
5960 catch (const runtime_error& f)
5961 {
5962 // non-integral $arg suffix: e.g. $argKKKSDF
5963 argno = 0;
5964 }
5965 }
5966
5967 // validation
5968 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5969 argno < 1 || argno > arg_count) // a $argN with out-of-range N
5970 {
5971 // NB: Either
5972 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5973 // 2) uprobe2_type $FOO (no probe args)
5974 // both of which get resolved later.
5975 // Throw it now, and it might be resolved by DWARF later.
5976 need_debug_info = true;
5977 throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
5978 }
5979 assert (arg_tokens.size() >= argno);
5980 return argno;
5981}
6ef331c8 5982
ac074daf
JL
5983long
5984sdt_uprobe_var_expanding_visitor::parse_out_arg_precision(string& asmarg)
5985{
5986 long precision;
5987 if (asmarg.find('@') != string::npos)
5988 {
5989 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5990 asmarg = asmarg.substr(asmarg.find('@')+1);
5991 }
5992 else
5993 {
5994 // V1/V2 do not have precision field so default to signed long
5995 // V3 asm does not have precision field so default to unsigned long
5996 if (probe_type == uprobe3_type)
5997 precision = sizeof(long); // this is an asm probe
5998 else
5999 precision = -sizeof(long);
6000 }
6001 return precision;
6002}
6003
0fbf6fb8
JL
6004expression*
6005sdt_uprobe_var_expanding_visitor::try_parse_arg_literal (target_symbol *e,
6006 const string& asmarg,
6007 long precision)
6008{
6009 expression *argexpr = NULL;
6010
6011 // Here, we test for a numeric literal.
6012 // Only accept (signed) decimals throughout. XXX
6013
6014 // PR11821. NB: on powerpc, literals are not prefixed with $,
6015 // so this regex does not match. But that's OK, since without
6016 // -mregnames, we can't tell them apart from register numbers
6017 // anyway. With -mregnames, we could, if gcc somehow
6018 // communicated to us the presence of that option, but alas it
6019 // doesn't. http://gcc.gnu.org/PR44995.
6020 vector<string> matches;
6021 if (!regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches))
6022 {
6023 string sn = matches[0].substr(1);
6024 int64_t n;
6025
6026 // We have to pay attention to the size & sign, as gcc sometimes
6027 // propagates constants that don't quite match, like a negative
6028 // value to fill an unsigned type.
6029 // NB: let it throw if something happens
6030 switch (precision)
6031 {
6032 case -1: n = lex_cast< int8_t>(sn); break;
6033 case 1: n = lex_cast< uint8_t>(sn); break;
6034 case -2: n = lex_cast< int16_t>(sn); break;
6035 case 2: n = lex_cast<uint16_t>(sn); break;
6036 case -4: n = lex_cast< int32_t>(sn); break;
6037 case 4: n = lex_cast<uint32_t>(sn); break;
6038 default:
6039 case -8: n = lex_cast< int64_t>(sn); break;
6040 case 8: n = lex_cast<uint64_t>(sn); break;
6041 }
6042
6043 literal_number* ln = new literal_number(n);
6044 ln->tok = e->tok;
6045 argexpr = ln;
6046 }
6047
6048 return argexpr;
6049}
6050
95b78bc9
JL
6051expression*
6052sdt_uprobe_var_expanding_visitor::try_parse_arg_register (target_symbol *e,
6053 const string& asmarg,
6054 long precision)
6055{
6056 expression *argexpr = NULL;
6057
6058 // test for REGISTER
6059 // NB: Because PR11821, we must use percent_regnames here.
6060 string regexp;
6061 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
6062 regexp = "^(" + regnames + ")$";
6063 else
6064 regexp = "^(" + percent_regnames + ")$";
6065
6066 vector<string> matches;
6067 if (!regexp_match(asmarg, regexp, matches))
6068 {
6069 string regname = matches[1];
6070 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
6071 if (ri != dwarf_regs.end()) // known register
6072 {
6073 embedded_expr *get_arg1 = new embedded_expr;
6074 string width_adjust;
6075 switch (ri->second.second)
6076 {
6077 case QI: width_adjust = ") & 0xff)"; break;
6078 case QIh: width_adjust = ">>8) & 0xff)"; break;
6079 case HI:
6080 // preserve 16 bit register signness
6081 width_adjust = ") & 0xffff)";
6082 if (precision < 0)
6083 width_adjust += " << 48 >> 48";
6084 break;
6085 case SI:
6086 // preserve 32 bit register signness
6087 width_adjust = ") & 0xffffffff)";
6088 if (precision < 0)
6089 width_adjust += " << 32 >> 32";
6090 break;
6091 default: width_adjust = "))";
6092 }
6093 string type = "";
6094 if (probe_type == uprobe3_type)
6095 type = (precision < 0
6096 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
6097 type = type + "((";
6098 get_arg1->tok = e->tok;
6099 get_arg1->code = string("/* unprivileged */ /* pure */")
6100 + string(" ((int64_t)") + type
6101 + (is_user_module (process_name)
6102 ? string("u_fetch_register(")
6103 : string("k_fetch_register("))
6104 + lex_cast(dwarf_regs[regname].first) + string("))")
6105 + width_adjust;
6106 argexpr = get_arg1;
6107 }
6108 }
6109 return argexpr;
6110}
6111
6ef331c8
SC
6112void
6113sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
6114{
b8688ee6
JL
6115 static unsigned tick = 0;
6116
6ef331c8
SC
6117 try
6118 {
03c45fcb 6119 unsigned argno = get_target_symbol_argno_and_validate(e); // the N in $argN
8aabf152 6120 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 6121
8aabf152
FCE
6122 // Now we try to parse this thing, which is an assembler operand
6123 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 6124 // and hope for the best. Here is the syntax for a few architectures.
9859b766 6125 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157 6126 //
b6aaaf21
JL
6127 // literal reg reg reg+ base+index*size+ VAR VAR+off RIP-relative
6128 // indirect offset offset VAR+off
6129 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6130 // x86_64 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
6131 // power iN R (R) N(R)
6132 // ia64 N rR [r16]
6133 // s390 N %rR 0(rR) N(r15)
6134 // arm #N rR [rR] [rR, #N]
b874bd52 6135
8aabf152
FCE
6136 expression* argexpr = 0; // filled in in case of successful parse
6137
8aabf152
FCE
6138 vector<string> matches;
6139 int rc;
6140
ac074daf
JL
6141 // Parse (and remove from asmarg) the leading length
6142 long precision = parse_out_arg_precision(asmarg);
40fe32e0 6143
0fbf6fb8 6144 try
8aabf152 6145 {
0fbf6fb8
JL
6146 if ((argexpr = try_parse_arg_literal(e, asmarg, precision)) != NULL)
6147 goto matched;
2e6d617a
JL
6148
6149 // all other matches require registers
6150 if (regnames == "")
6151 throw SEMANTIC_ERROR("no registers to use for parsing");
95b78bc9
JL
6152
6153 if ((argexpr = try_parse_arg_register(e, asmarg, precision)) != NULL)
6154 goto matched;
0fbf6fb8
JL
6155 }
6156 catch (const semantic_error& err)
6157 {
6158 e->chain(err);
6159 goto not_matched;
8aabf152
FCE
6160 }
6161
272c9036 6162 int reg, offset1;
e5b7b83f 6163 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 6164 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 6165 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
6166 // On ARM test for [REGISTER, OFFSET]
6167 if (elf_machine == EM_ARM)
6168 {
669a2feb 6169 rc = regexp_match (asmarg, string("^\\[(")+regnames+string(")(, #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$"), matches);
272c9036 6170 reg = 1;
669a2feb 6171 offset1 = 3;
272c9036
WF
6172 }
6173 else
6174 {
6175 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
6176 reg = 4;
6177 offset1 = 1;
6178 }
8aabf152
FCE
6179 if (! rc)
6180 {
e5b7b83f 6181 string regname;
8aabf152 6182 int64_t disp = 0;
272c9036
WF
6183 if (matches[reg].length())
6184 regname = matches[reg];
8095a157
FCE
6185 if (dwarf_regs.find (regname) == dwarf_regs.end())
6186 goto not_matched;
6187
272c9036 6188 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
6189 if (matches[i].length())
6190 try
6191 {
6192 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
6193 }
8aabf152
FCE
6194 catch (const runtime_error& f) // unparseable offset
6195 {
6196 goto not_matched; // can't just 'break' out of
6197 // this case or use a sentinel
6198 // value, unfortunately
6199 }
6200
8aabf152 6201 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
6202 embedded_expr *get_arg1 = new embedded_expr;
6203 get_arg1->tok = e->tok;
6204 get_arg1->code = string("/* unprivileged */ /* pure */")
6205 + (is_user_module (process_name)
6206 ? string("u_fetch_register(")
6207 : string("k_fetch_register("))
46a94997 6208 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 6209 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 6210
8aabf152
FCE
6211 literal_number* inc = new literal_number(disp);
6212 inc->tok = e->tok;
40fe32e0 6213
8aabf152
FCE
6214 binary_expression *be = new binary_expression;
6215 be->tok = e->tok;
6216 be->left = get_arg1;
6217 be->op = "+";
6218 be->right = inc;
40fe32e0 6219
8aabf152 6220 functioncall *fc = new functioncall;
40fe32e0
SC
6221 switch (precision)
6222 {
7f6ce9ab
SC
6223 case 1: case -1:
6224 fc->function = "user_int8"; break;
6225 case 2:
6226 fc->function = "user_uint16"; break;
6227 case -2:
6228 fc->function = "user_int16"; break;
6229 case 4:
6230 fc->function = "user_uint32"; break;
6231 case -4:
6232 fc->function = "user_int32"; break;
6233 case 8: case -8:
6234 fc->function = "user_int64"; break;
40fe32e0
SC
6235 default: fc->function = "user_long";
6236 }
8aabf152
FCE
6237 fc->tok = e->tok;
6238 fc->args.push_back(be);
366af4e7 6239
8aabf152
FCE
6240 argexpr = fc;
6241 goto matched;
6242 }
8095a157
FCE
6243
6244 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
6245 // NB: Despite PR11821, we can use regnames here, since the parentheses
6246 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 6247 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
6248 if (! rc)
6249 {
6250 string baseregname;
6251 string indexregname;
6252 int64_t disp = 0;
6253 short scale = 1;
6254
6255 if (matches[6].length())
6256 try
6257 {
6258 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
6259 // We could verify that scale is one of 1,2,4,8,
6260 // but it doesn't really matter. An erroneous
6261 // address merely results in run-time errors.
8aabf152 6262 }
8095a157
FCE
6263 catch (const runtime_error &f) // unparseable scale
6264 {
6265 goto not_matched;
6266 }
6267
6268 if (matches[4].length())
6269 baseregname = matches[4];
6270 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
6271 goto not_matched;
6272
6273 if (matches[5].length())
6274 indexregname = matches[5];
6275 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
6276 goto not_matched;
6277
f7719b3d 6278 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
6279 if (matches[i].length())
6280 try
6281 {
6282 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
6283 }
6284 catch (const runtime_error& f) // unparseable offset
6285 {
6286 goto not_matched; // can't just 'break' out of
6287 // this case or use a sentinel
6288 // value, unfortunately
6289 }
6290
6291 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
6292
6293 embedded_expr *get_arg1 = new embedded_expr;
6294 string regfn = is_user_module (process_name)
6295 ? string("u_fetch_register")
6296 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
6297
6298 get_arg1->tok = e->tok;
6299 get_arg1->code = string("/* unprivileged */ /* pure */")
6300 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
6301 + string("+(")
6302 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
6303 + string("*")
6304 + lex_cast(scale)
6305 + string(")");
6306
6307 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
6308 literal_number* inc = new literal_number(disp);
6309 inc->tok = e->tok;
6310
6311 binary_expression *be = new binary_expression;
6312 be->tok = e->tok;
6313 be->left = get_arg1;
6314 be->op = "+";
6315 be->right = inc;
6316
6317 functioncall *fc = new functioncall;
6318 switch (precision)
6319 {
6320 case 1: case -1:
6321 fc->function = "user_int8"; break;
6322 case 2:
6323 fc->function = "user_uint16"; break;
6324 case -2:
6325 fc->function = "user_int16"; break;
6326 case 4:
6327 fc->function = "user_uint32"; break;
6328 case -4:
6329 fc->function = "user_int32"; break;
6330 case 8: case -8:
6331 fc->function = "user_int64"; break;
6332 default: fc->function = "user_long";
6333 }
6334 fc->tok = e->tok;
6335 fc->args.push_back(be);
6336
6337 argexpr = fc;
6338 goto matched;
8aabf152
FCE
6339 }
6340
b8688ee6
JL
6341 // test for [OFF+]VARNAME[+OFF][(REG)], where VARNAME is a variable name.
6342 // NB: Despite PR11821, we can use regnames here, since the parentheses
6343 // make things unambiguous.
6344 rc = regexp_match (asmarg, string("^(([0-9]+)[+])?([a-zA-Z_][a-zA-Z0-9_]*)([+][0-9]+)?([(](")+regnames+string(")[)])?$"), matches);
6345 if (! rc)
6346 {
6347 assert(matches.size() >= 4);
6348 string varname = matches[3];
6349
6350 // OFF can be before VARNAME (put in matches[2]) or after (put in
6351 // matches[4]) (or both?). Seems like in most cases it comes after,
6352 // unless the code was compiled with -fPIC.
6353 int64_t offset = 0;
6354 if (!matches[2].empty())
6355 offset += lex_cast<int64_t>(matches[2]);
6356 if (matches.size() >= 5 && !matches[4].empty())
6357 offset += lex_cast<int64_t>(matches[4]);
6358
6359 string regname;
6360 if (matches.size() >= 7)
6361 regname = matches[6];
6362
6363 // If it's just VARNAME, then proceed. If it's VARNAME(REGISTER), then
6364 // only proceed if it's RIP-relative addressing on x86_64.
6365 if (regname.empty() || (regname == "%rip" && elf_machine == EM_X86_64))
6366 {
6367 dw.mod_info->get_symtab();
6368 if (dw.mod_info->symtab_status != info_present)
6369 goto not_matched;
6370
6371 assert(dw.mod_info->sym_table);
6372 map<string, Dwarf_Addr>& globals = dw.mod_info->sym_table->globals;
6373 map<string, Dwarf_Addr>& locals = dw.mod_info->sym_table->locals;
6374 Dwarf_Addr addr = 0;
6375
6376 // check symtab locals then globals
6377 if (locals.count(varname))
6378 addr = locals[varname];
6379 if (globals.count(varname))
6380 addr = globals[varname];
6381
6382 if (addr)
6383 {
6384 // add whatever offset is in the operand
6385 addr += offset;
6386
6387 // adjust for dw bias because relocate_address() expects a
6388 // libdw address and this addr is from the symtab
6389 dw.get_module_dwarf(false, false);
6390 addr -= dw.module_bias;
6391
6392 string reloc_section;
6393 Dwarf_Addr reloc_addr = dw.relocate_address(addr, reloc_section);
6394
6395 // OK, we have an address for the variable. Let's create a
6396 // function that will just relocate it at runtime, and then
6397 // call user_[u]int*() on the address it returns.
6398
6399 functioncall *user_int_call = new functioncall;
6400 switch (precision)
6401 {
6402 case 1: case -1:
6403 user_int_call->function = "user_int8"; break;
6404 case 2:
6405 user_int_call->function = "user_uint16"; break;
6406 case -2:
6407 user_int_call->function = "user_int16"; break;
6408 case 4:
6409 user_int_call->function = "user_uint32"; break;
6410 case -4:
6411 user_int_call->function = "user_int32"; break;
6412 case 8: case -8:
6413 user_int_call->function = "user_int64"; break;
6414 default: user_int_call->function = "user_long";
6415 }
6416 user_int_call->tok = e->tok;
6417
6418 functiondecl *get_addr_decl = new functiondecl;
6419 get_addr_decl->tok = e->tok;
6420 get_addr_decl->synthetic = true;
6421 get_addr_decl->name = "_sdt_arg_get_addr_" + lex_cast(tick++);
6422 get_addr_decl->type = pe_long;
6423
6424 // build _stp_[ku]module_relocate(module, addr, current)
6425 stringstream ss;
6426 ss << " /* unprivileged */ /* pure */ /* pragma:vma */" << endl;
6427 ss << "STAP_RETURN(";
6428
6429 if (is_user_module(process_name))
6430 {
6431 ss << "_stp_umodule_relocate(";
6432 ss << "\"" << path_remove_sysroot(session, process_name) << "\", ";
6433 ss << "0x" << hex << reloc_addr << dec << ", ";
6434 ss << "current";
6435 ss << ")";
6436 }
6437 else // NB: in practice sdt.h probes are for userspace only
6438 {
6439 ss << "_stp_kmodule_relocate(";
6440 ss << "\"" << process_name << "\", ";
6441 ss << "\"" << reloc_section << "\", ";
6442 ss << "0x" << hex << reloc_addr << dec;
6443 ss << ")";
6444 }
6445 ss << ");" << endl;
6446
6447 embeddedcode *ec = new embeddedcode;
6448 ec->tok = e->tok;
6449 ec->code = ss.str();
6450 get_addr_decl->body = ec;
6451 get_addr_decl->join(session);
6452
6453 functioncall *get_addr_call = new functioncall;
6454 get_addr_call->tok = e->tok;
6455 get_addr_call->function = get_addr_decl->name;
6456 user_int_call->args.push_back(get_addr_call);
6457
6458 argexpr = user_int_call;
6459 goto matched;
6460 }
6461 }
6462 }
8aabf152
FCE
6463
6464 not_matched:
6465 // The asmarg operand was not recognized. Back down to dwarf.
6466 if (! session.suppress_warnings)
84fef8ee
FCE
6467 {
6468 if (probe_type == UPROBE3_TYPE)
6c9e1946 6469 session.print_warning (_F("Can't parse SDT_V3 operand '%s' [man error::sdt]", asmarg.c_str()), e->tok);
84fef8ee 6470 else // must be *PROBE2; others don't get asm operands
b78a0fbb 6471 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s' [man error::sdt]",
84fef8ee
FCE
6472 asmarg.c_str()), e->tok);
6473 }
8aabf152
FCE
6474 assert (argexpr == 0);
6475 need_debug_info = true;
dc09353a 6476 throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo [man error::sdt]"), e->tok);
366af4e7 6477
8aabf152
FCE
6478 matched:
6479 assert (argexpr != 0);
366af4e7
RM
6480
6481 if (session.verbose > 2)
1e41115c 6482 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 6483 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 6484
aff5d390 6485 if (e->components.empty()) // We have a scalar
8aabf152
FCE
6486 {
6487 if (e->addressof)
dc09353a 6488 throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
6489 provide (argexpr);
6490 return;
6491 }
6492 else // $var->foo
6493 {
6494 cast_op *cast = new cast_op;
6495 cast->name = "@cast";
6496 cast->tok = e->tok;
6497 cast->operand = argexpr;
6498 cast->components = e->components;
6499 cast->type_name = probe_name + "_arg" + lex_cast(argno);
6500 cast->module = process_name;
6501 cast->visit(this);
6502 return;
6503 }
366af4e7 6504
8aabf152 6505 /* NOTREACHED */
aff5d390
SC
6506 }
6507 catch (const semantic_error &er)
6508 {
6509 e->chain (er);
6510 provide (e);
6511 }
6512}
6513
6514
6ef331c8
SC
6515void
6516sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
6517{
6518 try
6519 {
49131a6d 6520 assert(e->name.size() > 0
bd1fcbad 6521 && (e->name[0] == '$' || e->name == "@var"));
6ef331c8
SC
6522
6523 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
6524 visit_target_symbol_context (e);
6525 else
6526 visit_target_symbol_arg (e);
6527 }
6528 catch (const semantic_error &er)
6529 {
6530 e->chain (er);
6531 provide (e);
6532 }
6533}
6534
6535
bd1fcbad
YZ
6536void
6537sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
6538{
6539 need_debug_info = true;
6540
6541 // Fill in our current module context if needed
6542 if (e->module.empty())
6543 e->module = process_name;
6544
6545 var_expanding_visitor::visit_atvar_op(e);
6546}
6547
6548
40a0c64e
JS
6549void
6550sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
6551{
6552 // Fill in our current module context if needed
6553 if (e->module.empty())
6554 e->module = process_name;
6555
6556 var_expanding_visitor::visit_cast_op(e);
6557}
6558
6559
576eaefe
SC
6560void
6561plt_expanding_visitor::visit_target_symbol (target_symbol *e)
6562{
6563 try
6564 {
6565 if (e->name == "$$name")
6566 {
6567 literal_string *myname = new literal_string (entry);
6568 myname->tok = e->tok;
6569 provide(myname);
6570 return;
6571 }
3d69c03f
JS
6572
6573 // variable not found -> throw a semantic error
6574 // (only to be caught right away, but this may be more complex later...)
6575 string alternatives = "$$name";
dc09353a 6576 throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
3d69c03f 6577 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
6578 }
6579 catch (const semantic_error &er)
6580 {
6581 e->chain (er);
6582 provide (e);
6583 }
6584}
6585
6586
edce5b67
JS
6587struct sdt_query : public base_query
6588{
6589 sdt_query(probe * base_probe, probe_point * base_loc,
6590 dwflpp & dw, literal_map_t const & params,
51d6bda3 6591 vector<derived_probe *> & results, const string user_lib);
edce5b67 6592
51d6bda3 6593 void query_library (const char *data);
576eaefe 6594 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
6595 void handle_query_module();
6596
6597private:
15284963 6598 stap_sdt_probe_type probe_type;
d61ea602 6599 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
6600 probe * base_probe;
6601 probe_point * base_loc;
6846cfc8 6602 literal_map_t const & params;
edce5b67 6603 vector<derived_probe *> & results;
a794dbeb
FCE
6604 string pp_mark;
6605 string pp_provider;
51d6bda3 6606 string user_lib;
edce5b67
JS
6607
6608 set<string> probes_handled;
6609
6610 Elf_Data *pdata;
6611 size_t probe_scn_offset;
6612 size_t probe_scn_addr;
aff5d390 6613 uint64_t arg_count;
40fe32e0 6614 GElf_Addr base;
c57ea854 6615 GElf_Addr pc;
aff5d390 6616 string arg_string;
edce5b67 6617 string probe_name;
a794dbeb 6618 string provider_name;
909ab234 6619 GElf_Addr semaphore_load_offset;
79a0ca08 6620 Dwarf_Addr semaphore;
edce5b67
JS
6621
6622 bool init_probe_scn();
6b51ee12 6623 bool get_next_probe();
c57ea854
SC
6624 void iterate_over_probe_entries();
6625 void handle_probe_entry();
edce5b67 6626
488d3c1b 6627 static void setup_note_probe_entry_callback (sdt_query *me,
dbd24034
JL
6628 const string& scn_name,
6629 const string& note_name,
488d3c1b
JL
6630 int type,
6631 const char *data,
6632 size_t len);
dbd24034
JL
6633 void setup_note_probe_entry (const string& scn_name,
6634 const string& note_name, int type,
6635 const char *data, size_t len);
40fe32e0 6636
edce5b67 6637 void convert_probe(probe *base);
4ddb6dd0 6638 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 6639 probe* convert_location();
40fe32e0 6640 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
6641 bool have_debuginfo_uprobe(bool need_debug_info)
6642 {return probe_type == uprobe1_type
40fe32e0 6643 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 6644 && need_debug_info);}
40fe32e0 6645 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
6646};
6647
6648
6649sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
6650 dwflpp & dw, literal_map_t const & params,
51d6bda3 6651 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
6652 base_query(dw, params), probe_type(unknown_probe_type),
6653 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
6654 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
6655 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
909ab234 6656 semaphore_load_offset(0), semaphore(0)
edce5b67 6657{
a794dbeb
FCE
6658 assert(get_string_param(params, TOK_MARK, pp_mark));
6659 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
6660
ef428667
FCE
6661 // PR10245: permit usage of dtrace-y "-" separator in marker name;
6662 // map it to double-underscores.
6663 size_t pos = 0;
6664 while (1) // there may be more than one
6665 {
a794dbeb 6666 size_t i = pp_mark.find("-", pos);
ef428667 6667 if (i == string::npos) break;
a794dbeb 6668 pp_mark.replace (i, 1, "__");
ef428667
FCE
6669 pos = i+1; // resume searching after the inserted __
6670 }
a794dbeb
FCE
6671
6672 // XXX: same for pp_provider?
edce5b67
JS
6673}
6674
6675
6676void
c57ea854 6677sdt_query::handle_probe_entry()
edce5b67 6678{
c57ea854
SC
6679 if (! have_uprobe()
6680 && !probes_handled.insert(probe_name).second)
edce5b67
JS
6681 return;
6682
6683 if (sess.verbose > 3)
c57ea854 6684 {
b78a0fbb 6685 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
b530b5b3
LB
6686 //TRANSLATORS: is matched to.
6687 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
6688 switch (probe_type)
6689 {
6690 case uprobe1_type:
6691 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
6692 break;
6693 case uprobe2_type:
6694 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
6695 break;
40fe32e0
SC
6696 case uprobe3_type:
6697 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
6698 break;
d61ea602
JS
6699 default:
6700 clog << "unknown!" << endl;
6701 break;
c57ea854
SC
6702 }
6703 }
edce5b67 6704
c57ea854
SC
6705 // Extend the derivation chain
6706 probe *new_base = convert_location();
6707 probe_point *new_location = new_base->locations[0];
6708
c57ea854
SC
6709 bool need_debug_info = false;
6710
7d395255
JS
6711 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
6712 // or dwfl_module_getelf(...). We only need it for the machine type, which
6713 // should be the same. The bias is used for relocating debuginfoless probes,
6714 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 6715 Dwarf_Addr bias;
7d395255 6716 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 6717
1cc41cd6
DS
6718 /* Figure out the architecture of this particular ELF file. The
6719 dwarfless register-name mappings depend on it. */
6720 GElf_Ehdr ehdr_mem;
6721 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
e1c3b13a 6722 if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 6723 assert(em);
1cc41cd6 6724 int elf_machine = em->e_machine;
b8688ee6
JL
6725 sdt_uprobe_var_expanding_visitor svv (sess, dw, elf_machine, module_val,
6726 provider_name, probe_name, probe_type,
6727 arg_string, arg_count);
1cc41cd6
DS
6728 svv.replace (new_base->body);
6729 need_debug_info = svv.need_debug_info;
c57ea854 6730
1cc41cd6
DS
6731 // XXX: why not derive_probes() in the uprobes case too?
6732 literal_map_t params;
6733 for (unsigned i = 0; i < new_location->components.size(); ++i)
6734 {
6735 probe_point::component *c = new_location->components[i];
6736 params[c->functor] = c->arg;
6737 }
c57ea854 6738
73d53dd2 6739 unsigned prior_results_size = results.size();
1cc41cd6
DS
6740 dwarf_query q(new_base, new_location, dw, params, results, "", "");
6741 q.has_mark = true; // enables mid-statement probing
30263a73 6742
73d53dd2
JS
6743 // V1 probes always need dwarf info
6744 // V2+ probes need dwarf info in case of a variable reference
1cc41cd6 6745 if (have_debuginfo_uprobe(need_debug_info))
06de3a04 6746 dw.iterate_over_modules<base_query>(&query_module, &q);
73d53dd2
JS
6747
6748 // For V2+ probes, if variable references weren't used or failed (PR14369),
6749 // then try with the more direct approach. Unresolved $vars might still
6750 // cause their own error, but this gives them a chance to be optimized out.
6751 if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
1cc41cd6
DS
6752 {
6753 string section;
6754 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6755 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6756 {
6757 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6758 section = ".dynamic";
6759 }
6760 else
6761 section = ".absolute";
edce5b67 6762
1cc41cd6
DS
6763 uprobe_derived_probe* p =
6764 new uprobe_derived_probe ("", "", 0,
6765 path_remove_sysroot(sess,q.module_val),
6766 section,
6767 q.statement_num_val, reloc_addr, q, 0);
6768 p->saveargs (arg_count);
6769 results.push_back (p);
c57ea854 6770 }
487bf4e2 6771 sess.unwindsym_modules.insert (dw.module_name);
73d53dd2 6772 record_semaphore(results, prior_results_size);
c57ea854 6773}
edce5b67 6774
4ddb6dd0 6775
c57ea854
SC
6776void
6777sdt_query::handle_query_module()
6778{
6779 if (!init_probe_scn())
6780 return;
edce5b67 6781
c57ea854
SC
6782 if (sess.verbose > 3)
6783 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6784
40fe32e0
SC
6785 if (probe_loc == note_section)
6786 {
6787 GElf_Shdr shdr_mem;
6788 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6789
909ab234
JS
6790 // The 'base' lets us adjust the hardcoded addresses in notes for prelink
6791 // effects. The 'semaphore_load_offset' accounts for the difference in
6792 // load addresses between text and data, so the semaphore can be
6793 // converted to a file offset if needed.
40fe32e0 6794 if (shdr)
909ab234
JS
6795 {
6796 base = shdr->sh_addr;
6797 GElf_Addr base_offset = shdr->sh_offset;
6798 shdr = dw.get_section (".probes", &shdr_mem);
6799 if (shdr)
6800 semaphore_load_offset =
6801 (shdr->sh_addr - shdr->sh_offset) - (base - base_offset);
6802 }
40fe32e0 6803 else
909ab234
JS
6804 base = semaphore_load_offset = 0;
6805
488d3c1b 6806 dw.iterate_over_notes (this, &sdt_query::setup_note_probe_entry_callback);
40fe32e0 6807 }
d61ea602 6808 else if (probe_loc == probe_section)
40fe32e0 6809 iterate_over_probe_entries ();
edce5b67
JS
6810}
6811
6812
6813bool
6814sdt_query::init_probe_scn()
6815{
448a86b7 6816 Elf* elf;
edce5b67 6817 GElf_Shdr shdr_mem;
40fe32e0
SC
6818
6819 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6820 if (shdr)
6821 {
6822 probe_loc = note_section;
6823 return true;
6824 }
edce5b67 6825
448a86b7 6826 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6827 if (shdr)
edce5b67 6828 {
fea74777
SC
6829 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6830 probe_scn_offset = 0;
6831 probe_scn_addr = shdr->sh_addr;
6832 assert (pdata != NULL);
6833 if (sess.verbose > 4)
ce0f6648
LB
6834 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6835 << pdata->d_size << endl;
40fe32e0 6836 probe_loc = probe_section;
fea74777 6837 return true;
edce5b67 6838 }
fea74777 6839 else
edce5b67 6840 return false;
edce5b67
JS
6841}
6842
40fe32e0 6843void
dbd24034
JL
6844sdt_query::setup_note_probe_entry_callback (sdt_query *me,
6845 const string& scn_name,
6846 const string& note_name, int type,
6847 const char *data, size_t len)
40fe32e0 6848{
dbd24034 6849 me->setup_note_probe_entry (scn_name, note_name, type, data, len);
40fe32e0
SC
6850}
6851
6852
6853void
dbd24034
JL
6854sdt_query::setup_note_probe_entry (const string& scn_name,
6855 const string& note_name, int type,
6856 const char *data, size_t len)
40fe32e0 6857{
dbd24034
JL
6858 if (scn_name.compare(".note.stapsdt"))
6859 return;
6860#define _SDT_NOTE_NAME "stapsdt"
6861 if (note_name.compare(_SDT_NOTE_NAME))
6862 return;
40fe32e0
SC
6863#define _SDT_NOTE_TYPE 3
6864 if (type != _SDT_NOTE_TYPE)
6865 return;
6866
dbd24034 6867 // we found a probe entry
40fe32e0
SC
6868 union
6869 {
6870 Elf64_Addr a64[3];
6871 Elf32_Addr a32[3];
6872 } buf;
6873 Dwarf_Addr bias;
6874 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6875 Elf_Data dst =
6876 {
6877 &buf, ELF_T_ADDR, EV_CURRENT,
6878 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6879 };
6880 assert (dst.d_size <= sizeof buf);
6881
6882 if (len < dst.d_size + 3)
6883 return;
6884
6885 Elf_Data src =
6886 {
6887 (void *) data, ELF_T_ADDR, EV_CURRENT,
6888 dst.d_size, 0, 0
6889 };
6890
6891 if (gelf_xlatetom (elf, &dst, &src,
6892 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6893 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6894
6895 probe_type = uprobe3_type;
6896 const char * provider = data + dst.d_size;
3f803f9e 6897
40fe32e0 6898 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6899 if(name++ == NULL)
6900 return;
6901
6902 const char *args = (const char*)memchr (name, '\0', data + len - name);
6903 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6904 return;
6905
6906 provider_name = provider;
6907 probe_name = name;
6908 arg_string = args;
40fe32e0 6909
e90006d7
JL
6910 dw.mod_info->marks.insert(make_pair(provider, name));
6911
40fe32e0
SC
6912 // Did we find a matching probe?
6913 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6914 && ((pp_provider == "")
6915 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6916 return;
6917
e9a90eee
JS
6918 // PR13934: Assembly probes are not forced to use the N@OP form.
6919 // If we have '@' then great, else count based on space-delimiters.
6920 arg_count = count(arg_string.begin(), arg_string.end(), '@');
6921 if (!arg_count && !arg_string.empty())
6922 arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
6923
40fe32e0
SC
6924 GElf_Addr base_ref;
6925 if (gelf_getclass (elf) == ELFCLASS32)
6926 {
6927 pc = buf.a32[0];
6928 base_ref = buf.a32[1];
6929 semaphore = buf.a32[2];
6930 }
6931 else
6932 {
6933 pc = buf.a64[0];
6934 base_ref = buf.a64[1];
6935 semaphore = buf.a64[2];
6936 }
6937
6938 semaphore += base - base_ref;
6939 pc += base - base_ref;
6940
7d395255
JS
6941 // The semaphore also needs the ELF bias added now, so
6942 // record_semaphore can properly relocate it later.
6943 semaphore += bias;
6944
40fe32e0 6945 if (sess.verbose > 4)
b530b5b3 6946 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
6947
6948 handle_probe_entry();
6949}
6950
6951
c57ea854
SC
6952void
6953sdt_query::iterate_over_probe_entries()
edce5b67 6954{
c57ea854 6955 // probes are in the .probe section
edce5b67
JS
6956 while (probe_scn_offset < pdata->d_size)
6957 {
aff5d390
SC
6958 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6959 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6960 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6961 if (! have_uprobe())
edce5b67
JS
6962 {
6963 // Unless this is a mangled .probes section, this happens
6964 // because the name of the probe comes first, followed by
6965 // the sentinel.
6966 if (sess.verbose > 5)
b530b5b3 6967 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6968 probe_scn_offset += sizeof(__uint32_t);
6969 continue;
6970 }
aff5d390
SC
6971 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6972 {
6973 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6974 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6975 continue;
6976 }
6977
1cc41cd6 6978 if (probe_type == uprobe1_type)
aff5d390 6979 {
79a0ca08 6980 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6981 return;
79a0ca08 6982 semaphore = 0;
aff5d390 6983 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6984 provider_name = ""; // unknown
1cc41cd6
DS
6985 pc = pbe_v1->arg;
6986 arg_count = 0;
aff5d390
SC
6987 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6988 }
08b5a50c 6989 else if (probe_type == uprobe2_type)
aff5d390 6990 {
79a0ca08 6991 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6992 return;
79a0ca08 6993 semaphore = pbe_v2->semaphore;
aff5d390 6994 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6995 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6996 arg_count = pbe_v2->arg_count;
6997 pc = pbe_v2->pc;
6998 if (pbe_v2->arg_string)
6999 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
7000 // skip over pbe_v2, probe_name text and provider text
7001 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
7002 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 7003 }
edce5b67 7004 if (sess.verbose > 4)
b530b5b3 7005 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 7006 << "@0x" << hex << pc << dec << endl;
edce5b67 7007
e90006d7
JL
7008 dw.mod_info->marks.insert(make_pair(provider_name, probe_name));
7009
a794dbeb
FCE
7010 if (dw.function_name_matches_pattern (probe_name, pp_mark)
7011 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 7012 handle_probe_entry ();
edce5b67 7013 }
edce5b67
JS
7014}
7015
7016
6846cfc8 7017void
4ddb6dd0 7018sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 7019{
a794dbeb
FCE
7020 for (unsigned i=0; i<2; i++) {
7021 // prefer with-provider symbol; look without provider prefix for backward compatibility only
7022 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
7023 // XXX: multiple addresses?
7024 if (sess.verbose > 2)
b530b5b3 7025 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 7026
79a0ca08
SC
7027 Dwarf_Addr addr;
7028 if (this->semaphore)
7029 addr = this->semaphore;
7030 else
7031 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
7032 if (addr)
7033 {
7d395255 7034 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
7035 dwfl_module_relocate_address (dw.module, &addr);
7036 // XXX: relocation basis?
909ab234
JS
7037
7038 // Dyninst needs the *file*-based offset for semaphores,
7039 // so subtract the difference in load addresses between .text and .probes
7040 if (dw.sess.runtime_usermode_p())
7041 addr -= semaphore_load_offset;
7042
a794dbeb
FCE
7043 for (unsigned i = start; i < results.size(); ++i)
7044 results[i]->sdt_semaphore_addr = addr;
7045 if (sess.verbose > 2)
b530b5b3 7046 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
7047 return;
7048 }
7049 else
7050 if (sess.verbose > 2)
b530b5b3 7051 clog << _(", not found") << endl;
a794dbeb 7052 }
6846cfc8
SC
7053}
7054
7055
edce5b67
JS
7056void
7057sdt_query::convert_probe (probe *base)
7058{
7059 block *b = new block;
7060 b->tok = base->body->tok;
7061
edce5b67
JS
7062 // Generate: if (arg1 != mark("label")) next;
7063 functioncall *fc = new functioncall;
bbafcb1e 7064 fc->function = "ulong_arg";
edce5b67 7065 fc->tok = b->tok;
bbafcb1e 7066 literal_number* num = new literal_number(1);
edce5b67
JS
7067 num->tok = b->tok;
7068 fc->args.push_back(num);
7069
7070 functioncall *fcus = new functioncall;
7071 fcus->function = "user_string";
7072 fcus->type = pe_string;
7073 fcus->tok = b->tok;
7074 fcus->args.push_back(fc);
7075
7076 if_statement *is = new if_statement;
7077 is->thenblock = new next_statement;
7078 is->elseblock = NULL;
7079 is->tok = b->tok;
63ea4244 7080 is->thenblock->tok = b->tok;
edce5b67
JS
7081 comparison *be = new comparison;
7082 be->op = "!=";
7083 be->tok = b->tok;
7084 be->left = fcus;
7085 be->right = new literal_string(probe_name);
63ea4244 7086 be->right->tok = b->tok;
edce5b67
JS
7087 is->condition = be;
7088 b->statements.push_back(is);
7089
7090 // Now replace the body
7091 b->statements.push_back(base->body);
7092 base->body = b;
7093}
7094
7095
c72aa911
JS
7096probe*
7097sdt_query::convert_location ()
edce5b67 7098{
c72aa911 7099 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 7100 vector<probe_point::component*> derived_comps;
edce5b67 7101
662539d9
JS
7102 vector<probe_point::component*>::iterator it;
7103 for (it = specific_loc->components.begin();
7104 it != specific_loc->components.end(); ++it)
7105 if ((*it)->functor == TOK_PROCESS)
7106 {
1cc41cd6
DS
7107 // copy the process name
7108 derived_comps.push_back(*it);
662539d9
JS
7109 }
7110 else if ((*it)->functor == TOK_LIBRARY)
7111 {
1cc41cd6
DS
7112 // copy the library name for process probes
7113 derived_comps.push_back(*it);
662539d9
JS
7114 }
7115 else if ((*it)->functor == TOK_PROVIDER)
7116 {
7117 // replace the possibly wildcarded arg with the specific provider name
7118 *it = new probe_point::component(TOK_PROVIDER,
7119 new literal_string(provider_name));
7120 }
7121 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
7122 {
7123 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
7124 *it = new probe_point::component(TOK_MARK,
7125 new literal_string(probe_name));
a794dbeb 7126
aff5d390
SC
7127 if (sess.verbose > 3)
7128 switch (probe_type)
7129 {
7130 case uprobe1_type:
b530b5b3 7131 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
7132 << hex << pc << dec << endl;
7133 break;
7134 case uprobe2_type:
b530b5b3 7135 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
7136 << hex << pc << dec << endl;
7137 break;
40fe32e0 7138 case uprobe3_type:
b530b5b3 7139 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
7140 << hex << pc << dec << endl;
7141 break;
aff5d390 7142 default:
b530b5b3
LB
7143 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
7144 pp_mark.c_str()) << endl;
aff5d390
SC
7145 }
7146
c72aa911
JS
7147 switch (probe_type)
7148 {
aff5d390
SC
7149 case uprobe1_type:
7150 case uprobe2_type:
40fe32e0 7151 case uprobe3_type:
c72aa911 7152 // process("executable").statement(probe_arg)
662539d9
JS
7153 derived_comps.push_back
7154 (new probe_point::component(TOK_STATEMENT,
7155 new literal_number(pc, true)));
c72aa911
JS
7156 break;
7157
a794dbeb 7158 default: // deprecated
c72aa911 7159 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
7160 derived_comps.push_back
7161 (new probe_point::component(TOK_FUNCTION,
7162 new literal_string("*")));
7163 derived_comps.push_back
c72aa911 7164 (new probe_point::component(TOK_LABEL,
a794dbeb 7165 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
7166 break;
7167 }
7168 }
edce5b67 7169
662539d9
JS
7170 probe_point* derived_loc = new probe_point(*specific_loc);
7171 derived_loc->components = derived_comps;
8159bf55 7172 return new probe (new probe (base_probe, specific_loc), derived_loc);
edce5b67
JS
7173}
7174
7175
51d6bda3
SC
7176void
7177sdt_query::query_library (const char *library)
7178{
7179 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
7180}
7181
e90006d7
JL
7182string
7183suggest_marks(systemtap_session& sess,
7184 const set<string>& modules,
7185 const string& mark,
7186 const string& provider)
7187{
7188 if (mark.empty() || modules.empty() || sess.module_cache == NULL)
7189 return "";
7190
7191 set<string> marks;
7192 const map<string, module_info*> &cache = sess.module_cache->cache;
7193 bool dash_suggestions = (mark.find("-") != string::npos);
7194
7195 for (set<string>::iterator itmod = modules.begin();
7196 itmod != modules.end(); ++itmod)
7197 {
7198 map<string, module_info*>::const_iterator itcache;
7199 if ((itcache = cache.find(*itmod)) != cache.end())
7200 {
7201 set<pair<string,string> >::const_iterator itmarks;
7202 for (itmarks = itcache->second->marks.begin();
7203 itmarks != itcache->second->marks.end(); ++itmarks)
7204 {
7205 if (provider.empty()
7206 // simulating dw.function_name_matches_pattern()
7207 || (fnmatch(provider.c_str(), itmarks->first.c_str(), 0) == 0))
7208 {
7209 string marksug = itmarks->second;
7210 if (dash_suggestions)
7211 {
7212 size_t pos = 0;
7213 while (1) // there may be more than one
7214 {
7215 size_t i = marksug.find("__", pos);
7216 if (i == string::npos) break;
7217 marksug.replace (i, 2, "-");
7218 pos = i+1; // resume searching after the inserted -
7219 }
7220 }
7221 marks.insert(marksug);
7222 }
7223 }
7224 }
7225 }
7226
7227 if (sess.verbose > 2)
7228 {
7229 clog << "suggesting " << marks.size() << " marks "
7230 << "from modules:" << endl;
7231 for (set<string>::iterator itmod = modules.begin();
7232 itmod != modules.end(); ++itmod)
7233 clog << *itmod << endl;
7234 }
7235
7236 if (marks.empty())
7237 return "";
7238
7239 return levenshtein_suggest(mark, marks, 5); // print top 5 marks only
7240}
7241
40a70f52
JL
7242string
7243suggest_plt_functions(systemtap_session& sess,
7244 const set<string>& modules,
7245 const string& func)
7246{
7247 if (func.empty() || modules.empty() || sess.module_cache == NULL)
7248 return "";
7249
7250 set<string> funcs;
7251 const map<string, module_info*> &cache = sess.module_cache->cache;
7252
7253 for (set<string>::iterator itmod = modules.begin();
7254 itmod != modules.end(); ++itmod)
7255 {
7256 map<string, module_info*>::const_iterator itcache;
7257 if ((itcache = cache.find(*itmod)) != cache.end())
7258 funcs.insert(itcache->second->plt_funcs.begin(),
7259 itcache->second->plt_funcs.end());
7260 }
7261
7262 if (sess.verbose > 2)
d82dd71f
JL
7263 {
7264 clog << "suggesting " << funcs.size() << " plt functions "
7265 << "from modules:" << endl;
7266 for (set<string>::iterator itmod = modules.begin();
7267 itmod != modules.end(); ++itmod)
7268 clog << *itmod << endl;
7269 }
40a70f52
JL
7270
7271 if (funcs.empty())
7272 return "";
7273
7274 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
7275}
51d6bda3 7276
0508c45f
JL
7277string
7278suggest_dwarf_functions(systemtap_session& sess,
7279 const set<string>& modules,
7280 string func)
44ffe90c
JL
7281{
7282 // Trim any @ component
7283 size_t pos = func.find('@');
7284 if (pos != string::npos)
7285 func.erase(pos);
7286
0508c45f 7287 if (func.empty() || modules.empty() || sess.module_cache == NULL)
44ffe90c
JL
7288 return "";
7289
7290 // We must first aggregate all the functions from the cache
7291 set<string> funcs;
7292 const map<string, module_info*> &cache = sess.module_cache->cache;
7293
0508c45f
JL
7294 for (set<string>::iterator itmod = modules.begin();
7295 itmod != modules.end(); ++itmod)
44ffe90c 7296 {
6e6d9a3b
JL
7297 module_info *module;
7298
7299 // retrieve module_info from cache
44ffe90c
JL
7300 map<string, module_info*>::const_iterator itcache;
7301 if ((itcache = cache.find(*itmod)) != cache.end())
6e6d9a3b
JL
7302 module = itcache->second;
7303 else // module not found
7304 continue;
7305
7306 // add inlines
7307 funcs.insert(module->inlined_funcs.begin(),
7308 module->inlined_funcs.end());
7309
7310 // add all function symbols in cache
7311 if (module->symtab_status != info_present || module->sym_table == NULL)
7312 continue;
7313 map<string, func_info*>& modfuncs = module->sym_table->map_by_name;
7314 for (map<string, func_info*>::const_iterator itfuncs = modfuncs.begin();
7315 itfuncs != modfuncs.end(); ++itfuncs)
7316 funcs.insert(itfuncs->first);
44ffe90c
JL
7317 }
7318
7319 if (sess.verbose > 2)
d82dd71f
JL
7320 {
7321 clog << "suggesting " << funcs.size() << " dwarf functions "
7322 << "from modules:" << endl;
7323 for (set<string>::iterator itmod = modules.begin();
7324 itmod != modules.end(); ++itmod)
7325 clog << *itmod << endl;
7326 }
44ffe90c
JL
7327
7328 if (funcs.empty())
7329 return "";
7330
593f09eb 7331 return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
44ffe90c
JL
7332}
7333
20c6c071 7334void
5227f1ea 7335dwarf_builder::build(systemtap_session & sess,
7a053d3b 7336 probe * base,
20c6c071 7337 probe_point * location,
86bf665e 7338 literal_map_t const & parameters,
20c6c071
GH
7339 vector<derived_probe *> & finished_results)
7340{
b20febf3
FCE
7341 // NB: the kernel/user dwlfpp objects are long-lived.
7342 // XXX: but they should be per-session, as this builder object
7343 // may be reused if we try to cross-instrument multiple targets.
84048984 7344
7a24d422 7345 dwflpp* dw = 0;
6d5d594e 7346 literal_map_t filled_parameters = parameters;
7a24d422 7347
7a24d422 7348 string module_name;
ae2552da
FCE
7349 if (has_null_param (parameters, TOK_KERNEL))
7350 {
7351 dw = get_kern_dw(sess, "kernel");
7352 }
7353 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 7354 {
c523a015
LB
7355 size_t dash_pos = 0;
7356 while((dash_pos=module_name.find('-'))!=string::npos)
7357 module_name.replace(int(dash_pos),1,"_");
7358 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
7359 // NB: glob patterns get expanded later, during the offline
7360 // elfutils module listing.
ae2552da 7361 dw = get_kern_dw(sess, module_name);
b8da0ad1 7362 }
6d5d594e 7363 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 7364 {
05fb3e0c 7365 module_name = sess.sysroot + module_name;
6d5d594e
LB
7366 if(has_null_param(filled_parameters, TOK_PROCESS))
7367 {
fc18e6c4
JL
7368 string file;
7369 try
7370 {
7371 file = sess.cmd_file();
7372 }
7373 catch (const semantic_error& e)
7374 {
7375 throw SEMANTIC_ERROR(_("invalid -c command for unspecified process"
7376 " probe [man stapprobes]"), NULL, NULL, &e);
7377 }
48cd804a 7378 if(file.empty())
fc18e6c4
JL
7379 throw SEMANTIC_ERROR(_("unspecified process probe is invalid without"
7380 " a -c COMMAND [man stapprobes]"));
48cd804a 7381 module_name = sess.sysroot + file;
6d5d594e
LB
7382 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
7383 // in the case of TOK_MARK we need to modify locations as well
7384 if(location->components[0]->functor==TOK_PROCESS &&
7385 location->components[0]->arg == 0)
7386 location->components[0]->arg = new literal_string(module_name);
b78a0fbb 7387 }
5750ecc6 7388
37001baa
FCE
7389 // PR6456 process("/bin/*") glob handling
7390 if (contains_glob_chars (module_name))
7391 {
7392 // Expand glob via rewriting the probe-point process("....")
7393 // parameter, asserted to be the first one.
7394
7395 assert (location->components.size() > 0);
7396 assert (location->components[0]->functor == TOK_PROCESS);
7397 assert (location->components[0]->arg);
7398 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7399 assert (lit);
7400
7401 // Evaluate glob here, and call derive_probes recursively with each match.
7402 glob_t the_blob;
88f8e2c0 7403 set<string> dupes;
37001baa 7404 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3 7405 if (rc)
dc09353a 7406 throw SEMANTIC_ERROR (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
44ffe90c 7407 unsigned results_pre = finished_results.size();
37001baa
FCE
7408 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
7409 {
e19ebcf7 7410 assert_no_interrupts();
37001baa
FCE
7411
7412 const char* globbed = the_blob.gl_pathv[i];
7413 struct stat st;
7414
7415 if (access (globbed, X_OK) == 0
7416 && stat (globbed, &st) == 0
7417 && S_ISREG (st.st_mode)) // see find_executable()
7418 {
7977a734
FCE
7419 // Need to call canonicalize here, in order to path-expand
7420 // patterns like process("stap*"). Otherwise it may go through
7421 // to the next round of expansion as ("stap"), leading to a $PATH
7422 // search that's not consistent with the glob search already done.
5bca76a8
JS
7423 string canononicalized = resolve_path (globbed);
7424 globbed = canononicalized.c_str();
7977a734 7425
88f8e2c0
JS
7426 // The canonical names can result in duplication, for example
7427 // having followed symlinks that are common with shared
7428 // libraries. Filter those out.
7429 if (!dupes.insert(canononicalized).second)
7430 continue;
7431
37001baa
FCE
7432 // synthesize a new probe_point, with the glob-expanded string
7433 probe_point *pp = new probe_point (*location);
ef0943df
JL
7434 pp->from_glob = true;
7435
5750ecc6
FCE
7436 // PR13338: quote results to prevent recursion
7437 string eglobbed = escape_glob_chars (globbed);
7438
7439 if (sess.verbose > 1)
7440 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7441 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 7442 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 7443
37001baa 7444 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7445 new literal_string (eglobbed_tgt));
37001baa
FCE
7446 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7447 pp->components[0] = ppc;
7448
d885563b 7449 probe* new_probe = new probe (base, pp);
7977a734
FCE
7450
7451 // We override "optional = true" here, as if the
7452 // wildcarded probe point was given a "?" suffix.
7453
7454 // This is because wildcard probes will be expected
7455 // by users to apply only to some subset of the
7456 // matching binaries, in the sense of "any", rather
7457 // than "all", sort of similarly how
7458 // module("*").function("...") patterns work.
7459
7460 derive_probes (sess, new_probe, finished_results,
7461 true /* NB: not location->optional */ );
37001baa
FCE
7462 }
7463 }
7464
7465 globfree (& the_blob);
44ffe90c
JL
7466
7467 unsigned results_post = finished_results.size();
7468
e90006d7 7469 // Did we fail to find a function/plt/mark by name? Let's suggest
44ffe90c
JL
7470 // something!
7471 string func;
7472 if (results_pre == results_post
7473 && get_param(filled_parameters, TOK_FUNCTION, func)
7474 && !func.empty())
7475 {
0508c45f 7476 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7477 modules_seen.clear();
7478 if (!sugs.empty())
dc09353a 7479 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7480 "no match (similar functions: %s)",
7481 sugs.find(',') == string::npos,
7482 sugs.c_str()));
7483 }
40a70f52
JL
7484 else if (results_pre == results_post
7485 && get_param(filled_parameters, TOK_PLT, func)
7486 && !func.empty())
7487 {
7488 string sugs = suggest_plt_functions(sess, modules_seen, func);
7489 modules_seen.clear();
7490 if (!sugs.empty())
7491 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7492 "no match (similar functions: %s)",
7493 sugs.find(',') == string::npos,
7494 sugs.c_str()));
7495 }
e90006d7
JL
7496 else if (results_pre == results_post
7497 && get_param(filled_parameters, TOK_MARK, func)
7498 && !func.empty())
7499 {
7500 string provider;
7501 get_param(filled_parameters, TOK_PROVIDER, provider);
7502
7503 string sugs = suggest_marks(sess, modules_seen, func, provider);
7504 modules_seen.clear();
7505 if (!sugs.empty())
7506 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7507 "no match (similar marks: %s)",
7508 sugs.find(',') == string::npos,
7509 sugs.c_str()));
7510 }
44ffe90c 7511
37001baa
FCE
7512 return; // avoid falling through
7513 }
7514
5750ecc6
FCE
7515 // PR13338: unquote glob results
7516 module_name = unescape_glob_chars (module_name);
05fb3e0c 7517 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
7518
7519 // if the executable starts with "#!", we look for the interpreter of the script
7520 {
7521 ifstream script_file (user_path.c_str () );
7522
7523 if (script_file.good ())
7524 {
7525 string line;
7526
7527 getline (script_file, line);
7528
7529 if (line.compare (0, 2, "#!") == 0)
7530 {
7531 string path_head = line.substr(2);
7532
7533 // remove white spaces at the beginning of the string
7534 size_t p2 = path_head.find_first_not_of(" \t");
7535
7536 if (p2 != string::npos)
7537 {
7538 string path = path_head.substr(p2);
7539
7540 // remove white spaces at the end of the string
7541 p2 = path.find_last_not_of(" \t\n");
7542 if (string::npos != p2)
7543 path.erase(p2+1);
7544
8e13c1a1
RH
7545 // handle "#!/usr/bin/env" redirect
7546 size_t offset = 0;
7547 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
7548 {
7549 offset = sizeof("/bin/env")-1;
7550 }
7551 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
7552 {
7553 offset = sizeof("/usr/bin/env")-1;
7554 }
7555
7556 if (offset != 0)
7557 {
7558 size_t p3 = path.find_first_not_of(" \t", offset);
7559
7560 if (p3 != string::npos)
7561 {
7562 string env_path = path.substr(p3);
05fb3e0c
WF
7563 user_path = find_executable (env_path, sess.sysroot,
7564 sess.sysenv);
8e13c1a1
RH
7565 }
7566 }
7567 else
7568 {
05fb3e0c 7569 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 7570 }
d1bcbe71
RH
7571
7572 struct stat st;
7573
7574 if (access (user_path.c_str(), X_OK) == 0
7575 && stat (user_path.c_str(), &st) == 0
7576 && S_ISREG (st.st_mode)) // see find_executable()
7577 {
7578 if (sess.verbose > 1)
b530b5b3
LB
7579 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
7580 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
7581
7582 assert (location->components.size() > 0);
7583 assert (location->components[0]->functor == TOK_PROCESS);
7584 assert (location->components[0]->arg);
7585 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
7586 assert (lit);
7587
7588 // synthesize a new probe_point, with the expanded string
7589 probe_point *pp = new probe_point (*location);
05fb3e0c 7590 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 7591 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 7592 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
7593 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
7594 pp->components[0] = ppc;
7595
d885563b 7596 probe* new_probe = new probe (base, pp);
d1bcbe71
RH
7597
7598 derive_probes (sess, new_probe, finished_results);
7599
7600 script_file.close();
7601 return;
7602 }
7603 }
7604 }
7605 }
7606 script_file.close();
7607 }
7608
47e226ed 7609 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 7610 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
7611 {
7612 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
7613 "LD_LIBRARY_PATH");
7614 if (module_name.find('/') == string::npos)
7615 // We didn't find user_lib so use iterate_over_libraries
7616 module_name = user_path;
7617 }
63b4fd14 7618 else
b642c901 7619 module_name = user_path; // canonicalize it
d0a7f5a9 7620
3667d615 7621 // uretprobes aren't available everywhere
536f1261 7622 if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
2b69faaf 7623 {
3667d615
JS
7624 if (kernel_supports_inode_uprobes(sess) &&
7625 !kernel_supports_inode_uretprobes(sess))
dc09353a 7626 throw SEMANTIC_ERROR
3ffeaf3c 7627 (_("process return probes not available [man error::inode-uprobes]"));
2b69faaf 7628 }
3667d615 7629
f4000852
MW
7630 // There is a similar check in pass 4 (buildrun), but it is
7631 // needed here too to make sure alternatives for optional
7632 // (? or !) process probes are disposed and/or alternatives
7633 // are selected.
3667d615
JS
7634 if (!sess.runtime_usermode_p())
7635 check_process_probe_kernel_support(sess);
e34d5d13 7636
7a24d422
FCE
7637 // user-space target; we use one dwflpp instance per module name
7638 // (= program or shared library)
707bf35e 7639 dw = get_user_dw(sess, module_name);
c8959a29 7640 }
20c6c071 7641
1acfc030
JS
7642 assert(dw);
7643
e90006d7
JL
7644 unsigned results_pre = finished_results.size();
7645
5896cd05 7646 if (sess.verbose > 3)
b530b5b3 7647 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 7648
a794dbeb
FCE
7649 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
7650 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 7651 {
51d6bda3 7652 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
06de3a04 7653 dw->iterate_over_modules<base_query>(&query_module, &sdtq);
e90006d7
JL
7654
7655 // We need to update modules_seen with the modules we've visited
7656 modules_seen.insert(sdtq.visited_modules.begin(),
7657 sdtq.visited_modules.end());
7658
7659 // Did we fail to find a mark?
7660 if (results_pre == finished_results.size() && !location->from_glob)
7661 {
7662 string provider;
7663 get_param(filled_parameters, TOK_PROVIDER, provider);
7664
7665 string sugs = suggest_marks(sess, modules_seen, dummy_mark_name, provider);
7666 modules_seen.clear();
7667 if (!sugs.empty())
7668 throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
7669 "no match (similar marks: %s)",
7670 sugs.find(',') == string::npos,
7671 sugs.c_str()));
7672 }
7673
edce5b67 7674 return;
7a05f484 7675 }
20c6c071 7676
6d5d594e 7677 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
7678
7679 // XXX: kernel.statement.absolute is a special case that requires no
7680 // dwfl processing. This code should be in a separate builder.
7a24d422 7681 if (q.has_kernel && q.has_absolute)
37ebca01 7682 {
4baf0e53 7683 // assert guru mode for absolute probes
37ebca01
FCE
7684 if (! q.base_probe->privileged)
7685 {
dc09353a 7686 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 7687 q.base_probe->tok);
37ebca01
FCE
7688 }
7689
7690 // For kernel.statement(NUM).absolute probe points, we bypass
7691 // all the debuginfo stuff: We just wire up a
7692 // dwarf_derived_probe right here and now.
4baf0e53 7693 dwarf_derived_probe* p =
b8da0ad1
FCE
7694 new dwarf_derived_probe ("", "", 0, "kernel", "",
7695 q.statement_num_val, q.statement_num_val,
7696 q, 0);
37ebca01 7697 finished_results.push_back (p);
1a0dbc5a 7698 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
7699 return;
7700 }
7701
06de3a04 7702 dw->iterate_over_modules<base_query>(&query_module, &q);
8f14e444 7703
44ffe90c
JL
7704 // We need to update modules_seen with the modules we've visited
7705 modules_seen.insert(q.visited_modules.begin(),
7706 q.visited_modules.end());
8f14e444
FCE
7707
7708 // PR11553 special processing: .return probes requested, but
7709 // some inlined function instances matched.
7710 unsigned i_n_r = q.inlined_non_returnable.size();
7711 unsigned results_post = finished_results.size();
7712 if (i_n_r > 0)
7713 {
7714 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
7715 {
7716 string quicklist;
7717 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7718 it != q.inlined_non_returnable.end();
7719 it++)
7720 {
7721 quicklist += " " + (*it);
7722 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
7723 {
7724 quicklist += " ...";
7725 break;
7726 }
7727 }
c57ea854 7728
52c2652f 7729 sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
b530b5b3 7730 "cannot probe .return of %u inlined functions %s",
52c2652f 7731 quicklist.size(), i_n_r, quicklist.c_str()));
8f14e444
FCE
7732 // There will be also a "no matches" semantic error generated.
7733 }
7734 if (sess.verbose > 1)
52c2652f
NMA
7735 clog << _NF("skipped .return probe of %u inlined function",
7736 "skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
8f14e444
FCE
7737 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
7738 {
7739 for (set<string>::iterator it = q.inlined_non_returnable.begin();
7740 it != q.inlined_non_returnable.end();
7741 it++)
7742 clog << (*it) << " ";
7743 clog << endl;
7744 }
7745 } // i_n_r > 0
44ffe90c 7746
e90006d7 7747 // If we just failed to resolve a function/plt by name, we can suggest
ef0943df
JL
7748 // something. We only suggest things for probe points that were not
7749 // synthesized from a glob, i.e. only for 'real' probes. This is also
7750 // required because modules_seen needs to accumulate across recursive
7751 // calls for process(glob)[.library(glob)] probes.
44ffe90c 7752 string func;
ef0943df 7753 if (results_pre == results_post && !location->from_glob
44ffe90c
JL
7754 && get_param(filled_parameters, TOK_FUNCTION, func)
7755 && !func.empty())
7756 {
0508c45f 7757 string sugs = suggest_dwarf_functions(sess, modules_seen, func);
44ffe90c
JL
7758 modules_seen.clear();
7759 if (!sugs.empty())
dc09353a 7760 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
44ffe90c
JL
7761 "no match (similar functions: %s)",
7762 sugs.find(',') == string::npos,
7763 sugs.c_str()));
7764 }
ef0943df 7765 else if (results_pre == results_post && !location->from_glob
40a70f52
JL
7766 && get_param(filled_parameters, TOK_PLT, func)
7767 && !func.empty())
7768 {
7769 string sugs = suggest_plt_functions(sess, modules_seen, func);
7770 modules_seen.clear();
7771 if (!sugs.empty())
7772 throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
7773 "no match (similar functions: %s)",
7774 sugs.find(',') == string::npos,
7775 sugs.c_str()));
7776 }
44ffe90c
JL
7777 else if (results_pre != results_post)
7778 // Something was derived so we won't need to suggest something
7779 modules_seen.clear();
5f0a03a6
JK
7780}
7781
7782symbol_table::~symbol_table()
7783{
c9efa5c9 7784 delete_map(map_by_addr);
5f0a03a6
JK
7785}
7786
7787void
2867a2a1 7788symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
44ffe90c 7789 Dwarf_Addr addr, Dwarf_Addr* /*high_addr*/)
5f0a03a6 7790{
ab91b232
JK
7791#ifdef __powerpc__
7792 // Map ".sys_foo" to "sys_foo".
7793 if (name[0] == '.')
7794 name++;
7795#endif
5f0a03a6
JK
7796 func_info *fi = new func_info();
7797 fi->addr = addr;
7798 fi->name = name;
ab91b232 7799 fi->weak = weak;
2867a2a1 7800 fi->descriptor = descriptor;
5f0a03a6
JK
7801 map_by_name[fi->name] = fi;
7802 // TODO: Use a multimap in case there are multiple static
7803 // functions with the same name?
1c6b77e5 7804 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
7805}
7806
46f7b6be 7807void
f98c6346 7808symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
7809{
7810#ifdef __powerpc__
7811 /*
7812 * The .opd section contains function descriptors that can look
7813 * just like function entry points. For example, there's a function
7814 * descriptor called "do_exit" that links to the entry point ".do_exit".
7815 * Reject all symbols in .opd.
7816 */
7817 opd_section = SHN_UNDEF;
7818 Dwarf_Addr bias;
7819 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
7820 ?: dwfl_module_getelf (mod, &bias));
7821 Elf_Scn* scn = 0;
7822 size_t shstrndx;
7823
7824 if (!elf)
7825 return;
fcc30d6d 7826 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
7827 return;
7828 while ((scn = elf_nextscn(elf, scn)) != NULL)
7829 {
7830 GElf_Shdr shdr_mem;
7831 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
7832 if (!shdr)
7833 continue;
7834 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
7835 if (!strcmp(name, ".opd"))
7836 {
7837 opd_section = elf_ndxscn(scn);
7838 return;
7839 }
7840 }
7841#endif
7842}
7843
7844bool
7845symbol_table::reject_section(GElf_Word section)
7846{
7847 if (section == SHN_UNDEF)
7848 return true;
7849#ifdef __powerpc__
7850 if (section == opd_section)
7851 return true;
7852#endif
7853 return false;
7854}
7855
5f0a03a6
JK
7856enum info_status
7857symbol_table::get_from_elf()
7858{
7859 Dwarf_Addr high_addr = 0;
7860 Dwfl_Module *mod = mod_info->mod;
7861 int syments = dwfl_module_getsymtab(mod);
7862 assert(syments);
46f7b6be 7863 prepare_section_rejection(mod);
5f0a03a6
JK
7864 for (int i = 1; i < syments; ++i)
7865 {
7866 GElf_Sym sym;
ab91b232 7867 GElf_Word section;
cba67d8f
MW
7868 const char *name;
7869 GElf_Addr addr;
7870 bool reject;
7871
7872/* Note that dwfl_module_getsym does adjust the sym.st_value but doesn't
7873 try to resolve it to a function address. dwfl_module_getsym_info leaves
7874 the st_value in tact (no adjustment applied) and returns the fully
7875 resolved address separately. In that case we can simply reject the
7876 symbol if it is SHN_UNDEF and don't need to call reject_section which
7877 does extra checks to see whether the address fall in an architecture
7878 specific descriptor table (which will never be the case when using the
7879 new dwfl_module_getsym_info). dwfl_module_getsym will only provide us
7880 with the (adjusted) st_value of the symbol, which might point into a
7881 function descriptor table. So in that case we still have to call
7882 reject_section. */
7883#if _ELFUTILS_PREREQ (0, 158)
7884 name = dwfl_module_getsym_info (mod, i, &sym, &addr, &section,
7885 NULL, NULL);
7886 reject = section == SHN_UNDEF;
7887#else
7888 name = dwfl_module_getsym (mod, i, &sym, &section);
b23098cd 7889 addr = sym.st_value;
cba67d8f
MW
7890 reject = reject_section(section);
7891#endif
7892
2867a2a1 7893 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 7894 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
cba67d8f 7895 reject, addr, &high_addr);
2a4acb09
JL
7896 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
7897 && GELF_ST_BIND(sym.st_info) == STB_GLOBAL)
7898 globals[name] = addr;
7899 if (name && GELF_ST_TYPE(sym.st_info) == STT_OBJECT
7900 && GELF_ST_BIND(sym.st_info) == STB_LOCAL)
7901 locals[name] = addr;
5f0a03a6
JK
7902 }
7903 return info_present;
7904}
7905
5f0a03a6
JK
7906func_info *
7907symbol_table::get_func_containing_address(Dwarf_Addr addr)
7908{
1c6b77e5
JS
7909 iterator_t iter = map_by_addr.upper_bound(addr);
7910 if (iter == map_by_addr.begin())
5f0a03a6 7911 return NULL;
2e67a43b 7912 else
1c6b77e5 7913 return (--iter)->second;
5f0a03a6
JK
7914}
7915
3d372d6b
SC
7916func_info *
7917symbol_table::get_first_func()
7918{
7919 iterator_t iter = map_by_addr.begin();
7920 return (iter)->second;
7921}
7922
5f0a03a6
JK
7923func_info *
7924symbol_table::lookup_symbol(const string& name)
7925{
7926 map<string, func_info*>::iterator i = map_by_name.find(name);
7927 if (i == map_by_name.end())
7928 return NULL;
7929 return i->second;
7930}
7931
7932Dwarf_Addr
7933symbol_table::lookup_symbol_address(const string& name)
7934{
7935 func_info *fi = lookup_symbol(name);
7936 if (fi)
7937 return fi->addr;
7938 return 0;
7939}
7940
ab91b232
JK
7941// This is the kernel symbol table. The kernel macro cond_syscall creates
7942// a weak symbol for each system call and maps it to sys_ni_syscall.
7943// For system calls not implemented elsewhere, this weak symbol shows up
7944// in the kernel symbol table. Following the precedent of dwarfful stap,
7945// we refuse to consider such symbols. Here we delete them from our
7946// symbol table.
7947// TODO: Consider generalizing this and/or making it part of blacklist
7948// processing.
7949void
7950symbol_table::purge_syscall_stubs()
7951{
7952 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
7953 if (stub_addr == 0)
7954 return;
1c6b77e5 7955 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
7956 for (iterator_t iter = purge_range.first;
7957 iter != purge_range.second;
1c6b77e5 7958 )
ab91b232 7959 {
1c6b77e5 7960 func_info *fi = iter->second;
2e67a43b 7961 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 7962 {
2e67a43b 7963 map_by_name.erase(fi->name);
1c6b77e5 7964 map_by_addr.erase(iter++);
2e67a43b 7965 delete fi;
2e67a43b 7966 }
1c6b77e5
JS
7967 else
7968 iter++;
ab91b232
JK
7969 }
7970}
7971
5f0a03a6 7972void
5f52fafe 7973module_info::get_symtab()
5f0a03a6 7974{
1c6b77e5
JS
7975 if (symtab_status != info_unknown)
7976 return;
7977
5f0a03a6
JK
7978 sym_table = new symbol_table(this);
7979 if (!elf_path.empty())
7980 {
5f0a03a6
JK
7981 symtab_status = sym_table->get_from_elf();
7982 }
7983 else
7984 {
7985 assert(name == TOK_KERNEL);
ab3ed72d
DS
7986 symtab_status = info_absent;
7987 cerr << _("Error: Cannot find vmlinux.") << endl;;
5f0a03a6
JK
7988 }
7989 if (symtab_status == info_absent)
7990 {
7991 delete sym_table;
7992 sym_table = NULL;
7993 return;
7994 }
7995
ab91b232
JK
7996 if (name == TOK_KERNEL)
7997 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7998}
7999
1c6b77e5
JS
8000// update_symtab reconciles data between the elf symbol table and the dwarf
8001// function enumeration. It updates the symbol table entries with the dwarf
8002// die that describes the function, which also signals to query_module_symtab
8003// that a statement probe isn't needed. In return, it also adds aliases to the
8004// function table for names that share the same addr/die.
8005void
8006module_info::update_symtab(cu_function_cache_t *funcs)
8007{
8008 if (!sym_table)
8009 return;
8010
8011 cu_function_cache_t new_funcs;
8012
8013 for (cu_function_cache_t::iterator func = funcs->begin();
8014 func != funcs->end(); func++)
8015 {
8016 // optimization: inlines will never be in the symbol table
8017 if (dwarf_func_inline(&func->second) != 0)
6e6d9a3b
JL
8018 {
8019 inlined_funcs.insert(func->first);
8020 continue;
8021 }
1c6b77e5 8022
1ffb8bd1
JS
8023 // XXX We may want to make additional efforts to match mangled elf names
8024 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
8025 // missing, so we may also need to try matching by address. See also the
8026 // notes about _Z in dwflpp::iterate_over_functions().
8027
1c6b77e5
JS
8028 func_info *fi = sym_table->lookup_symbol(func->first);
8029 if (!fi)
8030 continue;
8031
8032 // iterate over all functions at the same address
8033 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
8034 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
8035 {
8036 // update this function with the dwarf die
8037 it->second->die = func->second;
8038
8039 // if this function is a new alias, then
8040 // save it to merge into the function cache
8041 if (it->second != fi)
b7478964 8042 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
8043 }
8044 }
8045
8046 // add all discovered aliases back into the function cache
8047 // NB: this won't replace any names that dwarf may have already found
8048 funcs->insert(new_funcs.begin(), new_funcs.end());
8049}
8050
5f0a03a6
JK
8051module_info::~module_info()
8052{
8053 if (sym_table)
8054 delete sym_table;
b55bc428
FCE
8055}
8056
935447c8 8057// ------------------------------------------------------------------------
888af770 8058// user-space probes
935447c8
DS
8059// ------------------------------------------------------------------------
8060
935447c8 8061
888af770 8062struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 8063{
89ba3085
FCE
8064private:
8065 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 8066 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
8067 }
8068
cfcab6c7
JS
8069 void emit_module_maxuprobes (systemtap_session& s);
8070
2b69faaf
JS
8071 // Using our own utrace-based uprobes
8072 void emit_module_utrace_decls (systemtap_session& s);
8073 void emit_module_utrace_init (systemtap_session& s);
8074 void emit_module_utrace_exit (systemtap_session& s);
8075
8076 // Using the upstream inode-based uprobes
8077 void emit_module_inode_decls (systemtap_session& s);
8078 void emit_module_inode_init (systemtap_session& s);
8079 void emit_module_inode_exit (systemtap_session& s);
8080
3a894f7e
JS
8081 // Using the dyninst backend (via stapdyn)
8082 void emit_module_dyninst_decls (systemtap_session& s);
8083 void emit_module_dyninst_init (systemtap_session& s);
8084 void emit_module_dyninst_exit (systemtap_session& s);
8085
935447c8 8086public:
888af770 8087 void emit_module_decls (systemtap_session& s);
935447c8
DS
8088 void emit_module_init (systemtap_session& s);
8089 void emit_module_exit (systemtap_session& s);
8090};
8091
8092
888af770
FCE
8093void
8094uprobe_derived_probe::join_group (systemtap_session& s)
8095{
8096 if (! s.uprobe_derived_probes)
8097 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
8098 s.uprobe_derived_probes->enroll (this);
f31a77f5
DS
8099 if (s.runtime_usermode_p())
8100 enable_dynprobes(s);
8101 else
4441e344 8102 enable_task_finder(s);
a96d1db0 8103
8a03658e 8104 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
8105 // signal staprun to load that module. If we're using the builtin
8106 // inode-uprobes, we still need to know that it is required.
8a03658e 8107 s.need_uprobes = true;
a96d1db0
DN
8108}
8109
888af770 8110
c0f84e7b
SC
8111void
8112uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
8113{
8114 dwarf_derived_probe::getargs(arg_set);
8115 arg_set.insert(arg_set.end(), args.begin(), args.end());
8116}
8117
8118
8119void
8120uprobe_derived_probe::saveargs(int nargs)
8121{
8122 for (int i = 1; i <= nargs; i++)
8123 args.push_back("$arg" + lex_cast (i) + ":long");
8124}
8125
8126
2865d17a 8127void
42e38653 8128uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
8129{
8130 // These probes are allowed for unprivileged users, but only in the
8131 // context of processes which they own.
8132 emit_process_owner_assertion (o);
8133}
8134
8135
888af770 8136struct uprobe_builder: public derived_probe_builder
a96d1db0 8137{
888af770 8138 uprobe_builder() {}
2b69faaf 8139 virtual void build(systemtap_session & sess,
a96d1db0
DN
8140 probe * base,
8141 probe_point * location,
86bf665e 8142 literal_map_t const & parameters,
a96d1db0
DN
8143 vector<derived_probe *> & finished_results)
8144 {
888af770 8145 int64_t process, address;
a96d1db0 8146
2b69faaf 8147 if (kernel_supports_inode_uprobes(sess))
dc09353a 8148 throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
2b69faaf 8149
888af770 8150 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 8151 (void) b1;
888af770 8152 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 8153 (void) b2;
888af770
FCE
8154 bool rr = has_null_param (parameters, TOK_RETURN);
8155 assert (b1 && b2); // by pattern_root construction
a96d1db0 8156
0973d815 8157 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
8158 }
8159};
8160
8161
8162void
cfcab6c7 8163uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 8164{
43241c44
FCE
8165 // We'll probably need at least this many:
8166 unsigned minuprobes = probes.size();
8167 // .. but we don't want so many that .bss is inflated (PR10507):
8168 unsigned uprobesize = 64;
8169 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
8170 unsigned maxuprobes = maxuprobesmem / uprobesize;
8171
aaf7ffe8
FCE
8172 // Let's choose a value on the geometric middle. This should end up
8173 // between minuprobes and maxuprobes. It's OK if this number turns
8174 // out to be < minuprobes or > maxuprobes. At worst, we get a
8175 // run-time error of one kind (too few: missed uprobe registrations)
8176 // or another (too many: vmalloc errors at module load time).
8177 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 8178
6d0f3f0c 8179 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 8180 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 8181 s.op->newline() << "#endif";
cfcab6c7
JS
8182}
8183
8184
8185void
8186uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
8187{
8188 if (probes.empty()) return;
8189 s.op->newline() << "/* ---- utrace uprobes ---- */";
8190 // If uprobes isn't in the kernel, pull it in from the runtime.
8191
8192 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
8193 s.op->newline() << "#include <linux/uprobes.h>";
8194 s.op->newline() << "#else";
2ba1736a 8195 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
8196 s.op->newline() << "#endif";
8197 s.op->newline() << "#ifndef UPROBES_API_VERSION";
8198 s.op->newline() << "#define UPROBES_API_VERSION 1";
8199 s.op->newline() << "#endif";
8200
8201 emit_module_maxuprobes (s);
a96d1db0 8202
cc52276b 8203 // Forward decls
2ba1736a 8204 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 8205
5e112f92
FCE
8206 // In .bss, the shared pool of uprobe/uretprobe structs. These are
8207 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
8208 // XXX: consider a slab cache or somesuch for stap_uprobes
8209 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
6b378b7c 8210 s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 8211
89ba3085
FCE
8212 s.op->assert_0_indent();
8213
89ba3085
FCE
8214 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
8215 // This means we process probes[] in two passes.
8216 map <string,unsigned> module_index;
8217 unsigned module_index_ctr = 0;
8218
cc52276b
WC
8219 // not const since embedded task_finder_target struct changes
8220 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
8221 s.op->indent(1);
8222 for (unsigned i=0; i<probes.size(); i++)
8223 {
8224 uprobe_derived_probe *p = probes[i];
8225 string pbmkey = make_pbm_key (p);
8226 if (module_index.find (pbmkey) == module_index.end())
8227 {
8228 module_index[pbmkey] = module_index_ctr++;
8229
8230 s.op->newline() << "{";
8231 // NB: it's essential that make_pbm_key() use all of and
8232 // only the same fields as we're about to emit.
8233 s.op->line() << " .finder={";
1af100fc 8234 s.op->line() << " .purpose=\"uprobes\",";
89ba3085 8235 if (p->pid != 0)
68910c97
JK
8236 s.op->line() << " .pid=" << p->pid << ",";
8237
8238 if (p->section == "") // .statement(addr).absolute
8239 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
8240 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8241 {
8242 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8243 s.op->line() << " .callback=&stap_uprobe_process_found,";
8244 }
68910c97 8245 else if (p->section != ".absolute") // ET_DYN
89ba3085 8246 {
4ad95bbc
SC
8247 if (p->has_library)
8248 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
8249 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
8250 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 8251 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 8252 }
89ba3085 8253 s.op->line() << " },";
68910c97
JK
8254 if (p->module != "")
8255 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
8256 s.op->line() << " },";
8257 }
c57ea854 8258 else
822a6a3d 8259 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
8260 }
8261 s.op->newline(-1) << "};";
8262
8263 s.op->assert_0_indent();
8264
3689db05
SC
8265 unsigned pci;
8266 for (pci=0; pci<probes.size(); pci++)
8267 {
8268 // List of perf counters used by each probe
8269 // This list is an index into struct stap_perf_probe,
8270 uprobe_derived_probe *p = probes[pci];
698de6cc 8271 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8272 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8273 for (pcii = p->perf_counter_refs.begin();
8274 pcii != p->perf_counter_refs.end(); pcii++)
8275 {
8276 map<string, pair<string,derived_probe*> >::iterator it;
8277 unsigned i = 0;
8278 // Find the associated perf.counter probe
8279 for (it=s.perf_counters.begin() ;
8280 it != s.perf_counters.end(); it++, i++)
8281 if ((*it).second.second == (*pcii))
8282 break;
8283 s.op->line() << lex_cast(i) << ", ";
8284 }
8285 s.op->newline() << "};";
8286 }
8287
cc52276b
WC
8288 // NB: read-only structure
8289 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 8290 s.op->indent(1);
888af770
FCE
8291 for (unsigned i =0; i<probes.size(); i++)
8292 {
8293 uprobe_derived_probe* p = probes[i];
8294 s.op->newline() << "{";
89ba3085
FCE
8295 string key = make_pbm_key (p);
8296 unsigned value = module_index[key];
759e1d76
FCE
8297 if (value != 0)
8298 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 8299 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 8300 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 8301
038c38c6 8302 if (p->sdt_semaphore_addr != 0)
63b4fd14 8303 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 8304 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0 8305
0d049a1d 8306 // XXX: don't bother emit if array is empty
3689db05
SC
8307 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8308 // List of perf counters used by a probe from above
0d049a1d 8309 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
3689db05 8310
4ddb6dd0
JS
8311 if (p->has_return)
8312 s.op->line() << " .return_p=1,";
888af770
FCE
8313 s.op->line() << " },";
8314 }
8315 s.op->newline(-1) << "};";
a96d1db0 8316
89ba3085
FCE
8317 s.op->assert_0_indent();
8318
48e685da 8319 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 8320 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 8321 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8322 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8323 "stp_probe_type_uprobe");
0e090c74 8324 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
8325 << "sup->spec_index >= " << probes.size() << ") {";
8326 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8327 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
8328 s.op->newline() << "goto probe_epilogue;";
8329 s.op->newline(-1) << "}";
d9aed31e 8330 s.op->newline() << "c->uregs = regs;";
e04b5d74 8331 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8332
8333 // Make it look like the IP is set as it would in the actual user
8334 // task when calling real probe handler. Reset IP regs on return, so
8335 // we don't confuse uprobes. PR10458
8336 s.op->newline() << "{";
8337 s.op->indent(1);
d9aed31e 8338 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 8339 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 8340 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8341 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8342 s.op->newline(-1) << "}";
8343
f887a8c9 8344 common_probe_entryfn_epilogue (s, true);
888af770 8345 s.op->newline(-1) << "}";
a96d1db0 8346
48e685da 8347 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 8348 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 8349 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
71db462b 8350 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sups->probe",
cda141c2 8351 "stp_probe_type_uretprobe");
6dceb5c9 8352 s.op->newline() << "c->ips.ri = inst;";
0e090c74 8353 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
8354 << "sup->spec_index >= " << probes.size() << ") {";
8355 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 8356 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
8357 s.op->newline() << "goto probe_epilogue;";
8358 s.op->newline(-1) << "}";
8359
d9aed31e 8360 s.op->newline() << "c->uregs = regs;";
e04b5d74 8361 s.op->newline() << "c->user_mode_p = 1;";
6415ddde
MW
8362
8363 // Make it look like the IP is set as it would in the actual user
8364 // task when calling real probe handler. Reset IP regs on return, so
8365 // we don't confuse uprobes. PR10458
8366 s.op->newline() << "{";
8367 s.op->indent(1);
d9aed31e 8368 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 8369 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 8370 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 8371 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
8372 s.op->newline(-1) << "}";
8373
f887a8c9 8374 common_probe_entryfn_epilogue (s, true);
a96d1db0
DN
8375 s.op->newline(-1) << "}";
8376
89ba3085 8377 s.op->newline();
2ba1736a 8378 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 8379 s.op->newline();
888af770 8380}
935447c8
DS
8381
8382
888af770 8383void
2b69faaf 8384uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 8385{
888af770 8386 if (probes.empty()) return;
935447c8 8387
2b69faaf 8388 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 8389
01b05e2e 8390 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
8391 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
8392 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
8393 // NB: we assume the rest of the struct (specificaly, sup->up) is
8394 // initialized to zero. This is so that we can use
8395 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
8396 s.op->newline(-1) << "}";
8397 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 8398
89ba3085
FCE
8399 // Set up the task_finders
8400 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
8401 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 8402 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 8403 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 8404
5e112f92
FCE
8405 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
8406 // finders already registered, since mere registration does not
8407 // cause any utrace or memory allocation actions. That happens only
8408 // later, once the task finder engine starts running. So, for a
8409 // partial initialization requiring unwind, we need do nothing.
8410 s.op->newline() << "if (rc) break;";
a7a68293 8411
888af770
FCE
8412 s.op->newline(-1) << "}";
8413}
d0ea46ce 8414
d0a7f5a9 8415
888af770 8416void
2b69faaf 8417uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
8418{
8419 if (probes.empty()) return;
2b69faaf 8420 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 8421
6d0f3f0c
FCE
8422 // NB: there is no stap_unregister_task_finder_target call;
8423 // important stuff like utrace cleanups are done by
d41d451c
FCE
8424 // __stp_task_finder_cleanup() via stap_stop_task_finder().
8425 //
8426 // This function blocks until all callbacks are completed, so there
8427 // is supposed to be no possibility of any registration-related code starting
8428 // to run in parallel with our shutdown here. So we don't need to protect the
8429 // stap_uprobes[] array with the mutex.
d0a7f5a9 8430
01b05e2e 8431 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 8432 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 8433 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 8434 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 8435
8faa1fc5 8436 // PR10655: decrement that ENABLED semaphore
c116c31b 8437 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
8438 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
8439 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
8440 s.op->newline() << "struct task_struct *tsk;";
8441 s.op->newline() << "rcu_read_lock();";
6846cfc8 8442
86229a55
DS
8443 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
8444 // that the pid is always in the global namespace, not in any
8445 // private namespace.
8faa1fc5 8446 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
8447 // We'd like to call find_task_by_pid_ns() here, but it isn't
8448 // exported. So, we call what it calls...
8449 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
8450 s.op->newline() << "#else";
8451 s.op->newline() << " tsk = find_task_by_pid (pid);";
8452 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
8453
8454 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 8455 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 8456 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 8457 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 8458 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 8459 s.op->newline() << "#endif";
3c5b8e2b 8460 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 8461 s.op->newline(-1) << "}";
8faa1fc5
FCE
8462 // XXX: need to analyze possibility of race condition
8463 s.op->newline(-1) << "}";
8464 s.op->newline() << "rcu_read_unlock();";
8465 s.op->newline(-1) << "}";
6846cfc8 8466
3568f1dd
FCE
8467 s.op->newline() << "if (sups->return_p) {";
8468 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 8469 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 8470 s.op->newline() << "#endif";
80b4ad8b
FCE
8471 // NB: PR6829 does not change that we still need to unregister at
8472 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
8473 s.op->newline() << "unregister_uretprobe (& sup->urp);";
8474 s.op->newline(-1) << "} else {";
8475 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 8476 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
8477 s.op->newline() << "#endif";
8478 s.op->newline() << "unregister_uprobe (& sup->up);";
8479 s.op->newline(-1) << "}";
935447c8 8480
6d0f3f0c 8481 s.op->newline() << "sup->spec_index = -1;";
935447c8 8482
3568f1dd
FCE
8483 // XXX: uprobe missed counts?
8484
6d0f3f0c 8485 s.op->newline(-1) << "}";
935447c8 8486
5e112f92 8487 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
8488}
8489
2b69faaf
JS
8490
8491void
8492uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
8493{
8494 if (probes.empty()) return;
8495 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8496 emit_module_maxuprobes (s);
2ba1736a 8497 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
8498
8499 // Write the probe handler.
79af55c3
JS
8500 s.op->newline() << "static int stapiu_probe_handler "
8501 << "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
8502 s.op->newline(1);
2dbbd473
JS
8503
8504 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8505 string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8506 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
2dbbd473
JS
8507 probe_type);
8508
3bff6634 8509 s.op->newline() << "c->uregs = regs;";
e04b5d74 8510 s.op->newline() << "c->user_mode_p = 1;";
497cfcb2 8511 // NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
2b69faaf 8512 s.op->newline() << "(*sup->probe->ph) (c);";
39e63bae 8513
f887a8c9 8514 common_probe_entryfn_epilogue (s, true);
2b69faaf
JS
8515 s.op->newline() << "return 0;";
8516 s.op->newline(-1) << "}";
8517 s.op->assert_0_indent();
8518
8519 // Index of all the modules for which we need inodes.
8520 map<string, unsigned> module_index;
8521 unsigned module_index_ctr = 0;
8522
8523 // Discover and declare targets for each unique path.
cfcab6c7 8524 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
8525 << "stap_inode_uprobe_targets[] = {";
8526 s.op->indent(1);
8527 for (unsigned i=0; i<probes.size(); i++)
8528 {
8529 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8530 const string key = make_pbm_key(p);
8531 if (module_index.find (key) == module_index.end())
2b69faaf 8532 {
cfcab6c7
JS
8533 module_index[key] = module_index_ctr++;
8534 s.op->newline() << "{";
8535 s.op->line() << " .finder={";
b78a0fbb 8536 s.op->line() << " .purpose=\"inode-uprobes\",";
cfcab6c7
JS
8537 if (p->pid != 0)
8538 s.op->line() << " .pid=" << p->pid << ",";
8539
8540 if (p->section == "") // .statement(addr).absolute XXX?
8541 s.op->line() << " .callback=&stapiu_process_found,";
8542 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
8543 {
8544 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
8545 s.op->line() << " .callback=&stapiu_process_found,";
8546 }
8547 else if (p->section != ".absolute") // ET_DYN
8548 {
8549 if (p->has_library)
8550 s.op->line() << " .procname=\"" << p->path << "\", ";
8551 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
8552 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
8553 s.op->line() << " .callback=&stapiu_process_munmap,";
8554 }
8555 s.op->line() << " },";
8556 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
8557 s.op->line() << " },";
2b69faaf
JS
8558 }
8559 }
8560 s.op->newline(-1) << "};";
8561 s.op->assert_0_indent();
8562
8563 // Declare the actual probes.
3689db05
SC
8564 unsigned pci;
8565 for (pci=0; pci<probes.size(); pci++)
8566 {
8567 // List of perf counters used by each probe
8568 // This list is an index into struct stap_perf_probe,
8569 uprobe_derived_probe *p = probes[pci];
698de6cc 8570 std::set<derived_probe*>::iterator pcii;
3689db05
SC
8571 s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
8572 for (pcii = p->perf_counter_refs.begin();
8573 pcii != p->perf_counter_refs.end(); pcii++)
8574 {
8575 map<string, pair<string,derived_probe*> >::iterator it;
8576 unsigned i = 0;
8577 // Find the associated perf.counter probe
4fa83377
SC
8578 for (it=s.perf_counters.begin() ;
8579 it != s.perf_counters.end(); it++, i++)
3689db05
SC
8580 if ((*it).second.second == (*pcii))
8581 break;
8582 s.op->line() << lex_cast(i) << ", ";
8583 }
8584 s.op->newline() << "};";
8585 }
8586
cfcab6c7 8587 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
8588 << "stap_inode_uprobe_consumers[] = {";
8589 s.op->indent(1);
8590 for (unsigned i=0; i<probes.size(); i++)
8591 {
8592 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
8593 unsigned index = module_index[make_pbm_key(p)];
8594 s.op->newline() << "{";
79af55c3
JS
8595 if (p->has_return)
8596 s.op->line() << " .return_p=1,";
cfcab6c7
JS
8597 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
8598 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
8599 if (p->sdt_semaphore_addr)
8600 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
8601 << hex << p->sdt_semaphore_addr << dec << "ULL,";
0d049a1d 8602 // XXX: don't bother emit if array is empty
3689db05
SC
8603 s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
8604 // List of perf counters used by a probe from above
0d049a1d 8605 s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
cfcab6c7
JS
8606 s.op->line() << " .probe=" << common_probe_init (p) << ",";
8607 s.op->line() << " },";
2b69faaf
JS
8608 }
8609 s.op->newline(-1) << "};";
8610 s.op->assert_0_indent();
8611}
8612
8613
8614void
8615uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
8616{
8617 if (probes.empty()) return;
8618 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
8619 // Let stapiu_init() handle reporting errors by setting probe_point
8620 // to NULL.
8621 s.op->newline() << "probe_point = NULL;";
cfcab6c7 8622 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
8623 << "stap_inode_uprobe_targets, "
8624 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8625 << "stap_inode_uprobe_consumers, "
8626 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8627}
8628
8629
8630void
8631uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
8632{
8633 if (probes.empty()) return;
8634 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 8635 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
8636 << "stap_inode_uprobe_targets, "
8637 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
8638 << "stap_inode_uprobe_consumers, "
8639 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
8640}
8641
8642
3a894f7e
JS
8643void
8644uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
8645{
8646 if (probes.empty()) return;
8647 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8648 emit_module_maxuprobes (s);
e00f3fb7 8649 s.op->newline() << "#include \"dyninst/uprobes.h\"";
3a894f7e 8650
f31a77f5
DS
8651 // Let the dynprobe_derived_probe_group handle outputting targets
8652 // and probes. This allows us to merge different types of probes.
8653 s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
8654 for (unsigned i = 0; i < probes.size(); i++)
3a894f7e
JS
8655 {
8656 uprobe_derived_probe *p = probes[i];
e00f3fb7 8657
f31a77f5
DS
8658 dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
8659 (p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
8660 common_probe_init(p));
3a894f7e 8661 }
874d38bf
JS
8662 // loc2c-generated code assumes pt_regs are available, so use this to make
8663 // sure we always have *something* for it to dereference...
f31a77f5 8664 s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
e00f3fb7 8665
3a894f7e
JS
8666 // Write the probe handler.
8667 // NB: not static, so dyninst can find it
8668 s.op->newline() << "int enter_dyninst_uprobe "
8669 << "(uint64_t index, struct pt_regs *regs) {";
e00f3fb7 8670 s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
92b97104
JS
8671
8672 // Since we're sharing the entry function, we have to dynamically choose the probe_type
8673 string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
8674 " stp_probe_type_uretprobe : stp_probe_type_uprobe)";
71db462b 8675 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sup->probe",
92b97104
JS
8676 probe_type);
8677
874d38bf 8678 s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
e04b5d74 8679 s.op->newline() << "c->user_mode_p = 1;";
3a894f7e
JS
8680 // XXX: once we have regs, check how dyninst sets the IP
8681 // XXX: the way that dyninst rewrites stuff is probably going to be
8682 // ... very confusing to our backtracer (at least if we stay in process)
8683 s.op->newline() << "(*sup->probe->ph) (c);";
f887a8c9 8684 common_probe_entryfn_epilogue (s, true);
3a894f7e
JS
8685 s.op->newline() << "return 0;";
8686 s.op->newline(-1) << "}";
3debb935 8687 s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
3a894f7e
JS
8688 s.op->assert_0_indent();
8689}
8690
8691
8692void
8693uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
8694{
8695 if (probes.empty()) return;
8696
8697 /* stapdyn handles the dirty work via dyninst */
8698 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8699 s.op->newline() << "/* this section left intentionally blank */";
8700}
8701
8702
8703void
8704uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
8705{
8706 if (probes.empty()) return;
8707
8708 /* stapdyn handles the dirty work via dyninst */
8709 s.op->newline() << "/* ---- dyninst uprobes ---- */";
8710 s.op->newline() << "/* this section left intentionally blank */";
8711}
8712
8713
2b69faaf
JS
8714void
8715uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8716{
ac3af990 8717 if (s.runtime_usermode_p())
4441e344
JS
8718 emit_module_dyninst_decls (s);
8719 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8720 emit_module_inode_decls (s);
8721 else
8722 emit_module_utrace_decls (s);
8723}
8724
8725
8726void
8727uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
8728{
ac3af990 8729 if (s.runtime_usermode_p())
4441e344
JS
8730 emit_module_dyninst_init (s);
8731 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8732 emit_module_inode_init (s);
8733 else
8734 emit_module_utrace_init (s);
8735}
8736
8737
8738void
8739uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
8740{
ac3af990 8741 if (s.runtime_usermode_p())
4441e344
JS
8742 emit_module_dyninst_exit (s);
8743 else if (kernel_supports_inode_uprobes (s))
2b69faaf
JS
8744 emit_module_inode_exit (s);
8745 else
8746 emit_module_utrace_exit (s);
8747}
8748
8749
e6fe60e7
AM
8750// ------------------------------------------------------------------------
8751// Kprobe derived probes
8752// ------------------------------------------------------------------------
8753
4627ed58 8754static const string TOK_KPROBE("kprobe");
935447c8 8755
bae55db9 8756struct kprobe_derived_probe: public derived_probe
d0ea46ce 8757{
23dc94f6
DS
8758 kprobe_derived_probe (systemtap_session& sess,
8759 vector<derived_probe *> & results,
8760 probe *base,
bae55db9
JS
8761 probe_point *location,
8762 const string& name,
8763 int64_t stmt_addr,
8764 bool has_return,
8765 bool has_statement,
8766 bool has_maxactive,
b642c901
SC
8767 bool has_path,
8768 bool has_library,
8769 long maxactive_val,
8770 const string& path,
8771 const string& library
bae55db9
JS
8772 );
8773 string symbol_name;
8774 Dwarf_Addr addr;
8775 bool has_return;
8776 bool has_statement;
8777 bool has_maxactive;
b642c901
SC
8778 bool has_path;
8779 bool has_library;
bae55db9 8780 long maxactive_val;
b642c901
SC
8781 string path;
8782 string library;
bae55db9
JS
8783 bool access_var;
8784 void printsig (std::ostream &o) const;
8785 void join_group (systemtap_session& s);
8786};
d0ea46ce 8787
bae55db9
JS
8788struct kprobe_derived_probe_group: public derived_probe_group
8789{
8790private:
8791 multimap<string,kprobe_derived_probe*> probes_by_module;
8792 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 8793
bae55db9
JS
8794public:
8795 void enroll (kprobe_derived_probe* probe);
8796 void emit_module_decls (systemtap_session& s);
8797 void emit_module_init (systemtap_session& s);
8798 void emit_module_exit (systemtap_session& s);
8799};
d0ea46ce 8800
23dc94f6
DS
8801struct kprobe_var_expanding_visitor: public var_expanding_visitor
8802{
8803 systemtap_session& sess;
8804 block *add_block;
8805 block *add_call_probe; // synthesized from .return probes with saved $vars
8806 bool add_block_tid, add_call_probe_tid;
bd5b25e1 8807 bool has_return;
23dc94f6 8808
bd5b25e1 8809 kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
23dc94f6 8810 sess(sess), add_block(NULL), add_call_probe(NULL),
bd5b25e1
JS
8811 add_block_tid(false), add_call_probe_tid(false),
8812 has_return(has_return) {}
23dc94f6
DS
8813
8814 void visit_entry_op (entry_op* e);
8815};
8816
8817
8818kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
8819 vector<derived_probe *> & results,
8820 probe *base,
e6fe60e7 8821 probe_point *location,
b6371390 8822 const string& name,
e6fe60e7 8823 int64_t stmt_addr,
b6371390
JS
8824 bool has_return,
8825 bool has_statement,
8826 bool has_maxactive,
b642c901
SC
8827 bool has_path,
8828 bool has_library,
8829 long maxactive_val,
8830 const string& path,
8831 const string& library
b6371390 8832 ):
4c5d1300 8833 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 8834 symbol_name (name), addr (stmt_addr),
b6371390 8835 has_return (has_return), has_statement (has_statement),
b642c901
SC
8836 has_maxactive (has_maxactive), has_path (has_path),
8837 has_library (has_library),
8838 maxactive_val (maxactive_val),
8839 path (path), library (library)
e6fe60e7
AM
8840{
8841 this->tok = base->tok;
8842 this->access_var = false;
d0ea46ce 8843
e6fe60e7
AM
8844#ifndef USHRT_MAX
8845#define USHRT_MAX 32767
8846#endif
d0ea46ce 8847
46856d8d
JS
8848 // Expansion of $target variables in the probe body produces an error during
8849 // translate phase, since we're not using debuginfo
d0ea46ce 8850
e6fe60e7 8851 vector<probe_point::component*> comps;
46856d8d 8852 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 8853
46856d8d
JS
8854 if (has_statement)
8855 {
9ea68eb9
JS
8856 comps.push_back (new probe_point::component(TOK_STATEMENT,
8857 new literal_number(addr, true)));
46856d8d
JS
8858 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
8859 }
8860 else
8861 {
8862 size_t pos = name.find(':');
8863 if (pos != string::npos)
d0ea46ce 8864 {
46856d8d
JS
8865 string module = name.substr(0, pos);
8866 string function = name.substr(pos + 1);
8867 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
8868 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
8869 }
8870 else
8871 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 8872 }
d0ea46ce 8873
b6371390
JS
8874 if (has_return)
8875 comps.push_back (new probe_point::component(TOK_RETURN));
8876 if (has_maxactive)
8877 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 8878
bd5b25e1 8879 kprobe_var_expanding_visitor v (sess, has_return);
23dc94f6
DS
8880 v.replace (this->body);
8881
8882 // If during target-variable-expanding the probe, we added a new block
8883 // of code, add it to the start of the probe.
8884 if (v.add_block)
8885 this->body = new block(v.add_block, this->body);
8886
8887 // If when target-variable-expanding the probe, we need to
8888 // synthesize a sibling function-entry probe. We don't go through
8889 // the whole probe derivation business (PR10642) that could lead to
8890 // wildcard/alias resolution, or for that dwarf-induced duplication.
8891 if (v.add_call_probe)
8892 {
8893 assert (has_return);
8894
8895 // We temporarily replace base.
8896 statement* old_body = base->body;
8897 base->body = v.add_call_probe;
8898
8899 derived_probe *entry_handler
8900 = new kprobe_derived_probe (sess, results, base, location, name, 0,
8901 false, has_statement, has_maxactive,
8902 has_path, has_library, maxactive_val,
8903 path, library);
8904 results.push_back (entry_handler);
8905
8906 base->body = old_body;
8907 }
8908
e6fe60e7
AM
8909 this->sole_location()->components = comps;
8910}
d0ea46ce 8911
e6fe60e7
AM
8912void kprobe_derived_probe::printsig (ostream& o) const
8913{
8914 sole_location()->print (o);
8915 o << " /* " << " name = " << symbol_name << "*/";
8916 printsig_nested (o);
8917}
d0ea46ce 8918
e6fe60e7
AM
8919void kprobe_derived_probe::join_group (systemtap_session& s)
8920{
d0ea46ce 8921
e6fe60e7
AM
8922 if (! s.kprobe_derived_probes)
8923 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
8924 s.kprobe_derived_probes->enroll (this);
d0ea46ce 8925
e6fe60e7 8926}
d0ea46ce 8927
e6fe60e7
AM
8928void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
8929{
8930 probes_by_module.insert (make_pair (p->symbol_name, p));
8931 // probes of same symbol should share single kprobe/kretprobe
8932}
d0ea46ce 8933
e6fe60e7
AM
8934void
8935kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
8936{
8937 if (probes_by_module.empty()) return;
d0ea46ce 8938
e6fe60e7 8939 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 8940
e6fe60e7
AM
8941 // Warn of misconfigured kernels
8942 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
8943 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
8944 s.op->newline() << "#endif";
8945 s.op->newline();
d0ea46ce 8946
f07c3b68 8947 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 8948 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
8949 s.op->newline() << "#endif";
8950
e6fe60e7 8951 // Forward declare the master entry functions
88747011 8952 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 8953 s.op->line() << " struct pt_regs *regs);";
88747011 8954 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 8955 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 8956
e6fe60e7
AM
8957 // Emit an array of kprobe/kretprobe pointers
8958 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 8959 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 8960 s.op->newline() << "#endif";
d0ea46ce 8961
e6fe60e7 8962 // Emit the actual probe list.
d0ea46ce 8963
e6fe60e7
AM
8964 s.op->newline() << "static struct stap_dwarfless_kprobe {";
8965 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
8966 s.op->newline() << "#ifdef __ia64__";
8967 s.op->newline() << "struct kprobe dummy;";
8968 s.op->newline() << "#endif";
8969 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
8970 // NB: bss!
d0ea46ce 8971
e6fe60e7
AM
8972 s.op->newline() << "static struct stap_dwarfless_probe {";
8973 s.op->newline(1) << "const unsigned return_p:1;";
8974 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 8975 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
8976 s.op->newline() << "unsigned registered_p:1;";
8977 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 8978
e6fe60e7
AM
8979 // Function Names are mostly small and uniform enough to justify putting
8980 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 8981
faea5e16
JS
8982 size_t symbol_string_name_max = 0;
8983 size_t symbol_string_name_tot = 0;
e6fe60e7 8984 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 8985 {
e6fe60e7
AM
8986 kprobe_derived_probe* p = it->second;
8987#define DOIT(var,expr) do { \
8988 size_t var##_size = (expr) + 1; \
8989 var##_max = max (var##_max, var##_size); \
8990 var##_tot += var##_size; } while (0)
e6fe60e7
AM
8991 DOIT(symbol_string_name, p->symbol_name.size());
8992#undef DOIT
6270adc1
MH
8993 }
8994
e6fe60e7
AM
8995#define CALCIT(var) \
8996 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 8997
e6fe60e7
AM
8998 CALCIT(symbol_string);
8999#undef CALCIT
6270adc1 9000
bd659351 9001 s.op->newline() << "unsigned long address;";
7c3e97f4 9002 s.op->newline() << "const struct stap_probe * const probe;";
e6fe60e7
AM
9003 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
9004 s.op->indent(1);
6270adc1 9005
e6fe60e7
AM
9006 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
9007 {
9008 kprobe_derived_probe* p = it->second;
9009 s.op->newline() << "{";
9010 if (p->has_return)
9011 s.op->line() << " .return_p=1,";
6270adc1 9012
e6fe60e7
AM
9013 if (p->has_maxactive)
9014 {
9015 s.op->line() << " .maxactive_p=1,";
9016 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
9017 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
9018 }
6270adc1 9019
b350f56b
JS
9020 if (p->locations[0]->optional)
9021 s.op->line() << " .optional_p=1,";
9022
e6fe60e7 9023 if (p->has_statement)
c8d9d15e 9024 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 9025 else
c8d9d15e 9026 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 9027
faea5e16 9028 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 9029 s.op->line() << " },";
935447c8
DS
9030 }
9031
e6fe60e7 9032 s.op->newline(-1) << "};";
5d67b47c 9033
e6fe60e7
AM
9034 // Emit the kprobes callback function
9035 s.op->newline();
88747011 9036 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
9037 s.op->line() << " struct pt_regs *regs) {";
9038 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9039 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9040 // Check that the index is plausible
9041 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9042 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9043 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9044 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9045 s.op->line() << "];";
71db462b 9046 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9047 "stp_probe_type_kprobe");
d9aed31e 9048 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
9049
9050 // Make it look like the IP is set as it wouldn't have been replaced
9051 // by a breakpoint instruction when calling real probe handler. Reset
9052 // IP regs on return, so we don't confuse kprobes. PR10458
9053 s.op->newline() << "{";
9054 s.op->indent(1);
d9aed31e 9055 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9056 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 9057 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9058 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9059 s.op->newline(-1) << "}";
9060
f887a8c9 9061 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9062 s.op->newline() << "return 0;";
9063 s.op->newline(-1) << "}";
935447c8 9064
e6fe60e7
AM
9065 // Same for kretprobes
9066 s.op->newline();
88747011 9067 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
9068 s.op->line() << " struct pt_regs *regs) {";
9069 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 9070
e6fe60e7
AM
9071 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
9072 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
9073 // Check that the index is plausible
9074 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
9075 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
9076 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
9077 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
9078 s.op->line() << "];";
935447c8 9079
71db462b 9080 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9081 "stp_probe_type_kretprobe");
d9aed31e 9082 s.op->newline() << "c->kregs = regs;";
6dceb5c9 9083 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
9084
9085 // Make it look like the IP is set as it wouldn't have been replaced
9086 // by a breakpoint instruction when calling real probe handler. Reset
9087 // IP regs on return, so we don't confuse kprobes. PR10458
9088 s.op->newline() << "{";
9089 s.op->indent(1);
d9aed31e 9090 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 9091 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 9092 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 9093 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
9094 s.op->newline(-1) << "}";
9095
f887a8c9 9096 common_probe_entryfn_epilogue (s, true);
e6fe60e7
AM
9097 s.op->newline() << "return 0;";
9098 s.op->newline(-1) << "}";
bd659351 9099
03a4ec63 9100 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9101 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
9102 s.op->newline() << " struct module *owner,";
9103 s.op->newline() << " unsigned long val) {";
9104 s.op->newline(1) << "int i;";
fc1d2aa2
MW
9105 s.op->newline() << "int *p = (int *) data;";
9106 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
9107 << " && *p > 0; i++) {";
bd659351 9108 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8c272819
YW
9109 s.op->newline() << "if (! sdp->address) {";
9110 s.op->indent(1);
9111 s.op->newline() << "const char *colon;";
9112 s.op->newline() << "if (owner && (colon = strchr(sdp->symbol_string, ':'))) {";
9113 s.op->indent(1);
9114 s.op->newline() << "if ((strlen(owner->name) == (colon - sdp->symbol_string))";
9115 s.op->newline() << " && (strncmp(sdp->symbol_string, owner->name, colon - sdp->symbol_string) == 0)";
9116 s.op->newline() << " && (strcmp(colon + 1, name) == 0)) {";
9117 s.op->newline(1) << "sdp->address = val;";
9118 s.op->newline() << "(*p)--;";
9119 s.op->newline(-1) << "}";
9120 s.op->newline(-1) << "}";
9121 s.op->newline() << "else {";
fc1d2aa2 9122 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 9123 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
9124 s.op->newline() << "(*p)--;";
9125 s.op->newline(-1) << "}";
8c272819
YW
9126 s.op->newline(-1) << "}";
9127 s.op->newline(-1) << "}";
9128 s.op->newline(-1) << "}";
fc1d2aa2 9129 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 9130 s.op->newline(-1) << "}";
03a4ec63 9131 s.op->newline() << "#endif";
935447c8
DS
9132}
9133
e6fe60e7 9134
6270adc1 9135void
e6fe60e7 9136kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 9137{
03a4ec63 9138 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
9139 s.op->newline() << "{";
9140 s.op->newline(1) << "int p = 0;";
9141 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
9142 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9143 s.op->newline() << "if (! sdp->address)";
9144 s.op->newline(1) << "p++;";
9145 s.op->newline(-2) << "}";
9146 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
9147 s.op->newline(-1) << "}";
03a4ec63 9148 s.op->newline() << "#endif";
bd659351 9149
e6fe60e7 9150 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 9151 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 9152 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 9153 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
9154 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
9155
9156 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
9157 s.op->newline() << "if (! addr) {";
9158 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
9159 s.op->newline() << "if (!sdp->optional_p)";
9160 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
9161 s.op->newline(-1) << "continue;";
bd659351 9162 s.op->newline(-1) << "}";
03a4ec63
MW
9163 s.op->newline() << "#endif";
9164
26e63673 9165 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 9166 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 9167 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 9168 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9169 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 9170 s.op->newline() << "#endif";
e6fe60e7
AM
9171 s.op->newline() << "if (sdp->maxactive_p) {";
9172 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
9173 s.op->newline(-1) << "} else {";
f07c3b68 9174 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 9175 s.op->newline(-1) << "}";
88747011 9176 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
9177 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
9178 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9179 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 9180 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9181 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 9182 s.op->newline() << "#endif";
c8d9d15e 9183 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
9184 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9185 s.op->newline() << "if (rc == 0) {";
9186 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
9187 s.op->newline() << "if (rc != 0)";
9188 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9189 s.op->newline(-2) << "}";
9190 s.op->newline() << "#else";
9191 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
9192 s.op->newline() << "#endif";
9193 s.op->newline(-1) << "} else {";
9194 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 9195 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 9196 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 9197 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 9198 s.op->newline() << "#endif";
88747011 9199 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 9200 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 9201 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 9202 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 9203 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 9204 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 9205 s.op->newline() << "#endif";
e6fe60e7
AM
9206 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
9207 s.op->newline() << "if (rc == 0) {";
9208 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
9209 s.op->newline() << "if (rc != 0)";
9210 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
9211 s.op->newline(-2) << "}";
9212 s.op->newline() << "#else";
9213 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
9214 s.op->newline() << "#endif";
9215 s.op->newline(-1) << "}";
9216 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
9217 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 9218 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 9219 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 9220 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
9221 // XXX: shall we increment numskipped?
9222 s.op->newline(-1) << "}";
6270adc1 9223
e6fe60e7
AM
9224 s.op->newline() << "else sdp->registered_p = 1;";
9225 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
9226}
9227
b4be7cbc 9228
e6fe60e7
AM
9229void
9230kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 9231{
e6fe60e7
AM
9232 //Unregister kprobes by batch interfaces.
9233 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
9234 s.op->newline() << "j = 0;";
9235 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9236 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9237 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9238 s.op->newline() << "if (! sdp->registered_p) continue;";
9239 s.op->newline() << "if (!sdp->return_p)";
c9116e99 9240 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 9241 s.op->newline(-2) << "}";
c9116e99 9242 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9243 s.op->newline() << "j = 0;";
9244 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9245 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9246 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9247 s.op->newline() << "if (! sdp->registered_p) continue;";
9248 s.op->newline() << "if (sdp->return_p)";
c9116e99 9249 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 9250 s.op->newline(-2) << "}";
c9116e99 9251 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9252 s.op->newline() << "#ifdef __ia64__";
9253 s.op->newline() << "j = 0;";
9254 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9255 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9256 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9257 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 9258 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 9259 s.op->newline(-1) << "}";
c9116e99 9260 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
9261 s.op->newline() << "#endif";
9262 s.op->newline() << "#endif";
3e3bd7b6 9263
e6fe60e7
AM
9264 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
9265 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
9266 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
9267 s.op->newline() << "if (! sdp->registered_p) continue;";
9268 s.op->newline() << "if (sdp->return_p) {";
9269 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9270 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
9271 s.op->newline() << "#endif";
065d5567 9272 s.op->newline() << "atomic_add (kp->u.krp.nmissed, skipped_count());";
e6fe60e7
AM
9273 s.op->newline() << "#ifdef STP_TIMING";
9274 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 9275 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7 9276 s.op->newline(-1) << "#endif";
065d5567 9277 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, skipped_count());";
e6fe60e7
AM
9278 s.op->newline() << "#ifdef STP_TIMING";
9279 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 9280 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
9281 s.op->newline(-1) << "#endif";
9282 s.op->newline(-1) << "} else {";
9283 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
9284 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
9285 s.op->newline() << "#endif";
065d5567 9286 s.op->newline() << "atomic_add (kp->u.kp.nmissed, skipped_count());";
e6fe60e7
AM
9287 s.op->newline() << "#ifdef STP_TIMING";
9288 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 9289 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
9290 s.op->newline(-1) << "#endif";
9291 s.op->newline(-1) << "}";
9292 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
9293 s.op->newline() << "unregister_kprobe (&kp->dummy);";
9294 s.op->newline() << "#endif";
9295 s.op->newline() << "sdp->registered_p = 0;";
9296 s.op->newline(-1) << "}";
f8a968bc
JS
9297}
9298
e6fe60e7 9299struct kprobe_builder: public derived_probe_builder
3c1b3d06 9300{
9fdf787d 9301public:
2a639817 9302 kprobe_builder() {}
9fdf787d 9303
2a639817 9304 void build_no_more (systemtap_session &s) {}
9fdf787d 9305
e6fe60e7
AM
9306 virtual void build(systemtap_session & sess,
9307 probe * base,
9308 probe_point * location,
9309 literal_map_t const & parameters,
9310 vector<derived_probe *> & finished_results);
9311};
3c1b3d06
FCE
9312
9313
79189b84 9314void
05fb3e0c 9315kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
9316 probe * base,
9317 probe_point * location,
9318 literal_map_t const & parameters,
9319 vector<derived_probe *> & finished_results)
79189b84 9320{
e6fe60e7 9321 string function_string_val, module_string_val;
05fb3e0c 9322 string path, library, path_tgt, library_tgt;
b6371390
JS
9323 int64_t statement_num_val = 0, maxactive_val = 0;
9324 bool has_function_str, has_module_str, has_statement_num;
9325 bool has_absolute, has_return, has_maxactive;
b642c901 9326 bool has_path, has_library;
79189b84 9327
b6371390
JS
9328 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
9329 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
9330 has_return = has_null_param (parameters, TOK_RETURN);
9331 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
9332 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
9333 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
9334 has_path = get_param (parameters, TOK_PROCESS, path);
9335 has_library = get_param (parameters, TOK_LIBRARY, library);
9336
9337 if (has_path)
05fb3e0c
WF
9338 {
9339 path = find_executable (path, sess.sysroot, sess.sysenv);
9340 path_tgt = path_remove_sysroot(sess, path);
9341 }
b642c901 9342 if (has_library)
05fb3e0c
WF
9343 {
9344 library = find_executable (library, sess.sysroot, sess.sysenv,
9345 "LD_LIBRARY_PATH");
9346 library_tgt = path_remove_sysroot(sess, library);
9347 }
c57ea854 9348
b6371390 9349 if (has_function_str)
6fb70fb7 9350 {
2a639817 9351 if (has_module_str)
9fdf787d
DS
9352 {
9353 function_string_val = module_string_val + ":" + function_string_val;
9354 derived_probe *dp
23dc94f6
DS
9355 = new kprobe_derived_probe (sess, finished_results, base,
9356 location, function_string_val,
9fdf787d
DS
9357 0, has_return, has_statement_num,
9358 has_maxactive, has_path, has_library,
9359 maxactive_val, path_tgt, library_tgt);
9360 finished_results.push_back (dp);
9361 }
9362 else
9363 {
2a639817
JS
9364 vector<string> matches;
9365
9366 // Simple names can be found directly
9367 if (function_string_val.find_first_of("*?[") == string::npos)
9368 {
9369 if (sess.kernel_functions.count(function_string_val))
9370 matches.push_back(function_string_val);
9371 }
9372 else // Search function name list for matching names
9373 {
9374 for (set<string>::const_iterator it = sess.kernel_functions.begin();
9375 it != sess.kernel_functions.end(); it++)
9376 // fnmatch returns zero for matching.
9377 if (fnmatch(function_string_val.c_str(), it->c_str(), 0) == 0)
9378 matches.push_back(*it);
9379 }
86758d5f 9380
2a639817
JS
9381 for (vector<string>::const_iterator it = matches.begin();
9382 it != matches.end(); it++)
9fdf787d 9383 {
2a639817
JS
9384 derived_probe *dp
9385 = new kprobe_derived_probe (sess, finished_results, base,
9386 location, *it, 0, has_return,
9387 has_statement_num,
9388 has_maxactive, has_path,
9389 has_library, maxactive_val,
9390 path_tgt, library_tgt);
9391 finished_results.push_back (dp);
9fdf787d
DS
9392 }
9393 }
6fb70fb7 9394 }
e6fe60e7 9395 else
b6371390
JS
9396 {
9397 // assert guru mode for absolute probes
9398 if ( has_statement_num && has_absolute && !base->privileged )
dc09353a 9399 throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390 9400
23dc94f6
DS
9401 finished_results.push_back (new kprobe_derived_probe (sess,
9402 finished_results,
9403 base,
b6371390
JS
9404 location, "",
9405 statement_num_val,
9406 has_return,
9407 has_statement_num,
9408 has_maxactive,
b642c901
SC
9409 has_path,
9410 has_library,
9411 maxactive_val,
05fb3e0c
WF
9412 path_tgt,
9413 library_tgt));
96b030fe 9414 }
79189b84
JS
9415}
9416
23dc94f6
DS
9417
9418void
9419kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
9420{
9421 expression *repl = e;
9422
bd5b25e1
JS
9423 if (has_return)
9424 {
9425 // expand the operand as if it weren't a return probe
9426 has_return = false;
9427 replace (e->operand);
9428 has_return = true;
23dc94f6 9429
bd5b25e1
JS
9430 // XXX it would be nice to use gen_kretprobe_saved_return when
9431 // available, but it requires knowing the types already, which is
9432 // problematic for arbitrary expressons.
9433 repl = gen_mapped_saved_return (sess, e->operand, "entry",
9434 add_block, add_block_tid,
9435 add_call_probe, add_call_probe_tid);
9436 }
23dc94f6
DS
9437 provide (repl);
9438}
9439
9440
dd225250
PS
9441// ------------------------------------------------------------------------
9442// Hardware breakpoint based probes.
9443// ------------------------------------------------------------------------
9444
9445static const string TOK_HWBKPT("data");
9446static const string TOK_HWBKPT_WRITE("write");
9447static const string TOK_HWBKPT_RW("rw");
9448static const string TOK_LENGTH("length");
9449
9450#define HWBKPT_READ 0
9451#define HWBKPT_WRITE 1
9452#define HWBKPT_RW 2
9453struct hwbkpt_derived_probe: public derived_probe
9454{
9455 hwbkpt_derived_probe (probe *base,
9456 probe_point *location,
9457 uint64_t addr,
9458 string symname,
9459 unsigned int len,
9460 bool has_only_read_access,
9461 bool has_only_write_access,
9462 bool has_rw_access
9463 );
9464 Dwarf_Addr hwbkpt_addr;
9465 string symbol_name;
9466 unsigned int hwbkpt_access,hwbkpt_len;
9467
9468 void printsig (std::ostream &o) const;
9469 void join_group (systemtap_session& s);
9470};
9471
9472struct hwbkpt_derived_probe_group: public derived_probe_group
9473{
dd225250 9474private:
dac77b80 9475 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
9476
9477public:
9478 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
9479 void emit_module_decls (systemtap_session& s);
9480 void emit_module_init (systemtap_session& s);
9481 void emit_module_exit (systemtap_session& s);
9482};
9483
9484hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
9485 probe_point *location,
9486 uint64_t addr,
9487 string symname,
9488 unsigned int len,
9489 bool has_only_read_access,
9490 bool has_only_write_access,
822a6a3d 9491 bool):
4c5d1300 9492 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
9493 hwbkpt_addr (addr),
9494 symbol_name (symname),
9495 hwbkpt_len (len)
9496{
9497 this->tok = base->tok;
9498
9499 vector<probe_point::component*> comps;
9500 comps.push_back (new probe_point::component(TOK_KERNEL));
9501
9502 if (hwbkpt_addr)
9ea68eb9
JS
9503 comps.push_back (new probe_point::component (TOK_HWBKPT,
9504 new literal_number(hwbkpt_addr, true)));
9505 else if (symbol_name.size())
9506 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
9507
9508 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
9509
9510 if (has_only_read_access)
9ea68eb9 9511 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
9512//TODO add code for comps.push_back for read, since this flag is not for x86
9513
9514 else
9ea68eb9
JS
9515 {
9516 if (has_only_write_access)
9517 {
9518 this->hwbkpt_access = HWBKPT_WRITE ;
9519 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
9520 }
9521 else
9522 {
9523 this->hwbkpt_access = HWBKPT_RW ;
9524 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
9525 }
9526 }
dd225250
PS
9527
9528 this->sole_location()->components = comps;
9529}
9530
9531void hwbkpt_derived_probe::printsig (ostream& o) const
9532{
9533 sole_location()->print (o);
9534 printsig_nested (o);
9535}
9536
9537void hwbkpt_derived_probe::join_group (systemtap_session& s)
9538{
dac77b80
FCE
9539 if (! s.hwbkpt_derived_probes)
9540 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
9541 s.hwbkpt_derived_probes->enroll (this, s);
9542}
9543
9544void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
9545{
dac77b80
FCE
9546 hwbkpt_probes.push_back (p);
9547
9548 unsigned max_hwbkpt_probes_by_arch = 0;
9549 if (s.architecture == "i386" || s.architecture == "x86_64")
9550 max_hwbkpt_probes_by_arch = 4;
9551 else if (s.architecture == "s390")
9552 max_hwbkpt_probes_by_arch = 1;
9553
c57ea854 9554 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 9555 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 9556 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
9557}
9558
9559void
9560hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
9561{
dac77b80 9562 if (hwbkpt_probes.empty()) return;
dd225250
PS
9563
9564 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
9565
9566 s.op->newline() << "#include <linux/perf_event.h>";
9567 s.op->newline() << "#include <linux/hw_breakpoint.h>";
9568 s.op->newline();
9569
9570 // Forward declare the master entry functions
23063de1 9571 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9572 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9573 s.op->line() << " int nmi,";
9574 s.op->line() << " struct perf_sample_data *data,";
9575 s.op->line() << " struct pt_regs *regs);";
23063de1
FCE
9576 s.op->newline() << "#else";
9577 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9578 s.op->line() << " struct perf_sample_data *data,";
9579 s.op->line() << " struct pt_regs *regs);";
9580 s.op->newline() << "#endif";
79189b84 9581
dd225250
PS
9582 // Emit the actual probe list.
9583
9584 s.op->newline() << "static struct perf_event_attr ";
dac77b80 9585 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9586
9587 s.op->newline() << "static struct perf_event **";
dac77b80 9588 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
9589 s.op->newline() << "static struct stap_hwbkpt_probe {";
9590 s.op->newline() << "int registered_p:1;";
43650b10 9591// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
9592// registered_p = 1 signifies a probe that got registered successfully
9593
faea5e16 9594 // Symbol Names are mostly small and uniform enough
dd225250 9595 // to justify putting const char*.
dac77b80 9596 s.op->newline() << "const char * const symbol;";
dd225250
PS
9597
9598 s.op->newline() << "const unsigned long address;";
9599 s.op->newline() << "uint8_t atype;";
bb0a4e12 9600 s.op->newline() << "unsigned int len;";
7c3e97f4 9601 s.op->newline() << "const struct stap_probe * const probe;";
dd225250
PS
9602 s.op->newline() << "} stap_hwbkpt_probes[] = {";
9603 s.op->indent(1);
9604
dac77b80 9605 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 9606 {
dac77b80 9607 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 9608 s.op->newline() << "{";
dd225250
PS
9609 if (p->symbol_name.size())
9610 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
9611 else
9612 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
9613 switch(p->hwbkpt_access){
9614 case HWBKPT_READ:
9615 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 9616 break;
dd225250
PS
9617 case HWBKPT_WRITE:
9618 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 9619 break;
dd225250
PS
9620 case HWBKPT_RW:
9621 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 9622 break;
dd225250
PS
9623 };
9624 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 9625 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 9626 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
9627 s.op->line() << " },";
9628 }
dac77b80 9629 s.op->newline(-1) << "};";
dd225250
PS
9630
9631 // Emit the hwbkpt callback function
9632 s.op->newline() ;
23063de1 9633 s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
dd225250
PS
9634 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9635 s.op->line() << " int nmi,";
9636 s.op->line() << " struct perf_sample_data *data,";
9637 s.op->line() << " struct pt_regs *regs) {";
23063de1
FCE
9638 s.op->newline() << "#else";
9639 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
9640 s.op->line() << " struct perf_sample_data *data,";
9641 s.op->line() << " struct pt_regs *regs) {";
9642 s.op->newline() << "#endif";
dac77b80
FCE
9643 s.op->newline(1) << "unsigned int i;";
9644 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
9645 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
9646 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9647 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
9648 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) {";
9649 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
71db462b 9650 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "sdp->probe",
cda141c2 9651 "stp_probe_type_hwbkpt");
d9aed31e 9652 s.op->newline() << "if (user_mode(regs)) {";
e04b5d74 9653 s.op->newline(1)<< "c->user_mode_p = 1;";
d9aed31e
MW
9654 s.op->newline() << "c->uregs = regs;";
9655 s.op->newline(-1) << "} else {";
9656 s.op->newline(1) << "c->kregs = regs;";
9657 s.op->newline(-1) << "}";
26e63673 9658 s.op->newline() << "(*sdp->probe->ph) (c);";
f887a8c9 9659 common_probe_entryfn_epilogue (s, true);
dac77b80 9660 s.op->newline(-1) << "}";
dd225250
PS
9661 s.op->newline(-1) << "}";
9662 s.op->newline() << "return 0;";
dac77b80 9663 s.op->newline(-1) << "}";
dd225250
PS
9664}
9665
9666void
9667hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
9668{
dac77b80 9669 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
9670 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
9671 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
9672 s.op->newline() << "void *addr = (void *) sdp->address;";
9673 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
9674 s.op->newline() << "hw_breakpoint_init(hp);";
9675 s.op->newline() << "if (addr)";
9676 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
9677 s.op->newline(-1) << "else { ";
9678 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
9679 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 9680 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
9681 s.op->newline() << "continue;";
9682 s.op->newline(-1) << "}";
9683 s.op->newline(-1) << "}";
9684 s.op->newline() << "hp->bp_type = sdp->atype;";
9685
9686 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 9687 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
9688 {
9689 s.op->newline() << "switch(sdp->len) {";
9690 s.op->newline() << "case 1:";
9691 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
9692 s.op->newline() << "break;";
9693 s.op->newline(-1) << "case 2:";
9694 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
9695 s.op->newline() << "break;";
9696 s.op->newline(-1) << "case 3:";
9697 s.op->newline() << "case 4:";
9698 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
9699 s.op->newline() << "break;";
9700 s.op->newline(-1) << "case 5:";
9701 s.op->newline() << "case 6:";
9702 s.op->newline() << "case 7:";
9703 s.op->newline() << "case 8:";
9704 s.op->newline() << "default:"; // XXX: could instead reject
9705 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
9706 s.op->newline() << "break;";
9707 s.op->newline(-1) << "}";
9708 }
9709 else // other architectures presumed straightforward
9710 s.op->newline() << "hp->bp_len = sdp->len;";
9711
26e63673 9712 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
9713 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
9714 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
9715 s.op->newline() << "#else";
dac77b80 9716 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 9717 s.op->newline() << "#endif";
43650b10 9718 s.op->newline() << "rc = 0;";
dac77b80 9719 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
9720 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
9721 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
9722 s.op->newline(-1) << "}";
217ef1f4
WC
9723 s.op->newline() << "if (rc) {";
9724 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 9725 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 9726 s.op->newline(-1) << "}";
dd225250 9727 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
9728 s.op->newline(-1) << "}"; // for loop
9729}
9730
9731void
9732hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
9733{
9734 //Unregister hwbkpt probes.
dac77b80 9735 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 9736 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
9737 s.op->newline() << "if (sdp->registered_p == 0) continue;";
9738 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
9739 s.op->newline() << "sdp->registered_p = 0;";
9740 s.op->newline(-1) << "}";
9741}
9742
9743struct hwbkpt_builder: public derived_probe_builder
9744{
9745 hwbkpt_builder() {}
9746 virtual void build(systemtap_session & sess,
9747 probe * base,
9748 probe_point * location,
9749 literal_map_t const & parameters,
9750 vector<derived_probe *> & finished_results);
9751};
9752
9753void
9754hwbkpt_builder::build(systemtap_session & sess,
9755 probe * base,
9756 probe_point * location,
9757 literal_map_t const & parameters,
9758 vector<derived_probe *> & finished_results)
9759{
9760 string symbol_str_val;
9761 int64_t hwbkpt_address, len;
9762 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
9763
b47f3a55 9764 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
dc09353a 9765 throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
9766 location->components[0]->tok);
9767 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
dc09353a 9768 throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
9769 location->components[0]->tok);
9770
dd225250
PS
9771 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
9772 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
9773 has_len = get_param (parameters, TOK_LENGTH, len);
9774 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
9775 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
9776
9777 if (!has_len)
9778 len = 1;
9779
9780 if (has_addr)
9781 finished_results.push_back (new hwbkpt_derived_probe (base,
9782 location,
9783 hwbkpt_address,
9784 "",len,0,
9785 has_write,
9786 has_rw));
5d8a0aea 9787 else if (has_symbol_str)
dd225250
PS
9788 finished_results.push_back (new hwbkpt_derived_probe (base,
9789 location,
9790 0,
9791 symbol_str_val,len,0,
9792 has_write,
9793 has_rw));
5d8a0aea
FCE
9794 else
9795 assert (0);
dd225250 9796}
342d3f96 9797
0a6f5a3f
JS
9798// ------------------------------------------------------------------------
9799// statically inserted kernel-tracepoint derived probes
9800// ------------------------------------------------------------------------
9801
6fb70fb7 9802struct tracepoint_arg
79189b84 9803{
ad370dcc 9804 string name, c_type, typecast;
dcaa1a65 9805 bool usable, used, isptr;
f8a968bc 9806 Dwarf_Die type_die;
dcaa1a65 9807 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 9808};
79189b84 9809
0a6f5a3f
JS
9810struct tracepoint_derived_probe: public derived_probe
9811{
79189b84
JS
9812 tracepoint_derived_probe (systemtap_session& s,
9813 dwflpp& dw, Dwarf_Die& func_die,
9814 const string& tracepoint_name,
9815 probe* base_probe, probe_point* location);
bc9a523d 9816
79189b84 9817 systemtap_session& sess;
6fb70fb7
JS
9818 string tracepoint_name, header;
9819 vector <struct tracepoint_arg> args;
bc9a523d 9820
6fb70fb7 9821 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 9822 void getargs (std::list<std::string> &arg_set) const;
79189b84 9823 void join_group (systemtap_session& s);
3e3bd7b6 9824 void print_dupe_stamp(ostream& o);
0a6f5a3f 9825};
79189b84
JS
9826
9827
0a6f5a3f 9828struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 9829{
79189b84
JS
9830 void emit_module_decls (systemtap_session& s);
9831 void emit_module_init (systemtap_session& s);
9832 void emit_module_exit (systemtap_session& s);
0a6f5a3f 9833};
79189b84 9834
bc9a523d 9835
f8a968bc
JS
9836struct tracepoint_var_expanding_visitor: public var_expanding_visitor
9837{
9838 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
9839 vector <struct tracepoint_arg>& args):
9840 dw (dw), probe_name (probe_name), args (args) {}
9841 dwflpp& dw;
9842 const string& probe_name;
9843 vector <struct tracepoint_arg>& args;
bc9a523d 9844
f8a968bc
JS
9845 void visit_target_symbol (target_symbol* e);
9846 void visit_target_symbol_arg (target_symbol* e);
9847 void visit_target_symbol_context (target_symbol* e);
9848};
79189b84
JS
9849
9850
f8a968bc
JS
9851void
9852tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 9853{
cc9001af 9854 string argname = e->sym_name();
75ead1f7 9855
f8a968bc
JS
9856 // search for a tracepoint parameter matching this name
9857 tracepoint_arg *arg = NULL;
9858 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 9859 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
9860 {
9861 arg = &args[i];
9862 arg->used = true;
9863 break;
9864 }
75ead1f7 9865
f8a968bc
JS
9866 if (arg == NULL)
9867 {
1d0499c2 9868 set<string> vars;
f8a968bc 9869 for (unsigned i = 0; i < args.size(); ++i)
1d0499c2
JL
9870 vars.insert("$" + args[i].name);
9871 vars.insert("$$name");
9872 vars.insert("$$parms");
9873 vars.insert("$$vars");
9874 string sugs = levenshtein_suggest(e->name, vars); // no need to limit, there's not that many
75ead1f7 9875
f8a968bc
JS
9876 // We hope that this value ends up not being referenced after all, so it
9877 // can be optimized out quietly.
1d0499c2
JL
9878 throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
9879 e->name.c_str(), sugs.empty() ? "" :
9880 (_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
9881 // NB: we use 'alternatives' because we list all
f8a968bc
JS
9882 // NB: we can have multiple errors, since a target variable
9883 // may be expanded in several different contexts:
9884 // trace ("*") { $foo->bar }
f8a968bc 9885 }
75ead1f7 9886
f8a968bc 9887 // make sure we're not dereferencing base types
dc5a09fc 9888 if (!arg->isptr)
d19a9a82 9889 e->assert_no_components("tracepoint", true);
75ead1f7 9890
f8a968bc
JS
9891 // we can only write to dereferenced fields, and only if guru mode is on
9892 bool lvalue = is_active_lvalue(e);
9893 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
dc09353a 9894 throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 9895
ad370dcc
JS
9896 // XXX: if a struct/union arg is passed by value, then writing to its fields
9897 // is also meaningless until you dereference past a pointer member. It's
9898 // harder to detect and prevent that though...
75ead1f7 9899
f8a968bc
JS
9900 if (e->components.empty())
9901 {
03c75a4a 9902 if (e->addressof)
dc09353a 9903 throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 9904
3e3bd7b6 9905 // Just grab the value from the probe locals
a45664f4
JS
9906 symbol* sym = new symbol;
9907 sym->tok = e->tok;
9908 sym->name = "__tracepoint_arg_" + arg->name;
9909 provide (sym);
f8a968bc
JS
9910 }
9911 else
9912 {
5f36109e
JS
9913 // make a copy of the original as a bare target symbol for the tracepoint
9914 // value, which will be passed into the dwarf dereferencing code
9915 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
9916 e2->components.clear();
9917
9918 if (e->components.back().type == target_symbol::comp_pretty_print)
9919 {
9920 if (lvalue)
dc09353a 9921 throw SEMANTIC_ERROR(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 9922
d19a9a82 9923 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
9924 dpp.expand()->visit (this);
9925 return;
9926 }
9927
1c0be8c7 9928 bool userspace_p = false;
f8a968bc 9929 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 9930 + "_" + e->sym_name()
aca66a36 9931 + "_" + lex_cast(tick++));
75ead1f7 9932
1c0be8c7
JS
9933 exp_type type = pe_long;
9934 string code = dw.literal_stmt_for_pointer (&arg->type_die, e, lvalue, type);
6fda2dff 9935
1c0be8c7
JS
9936 functioncall* n = synthetic_embedded_deref_call(dw.sess, fname, code, type,
9937 userspace_p, lvalue, e, e2);
75ead1f7 9938
f8a968bc
JS
9939 if (lvalue)
9940 {
9941 // Provide the functioncall to our parent, so that it can be
9942 // used to substitute for the assignment node immediately above
9943 // us.
9944 assert(!target_symbol_setter_functioncalls.empty());
9945 *(target_symbol_setter_functioncalls.top()) = n;
9946 }
75ead1f7 9947
1c0be8c7
JS
9948 // Revisit the functioncall so arguments can be expanded.
9949 n->visit (this);
f8a968bc 9950 }
75ead1f7
JS
9951}
9952
9953
f8a968bc
JS
9954void
9955tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 9956{
03c75a4a 9957 if (e->addressof)
dc09353a 9958 throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
03c75a4a 9959
f8a968bc 9960 if (is_active_lvalue (e))
dc09353a 9961 throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 9962
277c21bc 9963 if (e->name == "$$name")
f8a968bc 9964 {
5f36109e
JS
9965 e->assert_no_components("tracepoint");
9966
bfdaad1e
DS
9967 // Synthesize an embedded expression.
9968 embedded_expr *expr = new embedded_expr;
9969 expr->tok = e->tok;
9970 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 9971 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 9972 provide (expr);
f8a968bc 9973 }
277c21bc 9974 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 9975 {
5f36109e
JS
9976 e->assert_no_components("tracepoint", true);
9977
1c922ad7 9978 print_format* pf = print_format::create(e->tok, "sprintf");
0a6f5a3f 9979
f8a968bc 9980 for (unsigned i = 0; i < args.size(); ++i)
b278033a 9981 {
dcaa1a65
JS
9982 if (!args[i].usable)
9983 continue;
f8a968bc
JS
9984 if (i > 0)
9985 pf->raw_components += " ";
9986 pf->raw_components += args[i].name;
3e3bd7b6 9987 target_symbol *tsym = new target_symbol;
f8a968bc 9988 tsym->tok = e->tok;
277c21bc 9989 tsym->name = "$" + args[i].name;
5f36109e 9990 tsym->components = e->components;
b278033a 9991
f8a968bc
JS
9992 // every variable should always be accessible!
9993 tsym->saved_conversion_error = 0;
8c2f50c0 9994 expression *texp = require<expression> (tsym); // NB: throws nothing ...
14a97852
JS
9995 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
9996 {
9997 if (dw.sess.verbose>2)
e26c2f83 9998 for (const semantic_error *c = tsym->saved_conversion_error;
c081af73 9999 c != 0; c = c->get_chain())
4c5d9906 10000 clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
14a97852
JS
10001 pf->raw_components += "=?";
10002 continue;
10003 }
b278033a 10004
5f36109e
JS
10005 if (!e->components.empty() &&
10006 e->components[0].type == target_symbol::comp_pretty_print)
10007 pf->raw_components += "=%s";
10008 else
10009 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
10010 pf->args.push_back(texp);
10011 }
0a6f5a3f 10012
f8a968bc
JS
10013 pf->components = print_format::string_to_components(pf->raw_components);
10014 provide (pf);
b278033a 10015 }
f8a968bc
JS
10016 else
10017 assert(0); // shouldn't get here
0a6f5a3f
JS
10018}
10019
0a6f5a3f 10020void
f8a968bc 10021tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 10022{
aff5d390 10023 try
c69a87e0 10024 {
bd1fcbad 10025 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 10026
277c21bc 10027 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 10028 visit_target_symbol_context (e);
bd1fcbad 10029
c69a87e0
FCE
10030 else
10031 visit_target_symbol_arg (e);
10032 }
10033 catch (const semantic_error &er)
10034 {
1af1e62d 10035 e->chain (er);
c69a87e0
FCE
10036 provide (e);
10037 }
0a6f5a3f
JS
10038}
10039
10040
79189b84
JS
10041tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
10042 dwflpp& dw, Dwarf_Die& func_die,
10043 const string& tracepoint_name,
10044 probe* base, probe_point* loc):
4c5d1300 10045 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 10046 sess (s), tracepoint_name (tracepoint_name)
56894e91 10047{
79189b84
JS
10048 // create synthetic probe point name; preserve condition
10049 vector<probe_point::component*> comps;
10050 comps.push_back (new probe_point::component (TOK_KERNEL));
10051 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
10052 this->sole_location()->components = comps;
10053
6fb70fb7
JS
10054 // fill out the available arguments in this tracepoint
10055 build_args(dw, func_die);
56894e91 10056
6fb70fb7
JS
10057 // determine which header defined this tracepoint
10058 string decl_file = dwarf_decl_file(&func_die);
b78a0fbb 10059 header = decl_file;
d4393459
FCE
10060
10061#if 0 /* This convention is not enforced. */
6fb70fb7
JS
10062 size_t header_pos = decl_file.rfind("trace/");
10063 if (header_pos == string::npos)
dc09353a 10064 throw SEMANTIC_ERROR ("cannot parse header location for tracepoint '"
6fb70fb7
JS
10065 + tracepoint_name + "' in '"
10066 + decl_file + "'");
10067 header = decl_file.substr(header_pos);
d4393459 10068#endif
56894e91 10069
6fb70fb7
JS
10070 // tracepoints from FOO_event_types.h should really be included from FOO.h
10071 // XXX can dwarf tell us the include hierarchy? it would be better to
10072 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 10073 // XXX: see also PR9993.
d4393459 10074 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
10075 if (header_pos != string::npos)
10076 header.erase(header_pos, 12);
56894e91 10077
f8a968bc
JS
10078 // Now expand the local variables in the probe body
10079 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 10080 v.replace (this->body);
a45664f4
JS
10081 for (unsigned i = 0; i < args.size(); i++)
10082 if (args[i].used)
10083 {
10084 vardecl* v = new vardecl;
10085 v->name = "__tracepoint_arg_" + args[i].name;
10086 v->tok = this->tok;
58701b78 10087 v->set_arity(0, this->tok);
a45664f4 10088 v->type = pe_long;
69aa668e 10089 v->synthetic = true;
a45664f4
JS
10090 this->locals.push_back (v);
10091 }
56894e91 10092
79189b84 10093 if (sess.verbose > 2)
ce0f6648 10094 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 10095}
dc38c0ae 10096
56894e91 10097
f8a968bc 10098static bool
dcaa1a65 10099resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 10100{
d19a9a82 10101 Dwarf_Die type;
dcaa1a65 10102 switch (dwarf_tag(&arg.type_die))
b20febf3 10103 {
f8a968bc
JS
10104 case DW_TAG_typedef:
10105 case DW_TAG_const_type:
10106 case DW_TAG_volatile_type:
10107 // iterate on the referent type
3d1ad340 10108 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 10109 && resolve_tracepoint_arg_type(arg));
f8a968bc 10110 case DW_TAG_base_type:
a52d2ac0 10111 case DW_TAG_enumeration_type:
f8a968bc 10112 // base types will simply be treated as script longs
dcaa1a65 10113 arg.isptr = false;
f8a968bc
JS
10114 return true;
10115 case DW_TAG_pointer_type:
dcaa1a65
JS
10116 // pointers can be treated as script longs,
10117 // and if we know their type, they can also be dereferenced
d19a9a82
JS
10118 type = arg.type_die;
10119 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
10120 {
10121 // It still might be a non-type, e.g. const void,
10122 // so we need to strip away all qualifiers.
10123 int tag = dwarf_tag(&arg.type_die);
10124 if (tag != DW_TAG_typedef &&
10125 tag != DW_TAG_const_type &&
10126 tag != DW_TAG_volatile_type)
10127 {
10128 arg.isptr = true;
10129 break;
10130 }
10131 }
10132 if (!arg.isptr)
10133 arg.type_die = type;
ad370dcc
JS
10134 arg.typecast = "(intptr_t)";
10135 return true;
10136 case DW_TAG_structure_type:
10137 case DW_TAG_union_type:
10138 // for structs/unions which are passed by value, we turn it into
10139 // a pointer that can be dereferenced.
10140 arg.isptr = true;
10141 arg.typecast = "(intptr_t)&";
dcaa1a65 10142 return true;
f8a968bc
JS
10143 default:
10144 // should we consider other types too?
10145 return false;
b20febf3 10146 }
56894e91
JS
10147}
10148
10149
10150void
822a6a3d 10151tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 10152{
6fb70fb7
JS
10153 Dwarf_Die arg;
10154 if (dwarf_child(&func_die, &arg) == 0)
10155 do
10156 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
10157 {
10158 // build a tracepoint_arg for this parameter
10159 tracepoint_arg tparg;
c60517ca 10160 tparg.name = dwarf_diename(&arg) ?: "";
56894e91 10161
6fb70fb7 10162 // read the type of this parameter
3d1ad340 10163 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 10164 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
dc09353a 10165 throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
ce0f6648 10166 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 10167
dcaa1a65 10168 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
10169 args.push_back(tparg);
10170 if (sess.verbose > 4)
a52d2ac0
JS
10171 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
10172 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
10173 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
10174 }
10175 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
10176}
10177
dc38c0ae 10178void
d0bfd2ac 10179tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 10180{
dcaa1a65
JS
10181 for (unsigned i = 0; i < args.size(); ++i)
10182 if (args[i].usable)
d0bfd2ac 10183 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
10184}
10185
79189b84
JS
10186void
10187tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 10188{
79189b84
JS
10189 if (! s.tracepoint_derived_probes)
10190 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
10191 s.tracepoint_derived_probes->enroll (this);
10192}
e38d6504 10193
56894e91 10194
197a4d62 10195void
3e3bd7b6 10196tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 10197{
3e3bd7b6
JS
10198 for (unsigned i = 0; i < args.size(); i++)
10199 if (args[i].used)
10200 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 10201}
56894e91 10202
3e3bd7b6 10203
c9ccb642 10204static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 10205{
3c1b3d06
FCE
10206 vector<string> they_live;
10207 // PR 9993
10208 // XXX: may need this to be configurable
d4393459 10209 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
10210
10211 // PR11649: conditional extra header
10212 // for kvm tracepoints in 2.6.33ish
10213 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
10214 they_live.push_back ("#include <linux/kvm_host.h>");
10215 }
10216
50b72692 10217 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 10218 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
10219 if (s.kernel_source_tree != "")
10220 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
10221 they_live.push_back ("struct xfs_mount;");
10222 they_live.push_back ("struct xfs_inode;");
10223 they_live.push_back ("struct xfs_buf;");
10224 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 10225 they_live.push_back ("struct xfs_trans;");
9e0cd21a 10226 }
d4393459 10227
50b72692 10228 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
10229 they_live.push_back ("struct rpc_task;");
10230 }
b64d65e2
FCE
10231 // RHEL6.3
10232 if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
10233 they_live.push_back ("struct rpc_clnt;");
10234 they_live.push_back ("struct rpc_wait_queue;");
10235 }
d4393459
FCE
10236
10237 they_live.push_back ("#include <asm/cputime.h>");
10238
c2cf1b87
FCE
10239 // linux 3.0
10240 they_live.push_back ("struct cpu_workqueue_struct;");
10241
50b72692 10242 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
10243 if (s.kernel_source_tree != "")
10244 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
10245
d97d428e 10246 if (header.find("ext3") != string::npos)
50b72692
HP
10247 they_live.push_back ("struct ext3_reserve_window_node;");
10248
d97d428e
FCE
10249 if (header.find("workqueue") != string::npos)
10250 {
10251 they_live.push_back ("struct pool_workqueue;");
10252 they_live.push_back ("struct work_struct;");
10253 }
10254
10255 if (header.find("asoc") != string::npos)
10256 they_live.push_back ("struct snd_soc_dapm_path;");
10257
10258 if (header.find("9p") != string::npos)
10259 {
10260 they_live.push_back ("struct p9_client;");
10261 they_live.push_back ("struct p9_fcall;");
10262 }
10263
10264 if (header.find("bcache") != string::npos)
10265 {
10266 they_live.push_back ("struct bkey;");
10267 they_live.push_back ("struct btree;");
10268 they_live.push_back ("struct cache_set;");
10269 they_live.push_back ("struct cache;");
10270 }
10271
10272 if (header.find("f2fs") != string::npos)
10273 {
10274 // cannot get fs/f2fs/f2fs.h #included
10275 they_live.push_back ("typedef u32 block_t;");
10276 they_live.push_back ("typedef u32 nid_t;");
10277 }
10278
10279 if (header.find("radeon") != string::npos)
10280 they_live.push_back ("struct radeon_bo;");
10281
10282 // argh, 3.11, i915_trace.h -> i915_drv.h -> i915_reg.h without -I
10283 // also brcms_trace_events.h -> ... -> "types.h"
10284 // XXX: need a way to add a temporary -I flag
10285
10286 if (header.find("/ath/") != string::npos)
10287 they_live.push_back ("struct ath5k_hw;");
10288
10289
3c1b3d06
FCE
10290 return they_live;
10291}
47dd066d
WC
10292
10293
10294void
79189b84 10295tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 10296{
79189b84
JS
10297 if (probes.empty())
10298 return;
47dd066d 10299
96b030fe 10300 s.op->newline() << "/* ---- tracepoint probes ---- */";
3ef9830a 10301 s.op->newline() << "#include <linux/stp_tracepoint.h>" << endl;
96b030fe 10302 s.op->newline();
79189b84 10303
47dd066d 10304
a4b9c3b3
FCE
10305 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
10306 // to be separately compiled. That's because kernel tracepoint headers sometimes
10307 // conflict. PR13155.
10308
10309 map<string,translator_output*> per_header_aux;
10310 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 10311
6fb70fb7
JS
10312 for (unsigned i = 0; i < probes.size(); ++i)
10313 {
10314 tracepoint_derived_probe *p = probes[i];
75ae2ec9 10315 string header = p->header;
5f73a260 10316
a4b9c3b3
FCE
10317 // We cache the auxiliary output files on a per-header basis. We don't
10318 // need one aux file per tracepoint, only one per tracepoint-header.
10319 translator_output *tpop = per_header_aux[header];
10320 if (tpop == 0)
10321 {
10322 tpop = s.op_create_auxiliary();
10323 per_header_aux[header] = tpop;
10324
10325 // PR9993: Add extra headers to work around undeclared types in individual
10326 // include/trace/foo.h files
10327 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
10328 for (unsigned z=0; z<extra_decls.size(); z++)
10329 tpop->newline() << extra_decls[z] << "\n";
720c435f 10330
a4b9c3b3
FCE
10331 // strip include/ substring, the same way as done in get_tracequery_module()
10332 size_t root_pos = header.rfind("include/");
10333 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443 10334
3ef9830a 10335 tpop->newline() << "#include <linux/stp_tracepoint.h>" << endl;
a4b9c3b3 10336 tpop->newline() << "#include <" << header << ">";
a4b9c3b3
FCE
10337 }
10338
720c435f
JS
10339 // collect the args that are actually in use
10340 vector<const tracepoint_arg*> used_args;
6fb70fb7 10341 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
10342 if (p->args[j].used)
10343 used_args.push_back(&p->args[j]);
10344
3ef9830a
JS
10345 // forward-declare the generated-side tracepoint callback, and define the
10346 // generated-side tracepoint callback in the main translator-output
10347 string enter_real_fn = "enter_real_tracepoint_probe_" + lex_cast(i);
720c435f 10348 if (used_args.empty())
6fb70fb7 10349 {
3ef9830a
JS
10350 tpop->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
10351 s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ")";
6fb70fb7 10352 }
3ef9830a 10353 else
a4b9c3b3 10354 {
3ef9830a
JS
10355 tpop->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10356 s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
10357 s.op->indent(2);
10358 for (unsigned j = 0; j < used_args.size(); ++j)
10359 {
10360 tpop->line() << ", int64_t";
10361 s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
10362 }
10363 tpop->line() << ");";
10364 s.op->newline() << ")";
10365 s.op->indent(-2);
6fb70fb7 10366 }
3ef9830a 10367 s.op->newline() << "{";
7c3e97f4 10368 s.op->newline(1) << "const struct stap_probe * const probe = "
faea5e16 10369 << common_probe_init (p) << ";";
71db462b 10370 common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "probe",
cda141c2 10371 "stp_probe_type_tracepoint");
6dceb5c9 10372 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
10373 << lex_cast_qstring (p->tracepoint_name)
10374 << ";";
720c435f
JS
10375 for (unsigned j = 0; j < used_args.size(); ++j)
10376 {
10377 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 10378 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
10379 << " = __tracepoint_arg_" << used_args[j]->name << ";";
10380 }
26e63673 10381 s.op->newline() << "(*probe->ph) (c);";
f887a8c9 10382 common_probe_entryfn_epilogue (s, true);
6fb70fb7 10383 s.op->newline(-1) << "}";
47dd066d 10384
a4b9c3b3 10385 // define the real tracepoint callback function
3ef9830a
JS
10386 string enter_fn = "enter_tracepoint_probe_" + lex_cast(i);
10387 if (p->args.empty())
10388 tpop->newline() << "static STP_TRACE_ENTER_NOARGS(" << enter_fn << ")";
10389 else
a4b9c3b3 10390 {
3ef9830a
JS
10391 tpop->newline() << "static STP_TRACE_ENTER(" << enter_fn;
10392 s.op->indent(2);
10393 for (unsigned j = 0; j < p->args.size(); ++j)
10394 {
10395 tpop->newline() << ", " << p->args[j].c_type
10396 << " __tracepoint_arg_" << p->args[j].name;
10397 }
10398 tpop->newline() << ")";
10399 s.op->indent(-2);
a4b9c3b3 10400 }
3ef9830a
JS
10401 tpop->newline() << "{";
10402 tpop->newline(1) << enter_real_fn << "(";
720c435f
JS
10403 tpop->indent(2);
10404 for (unsigned j = 0; j < used_args.size(); ++j)
10405 {
10406 if (j > 0)
10407 tpop->line() << ", ";
10408 tpop->newline() << "(int64_t)" << used_args[j]->typecast
10409 << "__tracepoint_arg_" << used_args[j]->name;
10410 }
10411 tpop->newline() << ");";
10412 tpop->newline(-3) << "}";
a4b9c3b3
FCE
10413
10414
96b030fe 10415 // emit normalized registration functions
720c435f 10416 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10417 tpop->newline(1) << "return STP_TRACE_REGISTER(" << p->tracepoint_name
10418 << ", " << enter_fn << ");";
a4b9c3b3 10419 tpop->newline(-1) << "}";
47dd066d 10420
86758d5f
JS
10421 // NB: we're not prepared to deal with unreg failures. However, failures
10422 // can only occur if the tracepoint doesn't exist (yet?), or if we
10423 // weren't even registered. The former should be OKed by the initial
10424 // registration call, and the latter is safe to ignore.
720c435f 10425 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
3ef9830a
JS
10426 tpop->newline(1) << "(void) STP_TRACE_UNREGISTER(" << p->tracepoint_name
10427 << ", " << enter_fn << ");";
a4b9c3b3
FCE
10428 tpop->newline(-1) << "}";
10429 tpop->newline();
5f73a260 10430
720c435f
JS
10431 // declare normalized registration functions
10432 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
10433 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 10434
a4b9c3b3 10435 tpop->assert_0_indent();
af304783
DS
10436 }
10437
96b030fe
JS
10438 // emit an array of registration functions for easy init/shutdown
10439 s.op->newline() << "static struct stap_tracepoint_probe {";
10440 s.op->newline(1) << "int (*reg)(void);";
86758d5f 10441 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
10442 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
10443 s.op->indent(1);
10444 for (unsigned i = 0; i < probes.size(); ++i)
10445 {
10446 s.op->newline () << "{";
10447 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
10448 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
10449 s.op->line() << " },";
10450 }
10451 s.op->newline(-1) << "};";
10452 s.op->newline();
47dd066d
WC
10453}
10454
10455
79189b84
JS
10456void
10457tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 10458{
79189b84
JS
10459 if (probes.size () == 0)
10460 return;
47dd066d 10461
79189b84 10462 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
10463 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
10464 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
10465 s.op->newline() << "if (rc) {";
10466 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
10467 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
10468 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
10469 s.op->newline(-1) << "}";
10470 s.op->newline(-1) << "}";
47dd066d 10471
bc9a523d
FCE
10472 // This would be technically proper (on those autoconf-detectable
10473 // kernels that include this function in tracepoint.h), however we
10474 // already make several calls to synchronze_sched() during our
10475 // shutdown processes.
47dd066d 10476
bc9a523d
FCE
10477 // s.op->newline() << "if (rc)";
10478 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
10479 // s.op->indent(-1);
79189b84 10480}
47dd066d
WC
10481
10482
79189b84
JS
10483void
10484tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 10485{
79189b84
JS
10486 if (probes.empty())
10487 return;
47dd066d 10488
96b030fe
JS
10489 s.op->newline() << "/* deregister tracepoint probes */";
10490 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
10491 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
10492 s.op->indent(-1);
47dd066d 10493
bc9a523d 10494 // Not necessary: see above.
47dd066d 10495
bc9a523d 10496 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 10497}
b20febf3 10498
47dd066d 10499
75ead1f7 10500struct tracepoint_query : public base_query
47dd066d 10501{
75ead1f7
JS
10502 tracepoint_query(dwflpp & dw, const string & tracepoint,
10503 probe * base_probe, probe_point * base_loc,
10504 vector<derived_probe *> & results):
10505 base_query(dw, "*"), tracepoint(tracepoint),
10506 base_probe(base_probe), base_loc(base_loc),
10507 results(results) {}
47dd066d 10508
75ead1f7 10509 const string& tracepoint;
47dd066d 10510
75ead1f7
JS
10511 probe * base_probe;
10512 probe_point * base_loc;
10513 vector<derived_probe *> & results;
f982c59b 10514 set<string> probed_names;
47dd066d 10515
75ead1f7
JS
10516 void handle_query_module();
10517 int handle_query_cu(Dwarf_Die * cudie);
10518 int handle_query_func(Dwarf_Die * func);
822a6a3d 10519 void query_library (const char *) {}
576eaefe 10520 void query_plt (const char *entry, size_t addr) {}
b20febf3 10521
5c378838 10522 static int tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q);
7d007451 10523 static int tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q);
75ead1f7 10524};
47dd066d
WC
10525
10526
10527void
75ead1f7 10528tracepoint_query::handle_query_module()
47dd066d 10529{
75ead1f7 10530 // look for the tracepoints in each CU
337b7c44 10531 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
10532}
10533
10534
75ead1f7
JS
10535int
10536tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 10537{
75ead1f7 10538 dw.focus_on_cu (cudie);
5f52fafe 10539 dw.mod_info->get_symtab();
47dd066d 10540
75ead1f7
JS
10541 // look at each function to see if it's a tracepoint
10542 string function = "stapprobe_" + tracepoint;
10543 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
10544}
10545
10546
75ead1f7
JS
10547int
10548tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 10549{
75ead1f7 10550 dw.focus_on_function (func);
47dd066d 10551
60d98537 10552 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 10553 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
10554
10555 // check for duplicates -- sometimes tracepoint headers may be indirectly
10556 // included in more than one of our tracequery modules.
10557 if (!probed_names.insert(tracepoint_instance).second)
10558 return DWARF_CB_OK;
10559
79189b84
JS
10560 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
10561 tracepoint_instance,
10562 base_probe, base_loc);
10563 results.push_back (dp);
75ead1f7 10564 return DWARF_CB_OK;
47dd066d
WC
10565}
10566
10567
75ead1f7 10568int
5c378838 10569tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q)
47dd066d 10570{
85007c04 10571 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10572 return q->handle_query_cu(cudie);
47dd066d
WC
10573}
10574
10575
75ead1f7 10576int
7d007451 10577tracepoint_query::tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q)
47dd066d 10578{
85007c04 10579 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 10580 return q->handle_query_func(func);
47dd066d
WC
10581}
10582
10583
0a6f5a3f 10584struct tracepoint_builder: public derived_probe_builder
47dd066d 10585{
0a6f5a3f
JS
10586private:
10587 dwflpp *dw;
10588 bool init_dw(systemtap_session& s);
c9ccb642
FCE
10589 void get_tracequery_modules(systemtap_session& s,
10590 const vector<string>& headers,
10591 vector<string>& modules);
47dd066d 10592
0a6f5a3f 10593public:
47dd066d 10594
0a6f5a3f
JS
10595 tracepoint_builder(): dw(0) {}
10596 ~tracepoint_builder() { delete dw; }
47dd066d 10597
0a6f5a3f
JS
10598 void build_no_more (systemtap_session& s)
10599 {
10600 if (dw && s.verbose > 3)
b530b5b3 10601 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
10602 delete dw;
10603 dw = NULL;
435f53a7
FCE
10604
10605 delete_session_module_cache (s);
0a6f5a3f 10606 }
47dd066d 10607
0a6f5a3f
JS
10608 void build(systemtap_session& s,
10609 probe *base, probe_point *location,
10610 literal_map_t const& parameters,
10611 vector<derived_probe*>& finished_results);
10612};
47dd066d 10613
47dd066d 10614
c9ccb642 10615
2a0e62a8 10616// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
10617// tracepoint-related header files given. Return the generated or cached
10618// modules[].
10619
10620void
10621tracepoint_builder::get_tracequery_modules(systemtap_session& s,
10622 const vector<string>& headers,
10623 vector<string>& modules)
0a6f5a3f 10624{
c95eddf7 10625 if (s.verbose > 2)
55e50c24 10626 {
ce0f6648 10627 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
10628 for (size_t i = 0; i < headers.size(); ++i)
10629 clog << " " << headers[i] << endl;
10630 }
c95eddf7 10631
2a0e62a8
JS
10632 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
10633 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
10634 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
10635 // so we prefer not to repeat this.
10636 vector<string> uncached_headers;
10637 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 10638 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
10639
10640 // They may be in the cache already.
10641 if (s.use_cache && !s.poison_cache)
10642 for (size_t i=0; i<headers.size(); i++)
10643 {
10644 // see if the cached module exists
2a0e62a8 10645 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
10646 if (!tracequery_path.empty() && file_exists(tracequery_path))
10647 {
10648 if (s.verbose > 2)
10649 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 10650
c252fca2
JS
10651 // an empty file is a cached failure
10652 if (get_file_size(tracequery_path) > 0)
10653 modules.push_back (tracequery_path);
c9ccb642
FCE
10654 }
10655 else
10656 uncached_headers.push_back(headers[i]);
10657 }
10658 else
10659 uncached_headers = headers;
f982c59b 10660
c9ccb642
FCE
10661 // If we have nothing left to search for, quit
10662 if (uncached_headers.empty()) return;
55e50c24 10663
c9ccb642 10664 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 10665
c9ccb642
FCE
10666 // We could query several subsets of headers[] to make this go
10667 // faster, but let's KISS and do one at a time.
10668 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 10669 {
c9ccb642
FCE
10670 const string& header = uncached_headers[i];
10671
10672 // create a tracequery source file
10673 ostringstream osrc;
10674
10675 // PR9993: Add extra headers to work around undeclared types in individual
10676 // include/trace/foo.h files
10677 vector<string> short_decls = tracepoint_extra_decls(s, header);
10678
10679 // add each requested tracepoint header
75ae2ec9 10680 size_t root_pos = header.rfind("include/");
832f100d 10681 short_decls.push_back(string("#include <") +
75ae2ec9 10682 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 10683 string(">"));
f982c59b 10684
c9ccb642
FCE
10685 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
10686 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
10687
10688 // the kernel has changed this naming a few times, previously TPPROTO,
10689 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
10690 osrc << "#ifndef PARAMS" << endl;
10691 osrc << "#define PARAMS(args...) args" << endl;
10692 osrc << "#endif" << endl;
10693
c9ccb642
FCE
10694 // override DECLARE_TRACE to synthesize probe functions for us
10695 osrc << "#undef DECLARE_TRACE" << endl;
10696 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
10697 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 10698
c9ccb642
FCE
10699 // 2.6.35 added the NOARGS variant, but it's the same for us
10700 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
10701 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
10702 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
10703
10704 // 2.6.38 added the CONDITION variant, which can also just redirect
10705 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
10706 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
10707 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10708
c9ccb642
FCE
10709 // older tracepoints used DEFINE_TRACE, so redirect that too
10710 osrc << "#undef DEFINE_TRACE" << endl;
10711 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
10712 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
10713
c9ccb642
FCE
10714 // add the specified decls/#includes
10715 for (unsigned z=0; z<short_decls.size(); z++)
10716 osrc << "#undef TRACE_INCLUDE_FILE\n"
10717 << "#undef TRACE_INCLUDE_PATH\n"
10718 << short_decls[z] << "\n";
10719
10720 // finish up the module source
10721 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 10722
c9ccb642
FCE
10723 // save the source file away
10724 headers_tracequery_src[header] = osrc.str();
55e50c24 10725 }
f982c59b 10726
c9ccb642 10727 // now build them all together
2a0e62a8 10728 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 10729
c9ccb642 10730 // now plop them into the cache
b278033a 10731 if (s.use_cache)
c9ccb642
FCE
10732 for (size_t i=0; i<uncached_headers.size(); i++)
10733 {
10734 const string& header = uncached_headers[i];
2a0e62a8
JS
10735 const string& tracequery_obj = tracequery_objs[header];
10736 const string& tracequery_path = headers_cache_obj[header];
10737 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 10738 {
2a0e62a8 10739 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
10740 modules.push_back (tracequery_path);
10741 }
c252fca2
JS
10742 else
10743 // cache an empty file for failures
10744 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 10745 }
f982c59b
JS
10746}
10747
10748
d4393459 10749
f982c59b
JS
10750bool
10751tracepoint_builder::init_dw(systemtap_session& s)
10752{
10753 if (dw != NULL)
10754 return true;
10755
10756 vector<string> tracequery_modules;
55e50c24 10757 vector<string> system_headers;
f982c59b
JS
10758
10759 glob_t trace_glob;
d4393459
FCE
10760
10761 // find kernel_source_tree
10762 if (s.kernel_source_tree == "")
f982c59b 10763 {
d4393459 10764 unsigned found;
ccf2c922 10765 Dwfl *dwfl = setup_dwfl_kernel ("kernel", &found, s);
d4393459
FCE
10766 if (found)
10767 {
10768 Dwarf_Die *cudie = 0;
10769 Dwarf_Addr bias;
10770 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
10771 {
e19ebcf7 10772 assert_no_interrupts();
d4393459
FCE
10773 Dwarf_Attribute attr;
10774 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
36d65b45 10775 if (name)
d4393459 10776 {
36d65b45
JS
10777 // check that the path actually exists locally before we try to use it
10778 if (file_exists(name))
10779 {
10780 if (s.verbose > 2)
10781 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10782 s.kernel_source_tree = name;
10783 }
10784 else
10785 {
10786 if (s.verbose > 2)
10787 clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
10788 }
61f1a63b 10789
d4393459
FCE
10790 break; // skip others; modern Kbuild uses same comp_dir for them all
10791 }
10792 }
10793 }
44392d73 10794 dwfl_end (dwfl);
d4393459
FCE
10795 }
10796
10797 // prefixes
10798 vector<string> glob_prefixes;
10799 glob_prefixes.push_back (s.kernel_build_tree);
10800 if (s.kernel_source_tree != "")
10801 glob_prefixes.push_back (s.kernel_source_tree);
10802
10803 // suffixes
10804 vector<string> glob_suffixes;
10805 glob_suffixes.push_back("include/trace/events/*.h");
10806 glob_suffixes.push_back("include/trace/*.h");
d97d428e 10807 glob_suffixes.push_back("include/ras/*_event.h");
d4393459 10808 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
d97d428e
FCE
10809 glob_suffixes.push_back("arch/x86/kernel/*trace.h");
10810 glob_suffixes.push_back("arch/*/include/asm/trace*.h");
10811 glob_suffixes.push_back("arch/*/include/asm/trace/*.h");
f89ff3e2 10812 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d97d428e
FCE
10813 glob_suffixes.push_back("fs/*/*trace*.h");
10814 glob_suffixes.push_back("net/*/*trace*.h");
10815 glob_suffixes.push_back("sound/pci/hda/*_trace.h");
10816 glob_suffixes.push_back("drivers/gpu/drm/*_trace.h");
10817 glob_suffixes.push_back("drivers/gpu/drm/*/*_trace.h");
10818 glob_suffixes.push_back("drivers/net/wireless/*/*/*trace*.h");
10819 glob_suffixes.push_back("drivers/usb/host/*trace*.h");
10820
10821 // see also tracepoint_extra_decls above
d4393459
FCE
10822
10823 // compute cartesian product
10824 vector<string> globs;
10825 for (unsigned i=0; i<glob_prefixes.size(); i++)
10826 for (unsigned j=0; j<glob_suffixes.size(); j++)
10827 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
10828
8aa43b8d 10829 set<string> duped_headers;
d4393459
FCE
10830 for (unsigned z = 0; z < globs.size(); z++)
10831 {
10832 string glob_str = globs[z];
10833 if (s.verbose > 3)
b530b5b3 10834 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 10835
067cc66f
CM
10836 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
10837 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
10838 throw runtime_error("Error globbing tracepoint");
10839
f982c59b
JS
10840 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
10841 {
10842 string header(trace_glob.gl_pathv[i]);
10843
10844 // filter out a few known "internal-only" headers
60d98537
JS
10845 if (endswith(header, "/define_trace.h") ||
10846 endswith(header, "/ftrace.h") ||
10847 endswith(header, "/trace_events.h") ||
10848 endswith(header, "_event_types.h"))
f982c59b
JS
10849 continue;
10850
b1966849
FCE
10851 // With headers now plopped under arch/FOO/include/asm/*,
10852 // the following logic miss some tracepoints.
10853#if 0
8aa43b8d
JS
10854 // skip identical headers from the build and source trees.
10855 size_t root_pos = header.rfind("include/");
10856 if (root_pos != string::npos &&
10857 !duped_headers.insert(header.substr(root_pos + 8)).second)
10858 continue;
b1966849 10859#endif
8aa43b8d 10860
55e50c24 10861 system_headers.push_back(header);
f982c59b
JS
10862 }
10863 globfree(&trace_glob);
10864 }
10865
c9ccb642
FCE
10866 // Build tracequery modules
10867 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 10868
f982c59b
JS
10869 // TODO: consider other sources of tracepoint headers too, like from
10870 // a command-line parameter or some environment or .systemtaprc
47dd066d 10871
59c11f91 10872 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
10873 return true;
10874}
47dd066d 10875
0a6f5a3f
JS
10876void
10877tracepoint_builder::build(systemtap_session& s,
10878 probe *base, probe_point *location,
10879 literal_map_t const& parameters,
10880 vector<derived_probe*>& finished_results)
10881{
10882 if (!init_dw(s))
10883 return;
47dd066d 10884
75ead1f7
JS
10885 string tracepoint;
10886 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 10887
75ead1f7 10888 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
d906ab9d 10889 unsigned results_pre = finished_results.size();
06de3a04 10890 dw->iterate_over_modules<base_query>(&query_module, &q);
d906ab9d
JL
10891 unsigned results_post = finished_results.size();
10892
10893 // Did we fail to find a match? Let's suggest something!
10894 if (results_pre == results_post)
10895 {
10896 size_t pos;
10897 string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
10898 while ((pos = sugs.find("stapprobe_")) != string::npos)
10899 sugs.erase(pos, string("stapprobe_").size());
10900 if (!sugs.empty())
ece93f53
JL
10901 throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
10902 "no match (similar tracepoints: %s)",
d906ab9d
JL
10903 sugs.find(',') == string::npos,
10904 sugs.c_str()));
10905 }
47dd066d 10906}
47dd066d 10907
e6fe60e7 10908
b55bc428 10909// ------------------------------------------------------------------------
bd2b1e68 10910// Standard tapset registry.
b55bc428
FCE
10911// ------------------------------------------------------------------------
10912
7a053d3b 10913void
f8220a7b 10914register_standard_tapsets(systemtap_session & s)
b55bc428 10915{
47e0478e 10916 register_tapset_been(s);
93646f4d 10917 register_tapset_itrace(s);
dd0e4fa7 10918 register_tapset_mark(s);
7a212aa8 10919 register_tapset_procfs(s);
912e8c59 10920 register_tapset_timers(s);
8d9609f5 10921 register_tapset_netfilter(s);
b84779a5 10922 register_tapset_utrace(s);
b98a8d73 10923
7a24d422 10924 // dwarf-based kprobe/uprobe parts
c4ce66a1 10925 dwarf_derived_probe::register_patterns(s);
30a279be 10926
888af770
FCE
10927 // XXX: user-space starter set
10928 s.pattern_root->bind_num(TOK_PROCESS)
10929 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 10930 ->bind_privilege(pr_all)
888af770
FCE
10931 ->bind(new uprobe_builder ());
10932 s.pattern_root->bind_num(TOK_PROCESS)
10933 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 10934 ->bind_privilege(pr_all)
888af770
FCE
10935 ->bind(new uprobe_builder ());
10936
0a6f5a3f
JS
10937 // kernel tracepoint probes
10938 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
10939 ->bind(new tracepoint_builder());
10940
e6fe60e7
AM
10941 // Kprobe based probe
10942 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
10943 ->bind(new kprobe_builder());
3c57fe1f
JS
10944 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
10945 ->bind(new kprobe_builder());
e6fe60e7
AM
10946 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10947 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
3c57fe1f
JS
10948 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10949 ->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
e6fe60e7
AM
10950 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10951 ->bind(new kprobe_builder());
b6371390
JS
10952 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10953 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10954 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10955 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
10956 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
10957 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
10958 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
10959 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
10960 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
10961
10962 //Hwbkpt based probe
b47f3a55
FCE
10963 // NB: we formerly registered the probe point types only if the kernel configuration
10964 // allowed it. However, we get better error messages if we allow probes to resolve.
10965 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10966 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10967 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10968 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10969 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10970 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10971 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
10972 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10973 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10974 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
10975 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
10976 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
10977 // length supported with address only, not symbol names
83ea76b1
WC
10978
10979 //perf event based probe
4763f713 10980 register_tapset_perf(s);
a29858ef 10981 register_tapset_java(s);
b55bc428 10982}
dc38c0ae
DS
10983
10984
b20febf3
FCE
10985vector<derived_probe_group*>
10986all_session_groups(systemtap_session& s)
dc38c0ae 10987{
b20febf3 10988 vector<derived_probe_group*> g;
912e8c59
JS
10989
10990#define DOONE(x) \
10991 if (s. x##_derived_probes) \
10992 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
10993
10994 // Note that order *is* important here. We want to make sure we
10995 // register (actually run) begin probes before any other probe type
10996 // is run. Similarly, when unregistering probes, we want to
10997 // unregister (actually run) end probes after every other probe type
10998 // has be unregistered. To do the latter,
10999 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
11000 DOONE(be);
11001 DOONE(dwarf);
888af770 11002 DOONE(uprobe);
b20febf3
FCE
11003 DOONE(timer);
11004 DOONE(profile);
11005 DOONE(mark);
0a6f5a3f 11006 DOONE(tracepoint);
e6fe60e7 11007 DOONE(kprobe);
dd225250 11008 DOONE(hwbkpt);
83ea76b1 11009 DOONE(perf);
b20febf3 11010 DOONE(hrtimer);
ce82316f 11011 DOONE(procfs);
8d9609f5 11012 DOONE(netfilter);
935447c8
DS
11013
11014 // Another "order is important" item. We want to make sure we
11015 // "register" the dummy task_finder probe group after all probe
11016 // groups that use the task_finder.
11017 DOONE(utrace);
a96d1db0 11018 DOONE(itrace);
f31a77f5 11019 DOONE(dynprobe);
e7d4410d 11020 DOONE(java);
935447c8 11021 DOONE(task_finder);
b20febf3
FCE
11022#undef DOONE
11023 return g;
46b84a80 11024}
73267b89
JS
11025
11026/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.818853 seconds and 5 git commands to generate.