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