]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
Really old kprobes didn't have a symbol_name field, autoconf it.
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
4d0d9e8a 2// Copyright (C) 2005-2011 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"
56e12059 16#include "translate.h"
dc38c0ae 17#include "session.h"
72dbc915 18#include "util.h"
0a6f5a3f 19#include "buildrun.h"
86bf665e 20#include "dwarf_wrappers.h"
2e67a43b 21#include "auto_free.h"
b278033a 22#include "hash.h"
440f755a 23#include "dwflpp.h"
5f8ca04f 24#include "setupdwfl.h"
6b51ee12 25#include <gelf.h>
22d737e8 26
4d0d9e8a 27#include "sdt_types.h"
bd2b1e68 28
3b579393
FCE
29#include <cstdlib>
30#include <algorithm>
bd2b1e68 31#include <deque>
56e12059 32#include <iostream>
d1bcbe71 33#include <fstream>
bd2b1e68 34#include <map>
ec4373ff 35#include <set>
56e12059 36#include <sstream>
bd2b1e68 37#include <stdexcept>
b55bc428 38#include <vector>
e36387d7 39#include <cstdarg>
29e64872 40#include <cassert>
1969b5bc 41#include <iomanip>
f781f849 42#include <cerrno>
bd2b1e68
GH
43
44extern "C" {
df8fadee 45#include <fcntl.h>
bd2b1e68 46#include <elfutils/libdwfl.h>
7a053d3b 47#include <elfutils/libdw.h>
77de5e9e
GH
48#include <dwarf.h>
49#include <elf.h>
50#include <obstack.h>
b20febf3 51#include <glob.h>
30a279be 52#include <fnmatch.h>
5f0a03a6 53#include <stdio.h>
349dc70e 54#include <sys/types.h>
37001baa 55#include <sys/stat.h>
aaf7ffe8 56#include <math.h>
aff5d390 57#include <regex.h>
37001baa 58#include <unistd.h>
6d5d594e 59#include <wordexp.h>
4b1ad75e
RM
60
61#define __STDC_FORMAT_MACROS
62#include <inttypes.h>
bd2b1e68 63}
77de5e9e 64
56e12059
FCE
65
66using namespace std;
2171f774 67using namespace __gnu_cxx;
56e12059 68
47dd066d 69
b20febf3
FCE
70
71// ------------------------------------------------------------------------
faea5e16
JS
72
73string
74common_probe_init (derived_probe* p)
75{
26e63673
JS
76 assert(p->session_index != (unsigned)-1);
77 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
78}
79
80
b20febf3 81void
a58d79d0 82common_probe_entryfn_prologue (translator_output* o, string statestr,
6eefe942
MW
83 string probe, string probe_type,
84 bool overload_processing)
b20febf3 85{
653e6a9a
JS
86 o->newline() << "#ifdef STP_ALIBI";
87 o->newline() << "atomic_inc(&(" << probe << "->alibi));";
88 o->newline() << "#else";
89
72d18b98 90 o->newline() << "struct context* __restrict__ c;";
e0a17418
JS
91 o->newline() << "#if !INTERRUPTIBLE";
92 o->newline() << "unsigned long flags;";
93 o->newline() << "#endif";
b20febf3 94
a58d79d0
DS
95 if (overload_processing)
96 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
97 else
98 o->newline() << "#ifdef STP_TIMING";
99 o->newline() << "cycles_t cycles_atstart = get_cycles ();";
b20febf3 100 o->newline() << "#endif";
b20febf3 101
994aac0e 102 o->newline() << "#ifdef STP_TIMING";
26e63673 103 o->newline() << "Stat stat = " << probe << "->timing;";
994aac0e
JS
104 o->newline() << "#endif";
105
e0a17418
JS
106 o->newline() << "#if INTERRUPTIBLE";
107 o->newline() << "preempt_disable ();";
108 o->newline() << "#else";
109 o->newline() << "local_irq_save (flags);";
110 o->newline() << "#endif";
b20febf3 111
c931ec8a 112 // Check for enough free enough stack space
d05a1d00 113 o->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
a63401b1 114 o->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
d05a1d00
FCE
115 // XXX: may need porting to platforms where task_struct is not at bottom of kernel stack
116 // NB: see also CONFIG_DEBUG_STACKOVERFLOW
b3c3ca7c
FCE
117 o->newline() << "atomic_inc (& skipped_count);";
118 o->newline() << "#ifdef STP_TIMING";
119 o->newline() << "atomic_inc (& skipped_count_lowstack);";
120 o->newline() << "#endif";
c931ec8a
FCE
121 o->newline() << "goto probe_epilogue;";
122 o->newline(-1) << "}";
123
b20febf3
FCE
124 o->newline() << "if (atomic_read (&session_state) != " << statestr << ")";
125 o->newline(1) << "goto probe_epilogue;";
126 o->indent(-1);
9a604fac 127
4a0ae64c 128 o->newline() << "c = contexts[smp_processor_id()];";
b3c3ca7c 129 o->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
9c736061
FCE
130 o->newline(1) << "#if !INTERRUPTIBLE";
131 o->newline() << "atomic_inc (& skipped_count);";
132 o->newline() << "#endif";
b3c3ca7c
FCE
133 o->newline() << "#ifdef STP_TIMING";
134 o->newline() << "atomic_inc (& skipped_count_reentrant);";
c12d974f
FCE
135 o->newline() << "#ifdef DEBUG_REENTRANCY";
136 o->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 137 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
138 // NB: There is a conceivable race condition here with reading
139 // c->probe_point, knowing that this other probe is sort of running.
140 // However, in reality, it's interrupted. Plus even if it were able
141 // to somehow start again, and stop before we read c->probe_point,
142 // at least we have that ?: "?" bit in there to avoid a NULL deref.
143 o->newline() << "#endif";
b3c3ca7c 144 o->newline() << "#endif";
9a604fac 145 o->newline() << "atomic_dec (& c->busy);";
b20febf3 146 o->newline() << "goto probe_epilogue;";
9a604fac
FCE
147 o->newline(-1) << "}";
148 o->newline();
1e00cfb1 149 o->newline() << "c->last_stmt = 0;";
9a604fac 150 o->newline() << "c->last_error = 0;";
a7ed0d3e 151 o->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
22f8b401 152 o->newline() << "c->regs = 0;";
d4670309 153 o->newline() << "#if defined __ia64__";
b916df9c 154 o->newline() << "c->unwaddr = 0;";
d4670309 155 o->newline() << "#endif";
26e63673 156 o->newline() << "c->probe_point = " << probe << "->pp;";
d48df0cf 157 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
26e63673 158 o->newline() << "c->probe_name = " << probe << "->pn;";
2d767770 159 o->newline() << "#endif";
6eefe942 160 o->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9
MW
161 // reset Individual Probe State union
162 o->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
97cd9334 163 o->newline() << "c->regflags = 0;";
309d67d8 164 o->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
9addf322 165 o->newline() << "c->regparm = 0;";
309d67d8 166 o->newline() << "#endif";
e0a17418
JS
167
168 o->newline() << "#if INTERRUPTIBLE";
169 o->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
170 o->newline() << "#else";
171 o->newline() << "c->actionremaining = MAXACTION;";
172 o->newline() << "#endif";
9915575b
FCE
173 // NB: The following would actually be incorrect.
174 // That's because cycles_sum/cycles_base values are supposed to survive
175 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
176 // cycles), the values will be reset.
177 /*
f0e6dc63
FCE
178 o->newline() << "#ifdef STP_OVERLOAD";
179 o->newline() << "c->cycles_sum = 0;";
180 o->newline() << "c->cycles_base = 0;";
41c262f3 181 o->newline() << "#endif";
9915575b 182 */
b20febf3 183}
9a604fac 184
a44a0785 185
b20febf3 186void
a58d79d0 187common_probe_entryfn_epilogue (translator_output* o,
912e8c59 188 bool overload_processing)
b20febf3 189{
a58d79d0
DS
190 if (overload_processing)
191 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
192 else
193 o->newline() << "#ifdef STP_TIMING";
dbb68664 194 o->newline() << "{";
a58d79d0
DS
195 o->newline(1) << "cycles_t cycles_atend = get_cycles ();";
196 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
197 // fewer, if the hardware counter rolls over really quickly. We
198 // handle 32-bit wraparound here.
199 o->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
200 o->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
201 o->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
202 o->indent(-1);
dbb68664 203
a58d79d0 204 o->newline() << "#ifdef STP_TIMING";
994aac0e 205 o->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
a58d79d0
DS
206 o->newline() << "#endif";
207
208 if (overload_processing)
209 {
210 o->newline() << "#ifdef STP_OVERLOAD";
211 o->newline() << "{";
212 // If the cycle count has wrapped (cycles_atend > cycles_base),
213 // let's go ahead and pretend the interval has been reached.
214 // This should reset cycles_base and cycles_sum.
215 o->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
216 o->newline(1) << "? (cycles_atend - c->cycles_base)";
217 o->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
218 o->newline(-1) << "c->cycles_sum += cycles_elapsed;";
219
220 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
221 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
222 // has overloaded the system and we need to quit.
223 o->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
224 o->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
225 o->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
226 o->newline() << "atomic_set (&session_state, STAP_SESSION_ERROR);";
551e9f14 227 o->newline() << "atomic_inc (&error_count);";
a58d79d0 228 o->newline(-1) << "}";
e57b735a 229
a58d79d0
DS
230 o->newline() << "c->cycles_base = cycles_atend;";
231 o->newline() << "c->cycles_sum = 0;";
232 o->newline(-1) << "}";
233 o->newline(-1) << "}";
234 o->newline() << "#endif";
235 }
e57b735a 236
440f755a
JS
237 o->newline(-1) << "}";
238 o->newline() << "#endif";
e57b735a 239
440f755a 240 o->newline() << "c->probe_point = 0;"; // vacated
dc575eac 241 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
d48df0cf 242 o->newline() << "c->probe_name = 0;";
dc575eac 243 o->newline() << "#endif";
6eefe942 244 o->newline() << "c->probe_type = 0;";
440f755a
JS
245 o->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
246 o->newline(1) << "if (c->last_stmt != NULL)";
247 o->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
248 o->newline(-1) << "else";
249 o->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
250 o->indent(-1);
251 o->newline() << "atomic_inc (& error_count);";
252 o->newline() << "if (atomic_read (& error_count) > MAXERRORS) {";
253 o->newline(1) << "atomic_set (& session_state, STAP_SESSION_ERROR);";
254 o->newline() << "_stp_exit ();";
255 o->newline(-1) << "}";
256 o->newline(-1) << "}";
257 o->newline() << "atomic_dec (&c->busy);";
e57b735a 258
440f755a
JS
259 o->newline(-1) << "probe_epilogue:"; // context is free
260 o->indent(1);
e57b735a 261
440f755a
JS
262 // Check for excessive skip counts.
263 o->newline() << "if (unlikely (atomic_read (& skipped_count) > MAXSKIPPED)) {";
079915a5 264 o->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(& session_state, STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
f65166cc 265 o->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
440f755a 266 o->newline(-1) << "}";
e57b735a 267
440f755a
JS
268 o->newline() << "#if INTERRUPTIBLE";
269 o->newline() << "preempt_enable_no_resched ();";
270 o->newline() << "#else";
271 o->newline() << "local_irq_restore (flags);";
272 o->newline() << "#endif";
653e6a9a
JS
273
274 o->newline() << "#endif // STP_ALIBI";
440f755a 275}
e57b735a 276
e57b735a 277
440f755a 278// ------------------------------------------------------------------------
e57b735a 279
440f755a
JS
280// ------------------------------------------------------------------------
281// Dwarf derived probes. "We apologize for the inconvience."
282// ------------------------------------------------------------------------
e57b735a 283
4627ed58
JS
284static const string TOK_KERNEL("kernel");
285static const string TOK_MODULE("module");
286static const string TOK_FUNCTION("function");
287static const string TOK_INLINE("inline");
288static const string TOK_CALL("call");
289static const string TOK_RETURN("return");
290static const string TOK_MAXACTIVE("maxactive");
291static const string TOK_STATEMENT("statement");
292static const string TOK_ABSOLUTE("absolute");
293static const string TOK_PROCESS("process");
a794dbeb 294static const string TOK_PROVIDER("provider");
4627ed58
JS
295static const string TOK_MARK("mark");
296static const string TOK_TRACE("trace");
297static const string TOK_LABEL("label");
63b4fd14 298static const string TOK_LIBRARY("library");
e57b735a 299
1adf8ef1 300static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 301static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 302
440f755a
JS
303// Can we handle this query with just symbol-table info?
304enum dbinfo_reqt
305{
306 dbr_unknown,
307 dbr_none, // kernel.statement(NUM).absolute
308 dbr_need_symtab, // can get by with symbol table if there's no dwarf
309 dbr_need_dwarf
310};
e57b735a 311
20e4a32c 312
440f755a
JS
313struct base_query; // forward decls
314struct dwarf_query;
315struct dwflpp;
316struct symbol_table;
20e4a32c 317
a781f401 318
440f755a
JS
319struct
320symbol_table
321{
322 module_info *mod_info; // associated module
323 map<string, func_info*> map_by_name;
1c6b77e5
JS
324 multimap<Dwarf_Addr, func_info*> map_by_addr;
325 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
326 typedef pair<iterator_t, iterator_t> range_t;
327#ifdef __powerpc__
328 GElf_Word opd_section;
329#endif
2867a2a1
JS
330 void add_symbol(const char *name, bool weak, bool descriptor,
331 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 332 enum info_status read_symbols(FILE *f, const string& path);
83ca3872
MW
333 enum info_status read_from_elf_file(const string& path,
334 const systemtap_session &sess);
335 enum info_status read_from_text_file(const string& path,
336 const systemtap_session &sess);
440f755a
JS
337 enum info_status get_from_elf();
338 void prepare_section_rejection(Dwfl_Module *mod);
339 bool reject_section(GElf_Word section);
440f755a
JS
340 void purge_syscall_stubs();
341 func_info *lookup_symbol(const string& name);
342 Dwarf_Addr lookup_symbol_address(const string& name);
343 func_info *get_func_containing_address(Dwarf_Addr addr);
7a053d3b 344
440f755a
JS
345 symbol_table(module_info *mi) : mod_info(mi) {}
346 ~symbol_table();
347};
77de5e9e 348
440f755a
JS
349static bool null_die(Dwarf_Die *die)
350{
822a6a3d 351 static Dwarf_Die null;
440f755a
JS
352 return (!die || !memcmp(die, &null, sizeof(null)));
353}
c4ce66a1
JS
354
355
7a053d3b 356enum
bd2b1e68 357function_spec_type
7a053d3b 358 {
bd2b1e68
GH
359 function_alone,
360 function_and_file,
7a053d3b 361 function_file_and_line
bd2b1e68
GH
362 };
363
ec4373ff 364
bd2b1e68 365struct dwarf_builder;
f10534c6 366struct dwarf_var_expanding_visitor;
77de5e9e 367
2930abc7 368
b20febf3
FCE
369// XXX: This class is a candidate for subclassing to separate
370// the relocation vs non-relocation variants. Likewise for
371// kprobe vs kretprobe variants.
372
373struct dwarf_derived_probe: public derived_probe
b55bc428 374{
b20febf3
FCE
375 dwarf_derived_probe (const string& function,
376 const string& filename,
377 int line,
378 const string& module,
379 const string& section,
380 Dwarf_Addr dwfl_addr,
2930abc7 381 Dwarf_Addr addr,
b20febf3
FCE
382 dwarf_query & q,
383 Dwarf_Die* scope_die);
20e4a32c 384
b20febf3
FCE
385 string module;
386 string section;
387 Dwarf_Addr addr;
63b4fd14 388 string path;
27dc09b1 389 bool has_process;
2930abc7 390 bool has_return;
c9bad430 391 bool has_maxactive;
63b4fd14 392 bool has_library;
c9bad430 393 long maxactive_val;
4ad95bbc 394 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
395 string user_path;
396 string user_lib;
b95e2b79 397 bool access_vars;
2930abc7 398
af234c40
JS
399 unsigned saved_longs, saved_strings;
400 dwarf_derived_probe* entry_handler;
401
b8da0ad1 402 void printsig (std::ostream &o) const;
6b66b9f7 403 virtual void join_group (systemtap_session& s);
9020300d 404 void emit_probe_local_init(translator_output * o);
d0bfd2ac 405 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 406
27dc09b1
DB
407 void emit_unprivileged_assertion (translator_output*);
408 void print_dupe_stamp(ostream& o);
409
bd2b1e68 410 // Pattern registration helpers.
7a053d3b 411 static void register_statement_variants(match_node * root,
27dc09b1
DB
412 dwarf_builder * dw,
413 bool bind_unprivileged_p = false);
fd6602a0 414 static void register_function_variants(match_node * root,
27dc09b1
DB
415 dwarf_builder * dw,
416 bool bind_unprivileged_p = false);
7a053d3b 417 static void register_function_and_statement_variants(match_node * root,
27dc09b1
DB
418 dwarf_builder * dw,
419 bool bind_unprivileged_p = false);
c4ce66a1 420 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
421
422protected:
423 dwarf_derived_probe(probe *base,
424 probe_point *location,
425 Dwarf_Addr addr,
426 bool has_return):
427 derived_probe(base, location), addr(addr), has_return(has_return),
af234c40
JS
428 has_maxactive(0), maxactive_val(0), access_vars(false),
429 saved_longs(0), saved_strings(0), entry_handler(0)
6b66b9f7
JS
430 {}
431
432private:
d0bfd2ac 433 list<string> args;
8c67c337 434 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
435};
436
dc38c0ae 437
6b66b9f7 438struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 439{
6d0f3f0c 440 int pid; // 0 => unrestricted
0973d815 441
6d0f3f0c
FCE
442 uprobe_derived_probe (const string& function,
443 const string& filename,
444 int line,
445 const string& module,
6d0f3f0c
FCE
446 const string& section,
447 Dwarf_Addr dwfl_addr,
448 Dwarf_Addr addr,
449 dwarf_query & q,
6b66b9f7
JS
450 Dwarf_Die* scope_die):
451 dwarf_derived_probe(function, filename, line, module, section,
452 dwfl_addr, addr, q, scope_die), pid(0)
453 {}
6d0f3f0c 454
0973d815
FCE
455 // alternate constructor for process(PID).statement(ADDR).absolute
456 uprobe_derived_probe (probe *base,
457 probe_point *location,
458 int pid,
459 Dwarf_Addr addr,
6b66b9f7
JS
460 bool has_return):
461 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
462 {}
9ace370f 463
6d0f3f0c 464 void join_group (systemtap_session& s);
2865d17a
DB
465
466 void emit_unprivileged_assertion (translator_output*);
8f6d8c2b 467 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
468 void getargs(std::list<std::string> &arg_set) const;
469 void saveargs(int nargs);
470private:
471 list<string> args;
6d0f3f0c
FCE
472};
473
dc38c0ae
DS
474struct dwarf_derived_probe_group: public derived_probe_group
475{
476private:
62f52bb0 477 bool has_semaphores;
b20febf3
FCE
478 multimap<string,dwarf_derived_probe*> probes_by_module;
479 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
480
481public:
62f52bb0 482 dwarf_derived_probe_group(): has_semaphores(false) {}
b20febf3
FCE
483 void enroll (dwarf_derived_probe* probe);
484 void emit_module_decls (systemtap_session& s);
485 void emit_module_init (systemtap_session& s);
486 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
487};
488
489
20c6c071 490// Helper struct to thread through the dwfl callbacks.
2c384610 491struct base_query
20c6c071 492{
c4ce66a1
JS
493 base_query(dwflpp & dw, literal_map_t const & params);
494 base_query(dwflpp & dw, const string & module_val);
2c384610 495 virtual ~base_query() {}
bd2b1e68 496
5227f1ea 497 systemtap_session & sess;
2c384610 498 dwflpp & dw;
5227f1ea 499
bd2b1e68 500 // Parameter extractors.
86bf665e 501 static bool has_null_param(literal_map_t const & params,
888af770 502 string const & k);
86bf665e 503 static bool get_string_param(literal_map_t const & params,
bd2b1e68 504 string const & k, string & v);
86bf665e 505 static bool get_number_param(literal_map_t const & params,
bd2b1e68 506 string const & k, long & v);
86bf665e 507 static bool get_number_param(literal_map_t const & params,
c239d28c 508 string const & k, Dwarf_Addr & v);
f301a9ff
SC
509 static void query_library_callback (void *object, const char *data);
510 virtual void query_library (const char *data) = 0;
84c84ac4 511
b55bc428 512
2c384610
DS
513 // Extracted parameters.
514 bool has_kernel;
91af0778
FCE
515 bool has_module;
516 bool has_process;
63b4fd14 517 bool has_library;
2c384610 518 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 519 string path; // executable path if module is a .so
2c384610
DS
520
521 virtual void handle_query_module() = 0;
522};
523
524
c4ce66a1
JS
525base_query::base_query(dwflpp & dw, literal_map_t const & params):
526 sess(dw.sess), dw(dw)
2c384610 527{
91af0778 528 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
529 if (has_kernel)
530 module_val = "kernel";
91af0778
FCE
531
532 has_module = get_string_param (params, TOK_MODULE, module_val);
533 if (has_module)
534 has_process = false;
4baf0e53 535 else
d0a7f5a9 536 {
63b4fd14 537 string library_name;
d0a7f5a9 538 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 539 has_library = get_string_param (params, TOK_LIBRARY, library_name);
84c84ac4 540 if (has_process)
d0a7f5a9 541 module_val = find_executable (module_val);
84c84ac4
SC
542 if (has_library)
543 {
544 if (! contains_glob_chars (library_name))
545 {
546 path = module_val;
547 module_val = find_executable (library_name, "LD_LIBRARY_PATH");
548 }
549 else
550 path = library_name;
551 }
d0a7f5a9 552 }
91af0778
FCE
553
554 assert (has_kernel || has_process || has_module);
2c384610
DS
555}
556
c4ce66a1
JS
557base_query::base_query(dwflpp & dw, const string & module_val)
558 : sess(dw.sess), dw(dw), module_val(module_val)
559{
560 // NB: This uses '/' to distinguish between kernel modules and userspace,
561 // which means that userspace modules won't get any PATH searching.
562 if (module_val.find('/') == string::npos)
563 {
564 has_kernel = (module_val == TOK_KERNEL);
565 has_module = !has_kernel;
566 has_process = false;
567 }
568 else
569 {
570 has_kernel = has_module = false;
571 has_process = true;
572 }
573}
574
2c384610 575bool
86bf665e 576base_query::has_null_param(literal_map_t const & params,
2c384610
DS
577 string const & k)
578{
888af770 579 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
580}
581
582
583bool
86bf665e 584base_query::get_string_param(literal_map_t const & params,
2c384610
DS
585 string const & k, string & v)
586{
587 return derived_probe_builder::get_param (params, k, v);
588}
589
590
591bool
86bf665e 592base_query::get_number_param(literal_map_t const & params,
2c384610
DS
593 string const & k, long & v)
594{
595 int64_t value;
596 bool present = derived_probe_builder::get_param (params, k, value);
597 v = (long) value;
598 return present;
599}
600
601
602bool
86bf665e 603base_query::get_number_param(literal_map_t const & params,
2c384610
DS
604 string const & k, Dwarf_Addr & v)
605{
606 int64_t value;
607 bool present = derived_probe_builder::get_param (params, k, value);
608 v = (Dwarf_Addr) value;
609 return present;
610}
611
2c384610
DS
612struct dwarf_query : public base_query
613{
e1278bd4 614 dwarf_query(probe * base_probe,
2c384610
DS
615 probe_point * base_loc,
616 dwflpp & dw,
86bf665e 617 literal_map_t const & params,
b642c901
SC
618 vector<derived_probe *> & results,
619 const string user_path,
620 const string user_lib);
2c384610 621
c4ce66a1 622 vector<derived_probe *> & results;
8f14e444 623 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
624 probe * base_probe;
625 probe_point * base_loc;
b642c901
SC
626 string user_path;
627 string user_lib;
c4ce66a1 628
2c384610 629 virtual void handle_query_module();
5f0a03a6
JK
630 void query_module_dwarf();
631 void query_module_symtab();
5d5bd369 632 void query_library (const char *data);
2c384610 633
2930abc7
FCE
634 void add_probe_point(string const & funcname,
635 char const * filename,
636 int line,
637 Dwarf_Die *scope_die,
638 Dwarf_Addr addr);
36f9dd1d 639
857bdfd1
JS
640 // Track addresses we've already seen in a given module
641 set<Dwarf_Addr> alias_dupes;
642
7fdd3e2c
JS
643 // Track inlines we've already seen as well
644 // NB: this can't be compared just by entrypc, as inlines can overlap
645 set<inline_instance_info> inline_dupes;
646
2930abc7 647 // Extracted parameters.
7a053d3b 648 string function_val;
20c6c071
GH
649
650 bool has_function_str;
651 bool has_statement_str;
652 bool has_function_num;
653 bool has_statement_num;
7a053d3b
RM
654 string statement_str_val;
655 string function_str_val;
c239d28c
GH
656 Dwarf_Addr statement_num_val;
657 Dwarf_Addr function_num_val;
20c6c071 658
b8da0ad1
FCE
659 bool has_call;
660 bool has_inline;
20c6c071
GH
661 bool has_return;
662
c9bad430
DS
663 bool has_maxactive;
664 long maxactive_val;
665
20c6c071
GH
666 bool has_label;
667 string label_val;
668
669 bool has_relative;
670 long relative_val;
671
37ebca01
FCE
672 bool has_absolute;
673
467bea43
SC
674 bool has_mark;
675
5f0a03a6
JK
676 enum dbinfo_reqt dbinfo_reqt;
677 enum dbinfo_reqt assess_dbinfo_reqt();
678
7d6d0afc 679 void parse_function_spec(const string & spec);
20c6c071 680 function_spec_type spec_type;
7d6d0afc 681 vector<string> scopes;
20c6c071
GH
682 string function;
683 string file;
0c8b7d37 684 line_t line_type;
879eb9e9 685 int line[2];
5f0a03a6 686 bool query_done; // Found exact match
20c6c071 687
bd25380d 688 set<string> filtered_srcfiles;
7e1279ea
FCE
689
690 // Map official entrypc -> func_info object
86bf665e
TM
691 inline_instance_map_t filtered_inlines;
692 func_info_map_t filtered_functions;
7e1279ea
FCE
693 bool choose_next_line;
694 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
695
696 void query_module_functions ();
b55bc428
FCE
697};
698
98afd80e 699
435f53a7
FCE
700static void delete_session_module_cache (systemtap_session& s); // forward decl
701
702
98afd80e 703struct dwarf_builder: public derived_probe_builder
b55bc428 704{
665e1256 705 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 706 map <string,dwflpp*> user_dw;
b642c901
SC
707 string user_path;
708 string user_lib;
ae2552da 709 dwarf_builder() {}
aa30ccd3 710
ae2552da 711 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 712 {
ea14cf67
FCE
713 if (kern_dw[module] == 0)
714 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 715 return kern_dw[module];
707bf35e
JS
716 }
717
718 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
719 {
ea14cf67
FCE
720 if (user_dw[module] == 0)
721 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
722 return user_dw[module];
723 }
7a24d422
FCE
724
725 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 726 void dwarf_build_no_more (bool)
aa30ccd3 727 {
435f53a7
FCE
728 delete_map(kern_dw);
729 delete_map(user_dw);
7a24d422
FCE
730 }
731
732 void build_no_more (systemtap_session &s)
733 {
734 dwarf_build_no_more (s.verbose > 3);
435f53a7 735 delete_session_module_cache (s);
aa30ccd3
FCE
736 }
737
e38d6504
RM
738 ~dwarf_builder()
739 {
7a24d422 740 dwarf_build_no_more (false);
c8959a29 741 }
aa30ccd3 742
5227f1ea 743 virtual void build(systemtap_session & sess,
7a053d3b 744 probe * base,
20c6c071 745 probe_point * location,
86bf665e 746 literal_map_t const & parameters,
20c6c071 747 vector<derived_probe *> & finished_results);
b55bc428
FCE
748};
749
5111fc3e 750
e1278bd4 751dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
752 probe_point * base_loc,
753 dwflpp & dw,
86bf665e 754 literal_map_t const & params,
b642c901
SC
755 vector<derived_probe *> & results,
756 const string user_path,
757 const string user_lib)
c4ce66a1 758 : base_query(dw, params), results(results),
b642c901
SC
759 base_probe(base_probe), base_loc(base_loc),
760 user_path(user_path), user_lib(user_lib)
bd2b1e68
GH
761{
762 // Reduce the query to more reasonable semantic values (booleans,
763 // extracted strings, numbers, etc).
bd2b1e68
GH
764 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
765 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
766
767 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
768 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
769
0f336e95
SC
770 has_label = get_string_param(params, TOK_LABEL, label_val);
771
b8da0ad1
FCE
772 has_call = has_null_param(params, TOK_CALL);
773 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 774 has_return = has_null_param(params, TOK_RETURN);
c9bad430 775 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 776 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 777 has_mark = false;
37ebca01 778
bd2b1e68 779 if (has_function_str)
7d6d0afc 780 parse_function_spec(function_str_val);
bd2b1e68 781 else if (has_statement_str)
7d6d0afc 782 parse_function_spec(statement_str_val);
0daad364 783
5f0a03a6
JK
784 dbinfo_reqt = assess_dbinfo_reqt();
785 query_done = false;
0daad364
JS
786}
787
788
440f755a
JS
789func_info_map_t *
790get_filtered_functions(dwarf_query *q)
791{
792 return &q->filtered_functions;
793}
794
795
796inline_instance_map_t *
797get_filtered_inlines(dwarf_query *q)
798{
799 return &q->filtered_inlines;
800}
801
802
2c384610 803void
5f0a03a6 804dwarf_query::query_module_dwarf()
2c384610
DS
805{
806 if (has_function_num || has_statement_num)
807 {
808 // If we have module("foo").function(0xbeef) or
809 // module("foo").statement(0xbeef), the address is relative
810 // to the start of the module, so we seek the function
811 // number plus the module's bias.
6b517475
JS
812 Dwarf_Addr addr = has_function_num ?
813 function_num_val : statement_num_val;
08d1d520
MW
814
815 // These are raw addresses, we need to know what the elf_bias
816 // is to feed it to libdwfl based functions.
817 Dwarf_Addr elf_bias;
818 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
819 assert(elf);
820 addr += elf_bias;
6b517475 821 query_addr(addr, this);
2c384610
DS
822 }
823 else
824 {
825 // Otherwise if we have a function("foo") or statement("foo")
826 // specifier, we have to scan over all the CUs looking for
827 // the function(s) in question
828 assert(has_function_str || has_statement_str);
4df79aaf
JS
829
830 // For simple cases, no wildcard and no source:line, we can do a very
831 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
832 if (spec_type == function_alone &&
833 !dw.name_has_wildcard(function) &&
834 !startswith(function, "_Z"))
4df79aaf
JS
835 query_module_functions();
836 else
837 dw.iterate_over_cus(&query_cu, this);
2c384610
DS
838 }
839}
840
5f0a03a6
JK
841static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
842 dwarf_query * q);
843
844void
845dwarf_query::query_module_symtab()
846{
847 // Get the symbol table if it's necessary, sufficient, and not already got.
848 if (dbinfo_reqt == dbr_need_dwarf)
849 return;
850
851 module_info *mi = dw.mod_info;
852 if (dbinfo_reqt == dbr_need_symtab)
853 {
854 if (mi->symtab_status == info_unknown)
855 mi->get_symtab(this);
856 if (mi->symtab_status == info_absent)
857 return;
858 }
859
860 func_info *fi = NULL;
861 symbol_table *sym_table = mi->sym_table;
862
863 if (has_function_str)
864 {
865 // Per dwarf_query::assess_dbinfo_reqt()...
866 assert(spec_type == function_alone);
867 if (dw.name_has_wildcard(function_str_val))
868 {
869 // Until we augment the blacklist sufficently...
870 if (function_str_val.find_first_not_of("*?") == string::npos)
871 {
872 // e.g., kernel.function("*")
b530b5b3
LB
873 cerr << _F("Error: Pattern '%s' matches every single "
874 "instruction address in the symbol table,\n"
875 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
876 return;
877 }
2e67a43b 878 symbol_table::iterator_t iter;
1c6b77e5
JS
879 for (iter = sym_table->map_by_addr.begin();
880 iter != sym_table->map_by_addr.end();
2e67a43b 881 ++iter)
5f0a03a6 882 {
1c6b77e5 883 fi = iter->second;
5f0a03a6
JK
884 if (!null_die(&fi->die))
885 continue; // already handled in query_module_dwarf()
886 if (dw.function_name_matches_pattern(fi->name, function_str_val))
887 query_func_info(fi->addr, *fi, this);
888 }
889 }
890 else
891 {
892 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 893 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
894 query_func_info(fi->addr, *fi, this);
895 }
896 }
897 else
898 {
899 assert(has_function_num || has_statement_num);
900 // Find the "function" in which the indicated address resides.
901 Dwarf_Addr addr =
902 (has_function_num ? function_num_val : statement_num_val);
903 fi = sym_table->get_func_containing_address(addr);
904 if (!fi)
905 {
83ca3872 906 if (! sess.suppress_warnings)
b530b5b3
LB
907 cerr << _F("Warning: address %#" PRIx64 " out of range for module %s",
908 addr, dw.module_name.c_str());
5f0a03a6
JK
909 return;
910 }
911 if (!null_die(&fi->die))
912 {
913 // addr looks like it's in the compilation unit containing
914 // the indicated function, but query_module_dwarf() didn't
915 // match addr to any compilation unit, so addr must be
916 // above that cu's address range.
83ca3872 917 if (! sess.suppress_warnings)
b530b5b3
LB
918 cerr << _F("Warning: address %#" PRIx64 " maps to no known compilation unit in module %s",
919 addr, dw.module_name.c_str());
5f0a03a6
JK
920 return;
921 }
922 query_func_info(fi->addr, *fi, this);
923 }
924}
925
926void
927dwarf_query::handle_query_module()
928{
1c6b77e5
JS
929 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
930 dw.get_module_dwarf(false, report);
931
932 // prebuild the symbol table to resolve aliases
933 dw.mod_info->get_symtab(this);
934
857bdfd1
JS
935 // reset the dupe-checking for each new module
936 alias_dupes.clear();
7fdd3e2c 937 inline_dupes.clear();
857bdfd1 938
5f0a03a6
JK
939 if (dw.mod_info->dwarf_status == info_present)
940 query_module_dwarf();
1c6b77e5 941
5f0a03a6
JK
942 // Consult the symbol table if we haven't found all we're looking for.
943 // asm functions can show up in the symbol table but not in dwarf.
944 if (sess.consult_symtab && !query_done)
945 query_module_symtab();
946}
947
2c384610 948
7d6d0afc
JS
949void
950dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 951{
1d12a9b2
JS
952 line_type = ABSOLUTE;
953 line[0] = line[1] = 0;
954
7d6d0afc 955 size_t src_pos, line_pos, dash_pos, scope_pos, next_scope_pos;
bd2b1e68 956
7d6d0afc
JS
957 // look for named scopes
958 scope_pos = 0;
959 next_scope_pos = spec.find("::");
960 while (next_scope_pos != string::npos)
bd2b1e68 961 {
7d6d0afc
JS
962 scopes.push_back(spec.substr(scope_pos, next_scope_pos - scope_pos));
963 scope_pos = next_scope_pos + 2;
964 next_scope_pos = spec.find("::", scope_pos);
bd2b1e68
GH
965 }
966
7d6d0afc
JS
967 // look for a source separator
968 src_pos = spec.find('@', scope_pos);
969 if (src_pos == string::npos)
bd2b1e68 970 {
7d6d0afc
JS
971 function = spec.substr(scope_pos);
972 spec_type = function_alone;
bd2b1e68 973 }
7d6d0afc 974 else
879eb9e9 975 {
7d6d0afc 976 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 977
7d6d0afc
JS
978 // look for a line-number separator
979 line_pos = spec.find_first_of(":+", src_pos);
980 if (line_pos == string::npos)
981 {
982 file = spec.substr(src_pos + 1);
983 spec_type = function_and_file;
984 }
985 else
986 {
987 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
988
989 // classify the line spec
990 spec_type = function_file_and_line;
991 if (spec[line_pos] == '+')
992 line_type = RELATIVE;
993 else if (spec[line_pos + 1] == '*' &&
994 spec.length() == line_pos + 2)
995 line_type = WILDCARD;
996 else
997 line_type = ABSOLUTE;
998
999 if (line_type != WILDCARD)
1000 try
1001 {
1002 // try to parse either N or N-M
1003 dash_pos = spec.find('-', line_pos + 1);
1004 if (dash_pos == string::npos)
1005 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1006 else
1007 {
1008 line_type = RANGE;
1009 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1010 dash_pos - line_pos - 1));
1011 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1012 }
1013 }
1014 catch (runtime_error & exn)
1015 {
1016 goto bad;
1017 }
1018 }
bd2b1e68
GH
1019 }
1020
7d6d0afc
JS
1021 if (function.empty() ||
1022 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1023 goto bad;
1024
7d6d0afc 1025 if (sess.verbose > 2)
bd2b1e68 1026 {
b530b5b3
LB
1027 //clog << "parsed '" << spec << "'";
1028 clog << _F("parse '%s'", spec.c_str());
41c262f3 1029
7d6d0afc
JS
1030 if (!scopes.empty())
1031 clog << ", scope '" << scopes[0] << "'";
1032 for (unsigned i = 1; i < scopes.size(); ++i)
1033 clog << "::'" << scopes[i] << "'";
41c262f3 1034
7d6d0afc
JS
1035 clog << ", func '" << function << "'";
1036
1037 if (spec_type != function_alone)
1038 clog << ", file '" << file << "'";
1039
1040 if (spec_type == function_file_and_line)
1041 {
1042 clog << ", line ";
1043 switch (line_type)
1044 {
1045 case ABSOLUTE:
1046 clog << line[0];
1047 break;
1048
1049 case RELATIVE:
1050 clog << "+" << line[0];
1051 break;
1052
1053 case RANGE:
1054 clog << line[0] << " - " << line[1];
1055 break;
1056
1057 case WILDCARD:
1058 clog << "*";
1059 break;
1060 }
1061 }
1062
1063 clog << endl;
bd2b1e68
GH
1064 }
1065
7d6d0afc
JS
1066 return;
1067
1068bad:
b530b5b3 1069 throw semantic_error(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1070 base_probe->tok);
bd2b1e68
GH
1071}
1072
1073
36f9dd1d 1074void
1ffb8bd1 1075dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1076 const char* filename,
36f9dd1d 1077 int line,
b20febf3 1078 Dwarf_Die* scope_die,
36f9dd1d
FCE
1079 Dwarf_Addr addr)
1080{
b20febf3 1081 string reloc_section; // base section for relocation purposes
27646582 1082 Dwarf_Addr reloc_addr; // relocated
b20febf3 1083 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1084 string funcname = dw_funcname;
36f9dd1d 1085
37ebca01
FCE
1086 assert (! has_absolute); // already handled in dwarf_builder::build()
1087
789448a3 1088 reloc_addr = dw.relocate_address(addr, reloc_section);
2930abc7 1089
1ffb8bd1 1090 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1091 const char* linkage_name;
1092 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1093 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1094 funcname = linkage_name;
1095
7f9f3386
FCE
1096 if (sess.verbose > 1)
1097 {
b530b5b3 1098 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1099 if (string(module) == TOK_KERNEL)
b530b5b3 1100 clog << _(" kernel");
91af0778 1101 else if (has_module)
b530b5b3 1102 clog << _(" module=") << module;
91af0778 1103 else if (has_process)
b530b5b3 1104 clog << _(" process=") << module;
b20febf3 1105 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1106 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1107 }
4baf0e53 1108
27646582 1109 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1110 addr, has_return);
b20febf3
FCE
1111 if (sess.verbose > 1)
1112 clog << endl;
7f9f3386 1113
84048984
FCE
1114 if (module == TOK_KERNEL)
1115 {
1116 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1117 reloc_addr = addr - sess.sym_stext;
37ebca01 1118 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1119 }
1120
b20febf3
FCE
1121 if (! bad)
1122 {
1a0dbc5a 1123 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1124
1125 if (has_process)
1126 {
1127 results.push_back (new uprobe_derived_probe(funcname, filename, line,
6b66b9f7 1128 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1129 *this, scope_die));
1130 }
1131 else
1132 {
1133 assert (has_kernel || has_module);
1134 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1135 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1136 *this, scope_die));
1137 }
b20febf3 1138 }
2930abc7
FCE
1139}
1140
5f0a03a6
JK
1141enum dbinfo_reqt
1142dwarf_query::assess_dbinfo_reqt()
1143{
1144 if (has_absolute)
1145 {
1146 // kernel.statement(NUM).absolute
1147 return dbr_none;
1148 }
1149 if (has_inline)
1150 {
1151 // kernel.function("f").inline or module("m").function("f").inline
1152 return dbr_need_dwarf;
1153 }
1154 if (has_function_str && spec_type == function_alone)
1155 {
1156 // kernel.function("f") or module("m").function("f")
1157 return dbr_need_symtab;
1158 }
1159 if (has_statement_num)
1160 {
1161 // kernel.statement(NUM) or module("m").statement(NUM)
1162 // Technically, all we need is the module offset (or _stext, for
1163 // the kernel). But for that we need either the ELF file or (for
1164 // _stext) the symbol table. In either case, the symbol table
1165 // is available, and that allows us to map the NUM (address)
1166 // to a function, which is goodness.
1167 return dbr_need_symtab;
1168 }
1169 if (has_function_num)
1170 {
1171 // kernel.function(NUM) or module("m").function(NUM)
1172 // Need the symbol table so we can back up from NUM to the
1173 // start of the function.
1174 return dbr_need_symtab;
1175 }
1176 // Symbol table tells us nothing about source files or line numbers.
1177 return dbr_need_dwarf;
1178}
2930abc7
FCE
1179
1180
b8da0ad1
FCE
1181// The critical determining factor when interpreting a pattern
1182// string is, perhaps surprisingly: "presence of a lineno". The
1183// presence of a lineno changes the search strategy completely.
1184//
1185// Compare the two cases:
1186//
1187// 1. {statement,function}(foo@file.c:lineno)
1188// - find the files matching file.c
1189// - in each file, find the functions matching foo
1190// - query the file for line records matching lineno
1191// - iterate over the line records,
1192// - and iterate over the functions,
1193// - if(haspc(function.DIE, line.addr))
1194// - if looking for statements: probe(lineno.addr)
1195// - if looking for functions: probe(function.{entrypc,return,etc.})
1196//
1197// 2. {statement,function}(foo@file.c)
1198// - find the files matching file.c
1199// - in each file, find the functions matching foo
1200// - probe(function.{entrypc,return,etc.})
1201//
1202// Thus the first decision we make is based on the presence of a
1203// lineno, and we enter entirely different sets of callbacks
1204// depending on that decision.
1205//
1206// Note that the first case is a generalization fo the second, in that
1207// we could theoretically search through line records for matching
1208// file names (a "table scan" in rdbms lingo). Luckily, file names
1209// are already cached elsewhere, so we can do an "index scan" as an
1210// optimization.
7e1279ea 1211
bd2b1e68 1212static void
4cd232e4 1213query_statement (string const & func,
20e4a32c 1214 char const * file,
4cd232e4 1215 int line,
bcc12710 1216 Dwarf_Die *scope_die,
20e4a32c 1217 Dwarf_Addr stmt_addr,
4cd232e4 1218 dwarf_query * q)
bd2b1e68 1219{
39bcd429
FCE
1220 try
1221 {
cee35f73 1222 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1223 line, scope_die, stmt_addr);
39bcd429
FCE
1224 }
1225 catch (const semantic_error& e)
1226 {
1227 q->sess.print_error (e);
1228 }
bd2b1e68
GH
1229}
1230
6b517475
JS
1231static void
1232query_addr(Dwarf_Addr addr, dwarf_query *q)
1233{
1234 dwflpp &dw = q->dw;
1235
08d1d520
MW
1236 if (q->sess.verbose > 2)
1237 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1238
1239 // First pick which CU contains this address
1240 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1241 if (!cudie) // address could be wildly out of range
1242 return;
1243 dw.focus_on_cu(cudie);
1244
1245 // Now compensate for the dw bias
1246 addr -= dw.module_bias;
1247
1248 // Per PR5787, we look up the scope die even for
1249 // statement_num's, for blacklist sensitivity and $var
1250 // resolution purposes.
1251
1252 // Find the scopes containing this address
1253 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1254 if (scopes.empty())
1255 return;
1256
1257 // Look for the innermost containing function
1258 Dwarf_Die *fnscope = NULL;
1259 for (size_t i = 0; i < scopes.size(); ++i)
1260 {
1261 int tag = dwarf_tag(&scopes[i]);
1262 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1263 (tag == DW_TAG_inlined_subroutine &&
1264 !q->has_call && !q->has_return))
1265 {
1266 fnscope = &scopes[i];
1267 break;
1268 }
1269 }
1270 if (!fnscope)
1271 return;
1272 dw.focus_on_function(fnscope);
1273
1274 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1275
1276 const char *file = dwarf_decl_file(fnscope);
1277 int line;
1278 dwarf_decl_line(fnscope, &line);
1279
1280 // Function probes should reset the addr to the function entry
1281 // and possibly perform prologue searching
1282 if (q->has_function_num)
1283 {
1284 dw.die_entrypc(fnscope, &addr);
1285 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1286 (q->sess.prologue_searching || q->has_process)) // PR 6871
1287 {
1288 func_info func;
1289 func.die = *fnscope;
1290 func.name = dw.function_name;
1291 func.decl_file = file;
1292 func.decl_line = line;
1293 func.entrypc = addr;
1294
1295 func_info_map_t funcs(1, func);
1296 dw.resolve_prologue_endings (funcs);
1297 if (funcs[0].prologue_end)
1298 addr = funcs[0].prologue_end;
1299 }
1300 }
1301 else
1302 {
1303 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1304 if (address_line)
1305 {
1306 file = address_line.linesrc();
1307 line = address_line.lineno();
1308 }
1309
1310 // Verify that a raw address matches the beginning of a
1311 // statement. This is a somewhat lame check that the address
1312 // is at the start of an assembly instruction. Mark probes are in the
1313 // middle of a macro and thus not strictly at a statement beginning.
1314 // Guru mode may override this check.
1315 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1316 {
1317 stringstream msg;
b530b5b3
LB
1318 msg << _F("address 0x%#" PRIx64 " does not match the beginning of a statement",
1319 addr);
6b517475 1320 if (address_line)
b530b5b3 1321 msg << _F(" (try 0x%#" PRIx64 ")", address_line.addr());
6b517475 1322 else
b530b5b3
LB
1323 msg << _F(" (no line info found for '%s', in module '%s')",
1324 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475
JS
1325 if (! q->sess.guru_mode)
1326 throw semantic_error(msg.str());
1327 else if (! q->sess.suppress_warnings)
1328 q->sess.print_warning(msg.str());
1329 }
1330 }
1331
1332 // Build a probe at this point
1333 query_statement(dw.function_name, file, line, scope, addr, q);
1334}
1335
8096dd7d
JS
1336static void
1337query_label (string const & func,
1338 char const * label,
1339 char const * file,
1340 int line,
1341 Dwarf_Die *scope_die,
1342 Dwarf_Addr stmt_addr,
1343 dwarf_query * q)
1344{
6b517475
JS
1345 assert (q->has_statement_str || q->has_function_str);
1346
8096dd7d
JS
1347 size_t i = q->results.size();
1348
1349 // weed out functions whose decl_file isn't one of
1350 // the source files that we actually care about
6b517475 1351 if (q->spec_type != function_alone &&
8096dd7d
JS
1352 q->filtered_srcfiles.count(file) == 0)
1353 return;
1354
1355 query_statement(func, file, line, scope_die, stmt_addr, q);
1356
c72aa911
JS
1357 // after the fact, insert the label back into the derivation chain
1358 probe_point::component* ppc =
1359 new probe_point::component(TOK_LABEL, new literal_string (label));
1360 for (; i < q->results.size(); ++i)
1361 {
1362 derived_probe* p = q->results[i];
1363 probe_point* pp = new probe_point(*p->locations[0]);
1364 pp->components.push_back (ppc);
1365 p->base = p->base->create_alias(p->locations[0], pp);
1366 }
8096dd7d
JS
1367}
1368
7e1279ea 1369static void
3e961ba6 1370query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1371 dwarf_query * q)
1372{
b6581717 1373 try
7e1279ea 1374 {
8f14e444
FCE
1375 assert (! q->has_return); // checked by caller already
1376 if (q->sess.verbose>2)
b530b5b3
LB
1377 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1378 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1379 query_statement (ii.name, ii.decl_file, ii.decl_line,
1380 &ii.die, ii.entrypc, q);
7e1279ea 1381 }
b6581717 1382 catch (semantic_error &e)
7e1279ea 1383 {
b6581717 1384 q->sess.print_error (e);
7e1279ea
FCE
1385 }
1386}
1387
1388static void
1389query_func_info (Dwarf_Addr entrypc,
bcc12710 1390 func_info & fi,
7e1279ea
FCE
1391 dwarf_query * q)
1392{
b6581717 1393 try
7e1279ea 1394 {
b6581717
GH
1395 if (q->has_return)
1396 {
1397 // NB. dwarf_derived_probe::emit_registrations will emit a
1398 // kretprobe based on the entrypc in this case.
20e4a32c 1399 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1400 &fi.die, entrypc, q);
1401 }
1402 else
1403 {
35dc8b04 1404 if (fi.prologue_end != 0)
44f75386 1405 {
44f75386
FCE
1406 query_statement (fi.name, fi.decl_file, fi.decl_line,
1407 &fi.die, fi.prologue_end, q);
1408 }
1409 else
1410 {
1411 query_statement (fi.name, fi.decl_file, fi.decl_line,
1412 &fi.die, entrypc, q);
1413 }
b6581717 1414 }
7e1279ea 1415 }
b6581717 1416 catch (semantic_error &e)
7e1279ea 1417 {
b6581717 1418 q->sess.print_error (e);
7e1279ea
FCE
1419 }
1420}
1421
1422
bd4b874d
SC
1423static void
1424query_srcfile_label (const dwarf_line_t& line, void * arg)
1425{
1426 dwarf_query * q = static_cast<dwarf_query *>(arg);
1427
1428 Dwarf_Addr addr = line.addr();
1429
1430 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1431 i != q->filtered_functions.end(); ++i)
1432 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1433 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1434 q, query_label);
1435
1436 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1437 i != q->filtered_inlines.end(); ++i)
1438 if (q->dw.die_has_pc (i->die, addr))
1439 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1440 q, query_label);
bd4b874d
SC
1441}
1442
7e1279ea 1443static void
86bf665e 1444query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1445{
1446 dwarf_query * q = static_cast<dwarf_query *>(arg);
1447
86bf665e 1448 Dwarf_Addr addr = line.addr();
4cd232e4 1449
86bf665e 1450 int lineno = line.lineno();
847bf07f 1451
86bf665e 1452 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1453 i != q->filtered_functions.end(); ++i)
1454 {
3e961ba6 1455 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1456 {
b0ee93c4 1457 if (q->sess.verbose>3)
b530b5b3 1458 clog << _("function DIE lands on srcfile\n");
4cd232e4 1459 if (q->has_statement_str)
f5958c8f
JS
1460 {
1461 Dwarf_Die scope;
1462 q->dw.inner_die_containing_pc(i->die, addr, scope);
1463 query_statement (i->name, i->decl_file,
1464 lineno, // NB: not q->line !
1465 &scope, addr, q);
1466 }
4cd232e4 1467 else
3e961ba6 1468 query_func_info (i->entrypc, *i, q);
7e1279ea 1469 }
20e4a32c
RM
1470 }
1471
86bf665e 1472 for (inline_instance_map_t::iterator i
897820ca
GH
1473 = q->filtered_inlines.begin();
1474 i != q->filtered_inlines.end(); ++i)
1475 {
3e961ba6 1476 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1477 {
b0ee93c4 1478 if (q->sess.verbose>3)
b530b5b3 1479 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1480 if (q->has_statement_str)
f5958c8f
JS
1481 {
1482 Dwarf_Die scope;
1483 q->dw.inner_die_containing_pc(i->die, addr, scope);
1484 query_statement (i->name, i->decl_file,
1485 q->line[0], &scope, addr, q);
1486 }
897820ca 1487 else
3e961ba6 1488 query_inline_instance_info (*i, q);
897820ca 1489 }
20e4a32c 1490 }
7e1279ea
FCE
1491}
1492
1493
7fdd3e2c
JS
1494bool
1495inline_instance_info::operator<(const inline_instance_info& other) const
1496{
1497 if (entrypc != other.entrypc)
1498 return entrypc < other.entrypc;
1499
1500 if (decl_line != other.decl_line)
1501 return decl_line < other.decl_line;
1502
1503 int cmp = name.compare(other.name);
1504 if (!cmp)
1505 cmp = strcmp(decl_file, other.decl_file);
1506 return cmp < 0;
1507}
1508
1509
4fa7b22b 1510static int
7e1279ea 1511query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1512{
1513 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1514 assert (q->has_statement_str || q->has_function_str);
1515 assert (!q->has_call && !q->has_return);
bd2b1e68 1516
39bcd429 1517 try
7a053d3b 1518 {
b0ee93c4 1519 if (q->sess.verbose>2)
b530b5b3 1520 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1521
6b517475
JS
1522 Dwarf_Addr entrypc;
1523 if (q->dw.die_entrypc (die, &entrypc))
1524 {
1525 inline_instance_info inl;
1526 inl.die = *die;
1527 inl.name = q->dw.function_name;
1528 inl.entrypc = entrypc;
1529 q->dw.function_file (&inl.decl_file);
1530 q->dw.function_line (&inl.decl_line);
1531
1532 // make sure that this inline hasn't already
1533 // been matched from a different CU
1534 if (q->inline_dupes.insert(inl).second)
1535 q->filtered_inlines.push_back(inl);
1536 }
7e1279ea
FCE
1537 return DWARF_CB_OK;
1538 }
1539 catch (const semantic_error& e)
1540 {
1541 q->sess.print_error (e);
1542 return DWARF_CB_ABORT;
1543 }
1544}
bb788f9f 1545
7e1279ea 1546static int
2da9cedb 1547query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1548{
2da9cedb 1549 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1550 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1551
bd25380d
JS
1552 // weed out functions whose decl_file isn't one of
1553 // the source files that we actually care about
6b517475 1554 if (q->spec_type != function_alone &&
bd25380d 1555 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1556 return DWARF_CB_OK;
bd25380d 1557
7e1279ea
FCE
1558 try
1559 {
7e1279ea
FCE
1560 q->dw.focus_on_function (func);
1561
7d6d0afc
JS
1562 if (!q->dw.function_scope_matches(q->scopes))
1563 return DWARF_CB_OK;
1564
857bdfd1
JS
1565 // make sure that this function address hasn't
1566 // already been matched under an aliased name
1567 Dwarf_Addr addr;
1568 if (!q->dw.func_is_inline() &&
1569 dwarf_entrypc(func, &addr) == 0 &&
1570 !q->alias_dupes.insert(addr).second)
1571 return DWARF_CB_OK;
1572
6b517475 1573 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return))
7e1279ea 1574 {
b0ee93c4 1575 if (q->sess.verbose>3)
b530b5b3 1576 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
2da9cedb 1577 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1578 }
8f14e444
FCE
1579 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1580 {
1581 q->inlined_non_returnable.insert (q->dw.function_name);
1582 }
396afcee 1583 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1584 {
6b517475 1585 if (q->sess.verbose>2)
b530b5b3 1586 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1587
1588 func_info func;
1589 q->dw.function_die (&func.die);
1590 func.name = q->dw.function_name;
1591 q->dw.function_file (&func.decl_file);
1592 q->dw.function_line (&func.decl_line);
1593
1594 Dwarf_Addr entrypc;
1595 if (q->dw.function_entrypc (&entrypc))
1596 {
1597 func.entrypc = entrypc;
1598 q->filtered_functions.push_back (func);
1599 }
1600 /* else this function is fully inlined, just ignore it */
7e1279ea 1601 }
39bcd429 1602 return DWARF_CB_OK;
bd2b1e68 1603 }
39bcd429 1604 catch (const semantic_error& e)
bd2b1e68 1605 {
39bcd429
FCE
1606 q->sess.print_error (e);
1607 return DWARF_CB_ABORT;
bd2b1e68 1608 }
bd2b1e68
GH
1609}
1610
1611static int
1612query_cu (Dwarf_Die * cudie, void * arg)
1613{
20c6c071 1614 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1615 assert (q->has_statement_str || q->has_function_str);
1616
85007c04 1617 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1618
39bcd429 1619 try
bd2b1e68 1620 {
7e1279ea 1621 q->dw.focus_on_cu (cudie);
b5d77020 1622
b0ee93c4 1623 if (false && q->sess.verbose>2)
b530b5b3
LB
1624 clog << _F("focused on CU '%s', in module '%s'\n",
1625 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1626
6b517475
JS
1627 q->filtered_srcfiles.clear();
1628 q->filtered_functions.clear();
1629 q->filtered_inlines.clear();
1630
1631 // In this path, we find "abstract functions", record
1632 // information about them, and then (depending on lineno
1633 // matching) possibly emit one or more of the function's
1634 // associated addresses. Unfortunately the control of this
1635 // cannot easily be turned inside out.
1636
1637 if (q->spec_type != function_alone)
39bcd429 1638 {
6b517475
JS
1639 // If we have a pattern string with a filename, we need
1640 // to elaborate the srcfile mask in question first.
1641 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1642
1643 // If we have a file pattern and *no* srcfile matches, there's
1644 // no need to look further into this CU, so skip.
1645 if (q->filtered_srcfiles.empty())
1646 return DWARF_CB_OK;
1647 }
e4c58386 1648
6b517475
JS
1649 // Pick up [entrypc, name, DIE] tuples for all the functions
1650 // matching the query, and fill in the prologue endings of them
1651 // all in a single pass.
5898b6e1 1652 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1653 if (rc != DWARF_CB_OK)
1654 q->query_done = true;
1655
1656 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1657 && !q->has_statement_str) // PR 2608
1658 if (! q->filtered_functions.empty())
1659 q->dw.resolve_prologue_endings (q->filtered_functions);
1660
1661 if (q->spec_type == function_file_and_line)
1662 {
58b070fb 1663 // .statement(...:NN) often gets mixed up with .function(...:NN)
af2e341f 1664 if (q->has_function_str && ! q->sess.suppress_warnings)
b530b5b3
LB
1665 q->sess.print_warning (_("For probing a particular line, use a "
1666 ".statement() probe, not .function()"),
af2e341f 1667 q->base_probe->tok);
58b070fb 1668
6b517475
JS
1669 // If we have a pattern string with target *line*, we
1670 // have to look at lines in all the matched srcfiles.
1671 void (* callback) (const dwarf_line_t&, void*) =
1672 q->has_label ? query_srcfile_label : query_srcfile_line;
1673 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1674 i != q->filtered_srcfiles.end(); ++i)
1675 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1676 q->line_type, callback, q->function, q);
1677 }
1678 else if (q->has_label)
1679 {
1680 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1681 i != q->filtered_functions.end(); ++i)
1682 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1683 q, query_label);
1684
1685 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1686 i != q->filtered_inlines.end(); ++i)
1687 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1688 q, query_label);
39bcd429 1689 }
6b517475
JS
1690 else
1691 {
1692 // Otherwise, simply probe all resolved functions.
1693 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1694 i != q->filtered_functions.end(); ++i)
1695 query_func_info (i->entrypc, *i, q);
1696
1697 // And all inline instances (if we're not excluding inlines with ".call")
1698 if (! q->has_call)
1699 for (inline_instance_map_t::iterator i
1700 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1701 query_inline_instance_info (*i, q);
1702 }
39bcd429 1703 return DWARF_CB_OK;
bd2b1e68 1704 }
39bcd429 1705 catch (const semantic_error& e)
bd2b1e68 1706 {
39bcd429
FCE
1707 q->sess.print_error (e);
1708 return DWARF_CB_ABORT;
bd2b1e68 1709 }
bd2b1e68
GH
1710}
1711
0ce64fb8 1712
4df79aaf
JS
1713void
1714dwarf_query::query_module_functions ()
1715{
1716 try
1717 {
1718 filtered_srcfiles.clear();
1719 filtered_functions.clear();
1720 filtered_inlines.clear();
1721
1722 // Collect all module functions so we know which CUs are interesting
1723 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1724 if (rc != DWARF_CB_OK)
1725 {
1726 query_done = true;
1727 return;
1728 }
1729
1730 set<void*> used_cus; // by cu->addr
1731 vector<Dwarf_Die> cus;
1732 Dwarf_Die cu_mem;
1733
1734 for (func_info_map_t::iterator i = filtered_functions.begin();
1735 i != filtered_functions.end(); ++i)
1736 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1737 used_cus.insert(cu_mem.addr).second)
1738 cus.push_back(cu_mem);
1739
1740 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1741 i != filtered_inlines.end(); ++i)
1742 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1743 used_cus.insert(cu_mem.addr).second)
1744 cus.push_back(cu_mem);
1745
1746 // Reset the dupes since we didn't actually collect them the first time
1747 alias_dupes.clear();
1748 inline_dupes.clear();
1749
1750 // Run the query again on the individual CUs
1751 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1752 query_cu(&*i, this);
1753 }
1754 catch (const semantic_error& e)
1755 {
1756 sess.print_error (e);
1757 }
1758}
1759
1760
5f0a03a6
JK
1761static void
1762validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1763{
1764 // Validate the machine code in this elf file against the
1765 // session machine. This is important, in case the wrong kind
1766 // of debuginfo is being automagically processed by elfutils.
1767 // While we can tell i686 apart from x86-64, unfortunately
1768 // we can't help confusing i586 vs i686 (both EM_386).
1769
1770 Dwarf_Addr bias;
1771 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1772 // because dwfl_module_getelf can force costly section relocations
1773 // we don't really need, while either will do for this purpose.
1774 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1775 ?: dwfl_module_getelf (mod, &bias));
1776
1777 GElf_Ehdr ehdr_mem;
1778 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1779 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
5f0a03a6
JK
1780 int elf_machine = em->e_machine;
1781 const char* debug_filename = "";
1782 const char* main_filename = "";
1783 (void) dwfl_module_info (mod, NULL, NULL,
1784 NULL, NULL, NULL,
1785 & main_filename,
1786 & debug_filename);
1787 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1788
1789 string expect_machine; // to match sess.machine (i.e., kernel machine)
1790 string expect_machine2;
5f0a03a6 1791
d27e6fd5 1792 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1793 switch (elf_machine)
1794 {
756c9462
FCE
1795 // x86 and ppc are bi-architecture; a 64-bit kernel
1796 // can normally run either 32-bit or 64-bit *userspace*.
1797 case EM_386:
1798 expect_machine = "i?86";
1799 if (! q->has_process) break; // 32-bit kernel/module
1800 /* FALLSTHROUGH */
1801 case EM_X86_64:
1802 expect_machine2 = "x86_64";
1803 break;
1804 case EM_PPC:
756c9462 1805 case EM_PPC64:
5a1c472e 1806 expect_machine = "powerpc";
756c9462 1807 break;
3fe7d888 1808 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 1809 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 1810 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
1811 // XXX: fill in some more of these
1812 default: expect_machine = "?"; break;
1813 }
1814
1815 if (! debug_filename) debug_filename = main_filename;
1816 if (! debug_filename) debug_filename = name;
1817
756c9462
FCE
1818 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
1819 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
1820 {
1821 stringstream msg;
b530b5b3
LB
1822 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
1823 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
1824 sess_machine.c_str(), debug_filename);
5f0a03a6
JK
1825 throw semantic_error(msg.str ());
1826 }
1827
1828 if (q->sess.verbose>2)
b530b5b3
LB
1829 clog << _F("focused on module '%s' = [0x%#" PRIx64 ", -0x%#" PRIx64 ", bias 0x%#" PRIx64
1830 " file %s ELF machine %s|%s (code %d)\n",
1831 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
1832 q->dw.module_bias, debug_filename, expect_machine.c_str(),
1833 expect_machine2.c_str(), elf_machine);
5f0a03a6 1834}
1d3a40b6 1835
91af0778
FCE
1836
1837
1838static Dwarf_Addr
1839lookup_symbol_address (Dwfl_Module *m, const char* wanted)
1840{
1841 int syments = dwfl_module_getsymtab(m);
1842 assert(syments);
1843 for (int i = 1; i < syments; ++i)
1844 {
1845 GElf_Sym sym;
1846 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
1847 if (name != NULL && strcmp(name, wanted) == 0)
1848 return sym.st_value;
1849 }
1850
1851 return 0;
1852}
1853
1854
1855
bd2b1e68 1856static int
b8da0ad1 1857query_module (Dwfl_Module *mod,
91af0778 1858 void **,
b8da0ad1 1859 const char *name,
6f4c1275 1860 Dwarf_Addr addr,
b8da0ad1 1861 void *arg)
bd2b1e68 1862{
91af0778 1863 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 1864
39bcd429 1865 try
e38d6504 1866 {
91af0778
FCE
1867 module_info* mi = q->sess.module_cache->cache[name];
1868 if (mi == 0)
1869 {
1870 mi = q->sess.module_cache->cache[name] = new module_info(name);
1871
6f4c1275
FCE
1872 mi->mod = mod;
1873 mi->addr = addr;
91af0778 1874
6f4c1275
FCE
1875 const char* debug_filename = "";
1876 const char* main_filename = "";
1877 (void) dwfl_module_info (mod, NULL, NULL,
1878 NULL, NULL, NULL,
1879 & main_filename,
1880 & debug_filename);
1881
1882 if (q->sess.ignore_vmlinux && name == TOK_KERNEL)
91af0778
FCE
1883 {
1884 // report_kernel() in elfutils found vmlinux, but pretend it didn't.
1885 // Given a non-null path, returning 1 means keep reporting modules.
1886 mi->dwarf_status = info_absent;
1887 }
6f4c1275 1888 else if (debug_filename || main_filename)
91af0778 1889 {
6f4c1275
FCE
1890 mi->elf_path = debug_filename ?: main_filename;
1891 }
1892 else if (name == TOK_KERNEL)
1893 {
1894 mi->dwarf_status = info_absent;
91af0778 1895 }
91af0778
FCE
1896 }
1897 // OK, enough of that module_info caching business.
1898
5f0a03a6 1899 q->dw.focus_on_module(mod, mi);
d9b516ca 1900
39bcd429
FCE
1901 // If we have enough information in the pattern to skip a module and
1902 // the module does not match that information, return early.
b8da0ad1 1903 if (!q->dw.module_name_matches(q->module_val))
85007c04 1904 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
1905
1906 // Don't allow module("*kernel*") type expressions to match the
1907 // elfutils module "kernel", which we refer to in the probe
1908 // point syntax exclusively as "kernel.*".
1909 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 1910 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 1911
5f0a03a6
JK
1912 if (mod)
1913 validate_module_elf(mod, name, q);
1914 else
91af0778
FCE
1915 assert(q->has_kernel); // and no vmlinux to examine
1916
1917 if (q->sess.verbose>2)
b530b5b3 1918 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
1919
1920
1921 // Collect a few kernel addresses. XXX: these belong better
1922 // to the sess.module_info["kernel"] struct.
1923 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 1924 {
91af0778
FCE
1925 if (! q->sess.sym_kprobes_text_start)
1926 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
1927 if (! q->sess.sym_kprobes_text_end)
1928 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
1929 if (! q->sess.sym_stext)
1930 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
1931 }
1932
84c84ac4
SC
1933 if (q->has_library && contains_glob_chars (q->path))
1934 // handle .library(GLOB)
1935 q->dw.iterate_over_libraries (&q->query_library_callback, q);
1936 else
1937 // search the module for matches of the probe point.
1938 q->handle_query_module();
bb788f9f 1939
91af0778 1940
b8da0ad1 1941 // If we know that there will be no more matches, abort early.
85007c04 1942 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
1943 return DWARF_CB_ABORT;
1944 else
1945 return DWARF_CB_OK;
7a053d3b 1946 }
39bcd429 1947 catch (const semantic_error& e)
bd2b1e68 1948 {
39bcd429
FCE
1949 q->sess.print_error (e);
1950 return DWARF_CB_ABORT;
bd2b1e68 1951 }
bd2b1e68
GH
1952}
1953
35d4ab18 1954
84c84ac4 1955void
5d5bd369 1956base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
1957{
1958 base_query *me = (base_query*)q;
5d5bd369 1959 me->query_library (data);
84c84ac4
SC
1960}
1961
1962
1963void
51d6bda3
SC
1964query_one_library (const char *library, dwflpp & dw,
1965 const string user_lib, probe * base_probe, probe_point *base_loc,
1966 vector<derived_probe *> & results)
84c84ac4
SC
1967{
1968 if (dw.function_name_matches_pattern(library, user_lib))
1969 {
1970 string library_path = find_executable (library, "LD_LIBRARY_PATH");
1971 probe_point* specific_loc = new probe_point(*base_loc);
1972 specific_loc->optional = true;
1973 vector<probe_point::component*> derived_comps;
1974
1975 vector<probe_point::component*>::iterator it;
1976 for (it = specific_loc->components.begin();
1977 it != specific_loc->components.end(); ++it)
1978 if ((*it)->functor == TOK_LIBRARY)
1979 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
1980 new literal_string(library_path)));
1981 else
1982 derived_comps.push_back(*it);
1983 probe_point* derived_loc = new probe_point(*specific_loc);
1984 derived_loc->components = derived_comps;
1985 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
51d6bda3
SC
1986 derive_probes(dw.sess, new_base, results);
1987 if (dw.sess.verbose > 2)
84c84ac4
SC
1988 clog << _("module=") << library_path;
1989 }
1990}
1991
1992
51d6bda3
SC
1993void
1994dwarf_query::query_library (const char *library)
1995{
1996 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
1997}
1998
1999
435f53a7
FCE
2000// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2001// but the needed declaration for module_cache is not available there.
2002// Nor for that matter in session.cxx. Only in this CU is that field ever
2003// set (in query_module() above), so we clean it up here too.
2004static void
2005delete_session_module_cache (systemtap_session& s)
2006{
2007 if (s.module_cache) {
2008 if (s.verbose > 3)
b530b5b3 2009 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2010 delete s.module_cache;
2011 s.module_cache = 0;
2012 }
2013}
2014
2015
de688825 2016struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2017{
77de5e9e 2018 dwarf_query & q;
bcc12710 2019 Dwarf_Die *scope_die;
77de5e9e 2020 Dwarf_Addr addr;
8c819921 2021 block *add_block;
2260f4e3 2022 block *add_call_probe; // synthesized from .return probes with saved $vars
8cc799a5 2023 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2024 unsigned saved_longs, saved_strings; // data saved within kretprobes
2025 map<std::string, expression *> return_ts_map;
729455a7 2026 vector<Dwarf_Die> scopes;
b95e2b79 2027 bool visited;
77de5e9e 2028
de688825 2029 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2030 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2031 add_block_tid(false), add_call_probe_tid(false),
af234c40 2032 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2033 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2034 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2035 void visit_target_symbol_saved_return (target_symbol* e);
2036 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2037 void visit_target_symbol (target_symbol* e);
c24447be 2038 void visit_cast_op (cast_op* e);
8cc799a5 2039 void visit_entry_op (entry_op* e);
729455a7
JS
2040private:
2041 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2042};
2043
2044
de688825 2045unsigned var_expanding_visitor::tick = 0;
77de5e9e 2046
a50de939
DS
2047
2048var_expanding_visitor::var_expanding_visitor ()
2049{
2050 // FIXME: for the time being, by default we only support plain '$foo
2051 // = bar', not '+=' or any other op= variant. This is fixable, but a
2052 // bit ugly.
2053 //
2054 // If derived classes desire to add additional operator support, add
2055 // new operators to this list in the derived class constructor.
2056 valid_ops.insert ("=");
2057}
2058
2059
87214add
JS
2060bool
2061var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2062 expression*& lvalue, expression*& rvalue)
77de5e9e 2063{
e57b735a
GH
2064 // Our job would normally be to require() the left and right sides
2065 // into a new assignment. What we're doing is slightly trickier:
2066 // we're pushing a functioncall** onto a stack, and if our left
2067 // child sets the functioncall* for that value, we're going to
2068 // assume our left child was a target symbol -- transformed into a
2069 // set_target_foo(value) call, and it wants to take our right child
2070 // as the argument "value".
2071 //
2072 // This is why some people claim that languages with
2073 // constructor-decomposing case expressions have a leg up on
2074 // visitors.
2075
2076 functioncall *fcall = NULL;
d9b516ca 2077
a50de939 2078 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2079 const string* old_op = op;
2080 op = &eop;
a50de939 2081
e57b735a 2082 target_symbol_setter_functioncalls.push (&fcall);
87214add 2083 replace (lvalue);
e57b735a 2084 target_symbol_setter_functioncalls.pop ();
87214add
JS
2085 replace (rvalue);
2086
2087 op = old_op;
e57b735a
GH
2088
2089 if (fcall != NULL)
77de5e9e 2090 {
e57b735a
GH
2091 // Our left child is informing us that it was a target variable
2092 // and it has been replaced with a set_target_foo() function
2093 // call; we are going to provide that function call -- with the
2094 // right child spliced in as sole argument -- in place of
de688825 2095 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2096
87214add 2097 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2098 {
2099 // Build up a list of supported operators.
2100 string ops;
2101 std::set<string>::iterator i;
b530b5b3 2102 int valid_ops_size = 0;
a50de939 2103 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2104 {
a50de939 2105 ops += " " + *i + ",";
b530b5b3
LB
2106 valid_ops_size++;
2107 }
a50de939
DS
2108 ops.resize(ops.size() - 1); // chop off the last ','
2109
2110 // Throw the error.
1e41115c
LB
2111 throw semantic_error (_F(ngettext("Only the following assign operator is implemented on target variables: %s",
2112 "Only the following assign operators are implemented on target variables: %s",
b530b5b3
LB
2113 valid_ops_size), ops.c_str()), tok);
2114
a50de939 2115 }
e57b735a 2116
87214add
JS
2117 assert (lvalue == fcall);
2118 if (rvalue)
2119 fcall->args.push_back (rvalue);
4ed05b15 2120 provide (fcall);
87214add 2121 return true;
77de5e9e 2122 }
e57b735a 2123 else
87214add
JS
2124 return false;
2125}
2126
2127
2128void
2129var_expanding_visitor::visit_assignment (assignment* e)
2130{
2131 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2132 provide (e);
2133}
2134
2135
2136void
2137var_expanding_visitor::visit_pre_crement (pre_crement* e)
2138{
2139 expression *dummy = NULL;
2140 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2141 provide (e);
2142}
2143
2144
2145void
2146var_expanding_visitor::visit_post_crement (post_crement* e)
2147{
2148 expression *dummy = NULL;
2149 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2150 provide (e);
2151}
2152
2153
2154void
2155var_expanding_visitor::visit_delete_statement (delete_statement* s)
2156{
2157 string fakeop = "delete";
2158 expression *dummy = NULL;
2159 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2160 provide (s);
e57b735a 2161}
d9b516ca 2162
d7f3e0c5 2163
30263a73
FCE
2164void
2165var_expanding_visitor::visit_defined_op (defined_op* e)
2166{
2167 bool resolved = true;
2168
2169 defined_ops.push (e);
2170 try {
2171 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2172 // defined with a target_symbol* operand, a subsidiary call may attempt to
2173 // rewrite it to a general expression* instead, and require<> happily
2174 // casts to/from void*, causing possible memory corruption. We use
2175 // expression* here, being the general case of rewritten $variable.
2176 expression *foo1 = e->operand;
2177 foo1 = require (foo1);
2178
c69a87e0 2179 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2180 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2181 // erroneous resolutions. Some would signal a visit_target_symbol failure
2182 // with an exception, with a set flag within the target_symbol, or nothing
2183 // at all.
30263a73 2184 //
c69a87e0
FCE
2185 // Now, failures always have to be signalled with a
2186 // saved_conversion_error being chained to the target_symbol.
2187 // Successes have to result in an attempted rewrite of the
850bfddd 2188 // target_symbol (via provide()).
780f11ff 2189 //
c69a87e0
FCE
2190 // Edna Mode: "no capes". fche: "no exceptions".
2191
30263a73
FCE
2192 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2193 //
2194 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2195 //
2196 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2197 // dwarf probe to take care of it.
2198 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2199 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2200 //
30263a73
FCE
2201 // utrace: success: rewrites to function; failure: semantic_error
2202 //
850bfddd 2203 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2204
2205 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2206 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2207 resolved = false;
a45664f4 2208 else if (foo2) // unresolved but not marked failing
b7aedf26 2209 {
780f11ff
JS
2210 // There are some visitors that won't touch certain target_symbols,
2211 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2212 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2213 e->operand = foo2;
2214 provide (e);
2215 return;
2216 }
30263a73
FCE
2217 else // resolved, rewritten to some other expression type
2218 resolved = true;
780f11ff 2219 } catch (const semantic_error& e) {
c69a87e0 2220 assert (0); // should not happen
30263a73
FCE
2221 }
2222 defined_ops.pop ();
2223
2224 literal_number* ln = new literal_number (resolved ? 1 : 0);
2225 ln->tok = e->tok;
2226 provide (ln);
2227}
2228
2229
5f36109e
JS
2230struct dwarf_pretty_print
2231{
2232 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2233 const string& local, bool userspace_p,
2234 const target_symbol& e):
d19a9a82
JS
2235 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2236 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2237 {
2238 init_ts (e);
2239 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2240 }
2241
2242 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2243 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2244 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2245 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2246 {
2247 init_ts (e);
2248 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2249 }
2250
2251 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2252 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2253 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2254 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2255 {
2256 init_ts (e);
2257 dw.type_die_for_pointer (type_die, ts, &base_type);
2258 }
2259
2260 functioncall* expand ();
ce83ff57 2261 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2262
2263private:
2264 dwflpp& dw;
2265 target_symbol* ts;
7d11d8c9 2266 bool print_full;
5f36109e
JS
2267 Dwarf_Die base_type;
2268
2269 string local;
2270 vector<Dwarf_Die> scopes;
2271 Dwarf_Addr pc;
2272
2273 expression* pointer;
2274 Dwarf_Die pointer_type;
2275
d19a9a82 2276 const bool userspace_p, deref_p;
5f36109e
JS
2277
2278 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2279 print_format* pf, bool top=false);
5f36109e 2280 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2281 print_format* pf);
5f36109e 2282 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2283 print_format* pf, bool top);
5f36109e 2284 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2285 print_format* pf, bool top);
5f36109e 2286 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2287 print_format* pf, bool top);
5f36109e 2288 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2289 print_format* pf, int& count);
bbee5bb8 2290 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2291
2292 void init_ts (const target_symbol& e);
2293 expression* deref (target_symbol* e);
c55ea10d 2294 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2295};
2296
2297
2298void
2299dwarf_pretty_print::init_ts (const target_symbol& e)
2300{
2301 // Work with a new target_symbol so we can modify arguments
2302 ts = new target_symbol (e);
2303
2304 if (ts->addressof)
b530b5b3 2305 throw semantic_error(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2306
2307 if (ts->components.empty() ||
2308 ts->components.back().type != target_symbol::comp_pretty_print)
b530b5b3 2309 throw semantic_error(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2310 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2311 ts->components.pop_back();
2312}
2313
2314
2315functioncall*
2316dwarf_pretty_print::expand ()
2317{
2318 static unsigned tick = 0;
2319
2320 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2321 // try {
2322 // return sprintf("{.foo=...}", (ts)->foo, ...)
2323 // } catch {
2324 // return "ERROR"
2325 // }
5f36109e
JS
2326 // }
2327
2328 // Create the function decl and call.
2329
2330 functiondecl *fdecl = new functiondecl;
2331 fdecl->tok = ts->tok;
2332 fdecl->synthetic = true;
2333 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2334 fdecl->type = pe_string;
2335
2336 functioncall* fcall = new functioncall;
2337 fcall->tok = ts->tok;
2338 fcall->function = fdecl->name;
140be17a 2339 fcall->type = pe_string;
5f36109e
JS
2340
2341 // If there's a <pointer>, replace it with a new var and make that
2342 // the first function argument.
2343 if (pointer)
2344 {
2345 vardecl *v = new vardecl;
2346 v->type = pe_long;
2347 v->name = "pointer";
2348 v->tok = ts->tok;
2349 fdecl->formal_args.push_back (v);
2350 fcall->args.push_back (pointer);
2351
2352 symbol* sym = new symbol;
2353 sym->tok = ts->tok;
2354 sym->name = v->name;
5f36109e
JS
2355 pointer = sym;
2356 }
2357
2358 // For each expression argument, replace it with a function argument.
2359 for (unsigned i = 0; i < ts->components.size(); ++i)
2360 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2361 {
2362 vardecl *v = new vardecl;
2363 v->type = pe_long;
2364 v->name = "index" + lex_cast(i);
2365 v->tok = ts->tok;
2366 fdecl->formal_args.push_back (v);
2367 fcall->args.push_back (ts->components[i].expr_index);
2368
2369 symbol* sym = new symbol;
2370 sym->tok = ts->tok;
2371 sym->name = v->name;
5f36109e
JS
2372 ts->components[i].expr_index = sym;
2373 }
2374
2375 // Create the return sprintf.
2376 token* pf_tok = new token(*ts->tok);
2377 pf_tok->content = "sprintf";
2378 print_format* pf = print_format::create(pf_tok);
2379 return_statement* rs = new return_statement;
2380 rs->tok = ts->tok;
2381 rs->value = pf;
5f36109e
JS
2382
2383 // Recurse into the actual values.
7d11d8c9 2384 recurse (&base_type, ts, pf, true);
5f36109e
JS
2385 pf->components = print_format::string_to_components(pf->raw_components);
2386
7d11d8c9
JS
2387 // Create the try-catch net
2388 try_block* tb = new try_block;
2389 tb->tok = ts->tok;
2390 tb->try_block = rs;
2391 tb->catch_error_var = 0;
2392 return_statement* rs2 = new return_statement;
2393 rs2->tok = ts->tok;
2394 rs2->value = new literal_string ("ERROR");
2395 rs2->value->tok = ts->tok;
2396 tb->catch_block = rs2;
2397 fdecl->body = tb;
2398
f8809d54 2399 fdecl->join (dw.sess);
5f36109e
JS
2400 return fcall;
2401}
2402
2403
2404void
2405dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2406 print_format* pf, bool top)
5f36109e
JS
2407{
2408 Dwarf_Die type;
2409 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2410
2411 switch (dwarf_tag(&type))
2412 {
2413 default:
2414 // XXX need a warning?
2415 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2416 // + ") for " + dwarf_type_name(&type), e->tok);
2417 pf->raw_components.append("?");
2418 break;
2419
2420 case DW_TAG_enumeration_type:
2421 case DW_TAG_base_type:
7d11d8c9 2422 recurse_base (&type, e, pf);
5f36109e
JS
2423 break;
2424
2425 case DW_TAG_array_type:
7d11d8c9 2426 recurse_array (&type, e, pf, top);
5f36109e
JS
2427 break;
2428
2429 case DW_TAG_pointer_type:
2430 case DW_TAG_reference_type:
2431 case DW_TAG_rvalue_reference_type:
7d11d8c9 2432 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2433 break;
2434
2435 case DW_TAG_subroutine_type:
c55ea10d 2436 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2437 break;
2438
2439 case DW_TAG_union_type:
5f36109e
JS
2440 case DW_TAG_structure_type:
2441 case DW_TAG_class_type:
7d11d8c9 2442 recurse_struct (&type, e, pf, top);
5f36109e
JS
2443 break;
2444 }
2445}
2446
2447
2448void
2449dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2450 print_format* pf)
5f36109e
JS
2451{
2452 Dwarf_Attribute attr;
2453 Dwarf_Word encoding = (Dwarf_Word) -1;
2454 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2455 &encoding);
5f36109e
JS
2456 switch (encoding)
2457 {
2458 case DW_ATE_float:
2459 case DW_ATE_complex_float:
2460 // XXX need a warning?
2461 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2462 // + ") for " + dwarf_type_name(type), e->tok);
2463 pf->raw_components.append("?");
5f36109e
JS
2464 break;
2465
2466 case DW_ATE_signed_char:
2467 case DW_ATE_unsigned_char:
c55ea10d 2468 push_deref (pf, "'%c'", e);
5f36109e
JS
2469 break;
2470
2471 case DW_ATE_unsigned:
c55ea10d 2472 push_deref (pf, "%u", e);
5f36109e
JS
2473 break;
2474
2475 default:
c55ea10d 2476 push_deref (pf, "%i", e);
5f36109e
JS
2477 break;
2478 }
5f36109e
JS
2479}
2480
2481
2482void
2483dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2484 print_format* pf, bool top)
5f36109e 2485{
7d11d8c9
JS
2486 if (!top && !print_full)
2487 {
2488 pf->raw_components.append("[...]");
2489 return;
2490 }
2491
5f36109e
JS
2492 Dwarf_Die childtype;
2493 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2494
2495 if (print_chars (&childtype, e, pf))
2496 return;
2497
5f36109e
JS
2498 pf->raw_components.append("[");
2499
2500 // We print the array up to the first 5 elements.
2501 // XXX how can we determine the array size?
2502 // ... for now, just print the first element
64cddf39 2503 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2504 unsigned i, size = 1;
64cddf39 2505 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2506 {
2507 if (i > 0)
2508 pf->raw_components.append(", ");
2509 target_symbol* e2 = new target_symbol(*e);
2510 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2511 recurse (&childtype, e2, pf);
5f36109e
JS
2512 }
2513 if (i < size || 1/*XXX until real size is known */)
2514 pf->raw_components.append(", ...");
2515 pf->raw_components.append("]");
2516}
2517
2518
2519void
2520dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2521 print_format* pf, bool top)
5f36109e 2522{
7d11d8c9 2523 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2524 bool void_p = true;
7d11d8c9 2525 Dwarf_Die pointee;
bbee5bb8 2526 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2527 {
2528 try
2529 {
2530 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2531 void_p = false;
2532 }
2533 catch (const semantic_error&) {}
2534 }
2535
2536 if (!void_p)
5f36109e 2537 {
bbee5bb8
JS
2538 if (print_chars (&pointee, e, pf))
2539 return;
2540
2541 if (top)
2542 {
2543 recurse (&pointee, e, pf, top);
2544 return;
2545 }
5f36109e 2546 }
bbee5bb8 2547
c55ea10d 2548 push_deref (pf, "%p", e);
5f36109e
JS
2549}
2550
2551
2552void
2553dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2554 print_format* pf, bool top)
5f36109e 2555{
bdec0e18
JS
2556 if (dwarf_hasattr(type, DW_AT_declaration))
2557 {
a44a7cb5 2558 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2559 if (!resolved)
2560 {
2561 // could be an error, but for now just stub it
2562 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2563 pf->raw_components.append("{...}");
2564 return;
2565 }
2566 type = resolved;
2567 }
2568
5f36109e
JS
2569 int count = 0;
2570 pf->raw_components.append("{");
7d11d8c9
JS
2571 if (top || print_full)
2572 recurse_struct_members (type, e, pf, count);
2573 else
2574 pf->raw_components.append("...");
5f36109e
JS
2575 pf->raw_components.append("}");
2576}
2577
2578
2579void
2580dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2581 print_format* pf, int& count)
5f36109e 2582{
a80f28d8
JS
2583 /* With inheritance, a subclass may mask member names of parent classes, so
2584 * our search among the inheritance tree must be breadth-first rather than
2585 * depth-first (recursive). The type die is still our starting point. When
2586 * we encounter a masked name, just skip it. */
2587 set<string> dupes;
2588 deque<Dwarf_Die> inheritees(1, *type);
2589 for (; !inheritees.empty(); inheritees.pop_front())
2590 {
2591 Dwarf_Die child, childtype;
2592 if (dwarf_child (&inheritees.front(), &child) == 0)
2593 do
2594 {
2595 target_symbol* e2 = e;
5f36109e 2596
a80f28d8
JS
2597 // skip static members
2598 if (dwarf_hasattr(&child, DW_AT_declaration))
2599 continue;
5f36109e 2600
a80f28d8 2601 int tag = dwarf_tag (&child);
5f36109e 2602
a80f28d8
JS
2603 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2604 continue;
5f36109e 2605
a80f28d8 2606 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2607
a80f28d8
JS
2608 if (tag == DW_TAG_inheritance)
2609 {
2610 inheritees.push_back(childtype);
2611 continue;
2612 }
5f36109e 2613
a80f28d8
JS
2614 int childtag = dwarf_tag (&childtype);
2615 const char *member = dwarf_diename (&child);
3a147004 2616
a80f28d8
JS
2617 // "_vptr.foo" members are C++ virtual function tables,
2618 // which (generally?) aren't interesting for users.
2619 if (member && startswith(member, "_vptr."))
2620 continue;
3a147004 2621
a80f28d8
JS
2622 // skip inheritance-masked duplicates
2623 if (member && !dupes.insert(member).second)
2624 continue;
64cddf39 2625
a80f28d8
JS
2626 if (++count > 1)
2627 pf->raw_components.append(", ");
64cddf39 2628
a80f28d8
JS
2629 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2630 if (pf->args.size() >= 32)
2631 {
2632 pf->raw_components.append("...");
2633 break;
2634 }
2635
2636 if (member)
2637 {
2638 pf->raw_components.append(".");
2639 pf->raw_components.append(member);
5f36109e 2640
a80f28d8
JS
2641 e2 = new target_symbol(*e);
2642 e2->components.push_back (target_symbol::component(e->tok, member));
2643 }
2644 else if (childtag == DW_TAG_union_type)
2645 pf->raw_components.append("<union>");
2646 else if (childtag == DW_TAG_structure_type)
2647 pf->raw_components.append("<class>");
2648 else if (childtag == DW_TAG_class_type)
2649 pf->raw_components.append("<struct>");
2650 pf->raw_components.append("=");
2651 recurse (&childtype, e2, pf);
5f36109e 2652 }
a80f28d8
JS
2653 while (dwarf_siblingof (&child, &child) == 0);
2654 }
5f36109e
JS
2655}
2656
2657
bbee5bb8
JS
2658bool
2659dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2660 print_format* pf)
2661{
2662 Dwarf_Die type;
2663 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2664 const char *name = dwarf_diename (&type);
2665 if (name && (name == string("char") || name == string("unsigned char")))
2666 {
c55ea10d
JS
2667 if (push_deref (pf, "\"%s\"", e))
2668 {
2669 // steal the last arg for a string access
2670 assert (!pf->args.empty());
2671 functioncall* fcall = new functioncall;
2672 fcall->tok = e->tok;
2673 fcall->function = userspace_p ? "user_string2" : "kernel_string2";
2674 fcall->args.push_back (pf->args.back());
2675 expression *err_msg = new literal_string ("<unknown>");
2676 err_msg->tok = e->tok;
2677 fcall->args.push_back (err_msg);
2678 pf->args.back() = fcall;
2679 }
bbee5bb8
JS
2680 return true;
2681 }
2682 return false;
2683}
2684
2685
5f36109e
JS
2686expression*
2687dwarf_pretty_print::deref (target_symbol* e)
2688{
2689 static unsigned tick = 0;
2690
d19a9a82
JS
2691 if (!deref_p)
2692 {
2693 assert (pointer && e->components.empty());
2694 return pointer;
2695 }
2696
5f36109e
JS
2697 // Synthesize a function to dereference the dwarf fields,
2698 // with a pointer parameter that is the base tracepoint variable
2699 functiondecl *fdecl = new functiondecl;
2700 fdecl->synthetic = true;
2701 fdecl->tok = e->tok;
2702 embeddedcode *ec = new embeddedcode;
2703 ec->tok = e->tok;
2704
2705 fdecl->name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
2706 fdecl->body = ec;
2707
2708 // Synthesize a functioncall.
2709 functioncall* fcall = new functioncall;
2710 fcall->tok = e->tok;
2711 fcall->function = fdecl->name;
5f36109e
JS
2712
2713 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
2714 ec->code += "\n#define fetch_register " + string(userspace_p?"u":"k") + "_fetch_register\n";
2715 ec->code += "#define store_register " + string(userspace_p?"u":"k") + "_store_register\n";
2716
2717 if (pointer)
2718 {
2719 ec->code += dw.literal_stmt_for_pointer (&pointer_type, e,
2720 false, fdecl->type);
2721
2722 vardecl *v = new vardecl;
2723 v->type = pe_long;
2724 v->name = "pointer";
2725 v->tok = e->tok;
2726 fdecl->formal_args.push_back(v);
2727 fcall->args.push_back(pointer);
2728 }
2729 else if (!local.empty())
2730 ec->code += dw.literal_stmt_for_local (scopes, pc, local, e,
2731 false, fdecl->type);
2732 else
2733 ec->code += dw.literal_stmt_for_return (&scopes[0], pc, e,
2734 false, fdecl->type);
2735
2736 // Any non-literal indexes need to be passed in too.
2737 for (unsigned i = 0; i < e->components.size(); ++i)
2738 if (e->components[i].type == target_symbol::comp_expression_array_index)
2739 {
2740 vardecl *v = new vardecl;
2741 v->type = pe_long;
2742 v->name = "index" + lex_cast(i);
2743 v->tok = e->tok;
2744 fdecl->formal_args.push_back(v);
2745 fcall->args.push_back(e->components[i].expr_index);
2746 }
2747
2748 ec->code += "/* pure */";
2749 ec->code += "/* unprivileged */";
2750
2751 // PR10601
2752 ec->code += "\n#undef fetch_register\n";
2753 ec->code += "\n#undef store_register\n";
2754
f8809d54 2755 fdecl->join (dw.sess);
5f36109e
JS
2756 return fcall;
2757}
2758
2759
c55ea10d
JS
2760bool
2761dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
2762 target_symbol* e)
2763{
2764 expression* e2 = NULL;
2765 try
2766 {
2767 e2 = deref (e);
2768 }
2769 catch (const semantic_error&)
2770 {
2771 pf->raw_components.append ("?");
2772 return false;
2773 }
2774 pf->raw_components.append (fmt);
2775 pf->args.push_back (e2);
2776 return true;
2777}
2778
2779
e57b735a 2780void
a7999c82 2781dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 2782{
a7999c82
JS
2783 // Get the full name of the target symbol.
2784 stringstream ts_name_stream;
2785 e->print(ts_name_stream);
2786 string ts_name = ts_name_stream.str();
2787
2788 // Check and make sure we haven't already seen this target
2789 // variable in this return probe. If we have, just return our
2790 // last replacement.
af234c40 2791 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 2792 if (i != return_ts_map.end())
85ecf79a 2793 {
a7999c82
JS
2794 provide (i->second);
2795 return;
2796 }
85ecf79a 2797
70208613
JS
2798 // Attempt the expansion directly first, so if there's a problem with the
2799 // variable we won't have a bogus entry probe lying around. Like in
2800 // saveargs(), we pretend for a moment that we're not in a .return.
2801 bool saved_has_return = q.has_return;
2802 q.has_return = false;
2803 expression *repl = e;
2804 replace (repl);
2805 q.has_return = saved_has_return;
2806 target_symbol* n = dynamic_cast<target_symbol*>(repl);
2807 if (n && n->saved_conversion_error)
2808 {
2809 provide (repl);
2810 return;
2811 }
2812
af234c40
JS
2813 expression *exp;
2814 if (!q.has_process &&
2815 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 2816 exp = gen_kretprobe_saved_return(repl);
af234c40 2817 else
277c21bc 2818 exp = gen_mapped_saved_return(repl, e->name);
af234c40
JS
2819
2820 // Provide the variable to our parent so it can be used as a
2821 // substitute for the target symbol.
2822 provide (exp);
2823
2824 // Remember this replacement since we might be able to reuse
2825 // it later if the same return probe references this target
2826 // symbol again.
2827 return_ts_map[ts_name] = exp;
2828}
2829
2830expression*
70208613 2831dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
277c21bc 2832 const string& name)
af234c40 2833{
a7999c82
JS
2834 // We've got to do several things here to handle target
2835 // variables in return probes.
85ecf79a 2836
a7999c82
JS
2837 // (1) Synthesize two global arrays. One is the cache of the
2838 // target variable and the other contains a thread specific
2839 // nesting level counter. The arrays will look like
2840 // this:
2841 //
2842 // _dwarf_tvar_{name}_{num}
2843 // _dwarf_tvar_{name}_{num}_ctr
2844
2845 string aname = (string("_dwarf_tvar_")
277c21bc 2846 + name.substr(1)
aca66a36 2847 + "_" + lex_cast(tick++));
a7999c82
JS
2848 vardecl* vd = new vardecl;
2849 vd->name = aname;
2850 vd->tok = e->tok;
2851 q.sess.globals.push_back (vd);
2852
2853 string ctrname = aname + "_ctr";
2854 vd = new vardecl;
2855 vd->name = ctrname;
2856 vd->tok = e->tok;
2857 q.sess.globals.push_back (vd);
2858
2859 // (2) Create a new code block we're going to insert at the
2860 // beginning of this probe to get the cached value into a
2861 // temporary variable. We'll replace the target variable
2862 // reference with the temporary variable reference. The code
2863 // will look like this:
2864 //
2865 // _dwarf_tvar_tid = tid()
2866 // _dwarf_tvar_{name}_{num}_tmp
2867 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2868 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
2869 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2870 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
2871 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
2872 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
2873
2874 // (2a) Synthesize the tid temporary expression, which will look
2875 // like this:
2876 //
2877 // _dwarf_tvar_tid = tid()
2878 symbol* tidsym = new symbol;
2879 tidsym->name = string("_dwarf_tvar_tid");
2880 tidsym->tok = e->tok;
85ecf79a 2881
a7999c82
JS
2882 if (add_block == NULL)
2883 {
2884 add_block = new block;
2885 add_block->tok = e->tok;
8cc799a5 2886 }
8c819921 2887
8cc799a5
JS
2888 if (!add_block_tid)
2889 {
a7999c82
JS
2890 // Synthesize a functioncall to grab the thread id.
2891 functioncall* fc = new functioncall;
2892 fc->tok = e->tok;
2893 fc->function = string("tid");
8c819921 2894
a7999c82 2895 // Assign the tid to '_dwarf_tvar_tid'.
8c819921
DS
2896 assignment* a = new assignment;
2897 a->tok = e->tok;
2898 a->op = "=";
a7999c82
JS
2899 a->left = tidsym;
2900 a->right = fc;
8c819921
DS
2901
2902 expr_statement* es = new expr_statement;
2903 es->tok = e->tok;
2904 es->value = a;
8c819921 2905 add_block->statements.push_back (es);
8cc799a5 2906 add_block_tid = true;
a7999c82 2907 }
8c819921 2908
a7999c82
JS
2909 // (2b) Synthesize an array reference and assign it to a
2910 // temporary variable (that we'll use as replacement for the
2911 // target variable reference). It will look like this:
2912 //
2913 // _dwarf_tvar_{name}_{num}_tmp
2914 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2915 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
2916
2917 arrayindex* ai_tvar_base = new arrayindex;
2918 ai_tvar_base->tok = e->tok;
2919
2920 symbol* sym = new symbol;
2921 sym->name = aname;
2922 sym->tok = e->tok;
2923 ai_tvar_base->base = sym;
2924
2925 ai_tvar_base->indexes.push_back(tidsym);
2926
2927 // We need to create a copy of the array index in its current
2928 // state so we can have 2 variants of it (the original and one
2929 // that post-decrements the second index).
2930 arrayindex* ai_tvar = new arrayindex;
2931 arrayindex* ai_tvar_postdec = new arrayindex;
2932 *ai_tvar = *ai_tvar_base;
2933 *ai_tvar_postdec = *ai_tvar_base;
2934
2935 // Synthesize the
2936 // "_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]" used as the
2937 // second index into the array.
2938 arrayindex* ai_ctr = new arrayindex;
2939 ai_ctr->tok = e->tok;
2940
2941 sym = new symbol;
2942 sym->name = ctrname;
2943 sym->tok = e->tok;
2944 ai_ctr->base = sym;
2945 ai_ctr->indexes.push_back(tidsym);
2946 ai_tvar->indexes.push_back(ai_ctr);
2947
2948 symbol* tmpsym = new symbol;
2949 tmpsym->name = aname + "_tmp";
2950 tmpsym->tok = e->tok;
2951
2952 assignment* a = new assignment;
2953 a->tok = e->tok;
2954 a->op = "=";
2955 a->left = tmpsym;
2956 a->right = ai_tvar;
2957
2958 expr_statement* es = new expr_statement;
2959 es->tok = e->tok;
2960 es->value = a;
2961
2962 add_block->statements.push_back (es);
2963
2964 // (2c) Add a post-decrement to the second array index and
2965 // delete the array value. It will look like this:
2966 //
2967 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
2968 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
2969
2970 post_crement* pc = new post_crement;
2971 pc->tok = e->tok;
2972 pc->op = "--";
2973 pc->operand = ai_ctr;
2974 ai_tvar_postdec->indexes.push_back(pc);
2975
2976 delete_statement* ds = new delete_statement;
2977 ds->tok = e->tok;
2978 ds->value = ai_tvar_postdec;
2979
2980 add_block->statements.push_back (ds);
2981
2982 // (2d) Delete the counter value if it is 0. It will look like
2983 // this:
2984 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
2985 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
2986
2987 ds = new delete_statement;
2988 ds->tok = e->tok;
2989 ds->value = ai_ctr;
2990
2991 unary_expression *ue = new unary_expression;
2992 ue->tok = e->tok;
2993 ue->op = "!";
2994 ue->operand = ai_ctr;
2995
2996 if_statement *ifs = new if_statement;
2997 ifs->tok = e->tok;
2998 ifs->condition = ue;
2999 ifs->thenblock = ds;
3000 ifs->elseblock = NULL;
3001
3002 add_block->statements.push_back (ifs);
3003
3004 // (3) We need an entry probe that saves the value for us in the
3005 // global array we created. Create the entry probe, which will
3006 // look like this:
3007 //
2260f4e3 3008 // probe kernel.function("{function}").call {
a7999c82
JS
3009 // _dwarf_tvar_tid = tid()
3010 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3011 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3012 // = ${param}
3013 // }
3014
2260f4e3 3015 if (add_call_probe == NULL)
a7999c82 3016 {
2260f4e3
FCE
3017 add_call_probe = new block;
3018 add_call_probe->tok = e->tok;
8cc799a5 3019 }
4baf0e53 3020
8cc799a5
JS
3021 if (!add_call_probe_tid)
3022 {
a7999c82
JS
3023 // Synthesize a functioncall to grab the thread id.
3024 functioncall* fc = new functioncall;
3025 fc->tok = e->tok;
3026 fc->function = string("tid");
4baf0e53 3027
a7999c82
JS
3028 // Assign the tid to '_dwarf_tvar_tid'.
3029 assignment* a = new assignment;
8fc05e57
DS
3030 a->tok = e->tok;
3031 a->op = "=";
a7999c82
JS
3032 a->left = tidsym;
3033 a->right = fc;
8fc05e57 3034
a7999c82 3035 expr_statement* es = new expr_statement;
8fc05e57
DS
3036 es->tok = e->tok;
3037 es->value = a;
2260f4e3 3038 add_call_probe = new block(add_call_probe, es);
8cc799a5 3039 add_call_probe_tid = true;
85ecf79a 3040 }
cf2a1f85 3041
a7999c82
JS
3042 // Save the value, like this:
3043 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3044 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3045 // = ${param}
3046 arrayindex* ai_tvar_preinc = new arrayindex;
3047 *ai_tvar_preinc = *ai_tvar_base;
3048
3049 pre_crement* preinc = new pre_crement;
3050 preinc->tok = e->tok;
3051 preinc->op = "++";
3052 preinc->operand = ai_ctr;
3053 ai_tvar_preinc->indexes.push_back(preinc);
3054
3055 a = new assignment;
3056 a->tok = e->tok;
3057 a->op = "=";
3058 a->left = ai_tvar_preinc;
3059 a->right = e;
3060
3061 es = new expr_statement;
3062 es->tok = e->tok;
3063 es->value = a;
3064
2260f4e3 3065 add_call_probe = new block(add_call_probe, es);
a7999c82
JS
3066
3067 // (4) Provide the '_dwarf_tvar_{name}_{num}_tmp' variable to
3068 // our parent so it can be used as a substitute for the target
3069 // symbol.
af234c40
JS
3070 return tmpsym;
3071}
a7999c82 3072
af234c40
JS
3073
3074expression*
140be17a 3075dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3076{
3077 // The code for this is simple.
3078 //
3079 // .call:
3080 // _set_kretprobe_long(index, $value)
3081 //
3082 // .return:
3083 // _get_kretprobe_long(index)
3084 //
3085 // (or s/long/string/ for things like $$parms)
3086
3087 unsigned index;
3088 string setfn, getfn;
3089
140be17a
JS
3090 // We need the caller to predetermine the type of the expression!
3091 switch (e->type)
af234c40 3092 {
140be17a 3093 case pe_string:
af234c40
JS
3094 index = saved_strings++;
3095 setfn = "_set_kretprobe_string";
3096 getfn = "_get_kretprobe_string";
140be17a
JS
3097 break;
3098 case pe_long:
af234c40
JS
3099 index = saved_longs++;
3100 setfn = "_set_kretprobe_long";
3101 getfn = "_get_kretprobe_long";
140be17a
JS
3102 break;
3103 default:
b530b5b3 3104 throw semantic_error(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3105 }
3106
3107 // Create the entry code
3108 // _set_kretprobe_{long|string}(index, $value)
3109
3110 if (add_call_probe == NULL)
3111 {
3112 add_call_probe = new block;
3113 add_call_probe->tok = e->tok;
3114 }
3115
3116 functioncall* set_fc = new functioncall;
3117 set_fc->tok = e->tok;
3118 set_fc->function = setfn;
3119 set_fc->args.push_back(new literal_number(index));
3120 set_fc->args.back()->tok = e->tok;
3121 set_fc->args.push_back(e);
3122
3123 expr_statement* set_es = new expr_statement;
3124 set_es->tok = e->tok;
3125 set_es->value = set_fc;
3126
3127 add_call_probe->statements.push_back(set_es);
3128
3129 // Create the return code
3130 // _get_kretprobe_{long|string}(index)
3131
3132 functioncall* get_fc = new functioncall;
3133 get_fc->tok = e->tok;
3134 get_fc->function = getfn;
3135 get_fc->args.push_back(new literal_number(index));
3136 get_fc->args.back()->tok = e->tok;
3137
3138 return get_fc;
a7999c82 3139}
a43ba433 3140
2cb3fe26 3141
a7999c82
JS
3142void
3143dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3144{
9aa8ffce 3145 if (null_die(scope_die))
a7999c82 3146 return;
2cb3fe26 3147
5f36109e
JS
3148 target_symbol *tsym = new target_symbol(*e);
3149
fde50242
JS
3150 bool pretty = (!e->components.empty() &&
3151 e->components[0].type == target_symbol::comp_pretty_print);
3152 string format = pretty ? "=%s" : "=%#x";
a43ba433 3153
a7999c82
JS
3154 // Convert $$parms to sprintf of a list of parms and active local vars
3155 // which we recursively evaluate
a43ba433 3156
a7999c82
JS
3157 // NB: we synthesize a new token here rather than reusing
3158 // e->tok, because print_format::print likes to use
3159 // its tok->content.
5f36109e 3160 token* pf_tok = new token(*e->tok);
a7999c82 3161 pf_tok->type = tok_identifier;
b393f6f2 3162 pf_tok->content = "sprintf";
2cb3fe26 3163
d5e178c1 3164 print_format* pf = print_format::create(pf_tok);
a7999c82 3165
277c21bc 3166 if (q.has_return && (e->name == "$$return"))
a7999c82 3167 {
277c21bc 3168 tsym->name = "$return";
a7999c82
JS
3169
3170 // Ignore any variable that isn't accessible.
3171 tsym->saved_conversion_error = 0;
3172 expression *texp = tsym;
8b095b45 3173 replace (texp); // NB: throws nothing ...
a7999c82 3174 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3175 {
2cb3fe26 3176
a43ba433
FCE
3177 }
3178 else
3179 {
a7999c82 3180 pf->raw_components += "return";
5f36109e 3181 pf->raw_components += format;
a7999c82
JS
3182 pf->args.push_back(texp);
3183 }
3184 }
3185 else
3186 {
3187 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3188 bool first = true;
a7999c82 3189 Dwarf_Die result;
d48bc7eb
JS
3190 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3191 for (unsigned i = 0; i < scopes.size(); ++i)
3192 {
3193 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3194 break; // we don't want file-level variables
3195 if (dwarf_child (&scopes[i], &result) == 0)
3196 do
00cf3709 3197 {
d48bc7eb
JS
3198 switch (dwarf_tag (&result))
3199 {
3200 case DW_TAG_variable:
3201 if (e->name == "$$parms")
3202 continue;
3203 break;
3204 case DW_TAG_formal_parameter:
3205 if (e->name == "$$locals")
3206 continue;
3207 break;
3208
3209 default:
3210 continue;
3211 }
41c262f3 3212
d48bc7eb
JS
3213 const char *diename = dwarf_diename (&result);
3214 if (! diename) continue;
f76427a2 3215
d48bc7eb
JS
3216 if (! first)
3217 pf->raw_components += " ";
3218 pf->raw_components += diename;
fde50242
JS
3219 first = false;
3220
3221 // Write a placeholder for ugly aggregates
3222 Dwarf_Die type;
3223 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3224 {
3225 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3226 switch (dwarf_tag(&type))
3227 {
3228 case DW_TAG_union_type:
3229 case DW_TAG_structure_type:
3230 case DW_TAG_class_type:
3231 pf->raw_components += "={...}";
3232 continue;
3233
3234 case DW_TAG_array_type:
3235 pf->raw_components += "=[...]";
3236 continue;
3237 }
3238 }
345bbb3d 3239
d48bc7eb
JS
3240 tsym->name = "$";
3241 tsym->name += diename;
41c262f3 3242
d48bc7eb
JS
3243 // Ignore any variable that isn't accessible.
3244 tsym->saved_conversion_error = 0;
3245 expression *texp = tsym;
3246 replace (texp); // NB: throws nothing ...
3247 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3248 {
d48bc7eb
JS
3249 if (q.sess.verbose>2)
3250 {
3251 for (semantic_error *c = tsym->saved_conversion_error;
3252 c != 0;
3253 c = c->chain) {
b530b5b3 3254 clog << _("variable location problem: ") << c->what() << endl;
d48bc7eb
JS
3255 }
3256 }
3257
3258 pf->raw_components += "=?";
a43ba433 3259 }
d48bc7eb
JS
3260 else
3261 {
3262 pf->raw_components += format;
3263 pf->args.push_back(texp);
3264 }
a7999c82 3265 }
d48bc7eb
JS
3266 while (dwarf_siblingof (&result, &result) == 0);
3267 }
a7999c82 3268 }
2cb3fe26 3269
a7999c82 3270 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3271 pf->type = pe_string;
a7999c82
JS
3272 provide (pf);
3273}
3274
2cb3fe26 3275
a7999c82
JS
3276void
3277dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3278{
277c21bc 3279 assert(e->name.size() > 0 && e->name[0] == '$');
a7999c82 3280 visited = true;
30263a73
FCE
3281 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3282 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3283
70208613 3284 try
a7999c82 3285 {
c69a87e0
FCE
3286 bool lvalue = is_active_lvalue(e);
3287 if (lvalue && !q.sess.guru_mode)
b530b5b3 3288 throw semantic_error(_("write to target variable not permitted"), e->tok);
2cb3fe26 3289
c69a87e0 3290 // XXX: process $context vars should be writeable
70208613 3291
c69a87e0
FCE
3292 // See if we need to generate a new probe to save/access function
3293 // parameters from a return probe. PR 1382.
3294 if (q.has_return
3295 && !defined_being_checked
277c21bc
JS
3296 && e->name != "$return" // not the special return-value variable handled below
3297 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3298 {
3299 if (lvalue)
b530b5b3 3300 throw semantic_error(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3301 visit_target_symbol_saved_return(e);
3302 return;
3303 }
e57b735a 3304
277c21bc
JS
3305 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3306 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3307 {
3308 if (lvalue)
b530b5b3 3309 throw semantic_error(_("cannot write to context variable"), e->tok);
70208613 3310
c69a87e0 3311 if (e->addressof)
b530b5b3 3312 throw semantic_error(_("cannot take address of context variable"), e->tok);
70208613 3313
5f36109e
JS
3314 e->assert_no_components("dwarf", true);
3315
c69a87e0
FCE
3316 visit_target_symbol_context(e);
3317 return;
3318 }
70208613 3319
5f36109e
JS
3320 if (!e->components.empty() &&
3321 e->components.back().type == target_symbol::comp_pretty_print)
3322 {
3323 if (lvalue)
b530b5b3 3324 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3325
277c21bc 3326 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3327 {
3328 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3329 q.has_process, *e);
3330 dpp.expand()->visit(this);
3331 }
3332 else
3333 {
3334 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
277c21bc 3335 e->name.substr(1),
5f36109e
JS
3336 q.has_process, *e);
3337 dpp.expand()->visit(this);
3338 }
3339 return;
3340 }
3341
c69a87e0
FCE
3342 // Synthesize a function.
3343 functiondecl *fdecl = new functiondecl;
59de45f1 3344 fdecl->synthetic = true;
c69a87e0
FCE
3345 fdecl->tok = e->tok;
3346 embeddedcode *ec = new embeddedcode;
3347 ec->tok = e->tok;
70208613 3348
c69a87e0 3349 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
277c21bc 3350 + "_" + e->name.substr(1)
c69a87e0 3351 + "_" + lex_cast(tick++));
70208613 3352
b5a0dd41
FCE
3353 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
3354 ec->code += "\n#define fetch_register " + string(q.has_process?"u":"k") + "_fetch_register\n";
3355 ec->code += "#define store_register " + string(q.has_process?"u":"k") + "_store_register\n";
70208613 3356
277c21bc 3357 if (q.has_return && (e->name == "$return"))
e19fda4e 3358 {
b5a0dd41 3359 ec->code += q.dw.literal_stmt_for_return (scope_die,
e19fda4e 3360 addr,
b4c34c26 3361 e,
e19fda4e
DS
3362 lvalue,
3363 fdecl->type);
3364 }
3365 else
3366 {
b5a0dd41 3367 ec->code += q.dw.literal_stmt_for_local (getscopes(e),
e19fda4e 3368 addr,
277c21bc 3369 e->name.substr(1),
b4c34c26 3370 e,
e19fda4e
DS
3371 lvalue,
3372 fdecl->type);
3373 }
3374
1b07c728
FCE
3375 if (! lvalue)
3376 ec->code += "/* pure */";
64211010
DB
3377
3378 ec->code += "/* unprivileged */";
b5a0dd41
FCE
3379
3380 // PR10601
3381 ec->code += "\n#undef fetch_register\n";
3382 ec->code += "\n#undef store_register\n";
c69a87e0
FCE
3383
3384 fdecl->name = fname;
3385 fdecl->body = ec;
70208613 3386
c69a87e0
FCE
3387 // Any non-literal indexes need to be passed in too.
3388 for (unsigned i = 0; i < e->components.size(); ++i)
3389 if (e->components[i].type == target_symbol::comp_expression_array_index)
3390 {
3391 vardecl *v = new vardecl;
3392 v->type = pe_long;
3393 v->name = "index" + lex_cast(i);
3394 v->tok = e->tok;
3395 fdecl->formal_args.push_back(v);
3396 }
70208613 3397
c69a87e0
FCE
3398 if (lvalue)
3399 {
3400 // Modify the fdecl so it carries a single pe_long formal
3401 // argument called "value".
70208613 3402
c69a87e0
FCE
3403 // FIXME: For the time being we only support setting target
3404 // variables which have base types; these are 'pe_long' in
3405 // stap's type vocabulary. Strings and pointers might be
3406 // reasonable, some day, but not today.
70208613 3407
c69a87e0
FCE
3408 vardecl *v = new vardecl;
3409 v->type = pe_long;
3410 v->name = "value";
3411 v->tok = e->tok;
3412 fdecl->formal_args.push_back(v);
3413 }
f8809d54 3414 fdecl->join (q.sess);
70208613 3415
c69a87e0
FCE
3416 // Synthesize a functioncall.
3417 functioncall* n = new functioncall;
3418 n->tok = e->tok;
3419 n->function = fname;
140be17a 3420 n->type = fdecl->type;
70208613 3421
c69a87e0
FCE
3422 // Any non-literal indexes need to be passed in too.
3423 for (unsigned i = 0; i < e->components.size(); ++i)
3424 if (e->components[i].type == target_symbol::comp_expression_array_index)
3425 n->args.push_back(require(e->components[i].expr_index));
70208613 3426
c69a87e0
FCE
3427 if (lvalue)
3428 {
3429 // Provide the functioncall to our parent, so that it can be
3430 // used to substitute for the assignment node immediately above
3431 // us.
3432 assert(!target_symbol_setter_functioncalls.empty());
3433 *(target_symbol_setter_functioncalls.top()) = n;
3434 }
70208613 3435
c69a87e0 3436 provide (n);
66d284f4
FCE
3437 }
3438 catch (const semantic_error& er)
3439 {
9fab2262
JS
3440 // We suppress this error message, and pass the unresolved
3441 // target_symbol to the next pass. We hope that this value ends
3442 // up not being referenced after all, so it can be optimized out
3443 // quietly.
1af1e62d 3444 e->chain (er);
9fab2262 3445 provide (e);
66d284f4 3446 }
77de5e9e
GH
3447}
3448
3449
c24447be
JS
3450void
3451dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3452{
3453 // Fill in our current module context if needed
3454 if (e->module.empty())
3455 e->module = q.dw.module_name;
3456
3457 var_expanding_visitor::visit_cast_op(e);
3458}
3459
3460
8cc799a5
JS
3461void
3462dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3463{
3464 expression *repl = e;
3465 if (q.has_return)
3466 {
3467 // expand the operand as if it weren't a return probe
3468 q.has_return = false;
3469 replace (e->operand);
3470 q.has_return = true;
3471
3472 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3473 // but it requires knowing the types already, which is problematic for
3474 // arbitrary expressons.
3475 repl = gen_mapped_saved_return (e->operand, "@entry");
3476 }
3477 provide (repl);
3478}
3479
3480
729455a7
JS
3481vector<Dwarf_Die>&
3482dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3483{
3484 if (scopes.empty())
3485 {
f5958c8f 3486 scopes = q.dw.getscopes(scope_die);
729455a7 3487 if (scopes.empty())
b530b5b3
LB
3488 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3489 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
729455a7
JS
3490 throw semantic_error ("unable to find any scopes containing "
3491 + lex_cast_hex(addr)
3492 + ((scope_die == NULL) ? ""
3493 : (string (" in ")
3494 + (dwarf_diename(scope_die) ?: "<unknown>")
3495 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3496 + ")"))
3497 + " while searching for local '"
277c21bc 3498 + e->name.substr(1) + "'",
729455a7
JS
3499 e->tok);
3500 }
3501 return scopes;
3502}
3503
3504
5f36109e
JS
3505struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3506{
3507 systemtap_session& s;
3508 dwarf_builder& db;
3509
3510 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3511 s(s), db(db) {}
3512 void visit_cast_op (cast_op* e);
3513 void filter_special_modules(string& module);
3514};
3515
3516
c4ce66a1
JS
3517struct dwarf_cast_query : public base_query
3518{
946e1a48 3519 cast_op& e;
c4ce66a1 3520 const bool lvalue;
5f36109e
JS
3521 const bool userspace_p;
3522 functioncall*& result;
c4ce66a1 3523
5f36109e
JS
3524 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3525 const bool userspace_p, functioncall*& result):
abb41d92 3526 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3527 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3528
3529 void handle_query_module();
822a6a3d 3530 void query_library (const char *) {}
c4ce66a1
JS
3531};
3532
3533
c4ce66a1
JS
3534void
3535dwarf_cast_query::handle_query_module()
3536{
5f36109e
JS
3537 static unsigned tick = 0;
3538
3539 if (result)
c4ce66a1
JS
3540 return;
3541
ea1e477a 3542 // look for the type in any CU
a44a7cb5
JS
3543 Dwarf_Die* type_die = NULL;
3544 if (startswith(e.type_name, "class "))
3545 {
3546 // normalize to match dwflpp::global_alias_caching_callback
3547 string struct_name = "struct " + e.type_name.substr(6);
3548 type_die = dw.declaration_resolve_other_cus(struct_name);
3549 }
3550 else
3551 type_die = dw.declaration_resolve_other_cus(e.type_name);
3552
3553 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3554 // just "name". But since we didn't require users to be explicit before, and
3555 // actually sort of discouraged it, we must be flexible now. So if a lookup
3556 // fails with a bare name, try augmenting it.
3557 if (!type_die &&
3558 !startswith(e.type_name, "class ") &&
3559 !startswith(e.type_name, "struct ") &&
3560 !startswith(e.type_name, "union ") &&
3561 !startswith(e.type_name, "enum "))
3562 {
3563 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3564 if (!type_die)
3565 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3566 if (!type_die)
3567 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3568 }
3569
ea1e477a
JS
3570 if (!type_die)
3571 return;
c4ce66a1 3572
5f36109e
JS
3573 string code;
3574 exp_type type = pe_long;
3575
ea1e477a 3576 try
c4ce66a1 3577 {
ea1e477a
JS
3578 Dwarf_Die cu_mem;
3579 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
3580
3581 if (!e.components.empty() &&
3582 e.components.back().type == target_symbol::comp_pretty_print)
3583 {
3584 if (lvalue)
b530b5b3 3585 throw semantic_error(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 3586
d19a9a82 3587 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
3588 result = dpp.expand();
3589 return;
3590 }
3591
3592 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
3593 }
3594 catch (const semantic_error& er)
3595 {
3596 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
3597 // may be attempted using several different modules:
3598 // @cast(ptr, "type", "module1:module2:...")
3599 e.chain (er);
c4ce66a1 3600 }
c4ce66a1 3601
5f36109e
JS
3602 if (code.empty())
3603 return;
c4ce66a1 3604
5f36109e 3605 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
277c21bc 3606 + "_" + e.name.substr(1)
5f36109e 3607 + "_" + lex_cast(tick++));
c4ce66a1 3608
5f36109e
JS
3609 // Synthesize a function.
3610 functiondecl *fdecl = new functiondecl;
3611 fdecl->synthetic = true;
3612 fdecl->tok = e.tok;
3613 fdecl->type = type;
3614 fdecl->name = fname;
3615
3616 embeddedcode *ec = new embeddedcode;
3617 ec->tok = e.tok;
3618 fdecl->body = ec;
3619
3620 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
3621 ec->code += "\n#define fetch_register " + string(userspace_p?"u":"k") + "_fetch_register\n";
3622 ec->code += "#define store_register " + string(userspace_p?"u":"k") + "_store_register\n";
3623
3624 ec->code += code;
3625
3626 // Give the fdecl an argument for the pointer we're trying to cast
3627 vardecl *v1 = new vardecl;
3628 v1->type = pe_long;
3629 v1->name = "pointer";
3630 v1->tok = e.tok;
3631 fdecl->formal_args.push_back(v1);
3632
3633 // Any non-literal indexes need to be passed in too.
3634 for (unsigned i = 0; i < e.components.size(); ++i)
3635 if (e.components[i].type == target_symbol::comp_expression_array_index)
3636 {
3637 vardecl *v = new vardecl;
3638 v->type = pe_long;
3639 v->name = "index" + lex_cast(i);
3640 v->tok = e.tok;
3641 fdecl->formal_args.push_back(v);
3642 }
3643
3644 if (lvalue)
3645 {
3646 // Modify the fdecl so it carries a second pe_long formal
3647 // argument called "value".
3648
3649 // FIXME: For the time being we only support setting target
3650 // variables which have base types; these are 'pe_long' in
3651 // stap's type vocabulary. Strings and pointers might be
3652 // reasonable, some day, but not today.
3653
3654 vardecl *v2 = new vardecl;
3655 v2->type = pe_long;
3656 v2->name = "value";
3657 v2->tok = e.tok;
3658 fdecl->formal_args.push_back(v2);
3659 }
3660 else
3661 ec->code += "/* pure */";
3662
3663 ec->code += "/* unprivileged */";
3664
3665 // PR10601
3666 ec->code += "\n#undef fetch_register\n";
3667 ec->code += "\n#undef store_register\n";
3668
f8809d54 3669 fdecl->join (dw.sess);
5f36109e
JS
3670
3671 // Synthesize a functioncall.
3672 functioncall* n = new functioncall;
3673 n->tok = e.tok;
3674 n->function = fname;
5f36109e
JS
3675 n->args.push_back(e.operand);
3676
3677 // Any non-literal indexes need to be passed in too.
3678 for (unsigned i = 0; i < e.components.size(); ++i)
3679 if (e.components[i].type == target_symbol::comp_expression_array_index)
3680 n->args.push_back(e.components[i].expr_index);
3681
3682 result = n;
3683}
c4ce66a1
JS
3684
3685
fb0274bc
JS
3686void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
3687{
d90053e7 3688 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 3689 // for those cases, build a module including that header
d90053e7 3690 if (module[module.size() - 1] == '>' &&
60d98537 3691 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
3692 {
3693 string cached_module;
3694 if (s.use_cache)
3695 {
3696 // see if the cached module exists
a2639cb7 3697 cached_module = find_typequery_hash(s, module);
d105f664 3698 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
3699 {
3700 int fd = open(cached_module.c_str(), O_RDONLY);
3701 if (fd != -1)
3702 {
3703 if (s.verbose > 2)
b530b5b3
LB
3704 //TRANSLATORS: Here we're using a cached module.
3705 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
3706 module = cached_module;
3707 close(fd);
3708 return;
3709 }
3710 }
3711 }
3712
3713 // no cached module, time to make it
d90053e7 3714 if (make_typequery(s, module) == 0)
fb0274bc 3715 {
e16dc041 3716 // try to save typequery in the cache
fb0274bc 3717 if (s.use_cache)
e16dc041 3718 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
3719 }
3720 }
3721}
3722
3723
c4ce66a1
JS
3724void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
3725{
3726 bool lvalue = is_active_lvalue(e);
3727 if (lvalue && !s.guru_mode)
ce0f6648 3728 throw semantic_error(_("write to @cast context variable not permitted"), e->tok);
c4ce66a1
JS
3729
3730 if (e->module.empty())
3731 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
3732
5f36109e 3733 functioncall* result = NULL;
8b31197b
JS
3734
3735 // split the module string by ':' for alternatives
3736 vector<string> modules;
3737 tokenize(e->module, modules, ":");
b5a0dd41 3738 bool userspace_p=false; // PR10601
5f36109e 3739 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 3740 {
8b31197b 3741 string& module = modules[i];
fb0274bc 3742 filter_special_modules(module);
abb41d92 3743
c4ce66a1
JS
3744 // NB: This uses '/' to distinguish between kernel modules and userspace,
3745 // which means that userspace modules won't get any PATH searching.
3746 dwflpp* dw;
707bf35e
JS
3747 try
3748 {
b5a0dd41
FCE
3749 userspace_p=is_user_module (module);
3750 if (! userspace_p)
707bf35e
JS
3751 {
3752 // kernel or kernel module target
ae2552da 3753 dw = db.get_kern_dw(s, module);
707bf35e
JS
3754 }
3755 else
3756 {
3757 module = find_executable (module); // canonicalize it
3758 dw = db.get_user_dw(s, module);
3759 }
3760 }
3761 catch (const semantic_error& er)
3762 {
3763 /* ignore and go to the next module */
3764 continue;
3765 }
c4ce66a1 3766
5f36109e 3767 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 3768 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 3769 }
abb41d92 3770
5f36109e 3771 if (!result)
c4ce66a1 3772 {
946e1a48
JS
3773 // We pass the unresolved cast_op to the next pass, and hope
3774 // that this value ends up not being referenced after all, so
3775 // it can be optimized out quietly.
c4ce66a1
JS
3776 provide (e);
3777 return;
3778 }
3779
c4ce66a1
JS
3780 if (lvalue)
3781 {
3782 // Provide the functioncall to our parent, so that it can be
3783 // used to substitute for the assignment node immediately above
3784 // us.
3785 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 3786 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
3787 }
3788
5f36109e 3789 result->visit (this);
77de5e9e
GH
3790}
3791
3792
b8da0ad1
FCE
3793void
3794dwarf_derived_probe::printsig (ostream& o) const
3795{
3796 // Instead of just printing the plain locations, we add a PC value
3797 // as a comment as a way of telling e.g. apart multiple inlined
3798 // function instances. This is distinct from the verbose/clog
3799 // output, since this part goes into the cache hash calculations.
3800 sole_location()->print (o);
6d0f3f0c 3801 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
3802 printsig_nested (o);
3803}
3804
3805
3806
dc38c0ae 3807void
b20febf3
FCE
3808dwarf_derived_probe::join_group (systemtap_session& s)
3809{
af234c40
JS
3810 // skip probes which are paired entry-handlers
3811 if (!has_return && (saved_longs || saved_strings))
3812 return;
3813
b20febf3
FCE
3814 if (! s.dwarf_derived_probes)
3815 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
3816 s.dwarf_derived_probes->enroll (this);
b642c901 3817
62f52bb0
JS
3818 if (sdt_semaphore_addr != 0)
3819 enable_task_finder(s);
b20febf3
FCE
3820}
3821
3822
3823dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
3824 const string& filename,
3825 int line,
91af0778 3826 // module & section specify a relocation
b20febf3
FCE
3827 // base for <addr>, unless section==""
3828 // (equivalently module=="kernel")
3829 const string& module,
3830 const string& section,
3831 // NB: dwfl_addr is the virtualized
3832 // address for this symbol.
3833 Dwarf_Addr dwfl_addr,
3834 // addr is the section-offset for
3835 // actual relocation.
3836 Dwarf_Addr addr,
3837 dwarf_query& q,
37ebca01 3838 Dwarf_Die* scope_die /* may be null */)
4c5d1300 3839 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 3840 module (module), section (section), addr (addr),
63b4fd14 3841 path (q.path),
27dc09b1 3842 has_process (q.has_process),
c9bad430
DS
3843 has_return (q.has_return),
3844 has_maxactive (q.has_maxactive),
c57ea854 3845 has_library (q.has_library),
6b66b9f7 3846 maxactive_val (q.maxactive_val),
b642c901
SC
3847 user_path (q.user_path),
3848 user_lib (q.user_lib),
af234c40 3849 access_vars(false),
c57ea854 3850 saved_longs(0), saved_strings(0),
af234c40 3851 entry_handler(0)
bd2b1e68 3852{
b642c901
SC
3853 if (user_lib.size() != 0)
3854 has_library = true;
3855
6b66b9f7
JS
3856 if (q.has_process)
3857 {
3858 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
3859 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
3860 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
3861 // by the incoming section value (".absolute" vs. ".dynamic").
3862 // XXX Assert invariants here too?
3863 }
3864 else
3865 {
3866 // Assert kernel relocation invariants
3867 if (section == "" && dwfl_addr != addr) // addr should be absolute
ce0f6648 3868 throw semantic_error (_("missing relocation basis"), tok);
6b66b9f7 3869 if (section != "" && dwfl_addr == addr) // addr should be an offset
b530b5b3 3870 throw semantic_error (_("inconsistent relocation address"), tok);
6b66b9f7 3871 }
2930abc7 3872
21beacc9
FCE
3873 // XXX: hack for strange g++/gcc's
3874#ifndef USHRT_MAX
3875#define USHRT_MAX 32767
3876#endif
3877
606fd9c8 3878 // Range limit maxactive() value
6b66b9f7 3879 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
b530b5b3
LB
3880 throw semantic_error (_F("maxactive value out of range [0,%s]",
3881 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 3882
de688825 3883 // Expand target variables in the probe body
5f0a03a6 3884 if (!null_die(scope_die))
8fc05e57 3885 {
6b66b9f7 3886 // XXX: user-space deref's for q.has_process!
de688825 3887 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 3888 v.replace (this->body);
6b66b9f7
JS
3889 if (!q.has_process)
3890 access_vars = v.visited;
37ebca01
FCE
3891
3892 // If during target-variable-expanding the probe, we added a new block
3893 // of code, add it to the start of the probe.
3894 if (v.add_block)
ba6f838d 3895 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
3896
3897 // If when target-variable-expanding the probe, we need to synthesize a
3898 // sibling function-entry probe. We don't go through the whole probe derivation
3899 // business (PR10642) that could lead to wildcard/alias resolution, or for that
3900 // dwarf-induced duplication.
3901 if (v.add_call_probe)
37ebca01 3902 {
2260f4e3
FCE
3903 assert (q.has_return && !q.has_call);
3904
3905 // We temporarily replace q.base_probe.
3906 statement* old_body = q.base_probe->body;
3907 q.base_probe->body = v.add_call_probe;
3908 q.has_return = false;
3909 q.has_call = true;
af234c40 3910
da23eceb 3911 if (q.has_process)
af234c40
JS
3912 entry_handler = new uprobe_derived_probe (funcname, filename, line,
3913 module, section, dwfl_addr,
3914 addr, q, scope_die);
da23eceb 3915 else
af234c40
JS
3916 entry_handler = new dwarf_derived_probe (funcname, filename, line,
3917 module, section, dwfl_addr,
3918 addr, q, scope_die);
3919
3920 saved_longs = entry_handler->saved_longs = v.saved_longs;
3921 saved_strings = entry_handler->saved_strings = v.saved_strings;
3922
3923 q.results.push_back (entry_handler);
2260f4e3
FCE
3924
3925 q.has_return = true;
3926 q.has_call = false;
3927 q.base_probe->body = old_body;
37ebca01 3928 }
f10534c6
WH
3929 // Save the local variables for listing mode
3930 if (q.sess.listing_mode_vars)
8c67c337 3931 saveargs(q, scope_die, dwfl_addr);
8fc05e57 3932 }
37ebca01 3933 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 3934
f10534c6 3935 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 3936
5d23847d 3937 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
3938 // "reverse-engineered" form of the incoming (q.base_loc) probe
3939 // point. This allows a user to see what function / file / line
3940 // number any particular match of the wildcards.
2930abc7 3941
a229fcd7 3942 vector<probe_point::component*> comps;
91af0778
FCE
3943 if (q.has_kernel)
3944 comps.push_back (new probe_point::component(TOK_KERNEL));
3945 else if(q.has_module)
3946 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
3947 else if(q.has_process)
3948 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
3949 else
3950 assert (0);
b5d77020 3951
db520b00
FCE
3952 string fn_or_stmt;
3953 if (q.has_function_str || q.has_function_num)
3954 fn_or_stmt = "function";
3955 else
3956 fn_or_stmt = "statement";
a229fcd7 3957
b8da0ad1 3958 if (q.has_function_str || q.has_statement_str)
db520b00 3959 {
4cd232e4 3960 string retro_name = funcname;
b20febf3 3961 if (filename != "")
cee35f73 3962 {
fb84c077 3963 retro_name += ("@" + string (filename));
cee35f73 3964 if (line > 0)
aca66a36 3965 retro_name += (":" + lex_cast (line));
cee35f73 3966 }
db520b00
FCE
3967 comps.push_back
3968 (new probe_point::component
3969 (fn_or_stmt, new literal_string (retro_name)));
3970 }
b8da0ad1 3971 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
3972 {
3973 Dwarf_Addr retro_addr;
3974 if (q.has_function_num)
3975 retro_addr = q.function_num_val;
3976 else
3977 retro_addr = q.statement_num_val;
db520b00
FCE
3978 comps.push_back (new probe_point::component
3979 (fn_or_stmt,
9ea68eb9 3980 new literal_number(retro_addr, true)));
37ebca01
FCE
3981
3982 if (q.has_absolute)
3983 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
3984 }
3985
b8da0ad1
FCE
3986 if (q.has_call)
3987 comps.push_back (new probe_point::component(TOK_CALL));
3988 if (q.has_inline)
3989 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 3990 if (has_return)
b8da0ad1
FCE
3991 comps.push_back (new probe_point::component(TOK_RETURN));
3992 if (has_maxactive)
3993 comps.push_back (new probe_point::component
3994 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 3995
5d23847d
FCE
3996 // Overwrite it.
3997 this->sole_location()->components = comps;
2930abc7
FCE
3998}
3999
bd2b1e68 4000
0a98fd42 4001void
8c67c337
JS
4002dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4003 Dwarf_Addr dwfl_addr)
0a98fd42 4004{
9aa8ffce 4005 if (null_die(scope_die))
0a98fd42 4006 return;
0a98fd42 4007
8c67c337 4008 bool verbose = q.sess.verbose > 2;
0a98fd42 4009
8c67c337 4010 if (verbose)
b530b5b3 4011 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4012
8c67c337
JS
4013 if (has_return)
4014 {
4015 /* Only save the return value if it has a type. */
4016 string type_name;
4017 Dwarf_Die type_die;
4018 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4019 dwarf_type_name(&type_die, type_name))
4020 args.push_back("$return:"+type_name);
4021
4022 else if (verbose)
b530b5b3
LB
4023 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4024 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4025 }
d87623a1 4026
0a98fd42 4027 Dwarf_Die arg;
4ef35696
JS
4028 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4029 for (unsigned i = 0; i < scopes.size(); ++i)
4030 {
4031 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4032 break; // we don't want file-level variables
4033 if (dwarf_child (&scopes[i], &arg) == 0)
4034 do
0a98fd42 4035 {
4ef35696
JS
4036 switch (dwarf_tag (&arg))
4037 {
4038 case DW_TAG_variable:
4039 case DW_TAG_formal_parameter:
4040 break;
0a98fd42 4041
4ef35696
JS
4042 default:
4043 continue;
4044 }
0a98fd42 4045
4ef35696
JS
4046 /* Ignore this local if it has no name. */
4047 const char *arg_name = dwarf_diename (&arg);
4048 if (!arg_name)
8c67c337
JS
4049 {
4050 if (verbose)
b530b5b3
LB
4051 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4052 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4053 continue;
4054 }
4ef35696
JS
4055
4056 if (verbose)
b530b5b3
LB
4057 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4058 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4059
4060 /* Ignore this local if it has no location (or not at this PC). */
4061 /* NB: It still may not be directly accessible, e.g. if it is an
4062 * aggregate type, implicit_pointer, etc., but the user can later
4063 * figure out how to access the interesting parts. */
4064 Dwarf_Attribute attr_mem;
4065 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4066 {
4067 Dwarf_Op *expr;
4068 size_t len;
4069 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4070 {
4071 if (verbose)
b530b5b3
LB
4072 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4073 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4074 continue;
4075 }
4076 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4077 &len, 1) == 1 && len > 0))
4078 {
4079 if (verbose)
b530b5b3
LB
4080 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4081 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4ef35696
JS
4082 continue;
4083 }
4084 }
4085
4086 /* Ignore this local if it has no type. */
4087 string type_name;
4088 Dwarf_Die type_die;
4089 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4090 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4091 {
4092 if (verbose)
b530b5b3
LB
4093 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4094 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4095 continue;
4096 }
8c67c337 4097
4ef35696
JS
4098 /* This local looks good -- save it! */
4099 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4100 }
4ef35696
JS
4101 while (dwarf_siblingof (&arg, &arg) == 0);
4102 }
0a98fd42
JS
4103}
4104
4105
4106void
d0bfd2ac 4107dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4108{
d0bfd2ac 4109 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4110}
4111
4112
27dc09b1
DB
4113void
4114dwarf_derived_probe::emit_unprivileged_assertion (translator_output* o)
4115{
4116 if (has_process)
4117 {
4118 // These probes are allowed for unprivileged users, but only in the
4119 // context of processes which they own.
4120 emit_process_owner_assertion (o);
4121 return;
4122 }
4123
4124 // Other probes must contain the default assertion which aborts
4125 // if executed by an unprivileged user.
4126 derived_probe::emit_unprivileged_assertion (o);
4127}
4128
4129
4130void
4131dwarf_derived_probe::print_dupe_stamp(ostream& o)
4132{
4133 if (has_process)
4134 {
4135 // These probes are allowed for unprivileged users, but only in the
4136 // context of processes which they own.
4137 print_dupe_stamp_unprivileged_process_owner (o);
4138 return;
4139 }
4140
4141 // Other probes must contain the default dupe stamp
4142 derived_probe::print_dupe_stamp (o);
4143}
4144
64211010 4145
7a053d3b 4146void
20c6c071 4147dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1
DB
4148 dwarf_builder * dw,
4149 bool bind_unprivileged_p)
bd2b1e68 4150{
27dc09b1
DB
4151 root
4152 ->bind_unprivileged(bind_unprivileged_p)
4153 ->bind(dw);
54efe513
GH
4154}
4155
7a053d3b 4156void
fd6602a0 4157dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1
DB
4158 dwarf_builder * dw,
4159 bool bind_unprivileged_p)
2865d17a 4160{
27dc09b1
DB
4161 root
4162 ->bind_unprivileged(bind_unprivileged_p)
4163 ->bind(dw);
4164 root->bind(TOK_INLINE)
4165 ->bind_unprivileged(bind_unprivileged_p)
4166 ->bind(dw);
4167 root->bind(TOK_CALL)
4168 ->bind_unprivileged(bind_unprivileged_p)
4169 ->bind(dw);
4170 root->bind(TOK_RETURN)
4171 ->bind_unprivileged(bind_unprivileged_p)
4172 ->bind(dw);
4173 root->bind(TOK_RETURN)
4174 ->bind_unprivileged(bind_unprivileged_p)
4175 ->bind_num(TOK_MAXACTIVE)->bind(dw);
bd2b1e68
GH
4176}
4177
7a053d3b 4178void
27dc09b1
DB
4179dwarf_derived_probe::register_function_and_statement_variants(
4180 match_node * root,
4181 dwarf_builder * dw,
4182 bool bind_unprivileged_p
4183)
bd2b1e68
GH
4184{
4185 // Here we match 4 forms:
4186 //
4187 // .function("foo")
4188 // .function(0xdeadbeef)
4189 // .statement("foo")
4190 // .statement(0xdeadbeef)
4191
27dc09b1
DB
4192 register_function_variants(root->bind_str(TOK_FUNCTION), dw, bind_unprivileged_p);
4193 register_function_variants(root->bind_num(TOK_FUNCTION), dw, bind_unprivileged_p);
4194 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, bind_unprivileged_p);
4195 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, bind_unprivileged_p);
bd2b1e68
GH
4196}
4197
4198void
c4ce66a1 4199dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4200{
c4ce66a1 4201 match_node* root = s.pattern_root;
bd2b1e68
GH
4202 dwarf_builder *dw = new dwarf_builder();
4203
c4ce66a1
JS
4204 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4205 s.code_filters.push_back(filter);
4206
27dc09b1
DB
4207 register_function_and_statement_variants(root->bind(TOK_KERNEL), dw);
4208 register_function_and_statement_variants(root->bind_str(TOK_MODULE), dw);
4209
4210 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4211 ->bind(dw);
4212 root->bind(TOK_KERNEL)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4213 ->bind(dw);
d2c9ec9b 4214
2cab6244
JS
4215 root->bind_str(TOK_MODULE)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4216 ->bind(dw);
4217
27dc09b1
DB
4218 register_function_and_statement_variants(root->bind_str(TOK_PROCESS), dw,
4219 true/*bind_unprivileged*/);
6d5d594e
LB
4220 register_function_and_statement_variants(root->bind(TOK_PROCESS), dw,
4221 true/*bind_unprivileged*/);
4ad95bbc
SC
4222 register_function_and_statement_variants(root->bind_str(TOK_PROCESS)
4223 ->bind_str(TOK_LIBRARY), dw,
4224 true/*bind_unprivileged*/);
6d5d594e
LB
4225 register_function_and_statement_variants(root->bind(TOK_PROCESS)
4226 ->bind_str(TOK_LIBRARY), dw,
4227 true/*bind_unprivileged*/);
4ad95bbc 4228
d2c9ec9b 4229 root->bind_str(TOK_PROCESS)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
27dc09b1 4230 ->bind_unprivileged()
d2c9ec9b 4231 ->bind(dw);
6d5d594e
LB
4232 root->bind(TOK_PROCESS)->bind_str(TOK_FUNCTION)->bind_str(TOK_LABEL)
4233 ->bind_unprivileged()
4234 ->bind(dw);
63b4fd14 4235 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_MARK)
27dc09b1 4236 ->bind_unprivileged()
63b4fd14 4237 ->bind(dw);
6d5d594e
LB
4238 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_MARK)
4239 ->bind_unprivileged()
4240 ->bind(dw);
a794dbeb
FCE
4241 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4242 ->bind_unprivileged()
4243 ->bind(dw);
6d5d594e
LB
4244 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4245 ->bind_unprivileged()
4246 ->bind(dw);
d2c9ec9b 4247 root->bind_str(TOK_PROCESS)->bind_str(TOK_MARK)
27dc09b1 4248 ->bind_unprivileged()
d2c9ec9b 4249 ->bind(dw);
6d5d594e
LB
4250 root->bind(TOK_PROCESS)->bind_str(TOK_MARK)
4251 ->bind_unprivileged()
4252 ->bind(dw);
a794dbeb
FCE
4253 root->bind_str(TOK_PROCESS)->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
4254 ->bind_unprivileged()
4255 ->bind(dw);
bd2b1e68
GH
4256}
4257
9020300d
FCE
4258void
4259dwarf_derived_probe::emit_probe_local_init(translator_output * o)
4260{
b95e2b79
MH
4261 if (access_vars)
4262 {
4263 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4264 o->newline() << "#if defined __ia64__";
b95e2b79 4265 o->newline() << "bspcache(c->unwaddr, c->regs);";
d4670309 4266 o->newline() << "#endif";
b95e2b79 4267 }
9020300d 4268}
2930abc7 4269
b20febf3 4270// ------------------------------------------------------------------------
46b84a80
DS
4271
4272void
b20febf3 4273dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4274{
62f52bb0
JS
4275 if (p->sdt_semaphore_addr != 0)
4276 has_semaphores = true;
b20febf3 4277 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4278
4279 // XXX: probes put at the same address should all share a
4280 // single kprobe/kretprobe, and have their handlers executed
4281 // sequentially.
b55bc428
FCE
4282}
4283
7a053d3b 4284void
775d51e5 4285dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4286{
b20febf3 4287 if (probes_by_module.empty()) return;
2930abc7 4288
775d51e5
DS
4289 s.op->newline() << "/* ---- dwarf probes ---- */";
4290
4291 // Warn of misconfigured kernels
f41595cc
FCE
4292 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4293 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4294 s.op->newline() << "#endif";
775d51e5 4295 s.op->newline();
f41595cc 4296
f07c3b68 4297 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4298 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4299 s.op->newline() << "#endif";
4300
14cf7e42
SC
4301 // Forward decls
4302 s.op->newline() << "#include \"kprobes-common.h\"";
4303
b20febf3
FCE
4304 // Forward declare the master entry functions
4305 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4306 s.op->line() << " struct pt_regs *regs);";
4307 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4308 s.op->line() << " struct pt_regs *regs);";
4309
42cb22bd
MH
4310 // Emit an array of kprobe/kretprobe pointers
4311 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4312 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4313 s.op->newline() << "#endif";
4314
b20febf3 4315 // Emit the actual probe list.
606fd9c8
FCE
4316
4317 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4318 // struct stap_dwarf_probe, but it being initialized data makes it add
4319 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4320 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4321 // NB: bss!
4322
4c2732a1 4323 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4324 s.op->newline(1) << "const unsigned return_p:1;";
4325 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4326 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4327 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4328 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4329
af234c40
JS
4330 // data saved in the kretprobe_instance packet
4331 s.op->newline() << "const unsigned short saved_longs;";
4332 s.op->newline() << "const unsigned short saved_strings;";
4333
faea5e16 4334 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
4335 // are small and uniform enough to justify putting char[MAX]'s into
4336 // the array instead of relocated char*'s.
faea5e16
JS
4337 size_t module_name_max = 0, section_name_max = 0;
4338 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
4339 size_t all_name_cnt = probes_by_module.size(); // for average
4340 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
4341 {
4342 dwarf_derived_probe* p = it->second;
4343#define DOIT(var,expr) do { \
4344 size_t var##_size = (expr) + 1; \
4345 var##_max = max (var##_max, var##_size); \
4346 var##_tot += var##_size; } while (0)
4347 DOIT(module_name, p->module.size());
4348 DOIT(section_name, p->section.size());
606fd9c8
FCE
4349#undef DOIT
4350 }
4351
4352 // Decide whether it's worthwhile to use char[] or char* by comparing
4353 // the amount of average waste (max - avg) to the relocation data size
4354 // (3 native long words).
4355#define CALCIT(var) \
4356 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
4357 { \
4358 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
4359 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
4360 << "[" << var##_name_max << "]" << endl; \
4361 } \
4362 else \
4363 { \
b0986e7a 4364 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
4365 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
4366 }
4367
4368 CALCIT(module);
4369 CALCIT(section);
e6fe60e7 4370#undef CALCIT
606fd9c8 4371
b0986e7a 4372 s.op->newline() << "const unsigned long address;";
26e63673 4373 s.op->newline() << "struct stap_probe * const probe;";
c87ae2c1 4374 s.op->newline() << "struct stap_probe * const entry_probe;";
62f52bb0
JS
4375 if (has_semaphores)
4376 {
4377 s.op->newline() << "const unsigned long sdt_sem_offset;";
4378 s.op->newline() << "unsigned long sdt_sem_address;";
4379 s.op->newline() << "struct task_struct *tsk;";
4380 s.op->newline() << "const char *pathname;";
4381 s.op->newline() << "struct stap_task_finder_target finder;";
4382 }
b20febf3
FCE
4383 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
4384 s.op->indent(1);
4385
4386 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 4387 {
b20febf3
FCE
4388 dwarf_derived_probe* p = it->second;
4389 s.op->newline() << "{";
4390 if (p->has_return)
4391 s.op->line() << " .return_p=1,";
c9bad430 4392 if (p->has_maxactive)
606fd9c8
FCE
4393 {
4394 s.op->line() << " .maxactive_p=1,";
4395 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
4396 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
4397 }
af234c40
JS
4398 if (p->saved_longs || p->saved_strings)
4399 {
4400 if (p->saved_longs)
4401 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
4402 if (p->saved_strings)
4403 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
4404 if (p->entry_handler)
c87ae2c1 4405 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 4406 }
b350f56b
JS
4407 if (p->locations[0]->optional)
4408 s.op->line() << " .optional_p=1,";
dc38c256 4409 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
4410 s.op->line() << " .module=\"" << p->module << "\",";
4411 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 4412 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b642c901
SC
4413 if (p->sdt_semaphore_addr != 0)
4414 {
4415 s.op->line() << " .sdt_sem_offset=(unsigned long)0x" << hex << p->sdt_semaphore_addr << dec << "ULL,";
4416 s.op->line() << " .sdt_sem_address=0,";
4417 if (p->has_library)
4418 {
4419 s.op->line() << " .finder={";
4420 s.op->line() << " .pid=0,";
4421 s.op->line() << " .procname=\"" << p->user_path << "\",";
4422 s.op->line() << " .mmap_callback=&stap_kprobe_mmap_found,";
4423 s.op->line() << " },";
4424 s.op->line() << " .pathname=\"" << p->user_lib << "\",";
4425 }
4426 else
4427 {
4428 s.op->line() << " .finder={";
4429 s.op->line() << " .pid=0,";
4430 s.op->line() << " .procname=\"" << p->user_path << "\",";
4431 s.op->line() << " .callback=&stap_kprobe_process_found,";
4432 s.op->line() << " },";
4433 s.op->line() << " .pathname=\"" << p->user_path << "\",";
4434 }
4435
4436 }
b642c901 4437
b20febf3 4438 s.op->line() << " },";
2930abc7 4439 }
2930abc7 4440
b20febf3
FCE
4441 s.op->newline(-1) << "};";
4442
4443 // Emit the kprobes callback function
4444 s.op->newline();
4445 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4446 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
4447 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
4448 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
4449 // Check that the index is plausible
4450 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4451 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4452 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4453 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4454 s.op->line() << "];";
6eefe942
MW
4455 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
4456 "_STP_PROBE_HANDLER_KPROBE");
b20febf3 4457 s.op->newline() << "c->regs = regs;";
6415ddde
MW
4458
4459 // Make it look like the IP is set as it wouldn't have been replaced
4460 // by a breakpoint instruction when calling real probe handler. Reset
4461 // IP regs on return, so we don't confuse kprobes. PR10458
4462 s.op->newline() << "{";
4463 s.op->indent(1);
4464 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->regs);";
259d54c0 4465 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 4466 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 4467 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4468 s.op->newline(-1) << "}";
4469
b20febf3
FCE
4470 common_probe_entryfn_epilogue (s.op);
4471 s.op->newline() << "return 0;";
4472 s.op->newline(-1) << "}";
4473
4474 // Same for kretprobes
4475 s.op->newline();
af234c40
JS
4476 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
4477 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 4478 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
4479
4480 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 4481 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
4482 // Check that the index is plausible
4483 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4484 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4485 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4486 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4487 s.op->line() << "];";
4488
c87ae2c1
JS
4489 s.op->newline() << "struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
4490 s.op->newline() << "if (sp) {";
4491 s.op->indent(1);
6eefe942
MW
4492 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sp",
4493 "_STP_PROBE_HANDLER_KRETPROBE");
b20febf3 4494 s.op->newline() << "c->regs = regs;";
af234c40
JS
4495
4496 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
4497 s.op->newline() << "c->ips.krp.pi = inst;";
4498 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
4499
4500 // Make it look like the IP is set as it wouldn't have been replaced
4501 // by a breakpoint instruction when calling real probe handler. Reset
4502 // IP regs on return, so we don't confuse kprobes. PR10458
4503 s.op->newline() << "{";
c87ae2c1
JS
4504 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->regs);";
4505 s.op->newline() << "if (entry)";
4506 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
4507 s.op->newline(-1) << "else";
4508 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
4509 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 4510 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4511 s.op->newline(-1) << "}";
4512
b20febf3 4513 common_probe_entryfn_epilogue (s.op);
c87ae2c1 4514 s.op->newline(-1) << "}";
b20febf3
FCE
4515 s.op->newline() << "return 0;";
4516 s.op->newline(-1) << "}";
af234c40
JS
4517
4518 s.op->newline();
4519 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4520 s.op->line() << " struct pt_regs *regs) {";
4521 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
4522 s.op->newline(-1) << "}";
4523
4524 s.op->newline();
4525 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
4526 s.op->line() << " struct pt_regs *regs) {";
4527 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
4528 s.op->newline(-1) << "}";
b642c901 4529
14cf7e42 4530 s.op->newline();
62f52bb0
JS
4531 if (has_semaphores)
4532 s.op->newline() << "#define KPROBES_TASK_FINDER 1";
14cf7e42
SC
4533 s.op->newline() << "#include \"kprobes-common.c\"";
4534 s.op->newline();
20c6c071 4535}
ec4373ff 4536
20c6c071 4537
dc38c0ae 4538void
b20febf3
FCE
4539dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
4540{
62f52bb0 4541 if (has_semaphores) // Ignore if there are no semaphores
b642c901
SC
4542 {
4543 s.op->newline() << "for (i=0; i<ARRAY_SIZE(stap_dwarf_probes); i++) {";
4544 s.op->newline(1) << "int rc;";
4545 s.op->newline() << "struct stap_dwarf_probe *p = &stap_dwarf_probes[i];";
26e63673 4546 s.op->newline() << "probe_point = p->probe->pp;"; // for error messages
b642c901
SC
4547 s.op->newline() << "if (p->sdt_sem_offset) {";
4548 s.op->newline(1) << "rc = stap_register_task_finder_target(&p->finder);";
4549 s.op->newline(-1) << "}";
4550 s.op->newline() << "if (rc) break;";
4551 s.op->newline(-1) << "}";
4552 }
4553
b20febf3
FCE
4554 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4555 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4556 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 4557 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 4558 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 4559 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 4560 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 4561 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 4562 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 4563 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 4564 s.op->newline(-1) << "} else {";
f07c3b68 4565 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 4566 s.op->newline(-1) << "}";
606fd9c8 4567 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 4568 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 4569 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
4570 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4571 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4572 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4573 s.op->newline(-1) << "}";
4574 s.op->newline() << "#endif";
e4cb375f
MH
4575 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4576 s.op->newline() << "#ifdef __ia64__";
4577 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4578 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4579 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4580 s.op->newline() << "if (rc == 0) {";
4581 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4582 s.op->newline() << "if (rc != 0)";
4583 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4584 s.op->newline(-2) << "}";
4585 s.op->newline() << "#else";
606fd9c8 4586 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 4587 s.op->newline() << "#endif";
b20febf3 4588 s.op->newline(-1) << "} else {";
e4cb375f 4589 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
4590 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4591 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
4592 s.op->newline() << "#ifdef __ia64__";
4593 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
4594 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4595 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4596 s.op->newline() << "if (rc == 0) {";
4597 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
4598 s.op->newline() << "if (rc != 0)";
4599 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4600 s.op->newline(-2) << "}";
4601 s.op->newline() << "#else";
606fd9c8 4602 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 4603 s.op->newline() << "#endif";
b20febf3 4604 s.op->newline(-1) << "}";
9063462a
FCE
4605 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
4606 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 4607 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 4608 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 4609 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
4610 // XXX: shall we increment numskipped?
4611 s.op->newline(-1) << "}";
4612
4613#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 4614 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 4615 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
4616 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
4617 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
4618 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
4619 s.op->newline() << "#ifdef __ia64__";
4620 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
4621 s.op->newline() << "#endif";
c48cb0cc
FCE
4622 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
4623 // not run for this early-abort case.
4624 s.op->newline(-1) << "}";
4625 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 4626 s.op->newline(-1) << "}";
9063462a
FCE
4627#endif
4628
b20febf3
FCE
4629 s.op->newline() << "else sdp->registered_p = 1;";
4630 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
4631}
4632
4633
46b84a80 4634void
b20febf3 4635dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 4636{
62f52bb0
JS
4637 if (has_semaphores)
4638 {
4639 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4640 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4641 s.op->newline() << "unsigned short sdt_semaphore = 0;"; // NB: fixed size
4642 s.op->newline() << "if (sdp->sdt_sem_address && __access_process_vm_noflush (sdp->tsk, sdp->sdt_sem_address, &sdt_semaphore, sizeof (sdt_semaphore), 0)) {";
4643 s.op->newline(1) << "sdt_semaphore --;";
4644 s.op->newline() << "__access_process_vm_noflush (sdp->tsk, sdp->sdt_sem_address, &sdt_semaphore, sizeof (sdt_semaphore), 1);";
4645 s.op->newline(-1) << "}";
4646 s.op->newline(-1) << "}";
4647 }
b642c901 4648
42cb22bd
MH
4649 //Unregister kprobes by batch interfaces.
4650 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4651 s.op->newline() << "j = 0;";
4652 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4653 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4654 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4655 s.op->newline() << "if (! sdp->registered_p) continue;";
4656 s.op->newline() << "if (!sdp->return_p)";
4657 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
4658 s.op->newline(-2) << "}";
4659 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
4660 s.op->newline() << "j = 0;";
4661 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4662 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4663 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4664 s.op->newline() << "if (! sdp->registered_p) continue;";
4665 s.op->newline() << "if (sdp->return_p)";
4666 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
4667 s.op->newline(-2) << "}";
4668 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
4669 s.op->newline() << "#ifdef __ia64__";
4670 s.op->newline() << "j = 0;";
4671 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4672 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4673 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4674 s.op->newline() << "if (! sdp->registered_p) continue;";
4675 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
4676 s.op->newline(-1) << "}";
4677 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
4678 s.op->newline() << "#endif";
42cb22bd
MH
4679 s.op->newline() << "#endif";
4680
b20febf3
FCE
4681 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4682 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4683 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
4684 s.op->newline() << "if (! sdp->registered_p) continue;";
4685 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 4686 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 4687 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 4688 s.op->newline() << "#endif";
606fd9c8 4689 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
73209876
FCE
4690 s.op->newline() << "#ifdef STP_TIMING";
4691 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 4692 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 4693 s.op->newline(-1) << "#endif";
606fd9c8 4694 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
73209876
FCE
4695 s.op->newline() << "#ifdef STP_TIMING";
4696 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 4697 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 4698 s.op->newline(-1) << "#endif";
557fb7a8 4699 s.op->newline(-1) << "} else {";
42cb22bd 4700 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 4701 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 4702 s.op->newline() << "#endif";
606fd9c8 4703 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
73209876
FCE
4704 s.op->newline() << "#ifdef STP_TIMING";
4705 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 4706 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 4707 s.op->newline(-1) << "#endif";
b20febf3 4708 s.op->newline(-1) << "}";
e4cb375f
MH
4709 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
4710 s.op->newline() << "unregister_kprobe (&kp->dummy);";
4711 s.op->newline() << "#endif";
b20febf3
FCE
4712 s.op->newline() << "sdp->registered_p = 0;";
4713 s.op->newline(-1) << "}";
46b84a80
DS
4714}
4715
8aabf152
FCE
4716
4717struct sdt_kprobe_var_expanding_visitor: public var_expanding_visitor
4718{
4719 sdt_kprobe_var_expanding_visitor(const string & process_name,
4720 const string & provider_name,
4721 const string & probe_name,
4722 const string & arg_string,
4723 int arg_count):
4724 process_name (process_name), provider_name (provider_name), probe_name (probe_name),
4725 arg_count (arg_count)
4726 {
4727 tokenize(arg_string, arg_tokens, " ");
822a6a3d 4728 assert(arg_count <= 10);
8aabf152
FCE
4729 }
4730 const string & process_name;
4731 const string & provider_name;
4732 const string & probe_name;
4733 int arg_count;
4734 vector<string> arg_tokens;
4735
4736 void visit_target_symbol (target_symbol* e);
4737};
4738
4739
aff5d390 4740struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 4741{
ae1418f0 4742 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
4743 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
4744 int elf_machine,
4745 const string & process_name,
a794dbeb 4746 const string & provider_name,
aff5d390 4747 const string & probe_name,
71e5e13d 4748 stap_sdt_probe_type probe_type,
aff5d390 4749 const string & arg_string,
8aabf152 4750 int ac):
332ba7e7 4751 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
4752 provider_name (provider_name), probe_name (probe_name),
4753 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 4754 {
f83336a5
FCE
4755 /* Register name mapping table depends on the elf machine of this particular
4756 probe target process/file, not upon the host. So we can't just
4757 #ifdef _i686_ etc. */
ae1418f0
FCE
4758
4759#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 4760 if (elf_machine == EM_X86_64) {
46a94997
SC
4761 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
4762 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
4763 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
4764 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
4765 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
4766 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
4767 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
4768 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
4769 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
4770 DRI ("%sil", 4, QI);
4771 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
4772 DRI ("%dil", 5, QI);
4773 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
4774 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
4775 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
4776 DRI ("%r8b", 8, QI);
4777 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
4778 DRI ("%r9b", 9, QI);
4779 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
4780 DRI ("%r10b", 10, QI);
4781 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
4782 DRI ("%r11b", 11, QI);
4783 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
4784 DRI ("%r12b", 12, QI);
4785 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
4786 DRI ("%r13b", 13, QI);
4787 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
4788 DRI ("%r14b", 14, QI);
4789 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
4790 DRI ("%r15b", 15, QI);
f83336a5 4791 } else if (elf_machine == EM_386) {
46a94997
SC
4792 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
4793 DRI ("%ah", 0, QIh);
4794 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
4795 DRI ("%ch", 1, QIh);
4796 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
4797 DRI ("%dh", 2, QIh);
4798 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
4799 DRI ("%bh", 3, QIh);
4800 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
4801 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
4802 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
4803 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 4804 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
4805 DRI ("%r0", 0, DI);
4806 DRI ("%r1", 1, DI);
4807 DRI ("%r2", 2, DI);
4808 DRI ("%r3", 3, DI);
4809 DRI ("%r4", 4, DI);
4810 DRI ("%r5", 5, DI);
4811 DRI ("%r6", 6, DI);
4812 DRI ("%r7", 7, DI);
4813 DRI ("%r8", 8, DI);
4814 DRI ("%r9", 9, DI);
4815 DRI ("%r10", 10, DI);
4816 DRI ("%r11", 11, DI);
4817 DRI ("%r12", 12, DI);
4818 DRI ("%r13", 13, DI);
4819 DRI ("%r14", 14, DI);
4820 DRI ("%r15", 15, DI);
4821 DRI ("%r16", 16, DI);
4822 DRI ("%r17", 17, DI);
4823 DRI ("%r18", 18, DI);
4824 DRI ("%r19", 19, DI);
4825 DRI ("%r20", 20, DI);
4826 DRI ("%r21", 21, DI);
4827 DRI ("%r22", 22, DI);
4828 DRI ("%r23", 23, DI);
4829 DRI ("%r24", 24, DI);
4830 DRI ("%r25", 25, DI);
4831 DRI ("%r26", 26, DI);
4832 DRI ("%r27", 27, DI);
4833 DRI ("%r28", 28, DI);
4834 DRI ("%r29", 29, DI);
4835 DRI ("%r30", 30, DI);
4836 DRI ("%r31", 31, DI);
8aabf152 4837 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
4838 DRI ("0", 0, DI);
4839 DRI ("1", 1, DI);
4840 DRI ("2", 2, DI);
4841 DRI ("3", 3, DI);
4842 DRI ("4", 4, DI);
4843 DRI ("5", 5, DI);
4844 DRI ("6", 6, DI);
4845 DRI ("7", 7, DI);
4846 DRI ("8", 8, DI);
4847 DRI ("9", 9, DI);
4848 DRI ("10", 10, DI);
4849 DRI ("11", 11, DI);
4850 DRI ("12", 12, DI);
4851 DRI ("13", 13, DI);
4852 DRI ("14", 14, DI);
4853 DRI ("15", 15, DI);
4854 DRI ("16", 16, DI);
4855 DRI ("17", 17, DI);
4856 DRI ("18", 18, DI);
4857 DRI ("19", 19, DI);
4858 DRI ("20", 20, DI);
4859 DRI ("21", 21, DI);
4860 DRI ("22", 22, DI);
4861 DRI ("23", 23, DI);
4862 DRI ("24", 24, DI);
4863 DRI ("25", 25, DI);
4864 DRI ("26", 26, DI);
4865 DRI ("27", 27, DI);
4866 DRI ("28", 28, DI);
4867 DRI ("29", 29, DI);
4868 DRI ("30", 30, DI);
4869 DRI ("31", 31, DI);
14900130 4870 } else if (elf_machine == EM_S390) {
46a94997
SC
4871 DRI ("%r0", 0, DI);
4872 DRI ("%r1", 1, DI);
4873 DRI ("%r2", 2, DI);
4874 DRI ("%r3", 3, DI);
4875 DRI ("%r4", 4, DI);
4876 DRI ("%r5", 5, DI);
4877 DRI ("%r6", 6, DI);
4878 DRI ("%r7", 7, DI);
4879 DRI ("%r8", 8, DI);
4880 DRI ("%r9", 9, DI);
4881 DRI ("%r10", 10, DI);
4882 DRI ("%r11", 11, DI);
4883 DRI ("%r12", 12, DI);
4884 DRI ("%r13", 13, DI);
4885 DRI ("%r14", 14, DI);
4886 DRI ("%r15", 15, DI);
14900130 4887 } else if (arg_count) {
8aabf152 4888 /* permit this case; just fall back to dwarf */
f83336a5 4889 }
ae1418f0 4890#undef DRI
f83336a5 4891
ebbd2b45 4892 need_debug_info = false;
aff5d390 4893 tokenize(arg_string, arg_tokens, " ");
822a6a3d 4894 assert(arg_count <= 10);
a8ec7719 4895 }
8aabf152 4896
f83336a5 4897 systemtap_session& session;
332ba7e7 4898 int elf_machine;
aff5d390 4899 const string & process_name;
a794dbeb 4900 const string & provider_name;
aff5d390 4901 const string & probe_name;
71e5e13d 4902 stap_sdt_probe_type probe_type;
8aabf152 4903 unsigned arg_count;
aff5d390 4904 vector<string> arg_tokens;
46a94997 4905 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 4906 bool need_debug_info;
aff5d390
SC
4907
4908 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
4909 void visit_target_symbol_arg (target_symbol* e);
4910 void visit_target_symbol_context (target_symbol* e);
aff5d390
SC
4911};
4912
7a05f484
SC
4913
4914void
6ef331c8 4915sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 4916{
6ef331c8 4917 if (e->addressof)
b530b5b3 4918 throw semantic_error(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
4919
4920 if (e->name == "$$name")
7a05f484 4921 {
6ef331c8
SC
4922 literal_string *myname = new literal_string (probe_name);
4923 myname->tok = e->tok;
4924 provide(myname);
4925 return;
4926 }
7a05f484 4927
6ef331c8
SC
4928 else if (e->name == "$$provider")
4929 {
4930 literal_string *myname = new literal_string (provider_name);
4931 myname->tok = e->tok;
4932 provide(myname);
4933 return;
4934 }
a794dbeb 4935
6ef331c8
SC
4936 else if (e->name == "$$vars" || e->name == "$$parms")
4937 {
4938 e->assert_no_components("sdt", true);
822a6a3d 4939 assert(arg_count <= 10);
6ef331c8
SC
4940
4941 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
4942 // NB: we synthesize a new token here rather than reusing
4943 // e->tok, because print_format::print likes to use
4944 // its tok->content.
4945 token* pf_tok = new token(*e->tok);
4946 pf_tok->content = "sprintf";
63ea4244 4947
6ef331c8
SC
4948 print_format* pf = print_format::create(pf_tok);
4949
4950 for (unsigned i = 1; i <= arg_count; ++i)
4951 {
4952 if (i > 1)
4953 pf->raw_components += " ";
4954 target_symbol *tsym = new target_symbol;
4955 tsym->tok = e->tok;
4956 tsym->name = "$arg" + lex_cast(i);
4957 pf->raw_components += tsym->name;
4958 tsym->components = e->components;
4959
4960 expression *texp = require (tsym);
4961 if (!e->components.empty() &&
4962 e->components[0].type == target_symbol::comp_pretty_print)
4963 pf->raw_components += "=%s";
4964 else
4965 pf->raw_components += "=%#x";
4966 pf->args.push_back(texp);
4967 }
4968
4969 pf->components = print_format::string_to_components(pf->raw_components);
4970 provide (pf);
4971 }
4972 else
4973 assert(0); // shouldn't get here
4974}
4975
4976
4977void
4978sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
4979{
4980 try
4981 {
8aabf152 4982 unsigned argno = 0; // the N in $argN
c69a87e0 4983 try
aff5d390 4984 {
5ecaa5a7 4985 if (startswith(e->name, "$arg"))
8aabf152 4986 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 4987 }
c69a87e0 4988 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 4989 {
8aabf152 4990 argno = 0;
aff5d390 4991 }
5ecaa5a7 4992
8aabf152
FCE
4993 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
4994 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 4995 {
8aabf152
FCE
4996 // NB: Either
4997 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
4998 // 2) uprobe2_type $FOO (no probe args)
4999 // both of which get resolved later.
5000 need_debug_info = true;
5001 provide(e);
5002 return;
aff5d390 5003 }
277c21bc 5004
8aabf152
FCE
5005 assert (arg_tokens.size() >= argno);
5006 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5007
8aabf152
FCE
5008 // Now we try to parse this thing, which is an assembler operand
5009 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5010 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5011 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
b874bd52
SC
5012 // literal reg reg reg +
5013 // indirect offset
5014 // x86 $N %rR (%rR) N(%rR)
5015 // power iN R (R) N(R)
5016 // ia64 N rR [r16]
5017 // s390 N %rR 0(rR) N(r15)
5018 // arm #N rR [rR] [rR, #N]
5019
8aabf152
FCE
5020 expression* argexpr = 0; // filled in in case of successful parse
5021
5022 string percent_regnames;
5023 string regnames;
5024 vector<string> matches;
71e5e13d 5025 long precision;
8aabf152
FCE
5026 int rc;
5027
40fe32e0
SC
5028 // Parse the leading length
5029
5030 if (asmarg.find('@') != string::npos)
5031 {
5032 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5033 asmarg = asmarg.substr(asmarg.find('@')+1);
5034 }
71e5e13d
SC
5035 else
5036 {
5037 // V1/V2 do not have precision field so default to signed long
5038 // V3 asm does not have precision field so default to unsigned long
5039 if (probe_type == uprobe3_type)
5040 precision = sizeof(long); // this is an asm probe
5041 else
5042 precision = -sizeof(long);
5043 }
40fe32e0 5044
8aabf152
FCE
5045 // test for a numeric literal.
5046 // Only accept (signed) decimals throughout. XXX
5047
5048 // PR11821. NB: on powerpc, literals are not prefixed with $,
5049 // so this regex does not match. But that's OK, since without
5050 // -mregnames, we can't tell them apart from register numbers
5051 // anyway. With -mregnames, we could, if gcc somehow
5052 // communicated to us the presence of that option, but alas it
5053 // doesn't. http://gcc.gnu.org/PR44995.
9109f487 5054 rc = regexp_match (asmarg, "^[i\\$][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5055 if (! rc)
5056 {
75a371ce
JS
5057 string sn = matches[0].substr(1);
5058 int64_t n;
5059 try
5060 {
5061 // We have to pay attention to the size & sign, as gcc sometimes
5062 // propagates constants that don't quite match, like a negative
5063 // value to fill an unsigned type.
5064 switch (precision)
5065 {
5066 case -1: n = lex_cast< int8_t>(sn); break;
5067 case 1: n = lex_cast< uint8_t>(sn); break;
5068 case -2: n = lex_cast< int16_t>(sn); break;
5069 case 2: n = lex_cast<uint16_t>(sn); break;
5070 case -4: n = lex_cast< int32_t>(sn); break;
5071 case 4: n = lex_cast<uint32_t>(sn); break;
5072 default:
5073 case -8: n = lex_cast< int64_t>(sn); break;
5074 case 8: n = lex_cast<uint64_t>(sn); break;
5075 }
5076 }
5077 catch (std::runtime_error&)
5078 {
5079 goto not_matched;
5080 }
5081 literal_number* ln = new literal_number(n);
8aabf152
FCE
5082 ln->tok = e->tok;
5083 argexpr = ln;
5084 goto matched;
5085 }
5086
14900130
SC
5087 if (dwarf_regs.empty())
5088 goto not_matched;
d5b83cee 5089
8aabf152
FCE
5090 // Build regex pieces out of the known dwarf_regs. We keep two separate
5091 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5092 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5093 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5094 {
5095 string regname = ri->first;
5096 assert (regname != "");
5097 regnames += string("|")+regname;
5098 if (regname[0]=='%')
5099 percent_regnames += string("|")+regname;
5100 }
5101 // clip off leading |
5102 regnames = regnames.substr(1);
5103 percent_regnames = percent_regnames.substr(1);
5104
5105 // test for REGISTER
5106 // NB: Because PR11821, we must use percent_regnames here.
332ba7e7 5107 if (elf_machine == EM_PPC || elf_machine == EM_PPC64)
9109f487
SC
5108 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5109 else
332ba7e7 5110 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5111 if (! rc)
5112 {
5113 string regname = matches[1];
46a94997
SC
5114 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5115 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5116 {
5117 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5118 string width_adjust;
46a94997 5119 switch (ri->second.second)
19c22e1f 5120 {
892ec39a
SC
5121 case QI: width_adjust = ") & 0xff)"; break;
5122 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5123 case HI:
71e5e13d 5124 // preserve 16 bit register signness
892ec39a
SC
5125 width_adjust = ") & 0xffff)";
5126 if (precision < 0)
55b377f4 5127 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5128 break;
5129 case SI:
5130 // preserve 32 bit register signness
892ec39a
SC
5131 width_adjust = ") & 0xffffffff)";
5132 if (precision < 0)
55b377f4 5133 width_adjust += " << 32 >> 32";
19c22e1f 5134 break;
892ec39a 5135 default: width_adjust = "))";
19c22e1f 5136 }
55b377f4
SC
5137 string type = "";
5138 if (probe_type == uprobe3_type)
5139 type = (precision < 0
5140 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5141 type = type + "((";
8aabf152
FCE
5142 get_arg1->tok = e->tok;
5143 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5144 + string(" ((int64_t)") + type
8aabf152
FCE
5145 + (is_user_module (process_name)
5146 ? string("u_fetch_register(")
5147 : string("k_fetch_register("))
46a94997 5148 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5149 + width_adjust;
8aabf152
FCE
5150 argexpr = get_arg1;
5151 goto matched;
5152 }
5153 // invalid register name, fall through
5154 }
40fe32e0 5155
e5b7b83f 5156 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5157 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f
SC
5158 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
5159 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-]?[0-9]*)([+-]?[0-9]*)[(](")+regnames+string(")[)]$"), matches);
8aabf152
FCE
5160 if (! rc)
5161 {
e5b7b83f 5162 string regname;
8aabf152 5163 int64_t disp = 0;
e5b7b83f
SC
5164
5165 int idx;
5166 for (idx = matches.size() - 1; idx > 0; idx--)
5167 if (matches[idx].length())
5168 {
5169 regname = matches[idx];
5170 break;
5171 }
5172
5173 for (int i=1; i < idx; i++)
5174 if (matches[i].length())
5175 try
5176 {
5177 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5178 }
8aabf152
FCE
5179 catch (const runtime_error& f) // unparseable offset
5180 {
5181 goto not_matched; // can't just 'break' out of
5182 // this case or use a sentinel
5183 // value, unfortunately
5184 }
5185
8aabf152
FCE
5186 if (dwarf_regs.find (regname) != dwarf_regs.end()) // known register
5187 {
5188 // synthesize user_long(%{fetch_register(R)%} + D)
40fe32e0 5189
8aabf152
FCE
5190 embedded_expr *get_arg1 = new embedded_expr;
5191 get_arg1->tok = e->tok;
5192 get_arg1->code = string("/* unprivileged */ /* pure */")
5193 + (is_user_module (process_name)
5194 ? string("u_fetch_register(")
5195 : string("k_fetch_register("))
46a94997 5196 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5197 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5198
8aabf152
FCE
5199 literal_number* inc = new literal_number(disp);
5200 inc->tok = e->tok;
40fe32e0 5201
8aabf152
FCE
5202 binary_expression *be = new binary_expression;
5203 be->tok = e->tok;
5204 be->left = get_arg1;
5205 be->op = "+";
5206 be->right = inc;
40fe32e0 5207
8aabf152 5208 functioncall *fc = new functioncall;
40fe32e0
SC
5209 switch (precision)
5210 {
7f6ce9ab
SC
5211 case 1: case -1:
5212 fc->function = "user_int8"; break;
5213 case 2:
5214 fc->function = "user_uint16"; break;
5215 case -2:
5216 fc->function = "user_int16"; break;
5217 case 4:
5218 fc->function = "user_uint32"; break;
5219 case -4:
5220 fc->function = "user_int32"; break;
5221 case 8: case -8:
5222 fc->function = "user_int64"; break;
40fe32e0
SC
5223 default: fc->function = "user_long";
5224 }
8aabf152
FCE
5225 fc->tok = e->tok;
5226 fc->args.push_back(be);
366af4e7 5227
8aabf152
FCE
5228 argexpr = fc;
5229 goto matched;
5230 }
5231 // invalid register name, fall through
5232 }
5233
5234 not_matched:
5235 // The asmarg operand was not recognized. Back down to dwarf.
5236 if (! session.suppress_warnings)
84fef8ee
FCE
5237 {
5238 if (probe_type == UPROBE3_TYPE)
5239 session.print_warning (_F("Can't parse SDT_V3 operand '%s'", asmarg.c_str()), e->tok);
5240 else // must be *PROBE2; others don't get asm operands
5241 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s'",
5242 asmarg.c_str()), e->tok);
5243 }
8aabf152
FCE
5244 assert (argexpr == 0);
5245 need_debug_info = true;
5246 provide (e);
5247 return;
366af4e7 5248
8aabf152
FCE
5249 matched:
5250 assert (argexpr != 0);
366af4e7
RM
5251
5252 if (session.verbose > 2)
1e41115c 5253 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 5254 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 5255
aff5d390 5256 if (e->components.empty()) // We have a scalar
8aabf152
FCE
5257 {
5258 if (e->addressof)
b530b5b3 5259 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
5260 provide (argexpr);
5261 return;
5262 }
5263 else // $var->foo
5264 {
5265 cast_op *cast = new cast_op;
5266 cast->name = "@cast";
5267 cast->tok = e->tok;
5268 cast->operand = argexpr;
5269 cast->components = e->components;
5270 cast->type_name = probe_name + "_arg" + lex_cast(argno);
5271 cast->module = process_name;
5272 cast->visit(this);
5273 return;
5274 }
366af4e7 5275
8aabf152 5276 /* NOTREACHED */
aff5d390
SC
5277 }
5278 catch (const semantic_error &er)
5279 {
5280 e->chain (er);
5281 provide (e);
5282 }
5283}
5284
5285
6ef331c8
SC
5286void
5287sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
5288{
5289 try
5290 {
5291 assert(e->name.size() > 0 && e->name[0] == '$');
5292
5293 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
5294 visit_target_symbol_context (e);
5295 else
5296 visit_target_symbol_arg (e);
5297 }
5298 catch (const semantic_error &er)
5299 {
5300 e->chain (er);
5301 provide (e);
5302 }
5303}
5304
5305
aff5d390
SC
5306void
5307sdt_kprobe_var_expanding_visitor::visit_target_symbol (target_symbol *e)
5308{
5309 try
5310 {
277c21bc 5311 if (e->name == "$$name")
aff5d390
SC
5312 {
5313 if (e->addressof)
b530b5b3 5314 throw semantic_error(_("cannot take address of sdt context variable"), e->tok);
aff5d390
SC
5315
5316 literal_string *myname = new literal_string (probe_name);
5317 myname->tok = e->tok;
5318 provide(myname);
5319 return;
5320 }
277c21bc 5321 if (e->name == "$$provider")
a794dbeb
FCE
5322 {
5323 if (e->addressof)
b530b5b3 5324 throw semantic_error(_("cannot take address of sdt context variable"), e->tok);
a794dbeb
FCE
5325
5326 literal_string *myname = new literal_string (provider_name);
5327 myname->tok = e->tok;
5328 provide(myname);
5329 return;
5330 }
aff5d390 5331
5ecaa5a7 5332 int argno = -1;
aff5d390
SC
5333 try
5334 {
5ecaa5a7
JS
5335 if (startswith(e->name, "$arg"))
5336 argno = lex_cast<int>(e->name.substr(4));
aff5d390
SC
5337 }
5338 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
5339 {
aff5d390 5340 }
5ecaa5a7 5341 if (argno < 0)
b530b5b3 5342 throw semantic_error(_("invalid variable, must be of the form $argN"), e->tok);
aff5d390 5343 if (argno < 1 || argno > arg_count)
b530b5b3 5344 throw semantic_error(_("invalid argument number"), e->tok);
5ecaa5a7 5345
c69a87e0
FCE
5346 bool lvalue = is_active_lvalue(e);
5347 functioncall *fc = new functioncall;
63ea4244 5348
c69a87e0
FCE
5349 // First two args are hidden: 1. pointer to probe name 2. task id
5350 if (arg_count < 2)
aff5d390 5351 {
71e5e13d 5352 fc->function = "long_arg";
aff5d390
SC
5353 fc->type = pe_long;
5354 fc->tok = e->tok;
5355 // skip the hidden args
5356 literal_number* num = new literal_number(argno + 2);
5357 num->tok = e->tok;
5358 fc->args.push_back(num);
5359 }
5360 else
5361 {
5362 // args are passed in arg3 as members of a struct
5363 fc->function = "user_long";
5364 fc->tok = e->tok;
5365 binary_expression *be = new binary_expression;
5366 be->tok = e->tok;
5367 functioncall *get_arg1 = new functioncall;
5368 get_arg1->function = "pointer_arg";
5369 get_arg1->tok = e->tok;
5370 // arg3 is the pointer to a struct of arguments
c57ea854 5371 literal_number* num = new literal_number(3);
aff5d390
SC
5372 num->tok = e->tok;
5373 get_arg1->args.push_back(num);
5374
5375 be->left = get_arg1;
5376 be->op = "+";
5377 // offset in struct to the desired arg
5378 literal_number* inc = new literal_number((argno - 1) * 8);
5379 inc->tok = e->tok;
5380 be->right = inc;
5381 fc->args.push_back(be);
5382 }
c69a87e0 5383 if (lvalue)
aff5d390 5384 *(target_symbol_setter_functioncalls.top()) = fc;
63ea4244 5385
aff5d390
SC
5386 if (e->components.empty()) // We have a scalar
5387 {
5388 if (e->addressof)
b530b5b3 5389 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
63ea4244 5390
aff5d390
SC
5391 provide(fc);
5392 return;
5393 }
c69a87e0 5394 cast_op *cast = new cast_op;
277c21bc 5395 cast->name = "@cast";
c69a87e0
FCE
5396 cast->tok = e->tok;
5397 cast->operand = fc;
5398 cast->components = e->components;
7f6b80bd 5399 cast->type_name = probe_name + "_arg" + lex_cast(argno);
c69a87e0 5400 cast->module = process_name;
63ea4244 5401
c69a87e0 5402 cast->visit(this);
7a05f484 5403 }
c69a87e0 5404 catch (const semantic_error &er)
ad002306 5405 {
1af1e62d 5406 e->chain (er);
c69a87e0 5407 provide (e);
ad002306 5408 }
7a05f484 5409}
46b84a80 5410
277c21bc 5411
edce5b67
JS
5412struct sdt_query : public base_query
5413{
5414 sdt_query(probe * base_probe, probe_point * base_loc,
5415 dwflpp & dw, literal_map_t const & params,
51d6bda3 5416 vector<derived_probe *> & results, const string user_lib);
edce5b67 5417
51d6bda3 5418 void query_library (const char *data);
edce5b67
JS
5419 void handle_query_module();
5420
5421private:
15284963 5422 stap_sdt_probe_type probe_type;
9109f487 5423 enum {probe_section=0, note_section=1} probe_loc;
edce5b67
JS
5424 probe * base_probe;
5425 probe_point * base_loc;
6846cfc8 5426 literal_map_t const & params;
edce5b67 5427 vector<derived_probe *> & results;
a794dbeb
FCE
5428 string pp_mark;
5429 string pp_provider;
51d6bda3 5430 string user_lib;
edce5b67
JS
5431
5432 set<string> probes_handled;
5433
5434 Elf_Data *pdata;
5435 size_t probe_scn_offset;
5436 size_t probe_scn_addr;
aff5d390 5437 uint64_t arg_count;
40fe32e0 5438 GElf_Addr base;
c57ea854 5439 GElf_Addr pc;
aff5d390 5440 string arg_string;
edce5b67 5441 string probe_name;
a794dbeb 5442 string provider_name;
79a0ca08 5443 Dwarf_Addr semaphore;
edce5b67
JS
5444
5445 bool init_probe_scn();
6b51ee12 5446 bool get_next_probe();
c57ea854
SC
5447 void iterate_over_probe_entries();
5448 void handle_probe_entry();
edce5b67 5449
40fe32e0
SC
5450 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
5451 void setup_note_probe_entry (int type, const char *data, size_t len);
5452
edce5b67 5453 void convert_probe(probe *base);
4ddb6dd0 5454 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 5455 probe* convert_location();
40fe32e0 5456 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
aff5d390 5457 bool have_kprobe() {return probe_type == kprobe1_type || probe_type == kprobe2_type;}
c57ea854
SC
5458 bool have_debuginfo_uprobe(bool need_debug_info)
5459 {return probe_type == uprobe1_type
40fe32e0 5460 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 5461 && need_debug_info);}
40fe32e0 5462 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
5463};
5464
5465
5466sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
5467 dwflpp & dw, literal_map_t const & params,
51d6bda3 5468 vector<derived_probe *> & results, const string user_lib):
edce5b67 5469 base_query(dw, params), base_probe(base_probe),
51d6bda3 5470 base_loc(base_loc), params(params), results(results), user_lib(user_lib)
edce5b67 5471{
a794dbeb
FCE
5472 assert(get_string_param(params, TOK_MARK, pp_mark));
5473 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
5474
ef428667
FCE
5475 // PR10245: permit usage of dtrace-y "-" separator in marker name;
5476 // map it to double-underscores.
5477 size_t pos = 0;
5478 while (1) // there may be more than one
5479 {
a794dbeb 5480 size_t i = pp_mark.find("-", pos);
ef428667 5481 if (i == string::npos) break;
a794dbeb 5482 pp_mark.replace (i, 1, "__");
ef428667
FCE
5483 pos = i+1; // resume searching after the inserted __
5484 }
a794dbeb
FCE
5485
5486 // XXX: same for pp_provider?
edce5b67
JS
5487}
5488
5489
5490void
c57ea854 5491sdt_query::handle_probe_entry()
edce5b67 5492{
c57ea854
SC
5493 if (! have_uprobe()
5494 && !probes_handled.insert(probe_name).second)
edce5b67
JS
5495 return;
5496
5497 if (sess.verbose > 3)
c57ea854 5498 {
b530b5b3
LB
5499 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
5500 //TRANSLATORS: is matched to.
5501 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
5502 switch (probe_type)
5503 {
5504 case uprobe1_type:
5505 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
5506 break;
5507 case uprobe2_type:
5508 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
5509 break;
40fe32e0
SC
5510 case uprobe3_type:
5511 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
5512 break;
c57ea854
SC
5513 case kprobe1_type:
5514 clog << "kprobe1" << endl;
5515 break;
5516 case kprobe2_type:
5517 clog << "kprobe2" << endl;
5518 break;
5519 }
5520 }
edce5b67 5521
c57ea854
SC
5522 // Extend the derivation chain
5523 probe *new_base = convert_location();
5524 probe_point *new_location = new_base->locations[0];
5525
c57ea854
SC
5526 bool need_debug_info = false;
5527
7d395255
JS
5528 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
5529 // or dwfl_module_getelf(...). We only need it for the machine type, which
5530 // should be the same. The bias is used for relocating debuginfoless probes,
5531 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 5532 Dwarf_Addr bias;
7d395255 5533 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854
SC
5534
5535 if (have_kprobe())
edce5b67 5536 {
c57ea854 5537 convert_probe(new_base);
c57ea854
SC
5538 // Expand the local variables in the probe body
5539 sdt_kprobe_var_expanding_visitor svv (module_val,
5540 provider_name,
5541 probe_name,
5542 arg_string,
5543 arg_count);
5544 svv.replace (new_base->body);
5545 }
5546 else
5547 {
5548 /* Figure out the architecture of this particular ELF file.
5549 The dwarfless register-name mappings depend on it. */
5550 GElf_Ehdr ehdr_mem;
5551 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
5552 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
5553 int elf_machine = em->e_machine;
5554 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine,
5555 module_val,
5556 provider_name,
5557 probe_name,
71e5e13d 5558 probe_type,
c57ea854
SC
5559 arg_string,
5560 arg_count);
5561 svv.replace (new_base->body);
5562 need_debug_info = svv.need_debug_info;
5563 }
5564
5565 unsigned i = results.size();
edce5b67 5566
c57ea854
SC
5567 if (have_kprobe())
5568 derive_probes(sess, new_base, results);
5569
5570 else
5571 {
5572 // XXX: why not derive_probes() in the uprobes case too?
5573 literal_map_t params;
5574 for (unsigned i = 0; i < new_location->components.size(); ++i)
39a3e397 5575 {
c57ea854
SC
5576 probe_point::component *c = new_location->components[i];
5577 params[c->functor] = c->arg;
39a3e397 5578 }
30263a73 5579
c57ea854
SC
5580 dwarf_query q(new_base, new_location, dw, params, results, "", "");
5581 q.has_mark = true; // enables mid-statement probing
edce5b67 5582
c57ea854
SC
5583 // V2 probes need dwarf info in case of a variable reference
5584 if (have_debuginfo_uprobe(need_debug_info))
5585 dw.iterate_over_modules(&query_module, &q);
5586 else if (have_debuginfoless_uprobe())
aff5d390 5587 {
c57ea854
SC
5588 string section;
5589 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
5590 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
5591 {
5592 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
5593 section = ".dynamic";
5594 }
5595 else
5596 section = ".absolute";
5597
5598 uprobe_derived_probe* p =
5599 new uprobe_derived_probe ("", "", 0, q.module_val, section,
5600 q.statement_num_val, reloc_addr, q, 0);
5601 p->saveargs (arg_count);
5602 results.push_back (p);
aff5d390 5603 }
c57ea854 5604 }
487bf4e2 5605 sess.unwindsym_modules.insert (dw.module_name);
c57ea854
SC
5606 record_semaphore(results, i);
5607}
edce5b67 5608
4ddb6dd0 5609
c57ea854
SC
5610void
5611sdt_query::handle_query_module()
5612{
5613 if (!init_probe_scn())
5614 return;
edce5b67 5615
c57ea854
SC
5616 if (sess.verbose > 3)
5617 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 5618
40fe32e0
SC
5619 if (probe_loc == note_section)
5620 {
5621 GElf_Shdr shdr_mem;
5622 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
5623
5624 if (shdr)
5625 base = shdr->sh_addr;
5626 else
5627 base = 0;
5628 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
5629 }
5630 else
5631 iterate_over_probe_entries ();
edce5b67
JS
5632}
5633
5634
5635bool
5636sdt_query::init_probe_scn()
5637{
448a86b7 5638 Elf* elf;
edce5b67 5639 GElf_Shdr shdr_mem;
40fe32e0
SC
5640
5641 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
5642 if (shdr)
5643 {
5644 probe_loc = note_section;
5645 return true;
5646 }
edce5b67 5647
448a86b7 5648 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 5649 if (shdr)
edce5b67 5650 {
fea74777
SC
5651 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
5652 probe_scn_offset = 0;
5653 probe_scn_addr = shdr->sh_addr;
5654 assert (pdata != NULL);
5655 if (sess.verbose > 4)
ce0f6648
LB
5656 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
5657 << pdata->d_size << endl;
40fe32e0 5658 probe_loc = probe_section;
fea74777 5659 return true;
edce5b67 5660 }
fea74777 5661 else
edce5b67 5662 return false;
edce5b67
JS
5663}
5664
40fe32e0
SC
5665void
5666sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
5667{
5668 sdt_query *me = (sdt_query*)object;
5669 me->setup_note_probe_entry (type, data, len);
5670}
5671
5672
5673void
5674sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
5675{
5676 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
5677 // && !memcmp (data->d_buf + name_off,
5678 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
5679
5680 // probes are in the .note.stapsdt section
5681#define _SDT_NOTE_TYPE 3
5682 if (type != _SDT_NOTE_TYPE)
5683 return;
5684
5685 union
5686 {
5687 Elf64_Addr a64[3];
5688 Elf32_Addr a32[3];
5689 } buf;
5690 Dwarf_Addr bias;
5691 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
5692 Elf_Data dst =
5693 {
5694 &buf, ELF_T_ADDR, EV_CURRENT,
5695 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
5696 };
5697 assert (dst.d_size <= sizeof buf);
5698
5699 if (len < dst.d_size + 3)
5700 return;
5701
5702 Elf_Data src =
5703 {
5704 (void *) data, ELF_T_ADDR, EV_CURRENT,
5705 dst.d_size, 0, 0
5706 };
5707
5708 if (gelf_xlatetom (elf, &dst, &src,
5709 elf_getident (elf, NULL)[EI_DATA]) == NULL)
5710 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
5711
5712 probe_type = uprobe3_type;
5713 const char * provider = data + dst.d_size;
5714 provider_name = provider;
5715 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
5716 probe_name = ++name;
5717
5718 // Did we find a matching probe?
5719 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
5720 && ((pp_provider == "")
5721 || dw.function_name_matches_pattern (provider_name, pp_provider))))
5722 return;
5723
5724 const char *args = (const char*)memchr (name, '\0', data + len - name);
5725 if (args++ == NULL ||
5726 memchr (args, '\0', data + len - name) != data + len - 1)
5727 if (name == NULL)
5728 return;
5729 arg_string = args;
5730
5731 arg_count = 0;
5732 for (unsigned i = 0; i < arg_string.length(); i++)
5733 if (arg_string[i] == ' ')
5734 arg_count += 1;
5735 if (arg_string.length() != 0)
5736 arg_count += 1;
5737
5738 GElf_Addr base_ref;
5739 if (gelf_getclass (elf) == ELFCLASS32)
5740 {
5741 pc = buf.a32[0];
5742 base_ref = buf.a32[1];
5743 semaphore = buf.a32[2];
5744 }
5745 else
5746 {
5747 pc = buf.a64[0];
5748 base_ref = buf.a64[1];
5749 semaphore = buf.a64[2];
5750 }
5751
5752 semaphore += base - base_ref;
5753 pc += base - base_ref;
5754
7d395255
JS
5755 // The semaphore also needs the ELF bias added now, so
5756 // record_semaphore can properly relocate it later.
5757 semaphore += bias;
5758
40fe32e0 5759 if (sess.verbose > 4)
b530b5b3 5760 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
5761
5762 handle_probe_entry();
5763}
5764
5765
c57ea854
SC
5766void
5767sdt_query::iterate_over_probe_entries()
edce5b67 5768{
c57ea854 5769 // probes are in the .probe section
edce5b67
JS
5770 while (probe_scn_offset < pdata->d_size)
5771 {
aff5d390
SC
5772 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
5773 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 5774 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
aff5d390 5775 if (! have_uprobe() && ! have_kprobe())
edce5b67
JS
5776 {
5777 // Unless this is a mangled .probes section, this happens
5778 // because the name of the probe comes first, followed by
5779 // the sentinel.
5780 if (sess.verbose > 5)
b530b5b3 5781 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
5782 probe_scn_offset += sizeof(__uint32_t);
5783 continue;
5784 }
aff5d390
SC
5785 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
5786 {
5787 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
5788 if (pbe_v1->type_b != uprobe1_type && pbe_v1->type_b != kprobe1_type)
5789 continue;
5790 }
5791
5792 if (probe_type == uprobe1_type || probe_type == kprobe1_type)
5793 {
79a0ca08 5794 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 5795 return;
79a0ca08 5796 semaphore = 0;
aff5d390 5797 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 5798 provider_name = ""; // unknown
aff5d390
SC
5799 if (probe_type == uprobe1_type)
5800 {
5801 pc = pbe_v1->arg;
5802 arg_count = 0;
5803 }
5804 else if (probe_type == kprobe1_type)
5805 arg_count = pbe_v1->arg;
5806 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
5807 }
5808 else if (probe_type == uprobe2_type || probe_type == kprobe2_type)
5809 {
79a0ca08 5810 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 5811 return;
79a0ca08 5812 semaphore = pbe_v2->semaphore;
aff5d390 5813 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 5814 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
5815 arg_count = pbe_v2->arg_count;
5816 pc = pbe_v2->pc;
5817 if (pbe_v2->arg_string)
5818 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
5819 // skip over pbe_v2, probe_name text and provider text
5820 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
5821 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 5822 }
edce5b67 5823 if (sess.verbose > 4)
b530b5b3 5824 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 5825 << "@0x" << hex << pc << dec << endl;
edce5b67 5826
a794dbeb
FCE
5827 if (dw.function_name_matches_pattern (probe_name, pp_mark)
5828 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 5829 handle_probe_entry ();
edce5b67 5830 }
edce5b67
JS
5831}
5832
5833
6846cfc8 5834void
4ddb6dd0 5835sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 5836{
a794dbeb
FCE
5837 for (unsigned i=0; i<2; i++) {
5838 // prefer with-provider symbol; look without provider prefix for backward compatibility only
5839 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
5840 // XXX: multiple addresses?
5841 if (sess.verbose > 2)
b530b5b3 5842 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 5843
79a0ca08
SC
5844 Dwarf_Addr addr;
5845 if (this->semaphore)
5846 addr = this->semaphore;
5847 else
5848 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
5849 if (addr)
5850 {
7d395255 5851 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
5852 dwfl_module_relocate_address (dw.module, &addr);
5853 // XXX: relocation basis?
5854 for (unsigned i = start; i < results.size(); ++i)
5855 results[i]->sdt_semaphore_addr = addr;
5856 if (sess.verbose > 2)
b530b5b3 5857 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
5858 return;
5859 }
5860 else
5861 if (sess.verbose > 2)
b530b5b3 5862 clog << _(", not found") << endl;
a794dbeb 5863 }
6846cfc8
SC
5864}
5865
5866
edce5b67
JS
5867void
5868sdt_query::convert_probe (probe *base)
5869{
5870 block *b = new block;
5871 b->tok = base->body->tok;
5872
5873 // XXX: Does this also need to happen for i386 under x86_64 stap?
ebbd2b45 5874 if (sess.architecture == "i386" && have_kprobe())
edce5b67
JS
5875 {
5876 functioncall *rp = new functioncall;
edce5b67
JS
5877 rp->function = "regparm";
5878 rp->tok = b->tok;
5879 literal_number* littid = new literal_number(0);
5880 littid->tok = b->tok;
5881 rp->args.push_back(littid);
5882 expr_statement* es = new expr_statement;
5883 es->tok = b->tok;
5884 es->value = rp;
5885 b->statements.push_back(es);
5886 }
edce5b67 5887
aff5d390 5888 if (have_kprobe())
edce5b67 5889 {
aff5d390 5890 // Generate: if (arg2 != kprobe2_type) next;
edce5b67
JS
5891 if_statement *istid = new if_statement;
5892 istid->thenblock = new next_statement;
5893 istid->elseblock = NULL;
5894 istid->tok = b->tok;
63ea4244 5895 istid->thenblock->tok = b->tok;
edce5b67
JS
5896 comparison *betid = new comparison;
5897 betid->op = "!=";
5898 betid->tok = b->tok;
5899
5900 functioncall *arg2 = new functioncall;
5901 arg2->function = "ulong_arg";
5902 arg2->tok = b->tok;
5903 literal_number* num = new literal_number(2);
5904 num->tok = b->tok;
5905 arg2->args.push_back(num);
5906
5907 betid->left = arg2;
aff5d390 5908 literal_number* littid = new literal_number(probe_type);
edce5b67
JS
5909 littid->tok = b->tok;
5910 betid->right = littid;
5911 istid->condition = betid;
5912 b->statements.push_back(istid);
5913 }
5914
5915 // Generate: if (arg1 != mark("label")) next;
5916 functioncall *fc = new functioncall;
bbafcb1e 5917 fc->function = "ulong_arg";
edce5b67 5918 fc->tok = b->tok;
bbafcb1e 5919 literal_number* num = new literal_number(1);
edce5b67
JS
5920 num->tok = b->tok;
5921 fc->args.push_back(num);
5922
5923 functioncall *fcus = new functioncall;
5924 fcus->function = "user_string";
5925 fcus->type = pe_string;
5926 fcus->tok = b->tok;
5927 fcus->args.push_back(fc);
5928
5929 if_statement *is = new if_statement;
5930 is->thenblock = new next_statement;
5931 is->elseblock = NULL;
5932 is->tok = b->tok;
63ea4244 5933 is->thenblock->tok = b->tok;
edce5b67
JS
5934 comparison *be = new comparison;
5935 be->op = "!=";
5936 be->tok = b->tok;
5937 be->left = fcus;
5938 be->right = new literal_string(probe_name);
63ea4244 5939 be->right->tok = b->tok;
edce5b67
JS
5940 is->condition = be;
5941 b->statements.push_back(is);
5942
5943 // Now replace the body
5944 b->statements.push_back(base->body);
5945 base->body = b;
5946}
5947
5948
c72aa911
JS
5949probe*
5950sdt_query::convert_location ()
edce5b67 5951{
c72aa911 5952 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 5953 vector<probe_point::component*> derived_comps;
edce5b67 5954
662539d9
JS
5955 vector<probe_point::component*>::iterator it;
5956 for (it = specific_loc->components.begin();
5957 it != specific_loc->components.end(); ++it)
5958 if ((*it)->functor == TOK_PROCESS)
5959 {
5960 if (have_kprobe())
5961 // start the kernel probe_point
5962 derived_comps.push_back(new probe_point::component(TOK_KERNEL));
5963 else
5964 // copy the process name
5965 derived_comps.push_back(*it);
5966 }
5967 else if ((*it)->functor == TOK_LIBRARY)
5968 {
5969 if (!have_kprobe())
5970 // copy the library name for process probes
5971 derived_comps.push_back(*it);
5972 }
5973 else if ((*it)->functor == TOK_PROVIDER)
5974 {
5975 // replace the possibly wildcarded arg with the specific provider name
5976 *it = new probe_point::component(TOK_PROVIDER,
5977 new literal_string(provider_name));
5978 }
5979 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
5980 {
5981 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
5982 *it = new probe_point::component(TOK_MARK,
5983 new literal_string(probe_name));
a794dbeb 5984
aff5d390
SC
5985 if (sess.verbose > 3)
5986 switch (probe_type)
5987 {
5988 case uprobe1_type:
b530b5b3 5989 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
5990 << hex << pc << dec << endl;
5991 break;
5992 case uprobe2_type:
b530b5b3 5993 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
5994 << hex << pc << dec << endl;
5995 break;
40fe32e0 5996 case uprobe3_type:
b530b5b3 5997 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
5998 << hex << pc << dec << endl;
5999 break;
6000 case kprobe1_type:
6001 clog << "probe_type == kprobe1" << endl;
6002 break;
6003 case kprobe2_type:
6004 clog << "probe_type == kprobe2" << endl;
6005 break;
aff5d390 6006 default:
b530b5b3
LB
6007 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6008 pp_mark.c_str()) << endl;
aff5d390
SC
6009 }
6010
c72aa911
JS
6011 switch (probe_type)
6012 {
aff5d390
SC
6013 case uprobe1_type:
6014 case uprobe2_type:
40fe32e0 6015 case uprobe3_type:
c72aa911 6016 // process("executable").statement(probe_arg)
662539d9
JS
6017 derived_comps.push_back
6018 (new probe_point::component(TOK_STATEMENT,
6019 new literal_number(pc, true)));
c72aa911
JS
6020 break;
6021
aff5d390
SC
6022 case kprobe1_type:
6023 case kprobe2_type:
b642c901 6024 // kernel.function("*getegid*")
662539d9
JS
6025 derived_comps.push_back
6026 (new probe_point::component(TOK_FUNCTION,
6027 new literal_string("*getegid*")));
b642c901 6028 break;
c72aa911 6029
a794dbeb 6030 default: // deprecated
c72aa911 6031 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6032 derived_comps.push_back
6033 (new probe_point::component(TOK_FUNCTION,
6034 new literal_string("*")));
6035 derived_comps.push_back
c72aa911 6036 (new probe_point::component(TOK_LABEL,
a794dbeb 6037 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6038 break;
6039 }
6040 }
edce5b67 6041
662539d9
JS
6042 probe_point* derived_loc = new probe_point(*specific_loc);
6043 derived_loc->components = derived_comps;
c72aa911 6044 return base_probe->create_alias(derived_loc, specific_loc);
edce5b67
JS
6045}
6046
6047
51d6bda3
SC
6048void
6049sdt_query::query_library (const char *library)
6050{
6051 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6052}
6053
6054
20c6c071 6055void
5227f1ea 6056dwarf_builder::build(systemtap_session & sess,
7a053d3b 6057 probe * base,
20c6c071 6058 probe_point * location,
86bf665e 6059 literal_map_t const & parameters,
20c6c071
GH
6060 vector<derived_probe *> & finished_results)
6061{
b20febf3
FCE
6062 // NB: the kernel/user dwlfpp objects are long-lived.
6063 // XXX: but they should be per-session, as this builder object
6064 // may be reused if we try to cross-instrument multiple targets.
84048984 6065
7a24d422 6066 dwflpp* dw = 0;
6d5d594e 6067 literal_map_t filled_parameters = parameters;
7a24d422 6068
7a24d422 6069 string module_name;
ae2552da
FCE
6070 if (has_null_param (parameters, TOK_KERNEL))
6071 {
6072 dw = get_kern_dw(sess, "kernel");
6073 }
6074 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6075 {
c523a015
LB
6076 size_t dash_pos = 0;
6077 while((dash_pos=module_name.find('-'))!=string::npos)
6078 module_name.replace(int(dash_pos),1,"_");
6079 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6080 // NB: glob patterns get expanded later, during the offline
6081 // elfutils module listing.
ae2552da 6082 dw = get_kern_dw(sess, module_name);
b8da0ad1 6083 }
6d5d594e 6084 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6085 {
6d5d594e
LB
6086 if(has_null_param(filled_parameters, TOK_PROCESS))
6087 {
6088 wordexp_t words;
6089 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6090 if(rc || words.we_wordc <= 0)
6091 throw semantic_error(_("unspecified process probe is invalid without a -c COMMAND"));
6092 module_name = words.we_wordv[0];
6093 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6094 // in the case of TOK_MARK we need to modify locations as well
6095 if(location->components[0]->functor==TOK_PROCESS &&
6096 location->components[0]->arg == 0)
6097 location->components[0]->arg = new literal_string(module_name);
6098 wordfree (& words);
6099 }
37001baa
FCE
6100 // PR6456 process("/bin/*") glob handling
6101 if (contains_glob_chars (module_name))
6102 {
6103 // Expand glob via rewriting the probe-point process("....")
6104 // parameter, asserted to be the first one.
6105
6106 assert (location->components.size() > 0);
6107 assert (location->components[0]->functor == TOK_PROCESS);
6108 assert (location->components[0]->arg);
6109 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6110 assert (lit);
6111
6112 // Evaluate glob here, and call derive_probes recursively with each match.
6113 glob_t the_blob;
6114 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3
LB
6115 if (rc)
6116 throw semantic_error (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
37001baa
FCE
6117 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6118 {
6119 if (pending_interrupts) return;
6120
6121 const char* globbed = the_blob.gl_pathv[i];
6122 struct stat st;
6123
6124 if (access (globbed, X_OK) == 0
6125 && stat (globbed, &st) == 0
6126 && S_ISREG (st.st_mode)) // see find_executable()
6127 {
7977a734
FCE
6128 // Need to call canonicalize here, in order to path-expand
6129 // patterns like process("stap*"). Otherwise it may go through
6130 // to the next round of expansion as ("stap"), leading to a $PATH
6131 // search that's not consistent with the glob search already done.
6132
6133 char *cf = canonicalize_file_name (globbed);
6134 if (cf) globbed = cf;
6135
37001baa 6136 if (sess.verbose > 1)
ce0f6648 6137 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
b530b5b3 6138 module_name.c_str(), globbed) << endl;
37001baa
FCE
6139 // synthesize a new probe_point, with the glob-expanded string
6140 probe_point *pp = new probe_point (*location);
6141 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
6142 new literal_string (globbed));
6143 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6144 pp->components[0] = ppc;
6145
7977a734
FCE
6146 probe* new_probe = new probe (*base, pp);
6147
6148 // We override "optional = true" here, as if the
6149 // wildcarded probe point was given a "?" suffix.
6150
6151 // This is because wildcard probes will be expected
6152 // by users to apply only to some subset of the
6153 // matching binaries, in the sense of "any", rather
6154 // than "all", sort of similarly how
6155 // module("*").function("...") patterns work.
6156
6157 derive_probes (sess, new_probe, finished_results,
6158 true /* NB: not location->optional */ );
37001baa
FCE
6159 }
6160 }
6161
6162 globfree (& the_blob);
6163 return; // avoid falling through
6164 }
6165
b642c901 6166 user_path = find_executable (module_name); // canonicalize it
d1bcbe71
RH
6167
6168 // if the executable starts with "#!", we look for the interpreter of the script
6169 {
6170 ifstream script_file (user_path.c_str () );
6171
6172 if (script_file.good ())
6173 {
6174 string line;
6175
6176 getline (script_file, line);
6177
6178 if (line.compare (0, 2, "#!") == 0)
6179 {
6180 string path_head = line.substr(2);
6181
6182 // remove white spaces at the beginning of the string
6183 size_t p2 = path_head.find_first_not_of(" \t");
6184
6185 if (p2 != string::npos)
6186 {
6187 string path = path_head.substr(p2);
6188
6189 // remove white spaces at the end of the string
6190 p2 = path.find_last_not_of(" \t\n");
6191 if (string::npos != p2)
6192 path.erase(p2+1);
6193
8e13c1a1
RH
6194 // handle "#!/usr/bin/env" redirect
6195 size_t offset = 0;
6196 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
6197 {
6198 offset = sizeof("/bin/env")-1;
6199 }
6200 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
6201 {
6202 offset = sizeof("/usr/bin/env")-1;
6203 }
6204
6205 if (offset != 0)
6206 {
6207 size_t p3 = path.find_first_not_of(" \t", offset);
6208
6209 if (p3 != string::npos)
6210 {
6211 string env_path = path.substr(p3);
6212 user_path = find_executable (env_path);
6213 }
6214 }
6215 else
6216 {
6217 user_path = find_executable (path);
6218 }
d1bcbe71
RH
6219
6220 struct stat st;
6221
6222 if (access (user_path.c_str(), X_OK) == 0
6223 && stat (user_path.c_str(), &st) == 0
6224 && S_ISREG (st.st_mode)) // see find_executable()
6225 {
6226 if (sess.verbose > 1)
b530b5b3
LB
6227 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6228 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
6229
6230 assert (location->components.size() > 0);
6231 assert (location->components[0]->functor == TOK_PROCESS);
6232 assert (location->components[0]->arg);
6233 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6234 assert (lit);
6235
6236 // synthesize a new probe_point, with the expanded string
6237 probe_point *pp = new probe_point (*location);
6238 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
6239 new literal_string (user_path.c_str()));
6240 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6241 pp->components[0] = ppc;
6242
6243 probe* new_probe = new probe (*base, pp);
6244
6245 derive_probes (sess, new_probe, finished_results);
6246
6247 script_file.close();
6248 return;
6249 }
6250 }
6251 }
6252 }
6253 script_file.close();
6254 }
6255
378d78b5
LB
6256 if(get_param (parameters, TOK_LIBRARY, user_lib)
6257 && user_lib.length() && ! contains_glob_chars (user_lib))
6258 module_name = find_executable (user_lib, "LD_LIBRARY_PATH");
63b4fd14 6259 else
b642c901 6260 module_name = user_path; // canonicalize it
d0a7f5a9 6261
e34d5d13 6262 if (sess.kernel_config["CONFIG_UTRACE"] != string("y"))
b530b5b3 6263 throw semantic_error (_("process probes not available without kernel CONFIG_UTRACE"));
e34d5d13 6264
7a24d422
FCE
6265 // user-space target; we use one dwflpp instance per module name
6266 // (= program or shared library)
707bf35e 6267 dw = get_user_dw(sess, module_name);
c8959a29 6268 }
20c6c071 6269
5896cd05 6270 if (sess.verbose > 3)
b530b5b3 6271 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 6272
a794dbeb
FCE
6273 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
6274 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 6275 {
51d6bda3 6276 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
6277 dw->iterate_over_modules(&query_module, &sdtq);
6278 return;
7a05f484 6279 }
20c6c071 6280
8f14e444 6281 unsigned results_pre = finished_results.size();
6d5d594e 6282 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
6283
6284 // XXX: kernel.statement.absolute is a special case that requires no
6285 // dwfl processing. This code should be in a separate builder.
7a24d422 6286 if (q.has_kernel && q.has_absolute)
37ebca01 6287 {
4baf0e53 6288 // assert guru mode for absolute probes
37ebca01
FCE
6289 if (! q.base_probe->privileged)
6290 {
b530b5b3 6291 throw semantic_error (_("absolute statement probe in unprivileged script"),
edce5b67 6292 q.base_probe->tok);
37ebca01
FCE
6293 }
6294
6295 // For kernel.statement(NUM).absolute probe points, we bypass
6296 // all the debuginfo stuff: We just wire up a
6297 // dwarf_derived_probe right here and now.
4baf0e53 6298 dwarf_derived_probe* p =
b8da0ad1
FCE
6299 new dwarf_derived_probe ("", "", 0, "kernel", "",
6300 q.statement_num_val, q.statement_num_val,
6301 q, 0);
37ebca01 6302 finished_results.push_back (p);
1a0dbc5a 6303 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
6304 return;
6305 }
6306
51178501 6307 dw->iterate_over_modules(&query_module, &q);
8f14e444
FCE
6308
6309
6310 // PR11553 special processing: .return probes requested, but
6311 // some inlined function instances matched.
6312 unsigned i_n_r = q.inlined_non_returnable.size();
6313 unsigned results_post = finished_results.size();
6314 if (i_n_r > 0)
6315 {
6316 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
6317 {
6318 string quicklist;
6319 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6320 it != q.inlined_non_returnable.end();
6321 it++)
6322 {
6323 quicklist += " " + (*it);
6324 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
6325 {
6326 quicklist += " ...";
6327 break;
6328 }
6329 }
c57ea854 6330
b530b5b3
LB
6331 sess.print_warning (_F(ngettext("cannot probe .return of %u inlined function %s",
6332 "cannot probe .return of %u inlined functions %s",
6333 quicklist.size()), i_n_r, quicklist.c_str()));
8f14e444
FCE
6334 // There will be also a "no matches" semantic error generated.
6335 }
6336 if (sess.verbose > 1)
b530b5b3
LB
6337 clog << _F(ngettext("skipped .return probe of %u inlined function",
6338 "skipped .return probe of %u inlined functions", i_n_r), i_n_r) << endl;
8f14e444
FCE
6339 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
6340 {
6341 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6342 it != q.inlined_non_returnable.end();
6343 it++)
6344 clog << (*it) << " ";
6345 clog << endl;
6346 }
6347 } // i_n_r > 0
5f0a03a6
JK
6348}
6349
6350symbol_table::~symbol_table()
6351{
c9efa5c9 6352 delete_map(map_by_addr);
5f0a03a6
JK
6353}
6354
6355void
2867a2a1 6356symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
822a6a3d 6357 Dwarf_Addr addr, Dwarf_Addr */*high_addr*/)
5f0a03a6 6358{
ab91b232
JK
6359#ifdef __powerpc__
6360 // Map ".sys_foo" to "sys_foo".
6361 if (name[0] == '.')
6362 name++;
6363#endif
5f0a03a6
JK
6364 func_info *fi = new func_info();
6365 fi->addr = addr;
6366 fi->name = name;
ab91b232 6367 fi->weak = weak;
2867a2a1 6368 fi->descriptor = descriptor;
5f0a03a6
JK
6369 map_by_name[fi->name] = fi;
6370 // TODO: Use a multimap in case there are multiple static
6371 // functions with the same name?
1c6b77e5 6372 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
6373}
6374
6375enum info_status
6376symbol_table::read_symbols(FILE *f, const string& path)
6377{
6378 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
6379 int ret;
2e67a43b
TM
6380 char *name = 0;
6381 char *mod = 0;
5f0a03a6
JK
6382 char type;
6383 unsigned long long addr;
6384 Dwarf_Addr high_addr = 0;
6385 int line = 0;
6386
6387 // %as (non-POSIX) mallocs space for the string and stores its address.
6388 while ((ret = fscanf(f, "%llx %c %as [%as", &addr, &type, &name, &mod)) > 0)
6389 {
2e67a43b
TM
6390 auto_free free_name(name);
6391 auto_free free_mod(mod);
5f0a03a6
JK
6392 line++;
6393 if (ret < 3)
6394 {
1e41115c 6395 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]",
b530b5b3 6396 line, path.c_str());
5f0a03a6
JK
6397 // Caller should delete symbol_table object.
6398 return info_absent;
6399 }
2e67a43b 6400 else if (ret > 3)
5f0a03a6
JK
6401 {
6402 // Modules are loaded above the kernel, so if we're getting
6403 // modules, we're done.
2e67a43b 6404 break;
5f0a03a6 6405 }
ab91b232 6406 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 6407 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
6408 }
6409
1c6b77e5 6410 if (map_by_addr.size() < 1)
5f0a03a6 6411 {
b530b5b3
LB
6412 cerr << _F("Symbol table error: %s contains no function symbols.",
6413 path.c_str()) << endl;
5f0a03a6
JK
6414 return info_absent;
6415 }
6416 return info_present;
6417}
6418
6419// NB: This currently unused. We use get_from_elf() instead because
6420// that gives us raw addresses -- which we need for modules -- whereas
6421// nm provides the address relative to the beginning of the section.
6422enum info_status
83ca3872
MW
6423symbol_table::read_from_elf_file(const string &path,
6424 const systemtap_session &sess)
5f0a03a6 6425{
58502ae4
JS
6426 vector<string> cmd;
6427 cmd.push_back("/usr/bin/nm");
6428 cmd.push_back("-n");
6429 cmd.push_back("--defined-only");
6430 cmd.push_back("path");
6431
5f0a03a6 6432 FILE *f;
58502ae4
JS
6433 int child_fd;
6434 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
6435 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 6436 {
58502ae4 6437 // nm failures are detected by stap_waitpid
b530b5b3
LB
6438 cerr << _F("Internal error reading symbol table from %s -- %s",
6439 path.c_str(), strerror(errno));
5f0a03a6
JK
6440 return info_absent;
6441 }
6442 enum info_status status = read_symbols(f, path);
58502ae4 6443 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 6444 {
83ca3872 6445 if (status == info_present && ! sess.suppress_warnings)
b530b5b3 6446 cerr << _F("Warning: nm cannot read symbol table from %s", path.c_str());
5f0a03a6
JK
6447 return info_absent;
6448 }
6449 return status;
6450}
6451
6452enum info_status
83ca3872
MW
6453symbol_table::read_from_text_file(const string& path,
6454 const systemtap_session &sess)
5f0a03a6
JK
6455{
6456 FILE *f = fopen(path.c_str(), "r");
6457 if (!f)
6458 {
83ca3872 6459 if (! sess.suppress_warnings)
b530b5b3
LB
6460 cerr << _F("Warning: cannot read symbol table from %s -- %s",
6461 path.c_str(), strerror(errno));
5f0a03a6
JK
6462 return info_absent;
6463 }
6464 enum info_status status = read_symbols(f, path);
6465 (void) fclose(f);
6466 return status;
6467}
6468
46f7b6be 6469void
f98c6346 6470symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
6471{
6472#ifdef __powerpc__
6473 /*
6474 * The .opd section contains function descriptors that can look
6475 * just like function entry points. For example, there's a function
6476 * descriptor called "do_exit" that links to the entry point ".do_exit".
6477 * Reject all symbols in .opd.
6478 */
6479 opd_section = SHN_UNDEF;
6480 Dwarf_Addr bias;
6481 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
6482 ?: dwfl_module_getelf (mod, &bias));
6483 Elf_Scn* scn = 0;
6484 size_t shstrndx;
6485
6486 if (!elf)
6487 return;
fcc30d6d 6488 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
6489 return;
6490 while ((scn = elf_nextscn(elf, scn)) != NULL)
6491 {
6492 GElf_Shdr shdr_mem;
6493 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
6494 if (!shdr)
6495 continue;
6496 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
6497 if (!strcmp(name, ".opd"))
6498 {
6499 opd_section = elf_ndxscn(scn);
6500 return;
6501 }
6502 }
6503#endif
6504}
6505
6506bool
6507symbol_table::reject_section(GElf_Word section)
6508{
6509 if (section == SHN_UNDEF)
6510 return true;
6511#ifdef __powerpc__
6512 if (section == opd_section)
6513 return true;
6514#endif
6515 return false;
6516}
6517
5f0a03a6
JK
6518enum info_status
6519symbol_table::get_from_elf()
6520{
6521 Dwarf_Addr high_addr = 0;
6522 Dwfl_Module *mod = mod_info->mod;
6523 int syments = dwfl_module_getsymtab(mod);
6524 assert(syments);
46f7b6be 6525 prepare_section_rejection(mod);
5f0a03a6
JK
6526 for (int i = 1; i < syments; ++i)
6527 {
6528 GElf_Sym sym;
ab91b232
JK
6529 GElf_Word section;
6530 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 6531 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 6532 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 6533 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
6534 }
6535 return info_present;
6536}
6537
5f0a03a6
JK
6538func_info *
6539symbol_table::get_func_containing_address(Dwarf_Addr addr)
6540{
1c6b77e5
JS
6541 iterator_t iter = map_by_addr.upper_bound(addr);
6542 if (iter == map_by_addr.begin())
5f0a03a6 6543 return NULL;
2e67a43b 6544 else
1c6b77e5 6545 return (--iter)->second;
5f0a03a6
JK
6546}
6547
6548func_info *
6549symbol_table::lookup_symbol(const string& name)
6550{
6551 map<string, func_info*>::iterator i = map_by_name.find(name);
6552 if (i == map_by_name.end())
6553 return NULL;
6554 return i->second;
6555}
6556
6557Dwarf_Addr
6558symbol_table::lookup_symbol_address(const string& name)
6559{
6560 func_info *fi = lookup_symbol(name);
6561 if (fi)
6562 return fi->addr;
6563 return 0;
6564}
6565
ab91b232
JK
6566// This is the kernel symbol table. The kernel macro cond_syscall creates
6567// a weak symbol for each system call and maps it to sys_ni_syscall.
6568// For system calls not implemented elsewhere, this weak symbol shows up
6569// in the kernel symbol table. Following the precedent of dwarfful stap,
6570// we refuse to consider such symbols. Here we delete them from our
6571// symbol table.
6572// TODO: Consider generalizing this and/or making it part of blacklist
6573// processing.
6574void
6575symbol_table::purge_syscall_stubs()
6576{
6577 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
6578 if (stub_addr == 0)
6579 return;
1c6b77e5 6580 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
6581 for (iterator_t iter = purge_range.first;
6582 iter != purge_range.second;
1c6b77e5 6583 )
ab91b232 6584 {
1c6b77e5 6585 func_info *fi = iter->second;
2e67a43b 6586 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 6587 {
2e67a43b 6588 map_by_name.erase(fi->name);
1c6b77e5 6589 map_by_addr.erase(iter++);
2e67a43b 6590 delete fi;
2e67a43b 6591 }
1c6b77e5
JS
6592 else
6593 iter++;
ab91b232
JK
6594 }
6595}
6596
5f0a03a6
JK
6597void
6598module_info::get_symtab(dwarf_query *q)
6599{
6600 systemtap_session &sess = q->sess;
6601
1c6b77e5
JS
6602 if (symtab_status != info_unknown)
6603 return;
6604
5f0a03a6
JK
6605 sym_table = new symbol_table(this);
6606 if (!elf_path.empty())
6607 {
83ca3872
MW
6608 if (name == TOK_KERNEL && !sess.kernel_symtab_path.empty()
6609 && ! sess.suppress_warnings)
b530b5b3
LB
6610 cerr << _F("Warning: reading symbol table from %s -- ignoring %s",
6611 elf_path.c_str(), sess.kernel_symtab_path.c_str()) << endl;
5f0a03a6
JK
6612 symtab_status = sym_table->get_from_elf();
6613 }
6614 else
6615 {
6616 assert(name == TOK_KERNEL);
6617 if (sess.kernel_symtab_path.empty())
6618 {
6619 symtab_status = info_absent;
b530b5b3
LB
6620 cerr << _("Error: Cannot find vmlinux."
6621 " Consider using --kmap instead of --kelf.")
5f0a03a6
JK
6622 << endl;;
6623 }
6624 else
6625 {
6626 symtab_status =
83ca3872 6627 sym_table->read_from_text_file(sess.kernel_symtab_path, sess);
5f0a03a6
JK
6628 if (symtab_status == info_present)
6629 {
6630 sess.sym_kprobes_text_start =
6631 sym_table->lookup_symbol_address("__kprobes_text_start");
6632 sess.sym_kprobes_text_end =
6633 sym_table->lookup_symbol_address("__kprobes_text_end");
6634 sess.sym_stext = sym_table->lookup_symbol_address("_stext");
5f0a03a6
JK
6635 }
6636 }
6637 }
6638 if (symtab_status == info_absent)
6639 {
6640 delete sym_table;
6641 sym_table = NULL;
6642 return;
6643 }
6644
ab91b232
JK
6645 if (name == TOK_KERNEL)
6646 sym_table->purge_syscall_stubs();
5f0a03a6
JK
6647}
6648
1c6b77e5
JS
6649// update_symtab reconciles data between the elf symbol table and the dwarf
6650// function enumeration. It updates the symbol table entries with the dwarf
6651// die that describes the function, which also signals to query_module_symtab
6652// that a statement probe isn't needed. In return, it also adds aliases to the
6653// function table for names that share the same addr/die.
6654void
6655module_info::update_symtab(cu_function_cache_t *funcs)
6656{
6657 if (!sym_table)
6658 return;
6659
6660 cu_function_cache_t new_funcs;
6661
6662 for (cu_function_cache_t::iterator func = funcs->begin();
6663 func != funcs->end(); func++)
6664 {
6665 // optimization: inlines will never be in the symbol table
6666 if (dwarf_func_inline(&func->second) != 0)
6667 continue;
6668
1ffb8bd1
JS
6669 // XXX We may want to make additional efforts to match mangled elf names
6670 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
6671 // missing, so we may also need to try matching by address. See also the
6672 // notes about _Z in dwflpp::iterate_over_functions().
6673
1c6b77e5
JS
6674 func_info *fi = sym_table->lookup_symbol(func->first);
6675 if (!fi)
6676 continue;
6677
6678 // iterate over all functions at the same address
6679 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
6680 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
6681 {
6682 // update this function with the dwarf die
6683 it->second->die = func->second;
6684
6685 // if this function is a new alias, then
6686 // save it to merge into the function cache
6687 if (it->second != fi)
b7478964 6688 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
6689 }
6690 }
6691
6692 // add all discovered aliases back into the function cache
6693 // NB: this won't replace any names that dwarf may have already found
6694 funcs->insert(new_funcs.begin(), new_funcs.end());
6695}
6696
5f0a03a6
JK
6697module_info::~module_info()
6698{
6699 if (sym_table)
6700 delete sym_table;
b55bc428
FCE
6701}
6702
935447c8 6703// ------------------------------------------------------------------------
888af770 6704// user-space probes
935447c8
DS
6705// ------------------------------------------------------------------------
6706
935447c8 6707
888af770 6708struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 6709{
89ba3085
FCE
6710private:
6711 string make_pbm_key (uprobe_derived_probe* p) {
6712 return p->module + "|" + p->section + "|" + lex_cast(p->pid);
6713 }
6714
935447c8 6715public:
888af770 6716 void emit_module_decls (systemtap_session& s);
935447c8
DS
6717 void emit_module_init (systemtap_session& s);
6718 void emit_module_exit (systemtap_session& s);
6719};
6720
6721
888af770
FCE
6722void
6723uprobe_derived_probe::join_group (systemtap_session& s)
6724{
6725 if (! s.uprobe_derived_probes)
6726 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
6727 s.uprobe_derived_probes->enroll (this);
93646f4d 6728 enable_task_finder(s);
a96d1db0 6729
8a03658e
JS
6730 // Ask buildrun.cxx to build extra module if needed, and
6731 // signal staprun to load that module
6732 s.need_uprobes = true;
a96d1db0
DN
6733}
6734
888af770 6735
c0f84e7b
SC
6736void
6737uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
6738{
6739 dwarf_derived_probe::getargs(arg_set);
6740 arg_set.insert(arg_set.end(), args.begin(), args.end());
6741}
6742
6743
6744void
6745uprobe_derived_probe::saveargs(int nargs)
6746{
6747 for (int i = 1; i <= nargs; i++)
6748 args.push_back("$arg" + lex_cast (i) + ":long");
6749}
6750
6751
2865d17a
DB
6752void
6753uprobe_derived_probe::emit_unprivileged_assertion (translator_output* o)
6754{
6755 // These probes are allowed for unprivileged users, but only in the
6756 // context of processes which they own.
6757 emit_process_owner_assertion (o);
6758}
6759
6760
888af770 6761struct uprobe_builder: public derived_probe_builder
a96d1db0 6762{
888af770 6763 uprobe_builder() {}
822a6a3d 6764 virtual void build(systemtap_session &,
a96d1db0
DN
6765 probe * base,
6766 probe_point * location,
86bf665e 6767 literal_map_t const & parameters,
a96d1db0
DN
6768 vector<derived_probe *> & finished_results)
6769 {
888af770 6770 int64_t process, address;
a96d1db0 6771
888af770 6772 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 6773 (void) b1;
888af770 6774 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 6775 (void) b2;
888af770
FCE
6776 bool rr = has_null_param (parameters, TOK_RETURN);
6777 assert (b1 && b2); // by pattern_root construction
a96d1db0 6778
0973d815 6779 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
6780 }
6781};
6782
6783
6784void
775d51e5 6785uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
a96d1db0 6786{
888af770 6787 if (probes.empty()) return;
775d51e5 6788 s.op->newline() << "/* ---- user probes ---- */";
471fca5e
TM
6789 // If uprobes isn't in the kernel, pull it in from the runtime.
6790
6791 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
6792 s.op->newline() << "#include <linux/uprobes.h>";
6793 s.op->newline() << "#else";
6794 s.op->newline() << "#include \"uprobes/uprobes.h\"";
6795 s.op->newline() << "#endif";
6796 s.op->newline() << "#ifndef UPROBES_API_VERSION";
6797 s.op->newline() << "#define UPROBES_API_VERSION 1";
6798 s.op->newline() << "#endif";
a96d1db0 6799
43241c44
FCE
6800 // We'll probably need at least this many:
6801 unsigned minuprobes = probes.size();
6802 // .. but we don't want so many that .bss is inflated (PR10507):
6803 unsigned uprobesize = 64;
6804 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
6805 unsigned maxuprobes = maxuprobesmem / uprobesize;
6806
aaf7ffe8
FCE
6807 // Let's choose a value on the geometric middle. This should end up
6808 // between minuprobes and maxuprobes. It's OK if this number turns
6809 // out to be < minuprobes or > maxuprobes. At worst, we get a
6810 // run-time error of one kind (too few: missed uprobe registrations)
6811 // or another (too many: vmalloc errors at module load time).
6812 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 6813
6d0f3f0c 6814 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 6815 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 6816 s.op->newline() << "#endif";
a96d1db0 6817
cc52276b
WC
6818 // Forward decls
6819 s.op->newline() << "#include \"uprobes-common.h\"";
6820
5e112f92
FCE
6821 // In .bss, the shared pool of uprobe/uretprobe structs. These are
6822 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
6823 // XXX: consider a slab cache or somesuch for stap_uprobes
6824 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
5e112f92 6825 s.op->newline() << "DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 6826
89ba3085
FCE
6827 s.op->assert_0_indent();
6828
89ba3085
FCE
6829 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
6830 // This means we process probes[] in two passes.
6831 map <string,unsigned> module_index;
6832 unsigned module_index_ctr = 0;
6833
cc52276b
WC
6834 // not const since embedded task_finder_target struct changes
6835 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
6836 s.op->indent(1);
6837 for (unsigned i=0; i<probes.size(); i++)
6838 {
6839 uprobe_derived_probe *p = probes[i];
6840 string pbmkey = make_pbm_key (p);
6841 if (module_index.find (pbmkey) == module_index.end())
6842 {
6843 module_index[pbmkey] = module_index_ctr++;
6844
6845 s.op->newline() << "{";
6846 // NB: it's essential that make_pbm_key() use all of and
6847 // only the same fields as we're about to emit.
6848 s.op->line() << " .finder={";
6849 if (p->pid != 0)
68910c97
JK
6850 s.op->line() << " .pid=" << p->pid << ",";
6851
6852 if (p->section == "") // .statement(addr).absolute
6853 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
6854 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
6855 {
6856 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
6857 s.op->line() << " .callback=&stap_uprobe_process_found,";
6858 }
68910c97 6859 else if (p->section != ".absolute") // ET_DYN
89ba3085 6860 {
4ad95bbc
SC
6861 if (p->has_library)
6862 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
6863 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
6864 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 6865 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 6866 }
89ba3085 6867 s.op->line() << " },";
68910c97
JK
6868 if (p->module != "")
6869 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
6870 s.op->line() << " },";
6871 }
c57ea854 6872 else
822a6a3d 6873 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
6874 }
6875 s.op->newline(-1) << "};";
6876
6877 s.op->assert_0_indent();
6878
cc52276b
WC
6879 // NB: read-only structure
6880 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 6881 s.op->indent(1);
888af770
FCE
6882 for (unsigned i =0; i<probes.size(); i++)
6883 {
6884 uprobe_derived_probe* p = probes[i];
6885 s.op->newline() << "{";
89ba3085
FCE
6886 string key = make_pbm_key (p);
6887 unsigned value = module_index[key];
759e1d76
FCE
6888 if (value != 0)
6889 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 6890 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 6891 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 6892
038c38c6 6893 if (p->sdt_semaphore_addr != 0)
63b4fd14 6894 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 6895 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0
JS
6896
6897 if (p->has_return)
6898 s.op->line() << " .return_p=1,";
888af770
FCE
6899 s.op->line() << " },";
6900 }
6901 s.op->newline(-1) << "};";
a96d1db0 6902
89ba3085
FCE
6903 s.op->assert_0_indent();
6904
48e685da 6905 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 6906 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 6907 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
6908 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
6909 "_STP_PROBE_HANDLER_UPROBE");
0e090c74 6910 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
6911 << "sup->spec_index >= " << probes.size() << ") {";
6912 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 6913 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
6914 s.op->newline() << "atomic_dec (&c->busy);";
6915 s.op->newline() << "goto probe_epilogue;";
6916 s.op->newline(-1) << "}";
a96d1db0 6917 s.op->newline() << "c->regs = regs;";
97cd9334 6918 s.op->newline() << "c->regflags |= _STP_REGS_USER_FLAG;";
6415ddde
MW
6919
6920 // Make it look like the IP is set as it would in the actual user
6921 // task when calling real probe handler. Reset IP regs on return, so
6922 // we don't confuse uprobes. PR10458
6923 s.op->newline() << "{";
6924 s.op->indent(1);
6925 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->regs);";
259d54c0 6926 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 6927 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 6928 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
6929 s.op->newline(-1) << "}";
6930
a96d1db0 6931 common_probe_entryfn_epilogue (s.op);
888af770 6932 s.op->newline(-1) << "}";
a96d1db0 6933
48e685da 6934 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 6935 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 6936 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
6937 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
6938 "_STP_PROBE_HANDLER_URETPROBE");
6dceb5c9 6939 s.op->newline() << "c->ips.ri = inst;";
0e090c74 6940 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
6941 << "sup->spec_index >= " << probes.size() << ") {";
6942 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 6943 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
6944 s.op->newline() << "atomic_dec (&c->busy);";
6945 s.op->newline() << "goto probe_epilogue;";
6946 s.op->newline(-1) << "}";
6947
888af770 6948 s.op->newline() << "c->regs = regs;";
97cd9334 6949 s.op->newline() << "c->regflags |= _STP_REGS_USER_FLAG;";
6415ddde
MW
6950
6951 // Make it look like the IP is set as it would in the actual user
6952 // task when calling real probe handler. Reset IP regs on return, so
6953 // we don't confuse uprobes. PR10458
6954 s.op->newline() << "{";
6955 s.op->indent(1);
6956 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->regs);";
5e562a69 6957 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 6958 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 6959 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
6960 s.op->newline(-1) << "}";
6961
888af770 6962 common_probe_entryfn_epilogue (s.op);
a96d1db0
DN
6963 s.op->newline(-1) << "}";
6964
89ba3085 6965 s.op->newline();
cc52276b 6966 s.op->newline() << "#include \"uprobes-common.c\"";
6d0f3f0c 6967 s.op->newline();
888af770 6968}
935447c8
DS
6969
6970
888af770
FCE
6971void
6972uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
935447c8 6973{
888af770 6974 if (probes.empty()) return;
935447c8 6975
5e112f92 6976 s.op->newline() << "/* ---- user probes ---- */";
935447c8 6977
01b05e2e 6978 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
6979 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
6980 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
6981 // NB: we assume the rest of the struct (specificaly, sup->up) is
6982 // initialized to zero. This is so that we can use
6983 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
6984 s.op->newline(-1) << "}";
6985 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 6986
89ba3085
FCE
6987 // Set up the task_finders
6988 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
6989 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 6990 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 6991 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 6992
5e112f92
FCE
6993 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
6994 // finders already registered, since mere registration does not
6995 // cause any utrace or memory allocation actions. That happens only
6996 // later, once the task finder engine starts running. So, for a
6997 // partial initialization requiring unwind, we need do nothing.
6998 s.op->newline() << "if (rc) break;";
a7a68293 6999
888af770
FCE
7000 s.op->newline(-1) << "}";
7001}
d0ea46ce 7002
d0a7f5a9 7003
888af770
FCE
7004void
7005uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
7006{
7007 if (probes.empty()) return;
7008 s.op->newline() << "/* ---- user probes ---- */";
e56e51c9 7009
6d0f3f0c
FCE
7010 // NB: there is no stap_unregister_task_finder_target call;
7011 // important stuff like utrace cleanups are done by
d41d451c
FCE
7012 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7013 //
7014 // This function blocks until all callbacks are completed, so there
7015 // is supposed to be no possibility of any registration-related code starting
7016 // to run in parallel with our shutdown here. So we don't need to protect the
7017 // stap_uprobes[] array with the mutex.
d0a7f5a9 7018
01b05e2e 7019 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7020 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7021 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7022 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7023
8faa1fc5 7024 // PR10655: decrement that ENABLED semaphore
c116c31b 7025 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7026 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7027 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7028 s.op->newline() << "struct task_struct *tsk;";
7029 s.op->newline() << "rcu_read_lock();";
6846cfc8 7030
86229a55
DS
7031 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7032 // that the pid is always in the global namespace, not in any
7033 // private namespace.
8faa1fc5 7034 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7035 // We'd like to call find_task_by_pid_ns() here, but it isn't
7036 // exported. So, we call what it calls...
7037 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7038 s.op->newline() << "#else";
7039 s.op->newline() << " tsk = find_task_by_pid (pid);";
7040 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7041
7042 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7043 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7044 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7045 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7046 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7047 s.op->newline() << "#endif";
3c5b8e2b 7048 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7049 s.op->newline(-1) << "}";
8faa1fc5
FCE
7050 // XXX: need to analyze possibility of race condition
7051 s.op->newline(-1) << "}";
7052 s.op->newline() << "rcu_read_unlock();";
7053 s.op->newline(-1) << "}";
6846cfc8 7054
3568f1dd
FCE
7055 s.op->newline() << "if (sups->return_p) {";
7056 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7057 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 7058 s.op->newline() << "#endif";
80b4ad8b
FCE
7059 // NB: PR6829 does not change that we still need to unregister at
7060 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7061 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7062 s.op->newline(-1) << "} else {";
7063 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7064 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
7065 s.op->newline() << "#endif";
7066 s.op->newline() << "unregister_uprobe (& sup->up);";
7067 s.op->newline(-1) << "}";
935447c8 7068
6d0f3f0c 7069 s.op->newline() << "sup->spec_index = -1;";
935447c8 7070
3568f1dd
FCE
7071 // XXX: uprobe missed counts?
7072
6d0f3f0c 7073 s.op->newline(-1) << "}";
935447c8 7074
5e112f92 7075 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
7076}
7077
e6fe60e7
AM
7078// ------------------------------------------------------------------------
7079// Kprobe derived probes
7080// ------------------------------------------------------------------------
7081
4627ed58 7082static const string TOK_KPROBE("kprobe");
935447c8 7083
bae55db9 7084struct kprobe_derived_probe: public derived_probe
d0ea46ce 7085{
bae55db9
JS
7086 kprobe_derived_probe (probe *base,
7087 probe_point *location,
7088 const string& name,
7089 int64_t stmt_addr,
7090 bool has_return,
7091 bool has_statement,
7092 bool has_maxactive,
b642c901
SC
7093 bool has_path,
7094 bool has_library,
7095 long maxactive_val,
7096 const string& path,
7097 const string& library
bae55db9
JS
7098 );
7099 string symbol_name;
7100 Dwarf_Addr addr;
7101 bool has_return;
7102 bool has_statement;
7103 bool has_maxactive;
b642c901
SC
7104 bool has_path;
7105 bool has_library;
bae55db9 7106 long maxactive_val;
b642c901
SC
7107 string path;
7108 string library;
bae55db9
JS
7109 bool access_var;
7110 void printsig (std::ostream &o) const;
7111 void join_group (systemtap_session& s);
7112};
d0ea46ce 7113
bae55db9
JS
7114struct kprobe_derived_probe_group: public derived_probe_group
7115{
7116private:
7117 multimap<string,kprobe_derived_probe*> probes_by_module;
7118 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 7119
bae55db9
JS
7120public:
7121 void enroll (kprobe_derived_probe* probe);
7122 void emit_module_decls (systemtap_session& s);
7123 void emit_module_init (systemtap_session& s);
7124 void emit_module_exit (systemtap_session& s);
7125};
d0ea46ce 7126
e6fe60e7
AM
7127kprobe_derived_probe::kprobe_derived_probe (probe *base,
7128 probe_point *location,
b6371390 7129 const string& name,
e6fe60e7 7130 int64_t stmt_addr,
b6371390
JS
7131 bool has_return,
7132 bool has_statement,
7133 bool has_maxactive,
b642c901
SC
7134 bool has_path,
7135 bool has_library,
7136 long maxactive_val,
7137 const string& path,
7138 const string& library
b6371390 7139 ):
4c5d1300 7140 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 7141 symbol_name (name), addr (stmt_addr),
b6371390 7142 has_return (has_return), has_statement (has_statement),
b642c901
SC
7143 has_maxactive (has_maxactive), has_path (has_path),
7144 has_library (has_library),
7145 maxactive_val (maxactive_val),
7146 path (path), library (library)
e6fe60e7
AM
7147{
7148 this->tok = base->tok;
7149 this->access_var = false;
d0ea46ce 7150
e6fe60e7
AM
7151#ifndef USHRT_MAX
7152#define USHRT_MAX 32767
7153#endif
d0ea46ce 7154
46856d8d
JS
7155 // Expansion of $target variables in the probe body produces an error during
7156 // translate phase, since we're not using debuginfo
d0ea46ce 7157
e6fe60e7 7158 vector<probe_point::component*> comps;
46856d8d 7159 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 7160
46856d8d
JS
7161 if (has_statement)
7162 {
9ea68eb9
JS
7163 comps.push_back (new probe_point::component(TOK_STATEMENT,
7164 new literal_number(addr, true)));
46856d8d
JS
7165 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
7166 }
7167 else
7168 {
7169 size_t pos = name.find(':');
7170 if (pos != string::npos)
d0ea46ce 7171 {
46856d8d
JS
7172 string module = name.substr(0, pos);
7173 string function = name.substr(pos + 1);
7174 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
7175 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
7176 }
7177 else
7178 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 7179 }
d0ea46ce 7180
b6371390
JS
7181 if (has_return)
7182 comps.push_back (new probe_point::component(TOK_RETURN));
7183 if (has_maxactive)
7184 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 7185
e6fe60e7
AM
7186 this->sole_location()->components = comps;
7187}
d0ea46ce 7188
e6fe60e7
AM
7189void kprobe_derived_probe::printsig (ostream& o) const
7190{
7191 sole_location()->print (o);
7192 o << " /* " << " name = " << symbol_name << "*/";
7193 printsig_nested (o);
7194}
d0ea46ce 7195
e6fe60e7
AM
7196void kprobe_derived_probe::join_group (systemtap_session& s)
7197{
d0ea46ce 7198
e6fe60e7
AM
7199 if (! s.kprobe_derived_probes)
7200 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
7201 s.kprobe_derived_probes->enroll (this);
d0ea46ce 7202
e6fe60e7 7203}
d0ea46ce 7204
e6fe60e7
AM
7205void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
7206{
7207 probes_by_module.insert (make_pair (p->symbol_name, p));
7208 // probes of same symbol should share single kprobe/kretprobe
7209}
d0ea46ce 7210
e6fe60e7
AM
7211void
7212kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
7213{
7214 if (probes_by_module.empty()) return;
d0ea46ce 7215
e6fe60e7 7216 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 7217
e6fe60e7
AM
7218 // Warn of misconfigured kernels
7219 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
7220 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
7221 s.op->newline() << "#endif";
7222 s.op->newline();
d0ea46ce 7223
f07c3b68 7224 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 7225 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
7226 s.op->newline() << "#endif";
7227
e6fe60e7 7228 // Forward declare the master entry functions
88747011 7229 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 7230 s.op->line() << " struct pt_regs *regs);";
88747011 7231 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 7232 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 7233
e6fe60e7
AM
7234 // Emit an array of kprobe/kretprobe pointers
7235 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 7236 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 7237 s.op->newline() << "#endif";
d0ea46ce 7238
e6fe60e7 7239 // Emit the actual probe list.
d0ea46ce 7240
e6fe60e7
AM
7241 s.op->newline() << "static struct stap_dwarfless_kprobe {";
7242 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
7243 s.op->newline() << "#ifdef __ia64__";
7244 s.op->newline() << "struct kprobe dummy;";
7245 s.op->newline() << "#endif";
7246 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
7247 // NB: bss!
d0ea46ce 7248
e6fe60e7
AM
7249 s.op->newline() << "static struct stap_dwarfless_probe {";
7250 s.op->newline(1) << "const unsigned return_p:1;";
7251 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 7252 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
7253 s.op->newline() << "unsigned registered_p:1;";
7254 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 7255
e6fe60e7
AM
7256 // Function Names are mostly small and uniform enough to justify putting
7257 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 7258
faea5e16
JS
7259 size_t symbol_string_name_max = 0;
7260 size_t symbol_string_name_tot = 0;
e6fe60e7 7261 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 7262 {
e6fe60e7
AM
7263 kprobe_derived_probe* p = it->second;
7264#define DOIT(var,expr) do { \
7265 size_t var##_size = (expr) + 1; \
7266 var##_max = max (var##_max, var##_size); \
7267 var##_tot += var##_size; } while (0)
e6fe60e7
AM
7268 DOIT(symbol_string_name, p->symbol_name.size());
7269#undef DOIT
6270adc1
MH
7270 }
7271
e6fe60e7
AM
7272#define CALCIT(var) \
7273 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 7274
e6fe60e7
AM
7275 CALCIT(symbol_string);
7276#undef CALCIT
6270adc1 7277
bd659351 7278 s.op->newline() << "unsigned long address;";
26e63673 7279 s.op->newline() << "struct stap_probe * const probe;";
e6fe60e7
AM
7280 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
7281 s.op->indent(1);
6270adc1 7282
e6fe60e7
AM
7283 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
7284 {
7285 kprobe_derived_probe* p = it->second;
7286 s.op->newline() << "{";
7287 if (p->has_return)
7288 s.op->line() << " .return_p=1,";
6270adc1 7289
e6fe60e7
AM
7290 if (p->has_maxactive)
7291 {
7292 s.op->line() << " .maxactive_p=1,";
7293 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
7294 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
7295 }
6270adc1 7296
b350f56b
JS
7297 if (p->locations[0]->optional)
7298 s.op->line() << " .optional_p=1,";
7299
e6fe60e7 7300 if (p->has_statement)
c8d9d15e 7301 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 7302 else
c8d9d15e 7303 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 7304
faea5e16 7305 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 7306 s.op->line() << " },";
935447c8
DS
7307 }
7308
e6fe60e7 7309 s.op->newline(-1) << "};";
5d67b47c 7310
e6fe60e7
AM
7311 // Emit the kprobes callback function
7312 s.op->newline();
88747011 7313 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
7314 s.op->line() << " struct pt_regs *regs) {";
7315 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7316 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7317 // Check that the index is plausible
7318 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7319 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7320 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7321 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7322 s.op->line() << "];";
6eefe942
MW
7323 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7324 "_STP_PROBE_HANDLER_KPROBE");
e6fe60e7 7325 s.op->newline() << "c->regs = regs;";
6415ddde
MW
7326
7327 // Make it look like the IP is set as it wouldn't have been replaced
7328 // by a breakpoint instruction when calling real probe handler. Reset
7329 // IP regs on return, so we don't confuse kprobes. PR10458
7330 s.op->newline() << "{";
7331 s.op->indent(1);
7332 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->regs);";
259d54c0 7333 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 7334 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7335 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7336 s.op->newline(-1) << "}";
7337
e6fe60e7
AM
7338 common_probe_entryfn_epilogue (s.op);
7339 s.op->newline() << "return 0;";
7340 s.op->newline(-1) << "}";
935447c8 7341
e6fe60e7
AM
7342 // Same for kretprobes
7343 s.op->newline();
88747011 7344 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
7345 s.op->line() << " struct pt_regs *regs) {";
7346 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 7347
e6fe60e7
AM
7348 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7349 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7350 // Check that the index is plausible
7351 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7352 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7353 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7354 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7355 s.op->line() << "];";
935447c8 7356
6eefe942
MW
7357 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7358 "_STP_PROBE_HANDLER_KRETPROBE");
e6fe60e7 7359 s.op->newline() << "c->regs = regs;";
6dceb5c9 7360 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
7361
7362 // Make it look like the IP is set as it wouldn't have been replaced
7363 // by a breakpoint instruction when calling real probe handler. Reset
7364 // IP regs on return, so we don't confuse kprobes. PR10458
7365 s.op->newline() << "{";
7366 s.op->indent(1);
7367 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->regs);";
259d54c0 7368 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 7369 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7370 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7371 s.op->newline(-1) << "}";
7372
e6fe60e7
AM
7373 common_probe_entryfn_epilogue (s.op);
7374 s.op->newline() << "return 0;";
7375 s.op->newline(-1) << "}";
bd659351 7376
03a4ec63 7377 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7378 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
7379 s.op->newline() << " struct module *owner,";
7380 s.op->newline() << " unsigned long val) {";
7381 s.op->newline(1) << "int i;";
fc1d2aa2
MW
7382 s.op->newline() << "int *p = (int *) data;";
7383 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
7384 << " && *p > 0; i++) {";
bd659351
MW
7385 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7386 s.op->newline() << "if (! sdp->address)";
fc1d2aa2 7387 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 7388 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
7389 s.op->newline() << "(*p)--;";
7390 s.op->newline(-1) << "}";
7391 s.op->newline(-2) << "}";
7392 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 7393 s.op->newline(-1) << "}";
03a4ec63 7394 s.op->newline() << "#endif";
935447c8
DS
7395}
7396
e6fe60e7 7397
6270adc1 7398void
e6fe60e7 7399kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 7400{
03a4ec63 7401 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
7402 s.op->newline() << "{";
7403 s.op->newline(1) << "int p = 0;";
7404 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
7405 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7406 s.op->newline() << "if (! sdp->address)";
7407 s.op->newline(1) << "p++;";
7408 s.op->newline(-2) << "}";
7409 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
7410 s.op->newline(-1) << "}";
03a4ec63 7411 s.op->newline() << "#endif";
bd659351 7412
e6fe60e7 7413 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 7414 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 7415 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 7416 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
7417 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
7418
7419 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7420 s.op->newline() << "if (! addr) {";
7421 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
7422 s.op->newline() << "if (!sdp->optional_p)";
7423 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
7424 s.op->newline(-1) << "continue;";
bd659351 7425 s.op->newline(-1) << "}";
03a4ec63
MW
7426 s.op->newline() << "#endif";
7427
26e63673 7428 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 7429 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 7430 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 7431 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 7432 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 7433 s.op->newline() << "#endif";
e6fe60e7
AM
7434 s.op->newline() << "if (sdp->maxactive_p) {";
7435 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
7436 s.op->newline(-1) << "} else {";
f07c3b68 7437 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 7438 s.op->newline(-1) << "}";
88747011 7439 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
7440 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
7441 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 7442 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 7443 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 7444 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 7445 s.op->newline() << "#endif";
c8d9d15e 7446 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
7447 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
7448 s.op->newline() << "if (rc == 0) {";
7449 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
7450 s.op->newline() << "if (rc != 0)";
7451 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
7452 s.op->newline(-2) << "}";
7453 s.op->newline() << "#else";
7454 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
7455 s.op->newline() << "#endif";
7456 s.op->newline(-1) << "} else {";
7457 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 7458 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 7459 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 7460 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 7461 s.op->newline() << "#endif";
88747011 7462 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 7463 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 7464 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 7465 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 7466 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 7467 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 7468 s.op->newline() << "#endif";
e6fe60e7
AM
7469 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
7470 s.op->newline() << "if (rc == 0) {";
7471 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
7472 s.op->newline() << "if (rc != 0)";
7473 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
7474 s.op->newline(-2) << "}";
7475 s.op->newline() << "#else";
7476 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
7477 s.op->newline() << "#endif";
7478 s.op->newline(-1) << "}";
7479 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
7480 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 7481 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 7482 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 7483 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
7484 // XXX: shall we increment numskipped?
7485 s.op->newline(-1) << "}";
6270adc1 7486
e6fe60e7
AM
7487 s.op->newline() << "else sdp->registered_p = 1;";
7488 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
7489}
7490
e6fe60e7
AM
7491void
7492kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 7493{
e6fe60e7
AM
7494 //Unregister kprobes by batch interfaces.
7495 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
7496 s.op->newline() << "j = 0;";
7497 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7498 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7499 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7500 s.op->newline() << "if (! sdp->registered_p) continue;";
7501 s.op->newline() << "if (!sdp->return_p)";
c9116e99 7502 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 7503 s.op->newline(-2) << "}";
c9116e99 7504 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7505 s.op->newline() << "j = 0;";
7506 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7507 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7508 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7509 s.op->newline() << "if (! sdp->registered_p) continue;";
7510 s.op->newline() << "if (sdp->return_p)";
c9116e99 7511 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 7512 s.op->newline(-2) << "}";
c9116e99 7513 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7514 s.op->newline() << "#ifdef __ia64__";
7515 s.op->newline() << "j = 0;";
7516 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7517 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7518 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7519 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 7520 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 7521 s.op->newline(-1) << "}";
c9116e99 7522 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
7523 s.op->newline() << "#endif";
7524 s.op->newline() << "#endif";
3e3bd7b6 7525
e6fe60e7
AM
7526 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
7527 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7528 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
7529 s.op->newline() << "if (! sdp->registered_p) continue;";
7530 s.op->newline() << "if (sdp->return_p) {";
7531 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
7532 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
7533 s.op->newline() << "#endif";
7534 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
7535 s.op->newline() << "#ifdef STP_TIMING";
7536 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 7537 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
e6fe60e7
AM
7538 s.op->newline(-1) << "#endif";
7539 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
7540 s.op->newline() << "#ifdef STP_TIMING";
7541 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 7542 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
7543 s.op->newline(-1) << "#endif";
7544 s.op->newline(-1) << "} else {";
7545 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
7546 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
7547 s.op->newline() << "#endif";
7548 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
7549 s.op->newline() << "#ifdef STP_TIMING";
7550 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 7551 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
7552 s.op->newline(-1) << "#endif";
7553 s.op->newline(-1) << "}";
7554 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
7555 s.op->newline() << "unregister_kprobe (&kp->dummy);";
7556 s.op->newline() << "#endif";
7557 s.op->newline() << "sdp->registered_p = 0;";
7558 s.op->newline(-1) << "}";
f8a968bc
JS
7559}
7560
e6fe60e7 7561struct kprobe_builder: public derived_probe_builder
3c1b3d06 7562{
e6fe60e7
AM
7563 kprobe_builder() {}
7564 virtual void build(systemtap_session & sess,
7565 probe * base,
7566 probe_point * location,
7567 literal_map_t const & parameters,
7568 vector<derived_probe *> & finished_results);
7569};
3c1b3d06
FCE
7570
7571
79189b84 7572void
822a6a3d 7573kprobe_builder::build(systemtap_session &,
e6fe60e7
AM
7574 probe * base,
7575 probe_point * location,
7576 literal_map_t const & parameters,
7577 vector<derived_probe *> & finished_results)
79189b84 7578{
e6fe60e7 7579 string function_string_val, module_string_val;
b642c901 7580 string path, library;
b6371390
JS
7581 int64_t statement_num_val = 0, maxactive_val = 0;
7582 bool has_function_str, has_module_str, has_statement_num;
7583 bool has_absolute, has_return, has_maxactive;
b642c901 7584 bool has_path, has_library;
79189b84 7585
b6371390
JS
7586 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
7587 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
7588 has_return = has_null_param (parameters, TOK_RETURN);
7589 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
7590 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
7591 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
7592 has_path = get_param (parameters, TOK_PROCESS, path);
7593 has_library = get_param (parameters, TOK_LIBRARY, library);
7594
7595 if (has_path)
7596 path = find_executable (path);
7597 if (has_library)
7598 library = find_executable (library, "LD_LIBRARY_PATH");
c57ea854 7599
b6371390 7600 if (has_function_str)
6fb70fb7 7601 {
b6371390
JS
7602 if (has_module_str)
7603 function_string_val = module_string_val + ":" + function_string_val;
86758d5f 7604
b6371390
JS
7605 finished_results.push_back (new kprobe_derived_probe (base,
7606 location, function_string_val,
7607 0, has_return,
7608 has_statement_num,
7609 has_maxactive,
b642c901
SC
7610 has_path,
7611 has_library,
7612 maxactive_val,
7613 path,
7614 library));
6fb70fb7 7615 }
e6fe60e7 7616 else
b6371390
JS
7617 {
7618 // assert guru mode for absolute probes
7619 if ( has_statement_num && has_absolute && !base->privileged )
b530b5b3 7620 throw semantic_error (_("absolute statement probe in unprivileged script"), base->tok);
b6371390
JS
7621
7622 finished_results.push_back (new kprobe_derived_probe (base,
7623 location, "",
7624 statement_num_val,
7625 has_return,
7626 has_statement_num,
7627 has_maxactive,
b642c901
SC
7628 has_path,
7629 has_library,
7630 maxactive_val,
7631 path,
7632 library));
96b030fe 7633 }
79189b84
JS
7634}
7635
dd225250
PS
7636// ------------------------------------------------------------------------
7637// Hardware breakpoint based probes.
7638// ------------------------------------------------------------------------
7639
7640static const string TOK_HWBKPT("data");
7641static const string TOK_HWBKPT_WRITE("write");
7642static const string TOK_HWBKPT_RW("rw");
7643static const string TOK_LENGTH("length");
7644
7645#define HWBKPT_READ 0
7646#define HWBKPT_WRITE 1
7647#define HWBKPT_RW 2
7648struct hwbkpt_derived_probe: public derived_probe
7649{
7650 hwbkpt_derived_probe (probe *base,
7651 probe_point *location,
7652 uint64_t addr,
7653 string symname,
7654 unsigned int len,
7655 bool has_only_read_access,
7656 bool has_only_write_access,
7657 bool has_rw_access
7658 );
7659 Dwarf_Addr hwbkpt_addr;
7660 string symbol_name;
7661 unsigned int hwbkpt_access,hwbkpt_len;
7662
7663 void printsig (std::ostream &o) const;
7664 void join_group (systemtap_session& s);
7665};
7666
7667struct hwbkpt_derived_probe_group: public derived_probe_group
7668{
dd225250 7669private:
dac77b80 7670 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
7671
7672public:
7673 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
7674 void emit_module_decls (systemtap_session& s);
7675 void emit_module_init (systemtap_session& s);
7676 void emit_module_exit (systemtap_session& s);
7677};
7678
7679hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
7680 probe_point *location,
7681 uint64_t addr,
7682 string symname,
7683 unsigned int len,
7684 bool has_only_read_access,
7685 bool has_only_write_access,
822a6a3d 7686 bool):
4c5d1300 7687 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
7688 hwbkpt_addr (addr),
7689 symbol_name (symname),
7690 hwbkpt_len (len)
7691{
7692 this->tok = base->tok;
7693
7694 vector<probe_point::component*> comps;
7695 comps.push_back (new probe_point::component(TOK_KERNEL));
7696
7697 if (hwbkpt_addr)
9ea68eb9
JS
7698 comps.push_back (new probe_point::component (TOK_HWBKPT,
7699 new literal_number(hwbkpt_addr, true)));
7700 else if (symbol_name.size())
7701 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
7702
7703 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
7704
7705 if (has_only_read_access)
9ea68eb9 7706 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
7707//TODO add code for comps.push_back for read, since this flag is not for x86
7708
7709 else
9ea68eb9
JS
7710 {
7711 if (has_only_write_access)
7712 {
7713 this->hwbkpt_access = HWBKPT_WRITE ;
7714 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
7715 }
7716 else
7717 {
7718 this->hwbkpt_access = HWBKPT_RW ;
7719 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
7720 }
7721 }
dd225250
PS
7722
7723 this->sole_location()->components = comps;
7724}
7725
7726void hwbkpt_derived_probe::printsig (ostream& o) const
7727{
7728 sole_location()->print (o);
7729 printsig_nested (o);
7730}
7731
7732void hwbkpt_derived_probe::join_group (systemtap_session& s)
7733{
dac77b80
FCE
7734 if (! s.hwbkpt_derived_probes)
7735 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
7736 s.hwbkpt_derived_probes->enroll (this, s);
7737}
7738
7739void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
7740{
dac77b80
FCE
7741 hwbkpt_probes.push_back (p);
7742
7743 unsigned max_hwbkpt_probes_by_arch = 0;
7744 if (s.architecture == "i386" || s.architecture == "x86_64")
7745 max_hwbkpt_probes_by_arch = 4;
7746 else if (s.architecture == "s390")
7747 max_hwbkpt_probes_by_arch = 1;
7748
c57ea854 7749 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
dac77b80 7750 if (! s.suppress_warnings)
b530b5b3
LB
7751 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
7752 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
7753}
7754
7755void
7756hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
7757{
dac77b80 7758 if (hwbkpt_probes.empty()) return;
dd225250
PS
7759
7760 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
7761
7762 s.op->newline() << "#include <linux/perf_event.h>";
7763 s.op->newline() << "#include <linux/hw_breakpoint.h>";
7764 s.op->newline();
7765
7766 // Forward declare the master entry functions
7767 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
7768 s.op->line() << " int nmi,";
7769 s.op->line() << " struct perf_sample_data *data,";
7770 s.op->line() << " struct pt_regs *regs);";
79189b84 7771
dd225250
PS
7772 // Emit the actual probe list.
7773
7774 s.op->newline() << "static struct perf_event_attr ";
dac77b80 7775 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
7776
7777 s.op->newline() << "static struct perf_event **";
dac77b80 7778 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
7779 s.op->newline() << "static struct stap_hwbkpt_probe {";
7780 s.op->newline() << "int registered_p:1;";
43650b10 7781// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
7782// registered_p = 1 signifies a probe that got registered successfully
7783
faea5e16 7784 // Symbol Names are mostly small and uniform enough
dd225250 7785 // to justify putting const char*.
dac77b80 7786 s.op->newline() << "const char * const symbol;";
dd225250
PS
7787
7788 s.op->newline() << "const unsigned long address;";
7789 s.op->newline() << "uint8_t atype;";
bb0a4e12 7790 s.op->newline() << "unsigned int len;";
26e63673 7791 s.op->newline() << "struct stap_probe * const probe;";
dd225250
PS
7792 s.op->newline() << "} stap_hwbkpt_probes[] = {";
7793 s.op->indent(1);
7794
dac77b80 7795 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 7796 {
dac77b80 7797 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 7798 s.op->newline() << "{";
dd225250
PS
7799 if (p->symbol_name.size())
7800 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
7801 else
7802 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
7803 switch(p->hwbkpt_access){
7804 case HWBKPT_READ:
7805 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 7806 break;
dd225250
PS
7807 case HWBKPT_WRITE:
7808 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 7809 break;
dd225250
PS
7810 case HWBKPT_RW:
7811 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 7812 break;
dd225250
PS
7813 };
7814 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 7815 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 7816 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
7817 s.op->line() << " },";
7818 }
dac77b80 7819 s.op->newline(-1) << "};";
dd225250
PS
7820
7821 // Emit the hwbkpt callback function
7822 s.op->newline() ;
7823 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
7824 s.op->line() << " int nmi,";
7825 s.op->line() << " struct perf_sample_data *data,";
7826 s.op->line() << " struct pt_regs *regs) {";
dac77b80
FCE
7827 s.op->newline(1) << "unsigned int i;";
7828 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
7829 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
7830 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
7831 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
7832 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) {";
7833 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
6eefe942
MW
7834 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7835 "_STP_PROBE_HANDLER_HWBKPT");
dd225250 7836 s.op->newline() << "c->regs = regs;";
26e63673 7837 s.op->newline() << "(*sdp->probe->ph) (c);";
dd225250 7838 common_probe_entryfn_epilogue (s.op);
dac77b80 7839 s.op->newline(-1) << "}";
dd225250
PS
7840 s.op->newline(-1) << "}";
7841 s.op->newline() << "return 0;";
dac77b80 7842 s.op->newline(-1) << "}";
dd225250
PS
7843}
7844
7845void
7846hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
7847{
dac77b80 7848 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
7849 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
7850 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
7851 s.op->newline() << "void *addr = (void *) sdp->address;";
7852 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
7853 s.op->newline() << "hw_breakpoint_init(hp);";
7854 s.op->newline() << "if (addr)";
7855 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
7856 s.op->newline(-1) << "else { ";
7857 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
7858 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 7859 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
7860 s.op->newline() << "continue;";
7861 s.op->newline(-1) << "}";
7862 s.op->newline(-1) << "}";
7863 s.op->newline() << "hp->bp_type = sdp->atype;";
7864
7865 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 7866 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
7867 {
7868 s.op->newline() << "switch(sdp->len) {";
7869 s.op->newline() << "case 1:";
7870 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
7871 s.op->newline() << "break;";
7872 s.op->newline(-1) << "case 2:";
7873 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
7874 s.op->newline() << "break;";
7875 s.op->newline(-1) << "case 3:";
7876 s.op->newline() << "case 4:";
7877 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
7878 s.op->newline() << "break;";
7879 s.op->newline(-1) << "case 5:";
7880 s.op->newline() << "case 6:";
7881 s.op->newline() << "case 7:";
7882 s.op->newline() << "case 8:";
7883 s.op->newline() << "default:"; // XXX: could instead reject
7884 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
7885 s.op->newline() << "break;";
7886 s.op->newline(-1) << "}";
7887 }
7888 else // other architectures presumed straightforward
7889 s.op->newline() << "hp->bp_len = sdp->len;";
7890
26e63673 7891 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
7892 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
7893 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
7894 s.op->newline() << "#else";
dac77b80 7895 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 7896 s.op->newline() << "#endif";
43650b10
WC
7897 s.op->newline() << "rc = 0;";
7898 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
7899 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
7900 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
7901 s.op->newline(-1) << "}";
217ef1f4
WC
7902 s.op->newline() << "if (rc) {";
7903 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 7904 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 7905 s.op->newline(-1) << "}";
dd225250 7906 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
7907 s.op->newline(-1) << "}"; // for loop
7908}
7909
7910void
7911hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
7912{
7913 //Unregister hwbkpt probes.
dac77b80 7914 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 7915 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
7916 s.op->newline() << "if (sdp->registered_p == 0) continue;";
7917 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
7918 s.op->newline() << "sdp->registered_p = 0;";
7919 s.op->newline(-1) << "}";
7920}
7921
7922struct hwbkpt_builder: public derived_probe_builder
7923{
7924 hwbkpt_builder() {}
7925 virtual void build(systemtap_session & sess,
7926 probe * base,
7927 probe_point * location,
7928 literal_map_t const & parameters,
7929 vector<derived_probe *> & finished_results);
7930};
7931
7932void
7933hwbkpt_builder::build(systemtap_session & sess,
7934 probe * base,
7935 probe_point * location,
7936 literal_map_t const & parameters,
7937 vector<derived_probe *> & finished_results)
7938{
7939 string symbol_str_val;
7940 int64_t hwbkpt_address, len;
7941 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
7942
b47f3a55 7943 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
b530b5b3 7944 throw semantic_error (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
7945 location->components[0]->tok);
7946 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
b530b5b3 7947 throw semantic_error (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
7948 location->components[0]->tok);
7949
dd225250
PS
7950 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
7951 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
7952 has_len = get_param (parameters, TOK_LENGTH, len);
7953 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
7954 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
7955
7956 if (!has_len)
7957 len = 1;
7958
7959 if (has_addr)
7960 finished_results.push_back (new hwbkpt_derived_probe (base,
7961 location,
7962 hwbkpt_address,
7963 "",len,0,
7964 has_write,
7965 has_rw));
5d8a0aea 7966 else if (has_symbol_str)
dd225250
PS
7967 finished_results.push_back (new hwbkpt_derived_probe (base,
7968 location,
7969 0,
7970 symbol_str_val,len,0,
7971 has_write,
7972 has_rw));
5d8a0aea
FCE
7973 else
7974 assert (0);
dd225250 7975}
342d3f96 7976
0a6f5a3f
JS
7977// ------------------------------------------------------------------------
7978// statically inserted kernel-tracepoint derived probes
7979// ------------------------------------------------------------------------
7980
6fb70fb7 7981struct tracepoint_arg
79189b84 7982{
ad370dcc 7983 string name, c_type, typecast;
dcaa1a65 7984 bool usable, used, isptr;
f8a968bc 7985 Dwarf_Die type_die;
dcaa1a65 7986 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 7987};
79189b84 7988
0a6f5a3f
JS
7989struct tracepoint_derived_probe: public derived_probe
7990{
79189b84
JS
7991 tracepoint_derived_probe (systemtap_session& s,
7992 dwflpp& dw, Dwarf_Die& func_die,
7993 const string& tracepoint_name,
7994 probe* base_probe, probe_point* location);
bc9a523d 7995
79189b84 7996 systemtap_session& sess;
6fb70fb7
JS
7997 string tracepoint_name, header;
7998 vector <struct tracepoint_arg> args;
bc9a523d 7999
6fb70fb7 8000 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 8001 void getargs (std::list<std::string> &arg_set) const;
79189b84 8002 void join_group (systemtap_session& s);
3e3bd7b6 8003 void print_dupe_stamp(ostream& o);
0a6f5a3f 8004};
79189b84
JS
8005
8006
0a6f5a3f 8007struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 8008{
79189b84
JS
8009 void emit_module_decls (systemtap_session& s);
8010 void emit_module_init (systemtap_session& s);
8011 void emit_module_exit (systemtap_session& s);
0a6f5a3f 8012};
79189b84 8013
bc9a523d 8014
f8a968bc
JS
8015struct tracepoint_var_expanding_visitor: public var_expanding_visitor
8016{
8017 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
8018 vector <struct tracepoint_arg>& args):
8019 dw (dw), probe_name (probe_name), args (args) {}
8020 dwflpp& dw;
8021 const string& probe_name;
8022 vector <struct tracepoint_arg>& args;
bc9a523d 8023
f8a968bc
JS
8024 void visit_target_symbol (target_symbol* e);
8025 void visit_target_symbol_arg (target_symbol* e);
8026 void visit_target_symbol_context (target_symbol* e);
8027};
79189b84
JS
8028
8029
f8a968bc
JS
8030void
8031tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 8032{
277c21bc 8033 string argname = e->name.substr(1);
75ead1f7 8034
f8a968bc
JS
8035 // search for a tracepoint parameter matching this name
8036 tracepoint_arg *arg = NULL;
8037 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 8038 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
8039 {
8040 arg = &args[i];
8041 arg->used = true;
8042 break;
8043 }
75ead1f7 8044
f8a968bc
JS
8045 if (arg == NULL)
8046 {
8047 stringstream alternatives;
8048 for (unsigned i = 0; i < args.size(); ++i)
8049 alternatives << " $" << args[i].name;
046e7190 8050 alternatives << " $$name $$parms $$vars";
75ead1f7 8051
f8a968bc
JS
8052 // We hope that this value ends up not being referenced after all, so it
8053 // can be optimized out quietly.
b530b5b3
LB
8054 throw semantic_error(_F("unable to find tracepoint variable '%s' (alternatives: %s)",
8055 e->name.c_str(), alternatives.str().c_str()), e->tok);
f8a968bc
JS
8056 // NB: we can have multiple errors, since a target variable
8057 // may be expanded in several different contexts:
8058 // trace ("*") { $foo->bar }
f8a968bc 8059 }
75ead1f7 8060
f8a968bc 8061 // make sure we're not dereferencing base types
dc5a09fc 8062 if (!arg->isptr)
d19a9a82 8063 e->assert_no_components("tracepoint", true);
75ead1f7 8064
f8a968bc
JS
8065 // we can only write to dereferenced fields, and only if guru mode is on
8066 bool lvalue = is_active_lvalue(e);
8067 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
b530b5b3 8068 throw semantic_error(_F("write to tracepoint variable '%s' not permitted", e->name.c_str()), e->tok);
c69a87e0 8069
ad370dcc
JS
8070 // XXX: if a struct/union arg is passed by value, then writing to its fields
8071 // is also meaningless until you dereference past a pointer member. It's
8072 // harder to detect and prevent that though...
75ead1f7 8073
f8a968bc
JS
8074 if (e->components.empty())
8075 {
03c75a4a 8076 if (e->addressof)
b530b5b3 8077 throw semantic_error(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 8078
3e3bd7b6 8079 // Just grab the value from the probe locals
a45664f4
JS
8080 symbol* sym = new symbol;
8081 sym->tok = e->tok;
8082 sym->name = "__tracepoint_arg_" + arg->name;
8083 provide (sym);
f8a968bc
JS
8084 }
8085 else
8086 {
5f36109e
JS
8087 // make a copy of the original as a bare target symbol for the tracepoint
8088 // value, which will be passed into the dwarf dereferencing code
8089 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
8090 e2->components.clear();
8091
8092 if (e->components.back().type == target_symbol::comp_pretty_print)
8093 {
8094 if (lvalue)
b530b5b3 8095 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 8096
d19a9a82 8097 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
8098 dpp.expand()->visit (this);
8099 return;
8100 }
8101
f8a968bc
JS
8102 // Synthesize a function to dereference the dwarf fields,
8103 // with a pointer parameter that is the base tracepoint variable
8104 functiondecl *fdecl = new functiondecl;
59de45f1 8105 fdecl->synthetic = true;
f8a968bc
JS
8106 fdecl->tok = e->tok;
8107 embeddedcode *ec = new embeddedcode;
8108 ec->tok = e->tok;
75ead1f7 8109
f8a968bc 8110 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
277c21bc 8111 + "_" + e->name.substr(1)
aca66a36 8112 + "_" + lex_cast(tick++));
75ead1f7 8113
f8a968bc
JS
8114 fdecl->name = fname;
8115 fdecl->body = ec;
75ead1f7 8116
b5a0dd41
FCE
8117 // PR10601: adapt to kernel-vs-userspace loc2c-runtime
8118 ec->code += "\n#define fetch_register k_fetch_register\n";
8119 ec->code += "#define store_register k_store_register\n";
c69a87e0
FCE
8120
8121 ec->code += dw.literal_stmt_for_pointer (&arg->type_die, e,
f8a968bc 8122 lvalue, fdecl->type);
75ead1f7 8123
f8a968bc
JS
8124 // Give the fdecl an argument for the raw tracepoint value
8125 vardecl *v1 = new vardecl;
8126 v1->type = pe_long;
8127 v1->name = "pointer";
8128 v1->tok = e->tok;
8129 fdecl->formal_args.push_back(v1);
75ead1f7 8130
6fda2dff
JS
8131 // Any non-literal indexes need to be passed in too.
8132 for (unsigned i = 0; i < e->components.size(); ++i)
8133 if (e->components[i].type == target_symbol::comp_expression_array_index)
8134 {
8135 vardecl *v = new vardecl;
8136 v->type = pe_long;
aca66a36 8137 v->name = "index" + lex_cast(i);
6fda2dff
JS
8138 v->tok = e->tok;
8139 fdecl->formal_args.push_back(v);
8140 }
8141
f8a968bc
JS
8142 if (lvalue)
8143 {
8144 // Modify the fdecl so it carries a pe_long formal
8145 // argument called "value".
75ead1f7 8146
f8a968bc
JS
8147 // FIXME: For the time being we only support setting target
8148 // variables which have base types; these are 'pe_long' in
8149 // stap's type vocabulary. Strings and pointers might be
8150 // reasonable, some day, but not today.
8151
8152 vardecl *v2 = new vardecl;
8153 v2->type = pe_long;
8154 v2->name = "value";
8155 v2->tok = e->tok;
8156 fdecl->formal_args.push_back(v2);
8157 }
8158 else
8159 ec->code += "/* pure */";
8160
64211010
DB
8161 ec->code += "/* unprivileged */";
8162
b5a0dd41
FCE
8163 // PR10601
8164 ec->code += "\n#undef fetch_register\n";
8165 ec->code += "\n#undef store_register\n";
aff5d390 8166
f8809d54 8167 fdecl->join (dw.sess);
75ead1f7 8168
f8a968bc
JS
8169 // Synthesize a functioncall.
8170 functioncall* n = new functioncall;
8171 n->tok = e->tok;
8172 n->function = fname;
6fda2dff
JS
8173 n->args.push_back(require(e2));
8174
8175 // Any non-literal indexes need to be passed in too.
8176 for (unsigned i = 0; i < e->components.size(); ++i)
8177 if (e->components[i].type == target_symbol::comp_expression_array_index)
8178 n->args.push_back(require(e->components[i].expr_index));
75ead1f7 8179
f8a968bc
JS
8180 if (lvalue)
8181 {
8182 // Provide the functioncall to our parent, so that it can be
8183 // used to substitute for the assignment node immediately above
8184 // us.
8185 assert(!target_symbol_setter_functioncalls.empty());
8186 *(target_symbol_setter_functioncalls.top()) = n;
8187 }
75ead1f7 8188
f8a968bc
JS
8189 provide (n);
8190 }
75ead1f7
JS
8191}
8192
8193
f8a968bc
JS
8194void
8195tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 8196{
03c75a4a 8197 if (e->addressof)
b530b5b3 8198 throw semantic_error(_("cannot take address of context variable"), e->tok);
03c75a4a 8199
f8a968bc 8200 if (is_active_lvalue (e))
b530b5b3 8201 throw semantic_error(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 8202
277c21bc 8203 if (e->name == "$$name")
f8a968bc 8204 {
5f36109e
JS
8205 e->assert_no_components("tracepoint");
8206
bfdaad1e
DS
8207 // Synthesize an embedded expression.
8208 embedded_expr *expr = new embedded_expr;
8209 expr->tok = e->tok;
8210 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 8211 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 8212 provide (expr);
f8a968bc 8213 }
277c21bc 8214 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 8215 {
5f36109e
JS
8216 e->assert_no_components("tracepoint", true);
8217
f8a968bc
JS
8218 token* pf_tok = new token(*e->tok);
8219 pf_tok->content = "sprintf";
0a6f5a3f 8220
d5e178c1 8221 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 8222
f8a968bc 8223 for (unsigned i = 0; i < args.size(); ++i)
b278033a 8224 {
dcaa1a65
JS
8225 if (!args[i].usable)
8226 continue;
f8a968bc
JS
8227 if (i > 0)
8228 pf->raw_components += " ";
8229 pf->raw_components += args[i].name;
3e3bd7b6 8230 target_symbol *tsym = new target_symbol;
f8a968bc 8231 tsym->tok = e->tok;
277c21bc 8232 tsym->name = "$" + args[i].name;
5f36109e 8233 tsym->components = e->components;
b278033a 8234
f8a968bc
JS
8235 // every variable should always be accessible!
8236 tsym->saved_conversion_error = 0;
8237 expression *texp = require (tsym); // NB: throws nothing ...
14a97852
JS
8238 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
8239 {
8240 if (dw.sess.verbose>2)
8241 for (semantic_error *c = tsym->saved_conversion_error;
8242 c != 0; c = c->chain)
b530b5b3 8243 clog << _("variable location problem: ") << c->what() << endl;
14a97852
JS
8244 pf->raw_components += "=?";
8245 continue;
8246 }
b278033a 8247
5f36109e
JS
8248 if (!e->components.empty() &&
8249 e->components[0].type == target_symbol::comp_pretty_print)
8250 pf->raw_components += "=%s";
8251 else
8252 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
8253 pf->args.push_back(texp);
8254 }
0a6f5a3f 8255
f8a968bc
JS
8256 pf->components = print_format::string_to_components(pf->raw_components);
8257 provide (pf);
b278033a 8258 }
f8a968bc
JS
8259 else
8260 assert(0); // shouldn't get here
0a6f5a3f
JS
8261}
8262
0a6f5a3f 8263void
f8a968bc 8264tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 8265{
aff5d390 8266 try
c69a87e0 8267 {
277c21bc 8268 assert(e->name.size() > 0 && e->name[0] == '$');
aff5d390 8269
277c21bc 8270 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0
FCE
8271 visit_target_symbol_context (e);
8272 else
8273 visit_target_symbol_arg (e);
8274 }
8275 catch (const semantic_error &er)
8276 {
1af1e62d 8277 e->chain (er);
c69a87e0
FCE
8278 provide (e);
8279 }
0a6f5a3f
JS
8280}
8281
8282
8283
79189b84
JS
8284tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
8285 dwflpp& dw, Dwarf_Die& func_die,
8286 const string& tracepoint_name,
8287 probe* base, probe_point* loc):
4c5d1300 8288 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 8289 sess (s), tracepoint_name (tracepoint_name)
56894e91 8290{
79189b84
JS
8291 // create synthetic probe point name; preserve condition
8292 vector<probe_point::component*> comps;
8293 comps.push_back (new probe_point::component (TOK_KERNEL));
8294 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
8295 this->sole_location()->components = comps;
8296
6fb70fb7
JS
8297 // fill out the available arguments in this tracepoint
8298 build_args(dw, func_die);
56894e91 8299
6fb70fb7
JS
8300 // determine which header defined this tracepoint
8301 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
8302 header = decl_file;
8303
8304#if 0 /* This convention is not enforced. */
6fb70fb7
JS
8305 size_t header_pos = decl_file.rfind("trace/");
8306 if (header_pos == string::npos)
8307 throw semantic_error ("cannot parse header location for tracepoint '"
8308 + tracepoint_name + "' in '"
8309 + decl_file + "'");
8310 header = decl_file.substr(header_pos);
d4393459 8311#endif
56894e91 8312
6fb70fb7
JS
8313 // tracepoints from FOO_event_types.h should really be included from FOO.h
8314 // XXX can dwarf tell us the include hierarchy? it would be better to
8315 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 8316 // XXX: see also PR9993.
d4393459 8317 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
8318 if (header_pos != string::npos)
8319 header.erase(header_pos, 12);
56894e91 8320
f8a968bc
JS
8321 // Now expand the local variables in the probe body
8322 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 8323 v.replace (this->body);
a45664f4
JS
8324 for (unsigned i = 0; i < args.size(); i++)
8325 if (args[i].used)
8326 {
8327 vardecl* v = new vardecl;
8328 v->name = "__tracepoint_arg_" + args[i].name;
8329 v->tok = this->tok;
58701b78 8330 v->set_arity(0, this->tok);
a45664f4
JS
8331 v->type = pe_long;
8332 v->skip_init = true;
8333 this->locals.push_back (v);
8334 }
56894e91 8335
79189b84 8336 if (sess.verbose > 2)
ce0f6648 8337 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 8338}
dc38c0ae 8339
56894e91 8340
f8a968bc 8341static bool
dcaa1a65 8342resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 8343{
d19a9a82 8344 Dwarf_Die type;
dcaa1a65 8345 switch (dwarf_tag(&arg.type_die))
b20febf3 8346 {
f8a968bc
JS
8347 case DW_TAG_typedef:
8348 case DW_TAG_const_type:
8349 case DW_TAG_volatile_type:
8350 // iterate on the referent type
3d1ad340 8351 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 8352 && resolve_tracepoint_arg_type(arg));
f8a968bc
JS
8353 case DW_TAG_base_type:
8354 // base types will simply be treated as script longs
dcaa1a65 8355 arg.isptr = false;
f8a968bc
JS
8356 return true;
8357 case DW_TAG_pointer_type:
dcaa1a65
JS
8358 // pointers can be treated as script longs,
8359 // and if we know their type, they can also be dereferenced
d19a9a82
JS
8360 type = arg.type_die;
8361 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
8362 {
8363 // It still might be a non-type, e.g. const void,
8364 // so we need to strip away all qualifiers.
8365 int tag = dwarf_tag(&arg.type_die);
8366 if (tag != DW_TAG_typedef &&
8367 tag != DW_TAG_const_type &&
8368 tag != DW_TAG_volatile_type)
8369 {
8370 arg.isptr = true;
8371 break;
8372 }
8373 }
8374 if (!arg.isptr)
8375 arg.type_die = type;
ad370dcc
JS
8376 arg.typecast = "(intptr_t)";
8377 return true;
8378 case DW_TAG_structure_type:
8379 case DW_TAG_union_type:
8380 // for structs/unions which are passed by value, we turn it into
8381 // a pointer that can be dereferenced.
8382 arg.isptr = true;
8383 arg.typecast = "(intptr_t)&";
dcaa1a65 8384 return true;
f8a968bc
JS
8385 default:
8386 // should we consider other types too?
8387 return false;
b20febf3 8388 }
56894e91
JS
8389}
8390
8391
8392void
822a6a3d 8393tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 8394{
6fb70fb7
JS
8395 Dwarf_Die arg;
8396 if (dwarf_child(&func_die, &arg) == 0)
8397 do
8398 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
8399 {
8400 // build a tracepoint_arg for this parameter
8401 tracepoint_arg tparg;
23d106b9 8402 tparg.name = dwarf_diename(&arg);
56894e91 8403
6fb70fb7 8404 // read the type of this parameter
3d1ad340 8405 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 8406 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
ce0f6648
LB
8407 throw semantic_error (_F("cannot get type of parameter '%s' of tracepoint '%s'",
8408 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 8409
dcaa1a65 8410 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
8411 args.push_back(tparg);
8412 if (sess.verbose > 4)
b530b5b3
LB
8413 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s'",
8414 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str()) << endl;
6fb70fb7
JS
8415 }
8416 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
8417}
8418
dc38c0ae 8419void
d0bfd2ac 8420tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 8421{
dcaa1a65
JS
8422 for (unsigned i = 0; i < args.size(); ++i)
8423 if (args[i].usable)
d0bfd2ac 8424 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
8425}
8426
79189b84
JS
8427void
8428tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 8429{
79189b84
JS
8430 if (! s.tracepoint_derived_probes)
8431 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
8432 s.tracepoint_derived_probes->enroll (this);
8433}
e38d6504 8434
56894e91 8435
197a4d62 8436void
3e3bd7b6 8437tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 8438{
3e3bd7b6
JS
8439 for (unsigned i = 0; i < args.size(); i++)
8440 if (args[i].used)
8441 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 8442}
56894e91 8443
3e3bd7b6 8444
d4393459 8445static vector<string> tracepoint_extra_decls (systemtap_session& s)
47dd066d 8446{
3c1b3d06
FCE
8447 vector<string> they_live;
8448 // PR 9993
8449 // XXX: may need this to be configurable
d4393459 8450 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
8451
8452 // PR11649: conditional extra header
8453 // for kvm tracepoints in 2.6.33ish
8454 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
8455 they_live.push_back ("#include <linux/kvm_host.h>");
8456 }
8457
8458 if (s.kernel_config["CONFIG_XFS_FS"] != string("")) {
8459 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
8460 if (s.kernel_source_tree != "")
8461 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
8462 they_live.push_back ("struct xfs_mount;");
8463 they_live.push_back ("struct xfs_inode;");
8464 they_live.push_back ("struct xfs_buf;");
8465 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 8466 they_live.push_back ("struct xfs_trans;");
9e0cd21a 8467 }
d4393459
FCE
8468
8469 if (s.kernel_config["CONFIG_NFSD"] != string("")) {
8470 they_live.push_back ("struct rpc_task;");
8471 }
8472
8473 they_live.push_back ("#include <asm/cputime.h>");
8474
c2cf1b87
FCE
8475 // linux 3.0
8476 they_live.push_back ("struct cpu_workqueue_struct;");
8477
8478 if (s.kernel_config["CONFIG_EXT4_FS"] != string(""))
8479 if (s.kernel_source_tree != "")
8480 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
8481
3c1b3d06
FCE
8482 return they_live;
8483}
47dd066d
WC
8484
8485
8486void
79189b84 8487tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 8488{
79189b84
JS
8489 if (probes.empty())
8490 return;
47dd066d 8491
96b030fe
JS
8492 s.op->newline() << "/* ---- tracepoint probes ---- */";
8493 s.op->newline();
79189b84 8494
3c1b3d06
FCE
8495 // PR9993: Add extra headers to work around undeclared types in individual
8496 // include/trace/foo.h files
d4393459
FCE
8497 const vector<string>& extra_decls = tracepoint_extra_decls (s);
8498 for (unsigned z=0; z<extra_decls.size(); z++)
8499 s.op->newline() << extra_decls[z] << "\n";
47dd066d 8500
6fb70fb7
JS
8501 for (unsigned i = 0; i < probes.size(); ++i)
8502 {
8503 tracepoint_derived_probe *p = probes[i];
47dd066d 8504
96b030fe
JS
8505 // emit a separate entry function for each probe, since tracepoints
8506 // don't provide any sort of context pointer.
392e08b7 8507 s.op->newline() << "#undef TRACE_INCLUDE_FILE";
d4393459 8508 s.op->newline() << "#undef TRACE_INCLUDE_PATH";
75ae2ec9
FCE
8509
8510 // strip include/ substring, the same way as done in get_tracequery_module()
8511 string header = p->header;
8512 size_t root_pos = header.rfind("include/");
8513 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
8514 s.op->newline() << "#include <" << header << ">";
5f73a260
JS
8515
8516 // Starting in 2.6.35, at the same time NOARGS was added, the callback
8517 // always has a void* as the first parameter. PR11599
8518 s.op->newline() << "#ifdef DECLARE_TRACE_NOARGS";
8519 s.op->newline() << "#define STAP_TP_DATA , NULL";
8520 s.op->newline() << "#define STAP_TP_PROTO void *cb_data"
8521 << " __attribute__ ((unused))";
8522 if (!p->args.empty())
8523 s.op->line() << ",";
8524 s.op->newline() << "#else";
8525 s.op->newline() << "#define STAP_TP_DATA";
8526 s.op->newline() << "#define STAP_TP_PROTO";
8527 if (p->args.empty())
8528 s.op->line() << " void";
8529 s.op->newline() << "#endif";
8530
6fb70fb7 8531 s.op->newline() << "static void enter_tracepoint_probe_" << i << "(";
5f73a260
JS
8532 s.op->newline(2) << "STAP_TP_PROTO";
8533
6fb70fb7
JS
8534 for (unsigned j = 0; j < p->args.size(); ++j)
8535 {
8536 if (j > 0)
5f73a260
JS
8537 s.op->line() << ",";
8538 s.op->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
6fb70fb7 8539 }
5f73a260
JS
8540 s.op->newline() << ")";
8541 s.op->newline(-2) << "{";
8542
26e63673 8543 s.op->newline(1) << "struct stap_probe * const probe = "
faea5e16 8544 << common_probe_init (p) << ";";
6eefe942
MW
8545 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "probe",
8546 "_STP_PROBE_HANDLER_TRACEPOINT");
6dceb5c9 8547 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
8548 << lex_cast_qstring (p->tracepoint_name)
8549 << ";";
f8a968bc
JS
8550 for (unsigned j = 0; j < p->args.size(); ++j)
8551 if (p->args[j].used)
8552 {
66671fd8 8553 s.op->newline() << "c->probe_locals." << p->name << ".__tracepoint_arg_"
f8a968bc 8554 << p->args[j].name << " = (int64_t)";
ad370dcc 8555 s.op->line() << p->args[j].typecast;
f8a968bc
JS
8556 s.op->line() << "__tracepoint_arg_" << p->args[j].name << ";";
8557 }
26e63673 8558 s.op->newline() << "(*probe->ph) (c);";
6fb70fb7
JS
8559 common_probe_entryfn_epilogue (s.op);
8560 s.op->newline(-1) << "}";
47dd066d 8561
96b030fe
JS
8562 // emit normalized registration functions
8563 s.op->newline() << "static int register_tracepoint_probe_" << i << "(void) {";
8564 s.op->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 8565 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
96b030fe 8566 s.op->newline(-1) << "}";
47dd066d 8567
86758d5f
JS
8568 // NB: we're not prepared to deal with unreg failures. However, failures
8569 // can only occur if the tracepoint doesn't exist (yet?), or if we
8570 // weren't even registered. The former should be OKed by the initial
8571 // registration call, and the latter is safe to ignore.
8572 s.op->newline() << "static void unregister_tracepoint_probe_" << i << "(void) {";
8573 s.op->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 8574 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
96b030fe 8575 s.op->newline(-1) << "}";
6fb70fb7 8576 s.op->newline();
5f73a260
JS
8577
8578 s.op->newline() << "#undef STAP_TP_DATA";
8579 s.op->newline() << "#undef STAP_TP_PROTO";
8580 s.op->newline();
af304783
DS
8581 }
8582
96b030fe
JS
8583 // emit an array of registration functions for easy init/shutdown
8584 s.op->newline() << "static struct stap_tracepoint_probe {";
8585 s.op->newline(1) << "int (*reg)(void);";
86758d5f 8586 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
8587 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
8588 s.op->indent(1);
8589 for (unsigned i = 0; i < probes.size(); ++i)
8590 {
8591 s.op->newline () << "{";
8592 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
8593 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
8594 s.op->line() << " },";
8595 }
8596 s.op->newline(-1) << "};";
8597 s.op->newline();
47dd066d
WC
8598}
8599
8600
79189b84
JS
8601void
8602tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 8603{
79189b84
JS
8604 if (probes.size () == 0)
8605 return;
47dd066d 8606
79189b84 8607 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
8608 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
8609 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
8610 s.op->newline() << "if (rc) {";
8611 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
8612 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
8613 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
8614 s.op->newline(-1) << "}";
8615 s.op->newline(-1) << "}";
47dd066d 8616
bc9a523d
FCE
8617 // This would be technically proper (on those autoconf-detectable
8618 // kernels that include this function in tracepoint.h), however we
8619 // already make several calls to synchronze_sched() during our
8620 // shutdown processes.
47dd066d 8621
bc9a523d
FCE
8622 // s.op->newline() << "if (rc)";
8623 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
8624 // s.op->indent(-1);
79189b84 8625}
47dd066d
WC
8626
8627
79189b84
JS
8628void
8629tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 8630{
79189b84
JS
8631 if (probes.empty())
8632 return;
47dd066d 8633
96b030fe
JS
8634 s.op->newline() << "/* deregister tracepoint probes */";
8635 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
8636 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
8637 s.op->indent(-1);
47dd066d 8638
bc9a523d 8639 // Not necessary: see above.
47dd066d 8640
bc9a523d 8641 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 8642}
b20febf3 8643
47dd066d 8644
75ead1f7 8645struct tracepoint_query : public base_query
47dd066d 8646{
75ead1f7
JS
8647 tracepoint_query(dwflpp & dw, const string & tracepoint,
8648 probe * base_probe, probe_point * base_loc,
8649 vector<derived_probe *> & results):
8650 base_query(dw, "*"), tracepoint(tracepoint),
8651 base_probe(base_probe), base_loc(base_loc),
8652 results(results) {}
47dd066d 8653
75ead1f7 8654 const string& tracepoint;
47dd066d 8655
75ead1f7
JS
8656 probe * base_probe;
8657 probe_point * base_loc;
8658 vector<derived_probe *> & results;
f982c59b 8659 set<string> probed_names;
47dd066d 8660
75ead1f7
JS
8661 void handle_query_module();
8662 int handle_query_cu(Dwarf_Die * cudie);
8663 int handle_query_func(Dwarf_Die * func);
822a6a3d 8664 void query_library (const char *) {}
b20febf3 8665
75ead1f7
JS
8666 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
8667 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
8668};
47dd066d
WC
8669
8670
8671void
75ead1f7 8672tracepoint_query::handle_query_module()
47dd066d 8673{
75ead1f7
JS
8674 // look for the tracepoints in each CU
8675 dw.iterate_over_cus(tracepoint_query_cu, this);
47dd066d
WC
8676}
8677
8678
75ead1f7
JS
8679int
8680tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 8681{
75ead1f7 8682 dw.focus_on_cu (cudie);
47dd066d 8683
75ead1f7
JS
8684 // look at each function to see if it's a tracepoint
8685 string function = "stapprobe_" + tracepoint;
8686 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
8687}
8688
8689
75ead1f7
JS
8690int
8691tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 8692{
75ead1f7 8693 dw.focus_on_function (func);
47dd066d 8694
60d98537 8695 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 8696 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
8697
8698 // check for duplicates -- sometimes tracepoint headers may be indirectly
8699 // included in more than one of our tracequery modules.
8700 if (!probed_names.insert(tracepoint_instance).second)
8701 return DWARF_CB_OK;
8702
79189b84
JS
8703 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
8704 tracepoint_instance,
8705 base_probe, base_loc);
8706 results.push_back (dp);
75ead1f7 8707 return DWARF_CB_OK;
47dd066d
WC
8708}
8709
8710
75ead1f7
JS
8711int
8712tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 8713{
75ead1f7 8714 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 8715 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 8716 return q->handle_query_cu(cudie);
47dd066d
WC
8717}
8718
8719
75ead1f7
JS
8720int
8721tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 8722{
75ead1f7 8723 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 8724 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 8725 return q->handle_query_func(func);
47dd066d
WC
8726}
8727
8728
0a6f5a3f 8729struct tracepoint_builder: public derived_probe_builder
47dd066d 8730{
0a6f5a3f
JS
8731private:
8732 dwflpp *dw;
8733 bool init_dw(systemtap_session& s);
55e50c24
JS
8734 string get_tracequery_module(systemtap_session& s,
8735 const vector<string>& headers);
47dd066d 8736
0a6f5a3f 8737public:
47dd066d 8738
0a6f5a3f
JS
8739 tracepoint_builder(): dw(0) {}
8740 ~tracepoint_builder() { delete dw; }
47dd066d 8741
0a6f5a3f
JS
8742 void build_no_more (systemtap_session& s)
8743 {
8744 if (dw && s.verbose > 3)
b530b5b3 8745 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
8746 delete dw;
8747 dw = NULL;
435f53a7
FCE
8748
8749 delete_session_module_cache (s);
0a6f5a3f 8750 }
47dd066d 8751
0a6f5a3f
JS
8752 void build(systemtap_session& s,
8753 probe *base, probe_point *location,
8754 literal_map_t const& parameters,
8755 vector<derived_probe*>& finished_results);
8756};
47dd066d 8757
47dd066d 8758
f982c59b
JS
8759string
8760tracepoint_builder::get_tracequery_module(systemtap_session& s,
55e50c24 8761 const vector<string>& headers)
0a6f5a3f 8762{
c95eddf7 8763 if (s.verbose > 2)
55e50c24 8764 {
ce0f6648 8765 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
8766 for (size_t i = 0; i < headers.size(); ++i)
8767 clog << " " << headers[i] << endl;
8768 }
c95eddf7 8769
a2639cb7 8770 string tracequery_path;
b278033a
JS
8771 if (s.use_cache)
8772 {
8773 // see if the cached module exists
55e50c24 8774 tracequery_path = find_tracequery_hash(s, headers);
d105f664 8775 if (!tracequery_path.empty() && !s.poison_cache)
b278033a 8776 {
a2639cb7 8777 int fd = open(tracequery_path.c_str(), O_RDONLY);
b278033a
JS
8778 if (fd != -1)
8779 {
8780 if (s.verbose > 2)
b530b5b3 8781 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
b278033a 8782 close(fd);
f982c59b 8783 return tracequery_path;
b278033a
JS
8784 }
8785 }
8786 }
47dd066d 8787
b278033a 8788 // no cached module, time to make it
f982c59b 8789
55e50c24
JS
8790 // PR9993: Add extra headers to work around undeclared types in individual
8791 // include/trace/foo.h files
d4393459 8792 vector<string> short_decls = tracepoint_extra_decls(s);
55e50c24
JS
8793
8794 // add each requested tracepoint header
8795 for (size_t i = 0; i < headers.size(); ++i)
8796 {
8797 const string &header = headers[i];
75ae2ec9 8798 size_t root_pos = header.rfind("include/");
d4393459 8799 short_decls.push_back(string("#include <") +
75ae2ec9 8800 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 8801 string(">"));
55e50c24 8802 }
f982c59b 8803
0a6f5a3f 8804 string tracequery_ko;
d4393459 8805 int rc = make_tracequery(s, tracequery_ko, short_decls);
0a6f5a3f 8806 if (rc != 0)
c95eddf7 8807 tracequery_ko = "/dev/null";
47dd066d 8808
e16dc041 8809 // try to save tracequery in the cache
b278033a 8810 if (s.use_cache)
e16dc041
JS
8811 copy_file(tracequery_ko, tracequery_path, s.verbose > 2);
8812
f982c59b
JS
8813 return tracequery_ko;
8814}
8815
8816
d4393459 8817
f982c59b
JS
8818bool
8819tracepoint_builder::init_dw(systemtap_session& s)
8820{
8821 if (dw != NULL)
8822 return true;
8823
8824 vector<string> tracequery_modules;
55e50c24 8825 vector<string> system_headers;
f982c59b
JS
8826
8827 glob_t trace_glob;
d4393459
FCE
8828
8829 // find kernel_source_tree
8830 if (s.kernel_source_tree == "")
f982c59b 8831 {
d4393459
FCE
8832 unsigned found;
8833 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
8834 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
8835 if (found)
8836 {
8837 Dwarf_Die *cudie = 0;
8838 Dwarf_Addr bias;
8839 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
8840 {
8841 if (pending_interrupts) break;
8842 Dwarf_Attribute attr;
8843 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
8844 if (name)
8845 {
61f1a63b 8846 if (s.verbose > 2)
b530b5b3 8847 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
61f1a63b 8848
d4393459
FCE
8849 s.kernel_source_tree = name;
8850 break; // skip others; modern Kbuild uses same comp_dir for them all
8851 }
8852 }
8853 }
8854 }
8855
8856 // prefixes
8857 vector<string> glob_prefixes;
8858 glob_prefixes.push_back (s.kernel_build_tree);
8859 if (s.kernel_source_tree != "")
8860 glob_prefixes.push_back (s.kernel_source_tree);
8861
8862 // suffixes
8863 vector<string> glob_suffixes;
8864 glob_suffixes.push_back("include/trace/events/*.h");
8865 glob_suffixes.push_back("include/trace/*.h");
8866 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
f89ff3e2 8867 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d4393459
FCE
8868
8869 // compute cartesian product
8870 vector<string> globs;
8871 for (unsigned i=0; i<glob_prefixes.size(); i++)
8872 for (unsigned j=0; j<glob_suffixes.size(); j++)
8873 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
8874
8875 for (unsigned z = 0; z < globs.size(); z++)
8876 {
8877 string glob_str = globs[z];
8878 if (s.verbose > 3)
b530b5b3 8879 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 8880
f982c59b
JS
8881 glob(glob_str.c_str(), 0, NULL, &trace_glob);
8882 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
8883 {
8884 string header(trace_glob.gl_pathv[i]);
8885
8886 // filter out a few known "internal-only" headers
60d98537
JS
8887 if (endswith(header, "/define_trace.h") ||
8888 endswith(header, "/ftrace.h") ||
8889 endswith(header, "/trace_events.h") ||
8890 endswith(header, "_event_types.h"))
f982c59b
JS
8891 continue;
8892
55e50c24 8893 system_headers.push_back(header);
f982c59b
JS
8894 }
8895 globfree(&trace_glob);
8896 }
8897
55e50c24
JS
8898 // First attempt to do all system headers in one go
8899 string tracequery_path = get_tracequery_module(s, system_headers);
8900 // NB: An empty tracequery means that the header didn't compile correctly
8901 if (get_file_size(tracequery_path))
8902 tracequery_modules.push_back(tracequery_path);
8903 else
8904 // Otherwise try to do them one at a time (PR10424)
8905 for (size_t i = 0; i < system_headers.size(); ++i)
8906 {
85007c04 8907 if (pending_interrupts) return false;
55e50c24
JS
8908 vector<string> one_header(1, system_headers[i]);
8909 tracequery_path = get_tracequery_module(s, one_header);
8910 if (get_file_size(tracequery_path))
8911 tracequery_modules.push_back(tracequery_path);
8912 }
8913
f982c59b
JS
8914 // TODO: consider other sources of tracepoint headers too, like from
8915 // a command-line parameter or some environment or .systemtaprc
47dd066d 8916
59c11f91 8917 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
8918 return true;
8919}
47dd066d 8920
0a6f5a3f
JS
8921void
8922tracepoint_builder::build(systemtap_session& s,
8923 probe *base, probe_point *location,
8924 literal_map_t const& parameters,
8925 vector<derived_probe*>& finished_results)
8926{
8927 if (!init_dw(s))
8928 return;
47dd066d 8929
75ead1f7
JS
8930 string tracepoint;
8931 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 8932
75ead1f7 8933 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 8934 dw->iterate_over_modules(&query_module, &q);
47dd066d 8935}
47dd066d 8936
e6fe60e7 8937
b55bc428 8938// ------------------------------------------------------------------------
bd2b1e68 8939// Standard tapset registry.
b55bc428
FCE
8940// ------------------------------------------------------------------------
8941
7a053d3b 8942void
f8220a7b 8943register_standard_tapsets(systemtap_session & s)
b55bc428 8944{
47e0478e 8945 register_tapset_been(s);
93646f4d 8946 register_tapset_itrace(s);
dd0e4fa7 8947 register_tapset_mark(s);
7a212aa8 8948 register_tapset_procfs(s);
912e8c59 8949 register_tapset_timers(s);
b84779a5 8950 register_tapset_utrace(s);
b98a8d73 8951
7a24d422 8952 // dwarf-based kprobe/uprobe parts
c4ce66a1 8953 dwarf_derived_probe::register_patterns(s);
30a279be 8954
888af770
FCE
8955 // XXX: user-space starter set
8956 s.pattern_root->bind_num(TOK_PROCESS)
8957 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
27dc09b1 8958 ->bind_unprivileged()
888af770
FCE
8959 ->bind(new uprobe_builder ());
8960 s.pattern_root->bind_num(TOK_PROCESS)
8961 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
27dc09b1 8962 ->bind_unprivileged()
888af770
FCE
8963 ->bind(new uprobe_builder ());
8964
0a6f5a3f
JS
8965 // kernel tracepoint probes
8966 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
8967 ->bind(new tracepoint_builder());
8968
e6fe60e7
AM
8969 // Kprobe based probe
8970 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
8971 ->bind(new kprobe_builder());
8972 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
8973 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
8974 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
8975 ->bind(new kprobe_builder());
b6371390
JS
8976 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
8977 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
8978 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
8979 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
8980 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
8981 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
8982 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
8983 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
8984 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
8985
8986 //Hwbkpt based probe
b47f3a55
FCE
8987 // NB: we formerly registered the probe point types only if the kernel configuration
8988 // allowed it. However, we get better error messages if we allow probes to resolve.
8989 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
8990 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
8991 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
8992 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
8993 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
8994 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
8995 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
8996 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
8997 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
8998 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
8999 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9000 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9001 // length supported with address only, not symbol names
83ea76b1
WC
9002
9003 //perf event based probe
4763f713 9004 register_tapset_perf(s);
b55bc428 9005}
dc38c0ae
DS
9006
9007
b20febf3
FCE
9008vector<derived_probe_group*>
9009all_session_groups(systemtap_session& s)
dc38c0ae 9010{
b20febf3 9011 vector<derived_probe_group*> g;
912e8c59
JS
9012
9013#define DOONE(x) \
9014 if (s. x##_derived_probes) \
9015 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
9016
9017 // Note that order *is* important here. We want to make sure we
9018 // register (actually run) begin probes before any other probe type
9019 // is run. Similarly, when unregistering probes, we want to
9020 // unregister (actually run) end probes after every other probe type
9021 // has be unregistered. To do the latter,
9022 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
9023 DOONE(be);
9024 DOONE(dwarf);
888af770 9025 DOONE(uprobe);
b20febf3
FCE
9026 DOONE(timer);
9027 DOONE(profile);
9028 DOONE(mark);
0a6f5a3f 9029 DOONE(tracepoint);
e6fe60e7 9030 DOONE(kprobe);
dd225250 9031 DOONE(hwbkpt);
83ea76b1 9032 DOONE(perf);
b20febf3 9033 DOONE(hrtimer);
ce82316f 9034 DOONE(procfs);
935447c8
DS
9035
9036 // Another "order is important" item. We want to make sure we
9037 // "register" the dummy task_finder probe group after all probe
9038 // groups that use the task_finder.
9039 DOONE(utrace);
a96d1db0 9040 DOONE(itrace);
935447c8 9041 DOONE(task_finder);
b20febf3
FCE
9042#undef DOONE
9043 return g;
46b84a80 9044}
73267b89
JS
9045
9046/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 2.289815 seconds and 5 git commands to generate.