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