]> sourceware.org Git - systemtap.git/blame - tapsets.cxx
Fixed PR11424 by using System.map data to validate dwarfless kprobe probes.
[systemtap.git] / tapsets.cxx
CommitLineData
56e12059 1// tapset resolution
e3bbc038 2// Copyright (C) 2005-2012 Red Hat Inc.
aa30ccd3 3// Copyright (C) 2005-2007 Intel Corporation.
0b8f6579 4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
56e12059
FCE
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "config.h"
12#include "staptree.h"
13#include "elaborate.h"
b55bc428 14#include "tapsets.h"
93646f4d 15#include "task_finder.h"
56e12059 16#include "translate.h"
dc38c0ae 17#include "session.h"
72dbc915 18#include "util.h"
0a6f5a3f 19#include "buildrun.h"
86bf665e 20#include "dwarf_wrappers.h"
2e67a43b 21#include "auto_free.h"
b278033a 22#include "hash.h"
440f755a 23#include "dwflpp.h"
5f8ca04f 24#include "setupdwfl.h"
6b51ee12 25#include <gelf.h>
22d737e8 26
4d0d9e8a 27#include "sdt_types.h"
bd2b1e68 28
3b579393
FCE
29#include <cstdlib>
30#include <algorithm>
bd2b1e68 31#include <deque>
56e12059 32#include <iostream>
d1bcbe71 33#include <fstream>
bd2b1e68 34#include <map>
ec4373ff 35#include <set>
56e12059 36#include <sstream>
bd2b1e68 37#include <stdexcept>
b55bc428 38#include <vector>
e36387d7 39#include <cstdarg>
29e64872 40#include <cassert>
1969b5bc 41#include <iomanip>
f781f849 42#include <cerrno>
bd2b1e68
GH
43
44extern "C" {
df8fadee 45#include <fcntl.h>
bd2b1e68 46#include <elfutils/libdwfl.h>
7a053d3b 47#include <elfutils/libdw.h>
77de5e9e
GH
48#include <dwarf.h>
49#include <elf.h>
50#include <obstack.h>
b20febf3 51#include <glob.h>
30a279be 52#include <fnmatch.h>
5f0a03a6 53#include <stdio.h>
349dc70e 54#include <sys/types.h>
37001baa 55#include <sys/stat.h>
aaf7ffe8 56#include <math.h>
aff5d390 57#include <regex.h>
37001baa 58#include <unistd.h>
6d5d594e 59#include <wordexp.h>
4b1ad75e
RM
60
61#define __STDC_FORMAT_MACROS
62#include <inttypes.h>
bd2b1e68 63}
77de5e9e 64
56e12059
FCE
65
66using namespace std;
2171f774 67using namespace __gnu_cxx;
56e12059 68
47dd066d 69
b20febf3
FCE
70
71// ------------------------------------------------------------------------
faea5e16
JS
72
73string
74common_probe_init (derived_probe* p)
75{
26e63673
JS
76 assert(p->session_index != (unsigned)-1);
77 return "(&stap_probes[" + lex_cast(p->session_index) + "])";
faea5e16
JS
78}
79
80
b20febf3 81void
a58d79d0 82common_probe_entryfn_prologue (translator_output* o, string statestr,
6eefe942
MW
83 string probe, string probe_type,
84 bool overload_processing)
b20febf3 85{
653e6a9a
JS
86 o->newline() << "#ifdef STP_ALIBI";
87 o->newline() << "atomic_inc(&(" << probe << "->alibi));";
88 o->newline() << "#else";
89
72d18b98 90 o->newline() << "struct context* __restrict__ c;";
e0a17418
JS
91 o->newline() << "#if !INTERRUPTIBLE";
92 o->newline() << "unsigned long flags;";
93 o->newline() << "#endif";
b20febf3 94
a58d79d0
DS
95 if (overload_processing)
96 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
97 else
98 o->newline() << "#ifdef STP_TIMING";
99 o->newline() << "cycles_t cycles_atstart = get_cycles ();";
b20febf3 100 o->newline() << "#endif";
b20febf3 101
994aac0e 102 o->newline() << "#ifdef STP_TIMING";
26e63673 103 o->newline() << "Stat stat = " << probe << "->timing;";
994aac0e
JS
104 o->newline() << "#endif";
105
e0a17418
JS
106 o->newline() << "#if INTERRUPTIBLE";
107 o->newline() << "preempt_disable ();";
108 o->newline() << "#else";
109 o->newline() << "local_irq_save (flags);";
110 o->newline() << "#endif";
b20febf3 111
c931ec8a 112 // Check for enough free enough stack space
d05a1d00 113 o->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
a63401b1 114 o->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
d05a1d00
FCE
115 // XXX: may need porting to platforms where task_struct is not at bottom of kernel stack
116 // NB: see also CONFIG_DEBUG_STACKOVERFLOW
b3c3ca7c
FCE
117 o->newline() << "atomic_inc (& skipped_count);";
118 o->newline() << "#ifdef STP_TIMING";
119 o->newline() << "atomic_inc (& skipped_count_lowstack);";
120 o->newline() << "#endif";
c931ec8a
FCE
121 o->newline() << "goto probe_epilogue;";
122 o->newline(-1) << "}";
123
b20febf3
FCE
124 o->newline() << "if (atomic_read (&session_state) != " << statestr << ")";
125 o->newline(1) << "goto probe_epilogue;";
126 o->indent(-1);
9a604fac 127
4a0ae64c 128 o->newline() << "c = contexts[smp_processor_id()];";
b3c3ca7c 129 o->newline() << "if (atomic_inc_return (& c->busy) != 1) {";
9c736061
FCE
130 o->newline(1) << "#if !INTERRUPTIBLE";
131 o->newline() << "atomic_inc (& skipped_count);";
132 o->newline() << "#endif";
b3c3ca7c
FCE
133 o->newline() << "#ifdef STP_TIMING";
134 o->newline() << "atomic_inc (& skipped_count_reentrant);";
c12d974f
FCE
135 o->newline() << "#ifdef DEBUG_REENTRANCY";
136 o->newline() << "_stp_warn (\"Skipped %s due to %s residency on cpu %u\\n\", "
26e63673 137 << probe << "->pp, c->probe_point ?: \"?\", smp_processor_id());";
c12d974f
FCE
138 // NB: There is a conceivable race condition here with reading
139 // c->probe_point, knowing that this other probe is sort of running.
140 // However, in reality, it's interrupted. Plus even if it were able
141 // to somehow start again, and stop before we read c->probe_point,
142 // at least we have that ?: "?" bit in there to avoid a NULL deref.
143 o->newline() << "#endif";
b3c3ca7c 144 o->newline() << "#endif";
9a604fac 145 o->newline() << "atomic_dec (& c->busy);";
b20febf3 146 o->newline() << "goto probe_epilogue;";
9a604fac
FCE
147 o->newline(-1) << "}";
148 o->newline();
1e00cfb1 149 o->newline() << "c->last_stmt = 0;";
9a604fac 150 o->newline() << "c->last_error = 0;";
a7ed0d3e 151 o->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
d9aed31e
MW
152 o->newline() << "c->uregs = 0;";
153 o->newline() << "c->kregs = 0;";
d4670309 154 o->newline() << "#if defined __ia64__";
b916df9c 155 o->newline() << "c->unwaddr = 0;";
d4670309 156 o->newline() << "#endif";
26e63673 157 o->newline() << "c->probe_point = " << probe << "->pp;";
d48df0cf 158 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
26e63673 159 o->newline() << "c->probe_name = " << probe << "->pn;";
2d767770 160 o->newline() << "#endif";
6eefe942 161 o->newline() << "c->probe_type = " << probe_type << ";";
6dceb5c9
MW
162 // reset Individual Probe State union
163 o->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
92c25572 164 o->newline() << "c->probe_flags = 0;";
309d67d8 165 o->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
9addf322 166 o->newline() << "c->regparm = 0;";
309d67d8 167 o->newline() << "#endif";
e0a17418
JS
168
169 o->newline() << "#if INTERRUPTIBLE";
170 o->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
171 o->newline() << "#else";
172 o->newline() << "c->actionremaining = MAXACTION;";
173 o->newline() << "#endif";
9915575b
FCE
174 // NB: The following would actually be incorrect.
175 // That's because cycles_sum/cycles_base values are supposed to survive
176 // between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
177 // cycles), the values will be reset.
178 /*
f0e6dc63
FCE
179 o->newline() << "#ifdef STP_OVERLOAD";
180 o->newline() << "c->cycles_sum = 0;";
181 o->newline() << "c->cycles_base = 0;";
41c262f3 182 o->newline() << "#endif";
9915575b 183 */
b20febf3 184}
9a604fac 185
a44a0785 186
b20febf3 187void
a58d79d0 188common_probe_entryfn_epilogue (translator_output* o,
7baf48e9
FCE
189 bool overload_processing,
190 bool suppress_handler_errors)
b20febf3 191{
a58d79d0
DS
192 if (overload_processing)
193 o->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
194 else
195 o->newline() << "#ifdef STP_TIMING";
dbb68664 196 o->newline() << "{";
a58d79d0
DS
197 o->newline(1) << "cycles_t cycles_atend = get_cycles ();";
198 // NB: we truncate cycles counts to 32 bits. Perhaps it should be
199 // fewer, if the hardware counter rolls over really quickly. We
200 // handle 32-bit wraparound here.
201 o->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
202 o->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
203 o->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
204 o->indent(-1);
dbb68664 205
a58d79d0 206 o->newline() << "#ifdef STP_TIMING";
994aac0e 207 o->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed);";
a58d79d0
DS
208 o->newline() << "#endif";
209
210 if (overload_processing)
211 {
212 o->newline() << "#ifdef STP_OVERLOAD";
213 o->newline() << "{";
214 // If the cycle count has wrapped (cycles_atend > cycles_base),
215 // let's go ahead and pretend the interval has been reached.
216 // This should reset cycles_base and cycles_sum.
217 o->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
218 o->newline(1) << "? (cycles_atend - c->cycles_base)";
219 o->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
220 o->newline(-1) << "c->cycles_sum += cycles_elapsed;";
221
222 // If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
223 // probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
224 // has overloaded the system and we need to quit.
7baf48e9
FCE
225 // NB: this is not suppressible via --suppress-runtime-errors,
226 // because this is a system safety metric that we cannot trust
227 // unprivileged users to override.
a58d79d0
DS
228 o->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
229 o->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
230 o->newline(1) << "_stp_error (\"probe overhead exceeded threshold\");";
231 o->newline() << "atomic_set (&session_state, STAP_SESSION_ERROR);";
551e9f14 232 o->newline() << "atomic_inc (&error_count);";
a58d79d0 233 o->newline(-1) << "}";
e57b735a 234
a58d79d0
DS
235 o->newline() << "c->cycles_base = cycles_atend;";
236 o->newline() << "c->cycles_sum = 0;";
237 o->newline(-1) << "}";
238 o->newline(-1) << "}";
239 o->newline() << "#endif";
240 }
e57b735a 241
440f755a
JS
242 o->newline(-1) << "}";
243 o->newline() << "#endif";
e57b735a 244
440f755a 245 o->newline() << "c->probe_point = 0;"; // vacated
dc575eac 246 o->newline() << "#ifdef STP_NEED_PROBE_NAME";
d48df0cf 247 o->newline() << "c->probe_name = 0;";
dc575eac 248 o->newline() << "#endif";
6eefe942 249 o->newline() << "c->probe_type = 0;";
7baf48e9
FCE
250
251
440f755a 252 o->newline() << "if (unlikely (c->last_error && c->last_error[0])) {";
7baf48e9
FCE
253 o->indent(1);
254 if (suppress_handler_errors) // PR 13306
255 {
256 o->newline() << "atomic_inc (& error_count);";
257 }
258 else
259 {
260 o->newline() << "if (c->last_stmt != NULL)";
261 o->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
262 o->newline(-1) << "else";
263 o->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
264 o->indent(-1);
265 o->newline() << "atomic_inc (& error_count);";
266 o->newline() << "if (atomic_read (& error_count) > MAXERRORS) {";
267 o->newline(1) << "atomic_set (& session_state, STAP_SESSION_ERROR);";
268 o->newline() << "_stp_exit ();";
269 o->newline(-1) << "}";
270 }
271
440f755a 272 o->newline(-1) << "}";
7baf48e9
FCE
273
274
440f755a 275 o->newline() << "atomic_dec (&c->busy);";
e57b735a 276
440f755a
JS
277 o->newline(-1) << "probe_epilogue:"; // context is free
278 o->indent(1);
e57b735a 279
7baf48e9
FCE
280 if (! suppress_handler_errors) // PR 13306
281 {
282 // Check for excessive skip counts.
283 o->newline() << "if (unlikely (atomic_read (& skipped_count) > MAXSKIPPED)) {";
284 o->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(& session_state, STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
285 o->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
286 o->newline(-1) << "}";
287 }
e57b735a 288
440f755a
JS
289 o->newline() << "#if INTERRUPTIBLE";
290 o->newline() << "preempt_enable_no_resched ();";
291 o->newline() << "#else";
292 o->newline() << "local_irq_restore (flags);";
293 o->newline() << "#endif";
653e6a9a
JS
294
295 o->newline() << "#endif // STP_ALIBI";
440f755a 296}
e57b735a 297
e57b735a 298
440f755a 299// ------------------------------------------------------------------------
e57b735a 300
440f755a
JS
301// ------------------------------------------------------------------------
302// Dwarf derived probes. "We apologize for the inconvience."
303// ------------------------------------------------------------------------
e57b735a 304
4627ed58
JS
305static const string TOK_KERNEL("kernel");
306static const string TOK_MODULE("module");
307static const string TOK_FUNCTION("function");
308static const string TOK_INLINE("inline");
309static const string TOK_CALL("call");
4bda987e 310static const string TOK_EXPORTED("exported");
4627ed58
JS
311static const string TOK_RETURN("return");
312static const string TOK_MAXACTIVE("maxactive");
313static const string TOK_STATEMENT("statement");
314static const string TOK_ABSOLUTE("absolute");
315static const string TOK_PROCESS("process");
a794dbeb 316static const string TOK_PROVIDER("provider");
4627ed58
JS
317static const string TOK_MARK("mark");
318static const string TOK_TRACE("trace");
319static const string TOK_LABEL("label");
63b4fd14 320static const string TOK_LIBRARY("library");
576eaefe 321static const string TOK_PLT("plt");
e57b735a 322
1adf8ef1 323static int query_cu (Dwarf_Die * cudie, void * arg);
6b517475 324static void query_addr(Dwarf_Addr addr, dwarf_query *q);
e57b735a 325
440f755a
JS
326// Can we handle this query with just symbol-table info?
327enum dbinfo_reqt
328{
329 dbr_unknown,
330 dbr_none, // kernel.statement(NUM).absolute
331 dbr_need_symtab, // can get by with symbol table if there's no dwarf
332 dbr_need_dwarf
333};
e57b735a 334
20e4a32c 335
440f755a
JS
336struct base_query; // forward decls
337struct dwarf_query;
338struct dwflpp;
339struct symbol_table;
20e4a32c 340
a781f401 341
440f755a
JS
342struct
343symbol_table
344{
345 module_info *mod_info; // associated module
346 map<string, func_info*> map_by_name;
1c6b77e5
JS
347 multimap<Dwarf_Addr, func_info*> map_by_addr;
348 typedef multimap<Dwarf_Addr, func_info*>::iterator iterator_t;
440f755a
JS
349 typedef pair<iterator_t, iterator_t> range_t;
350#ifdef __powerpc__
351 GElf_Word opd_section;
352#endif
2867a2a1
JS
353 void add_symbol(const char *name, bool weak, bool descriptor,
354 Dwarf_Addr addr, Dwarf_Addr *high_addr);
440f755a 355 enum info_status read_symbols(FILE *f, const string& path);
83ca3872 356 enum info_status read_from_elf_file(const string& path,
2713ea24 357 systemtap_session &sess);
83ca3872 358 enum info_status read_from_text_file(const string& path,
2713ea24 359 systemtap_session &sess);
440f755a
JS
360 enum info_status get_from_elf();
361 void prepare_section_rejection(Dwfl_Module *mod);
362 bool reject_section(GElf_Word section);
440f755a
JS
363 void purge_syscall_stubs();
364 func_info *lookup_symbol(const string& name);
365 Dwarf_Addr lookup_symbol_address(const string& name);
366 func_info *get_func_containing_address(Dwarf_Addr addr);
3d372d6b 367 func_info *get_first_func();
7a053d3b 368
440f755a
JS
369 symbol_table(module_info *mi) : mod_info(mi) {}
370 ~symbol_table();
371};
77de5e9e 372
440f755a
JS
373static bool null_die(Dwarf_Die *die)
374{
822a6a3d 375 static Dwarf_Die null;
440f755a
JS
376 return (!die || !memcmp(die, &null, sizeof(null)));
377}
c4ce66a1
JS
378
379
7a053d3b 380enum
bd2b1e68 381function_spec_type
7a053d3b 382 {
bd2b1e68
GH
383 function_alone,
384 function_and_file,
7a053d3b 385 function_file_and_line
bd2b1e68
GH
386 };
387
ec4373ff 388
bd2b1e68 389struct dwarf_builder;
f10534c6 390struct dwarf_var_expanding_visitor;
77de5e9e 391
2930abc7 392
b20febf3
FCE
393// XXX: This class is a candidate for subclassing to separate
394// the relocation vs non-relocation variants. Likewise for
395// kprobe vs kretprobe variants.
396
397struct dwarf_derived_probe: public derived_probe
b55bc428 398{
b20febf3
FCE
399 dwarf_derived_probe (const string& function,
400 const string& filename,
401 int line,
402 const string& module,
403 const string& section,
404 Dwarf_Addr dwfl_addr,
2930abc7 405 Dwarf_Addr addr,
b20febf3
FCE
406 dwarf_query & q,
407 Dwarf_Die* scope_die);
20e4a32c 408
b20febf3
FCE
409 string module;
410 string section;
411 Dwarf_Addr addr;
63b4fd14 412 string path;
27dc09b1 413 bool has_process;
2930abc7 414 bool has_return;
c9bad430 415 bool has_maxactive;
63b4fd14 416 bool has_library;
c9bad430 417 long maxactive_val;
4ad95bbc 418 // dwarf_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
b642c901
SC
419 string user_path;
420 string user_lib;
b95e2b79 421 bool access_vars;
2930abc7 422
af234c40
JS
423 unsigned saved_longs, saved_strings;
424 dwarf_derived_probe* entry_handler;
425
b8da0ad1 426 void printsig (std::ostream &o) const;
6b66b9f7 427 virtual void join_group (systemtap_session& s);
9020300d 428 void emit_probe_local_init(translator_output * o);
d0bfd2ac 429 void getargs(std::list<std::string> &arg_set) const;
0a98fd42 430
42e38653 431 void emit_privilege_assertion (translator_output*);
27dc09b1
DB
432 void print_dupe_stamp(ostream& o);
433
bd2b1e68 434 // Pattern registration helpers.
7a053d3b 435 static void register_statement_variants(match_node * root,
27dc09b1 436 dwarf_builder * dw,
42e38653 437 privilege_t privilege);
fd6602a0 438 static void register_function_variants(match_node * root,
27dc09b1 439 dwarf_builder * dw,
42e38653 440 privilege_t privilege);
440d9b00
DB
441 static void register_function_and_statement_variants(systemtap_session& s,
442 match_node * root,
27dc09b1 443 dwarf_builder * dw,
42e38653 444 privilege_t privilege);
b1615c74
JS
445 static void register_sdt_variants(systemtap_session& s,
446 match_node * root,
447 dwarf_builder * dw);
448 static void register_plt_variants(systemtap_session& s,
449 match_node * root,
450 dwarf_builder * dw);
c4ce66a1 451 static void register_patterns(systemtap_session& s);
6b66b9f7
JS
452
453protected:
454 dwarf_derived_probe(probe *base,
455 probe_point *location,
456 Dwarf_Addr addr,
457 bool has_return):
74fe61bc
LB
458 derived_probe(base, location), addr(addr), has_process(0),
459 has_return(has_return), has_maxactive(0), has_library(0),
460 maxactive_val(0), access_vars(false), saved_longs(0),
461 saved_strings(0), entry_handler(0)
6b66b9f7
JS
462 {}
463
464private:
d0bfd2ac 465 list<string> args;
8c67c337 466 void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
20c6c071
GH
467};
468
dc38c0ae 469
6b66b9f7 470struct uprobe_derived_probe: public dwarf_derived_probe
6d0f3f0c 471{
6d0f3f0c 472 int pid; // 0 => unrestricted
0973d815 473
6d0f3f0c
FCE
474 uprobe_derived_probe (const string& function,
475 const string& filename,
476 int line,
477 const string& module,
6d0f3f0c
FCE
478 const string& section,
479 Dwarf_Addr dwfl_addr,
480 Dwarf_Addr addr,
481 dwarf_query & q,
6b66b9f7
JS
482 Dwarf_Die* scope_die):
483 dwarf_derived_probe(function, filename, line, module, section,
484 dwfl_addr, addr, q, scope_die), pid(0)
485 {}
6d0f3f0c 486
0973d815
FCE
487 // alternate constructor for process(PID).statement(ADDR).absolute
488 uprobe_derived_probe (probe *base,
489 probe_point *location,
490 int pid,
491 Dwarf_Addr addr,
6b66b9f7
JS
492 bool has_return):
493 dwarf_derived_probe(base, location, addr, has_return), pid(pid)
494 {}
9ace370f 495
6d0f3f0c 496 void join_group (systemtap_session& s);
2865d17a 497
42e38653 498 void emit_privilege_assertion (translator_output*);
8f6d8c2b 499 void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
c0f84e7b
SC
500 void getargs(std::list<std::string> &arg_set) const;
501 void saveargs(int nargs);
502private:
503 list<string> args;
6d0f3f0c
FCE
504};
505
dc38c0ae
DS
506struct dwarf_derived_probe_group: public derived_probe_group
507{
508private:
b20febf3
FCE
509 multimap<string,dwarf_derived_probe*> probes_by_module;
510 typedef multimap<string,dwarf_derived_probe*>::iterator p_b_m_iterator;
dc38c0ae
DS
511
512public:
08b5a50c 513 dwarf_derived_probe_group() {}
b20febf3
FCE
514 void enroll (dwarf_derived_probe* probe);
515 void emit_module_decls (systemtap_session& s);
516 void emit_module_init (systemtap_session& s);
b4be7cbc 517 void emit_module_refresh (systemtap_session& s);
b20febf3 518 void emit_module_exit (systemtap_session& s);
dc38c0ae
DS
519};
520
521
20c6c071 522// Helper struct to thread through the dwfl callbacks.
2c384610 523struct base_query
20c6c071 524{
c4ce66a1
JS
525 base_query(dwflpp & dw, literal_map_t const & params);
526 base_query(dwflpp & dw, const string & module_val);
2c384610 527 virtual ~base_query() {}
bd2b1e68 528
5227f1ea 529 systemtap_session & sess;
2c384610 530 dwflpp & dw;
5227f1ea 531
bd2b1e68 532 // Parameter extractors.
86bf665e 533 static bool has_null_param(literal_map_t const & params,
888af770 534 string const & k);
86bf665e 535 static bool get_string_param(literal_map_t const & params,
bd2b1e68 536 string const & k, string & v);
86bf665e 537 static bool get_number_param(literal_map_t const & params,
bd2b1e68 538 string const & k, long & v);
86bf665e 539 static bool get_number_param(literal_map_t const & params,
c239d28c 540 string const & k, Dwarf_Addr & v);
f301a9ff 541 static void query_library_callback (void *object, const char *data);
576eaefe 542 static void query_plt_callback (void *object, const char *link, size_t addr);
f301a9ff 543 virtual void query_library (const char *data) = 0;
576eaefe 544 virtual void query_plt (const char *link, size_t addr) = 0;
84c84ac4 545
b55bc428 546
2c384610
DS
547 // Extracted parameters.
548 bool has_kernel;
91af0778
FCE
549 bool has_module;
550 bool has_process;
63b4fd14 551 bool has_library;
576eaefe
SC
552 bool has_plt;
553 bool has_statement;
2c384610 554 string module_val; // has_kernel => module_val = "kernel"
63b4fd14 555 string path; // executable path if module is a .so
576eaefe 556 string plt_val; // has_plt => plt wildcard
2c384610
DS
557
558 virtual void handle_query_module() = 0;
559};
560
561
c4ce66a1 562base_query::base_query(dwflpp & dw, literal_map_t const & params):
576eaefe 563 sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false)
2c384610 564{
91af0778 565 has_kernel = has_null_param (params, TOK_KERNEL);
2c384610
DS
566 if (has_kernel)
567 module_val = "kernel";
91af0778
FCE
568
569 has_module = get_string_param (params, TOK_MODULE, module_val);
570 if (has_module)
571 has_process = false;
4baf0e53 572 else
d0a7f5a9 573 {
63b4fd14 574 string library_name;
576eaefe 575 long statement_num_val;
d0a7f5a9 576 has_process = get_string_param(params, TOK_PROCESS, module_val);
63b4fd14 577 has_library = get_string_param (params, TOK_LIBRARY, library_name);
576eaefe
SC
578 if ((has_plt = has_null_param (params, TOK_PLT)))
579 plt_val = "*";
580 else has_plt = get_string_param (params, TOK_PLT, plt_val);
18418d34
SC
581 if (has_plt)
582 sess.consult_symtab = true;
576eaefe
SC
583 has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
584
84c84ac4 585 if (has_process)
05fb3e0c 586 module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
84c84ac4
SC
587 if (has_library)
588 {
589 if (! contains_glob_chars (library_name))
590 {
05fb3e0c
WF
591 path = path_remove_sysroot(sess, module_val);
592 module_val = find_executable (library_name, sess.sysroot,
593 sess.sysenv, "LD_LIBRARY_PATH");
47e226ed
SC
594 if (module_val.find('/') == string::npos)
595 {
596 // We didn't find library_name so use iterate_over_libraries
597 module_val = path;
598 path = library_name;
599 }
84c84ac4
SC
600 }
601 else
602 path = library_name;
603 }
d0a7f5a9 604 }
91af0778
FCE
605
606 assert (has_kernel || has_process || has_module);
2c384610
DS
607}
608
c4ce66a1 609base_query::base_query(dwflpp & dw, const string & module_val)
576eaefe
SC
610 : sess(dw.sess), dw(dw), has_library(false), has_plt(false), has_statement(false),
611 module_val(module_val)
c4ce66a1
JS
612{
613 // NB: This uses '/' to distinguish between kernel modules and userspace,
614 // which means that userspace modules won't get any PATH searching.
615 if (module_val.find('/') == string::npos)
616 {
617 has_kernel = (module_val == TOK_KERNEL);
618 has_module = !has_kernel;
619 has_process = false;
620 }
621 else
622 {
623 has_kernel = has_module = false;
624 has_process = true;
625 }
626}
627
2c384610 628bool
86bf665e 629base_query::has_null_param(literal_map_t const & params,
2c384610
DS
630 string const & k)
631{
888af770 632 return derived_probe_builder::has_null_param(params, k);
2c384610
DS
633}
634
635
636bool
86bf665e 637base_query::get_string_param(literal_map_t const & params,
2c384610
DS
638 string const & k, string & v)
639{
640 return derived_probe_builder::get_param (params, k, v);
641}
642
643
644bool
86bf665e 645base_query::get_number_param(literal_map_t const & params,
2c384610
DS
646 string const & k, long & v)
647{
648 int64_t value;
649 bool present = derived_probe_builder::get_param (params, k, value);
650 v = (long) value;
651 return present;
652}
653
654
655bool
86bf665e 656base_query::get_number_param(literal_map_t const & params,
2c384610
DS
657 string const & k, Dwarf_Addr & v)
658{
659 int64_t value;
660 bool present = derived_probe_builder::get_param (params, k, value);
661 v = (Dwarf_Addr) value;
662 return present;
663}
664
2c384610
DS
665struct dwarf_query : public base_query
666{
e1278bd4 667 dwarf_query(probe * base_probe,
2c384610
DS
668 probe_point * base_loc,
669 dwflpp & dw,
86bf665e 670 literal_map_t const & params,
b642c901
SC
671 vector<derived_probe *> & results,
672 const string user_path,
673 const string user_lib);
2c384610 674
c4ce66a1 675 vector<derived_probe *> & results;
8f14e444 676 set<string> inlined_non_returnable; // function names
c4ce66a1
JS
677 probe * base_probe;
678 probe_point * base_loc;
b642c901
SC
679 string user_path;
680 string user_lib;
c4ce66a1 681
2c384610 682 virtual void handle_query_module();
5f0a03a6
JK
683 void query_module_dwarf();
684 void query_module_symtab();
5d5bd369 685 void query_library (const char *data);
576eaefe 686 void query_plt (const char *entry, size_t addr);
2c384610 687
2930abc7
FCE
688 void add_probe_point(string const & funcname,
689 char const * filename,
690 int line,
691 Dwarf_Die *scope_die,
692 Dwarf_Addr addr);
36f9dd1d 693
857bdfd1
JS
694 // Track addresses we've already seen in a given module
695 set<Dwarf_Addr> alias_dupes;
696
7fdd3e2c
JS
697 // Track inlines we've already seen as well
698 // NB: this can't be compared just by entrypc, as inlines can overlap
699 set<inline_instance_info> inline_dupes;
700
2930abc7 701 // Extracted parameters.
7a053d3b 702 string function_val;
20c6c071
GH
703
704 bool has_function_str;
705 bool has_statement_str;
706 bool has_function_num;
707 bool has_statement_num;
7a053d3b
RM
708 string statement_str_val;
709 string function_str_val;
c239d28c
GH
710 Dwarf_Addr statement_num_val;
711 Dwarf_Addr function_num_val;
20c6c071 712
b8da0ad1 713 bool has_call;
4bda987e 714 bool has_exported;
b8da0ad1 715 bool has_inline;
20c6c071
GH
716 bool has_return;
717
c9bad430
DS
718 bool has_maxactive;
719 long maxactive_val;
720
20c6c071
GH
721 bool has_label;
722 string label_val;
723
724 bool has_relative;
725 long relative_val;
726
37ebca01
FCE
727 bool has_absolute;
728
467bea43
SC
729 bool has_mark;
730
5f0a03a6
JK
731 enum dbinfo_reqt dbinfo_reqt;
732 enum dbinfo_reqt assess_dbinfo_reqt();
733
7d6d0afc 734 void parse_function_spec(const string & spec);
20c6c071 735 function_spec_type spec_type;
7d6d0afc 736 vector<string> scopes;
20c6c071
GH
737 string function;
738 string file;
0c8b7d37 739 line_t line_type;
879eb9e9 740 int line[2];
5f0a03a6 741 bool query_done; // Found exact match
20c6c071 742
bd25380d 743 set<string> filtered_srcfiles;
7e1279ea
FCE
744
745 // Map official entrypc -> func_info object
86bf665e
TM
746 inline_instance_map_t filtered_inlines;
747 func_info_map_t filtered_functions;
7e1279ea
FCE
748 bool choose_next_line;
749 Dwarf_Addr entrypc_for_next_line;
4df79aaf
JS
750
751 void query_module_functions ();
b55bc428
FCE
752};
753
98afd80e 754
435f53a7
FCE
755static void delete_session_module_cache (systemtap_session& s); // forward decl
756
757
98afd80e 758struct dwarf_builder: public derived_probe_builder
b55bc428 759{
665e1256 760 map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
7a24d422 761 map <string,dwflpp*> user_dw;
b642c901
SC
762 string user_path;
763 string user_lib;
ae2552da 764 dwarf_builder() {}
aa30ccd3 765
ae2552da 766 dwflpp *get_kern_dw(systemtap_session& sess, const string& module)
707bf35e 767 {
ea14cf67
FCE
768 if (kern_dw[module] == 0)
769 kern_dw[module] = new dwflpp(sess, module, true); // might throw
ae2552da 770 return kern_dw[module];
707bf35e
JS
771 }
772
773 dwflpp *get_user_dw(systemtap_session& sess, const string& module)
774 {
ea14cf67
FCE
775 if (user_dw[module] == 0)
776 user_dw[module] = new dwflpp(sess, module, false); // might throw
707bf35e
JS
777 return user_dw[module];
778 }
7a24d422
FCE
779
780 /* NB: not virtual, so can be called from dtor too: */
822a6a3d 781 void dwarf_build_no_more (bool)
aa30ccd3 782 {
435f53a7
FCE
783 delete_map(kern_dw);
784 delete_map(user_dw);
7a24d422
FCE
785 }
786
787 void build_no_more (systemtap_session &s)
788 {
789 dwarf_build_no_more (s.verbose > 3);
435f53a7 790 delete_session_module_cache (s);
aa30ccd3
FCE
791 }
792
e38d6504
RM
793 ~dwarf_builder()
794 {
7a24d422 795 dwarf_build_no_more (false);
c8959a29 796 }
aa30ccd3 797
5227f1ea 798 virtual void build(systemtap_session & sess,
7a053d3b 799 probe * base,
20c6c071 800 probe_point * location,
86bf665e 801 literal_map_t const & parameters,
20c6c071 802 vector<derived_probe *> & finished_results);
b55bc428
FCE
803};
804
5111fc3e 805
e1278bd4 806dwarf_query::dwarf_query(probe * base_probe,
20c6c071
GH
807 probe_point * base_loc,
808 dwflpp & dw,
86bf665e 809 literal_map_t const & params,
b642c901
SC
810 vector<derived_probe *> & results,
811 const string user_path,
812 const string user_lib)
c4ce66a1 813 : base_query(dw, params), results(results),
b642c901 814 base_probe(base_probe), base_loc(base_loc),
74fe61bc
LB
815 user_path(user_path), user_lib(user_lib), has_relative(false),
816 relative_val(0), choose_next_line(false), entrypc_for_next_line(0)
bd2b1e68
GH
817{
818 // Reduce the query to more reasonable semantic values (booleans,
819 // extracted strings, numbers, etc).
bd2b1e68
GH
820 has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
821 has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
822
823 has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
824 has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
825
0f336e95
SC
826 has_label = get_string_param(params, TOK_LABEL, label_val);
827
b8da0ad1 828 has_call = has_null_param(params, TOK_CALL);
4bda987e 829 has_exported = has_null_param(params, TOK_EXPORTED);
b8da0ad1 830 has_inline = has_null_param(params, TOK_INLINE);
bd2b1e68 831 has_return = has_null_param(params, TOK_RETURN);
c9bad430 832 has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
37ebca01 833 has_absolute = has_null_param(params, TOK_ABSOLUTE);
467bea43 834 has_mark = false;
37ebca01 835
bd2b1e68 836 if (has_function_str)
7d6d0afc 837 parse_function_spec(function_str_val);
bd2b1e68 838 else if (has_statement_str)
7d6d0afc 839 parse_function_spec(statement_str_val);
0daad364 840
5f0a03a6
JK
841 dbinfo_reqt = assess_dbinfo_reqt();
842 query_done = false;
0daad364
JS
843}
844
845
440f755a
JS
846func_info_map_t *
847get_filtered_functions(dwarf_query *q)
848{
849 return &q->filtered_functions;
850}
851
852
853inline_instance_map_t *
854get_filtered_inlines(dwarf_query *q)
855{
856 return &q->filtered_inlines;
857}
858
859
2c384610 860void
5f0a03a6 861dwarf_query::query_module_dwarf()
2c384610
DS
862{
863 if (has_function_num || has_statement_num)
864 {
865 // If we have module("foo").function(0xbeef) or
866 // module("foo").statement(0xbeef), the address is relative
867 // to the start of the module, so we seek the function
868 // number plus the module's bias.
6b517475
JS
869 Dwarf_Addr addr = has_function_num ?
870 function_num_val : statement_num_val;
08d1d520
MW
871
872 // These are raw addresses, we need to know what the elf_bias
873 // is to feed it to libdwfl based functions.
874 Dwarf_Addr elf_bias;
875 Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
876 assert(elf);
877 addr += elf_bias;
6b517475 878 query_addr(addr, this);
2c384610
DS
879 }
880 else
881 {
882 // Otherwise if we have a function("foo") or statement("foo")
883 // specifier, we have to scan over all the CUs looking for
884 // the function(s) in question
885 assert(has_function_str || has_statement_str);
4df79aaf
JS
886
887 // For simple cases, no wildcard and no source:line, we can do a very
888 // quick function lookup in a module-wide cache.
1ffb8bd1
JS
889 if (spec_type == function_alone &&
890 !dw.name_has_wildcard(function) &&
891 !startswith(function, "_Z"))
4df79aaf
JS
892 query_module_functions();
893 else
337b7c44 894 dw.iterate_over_cus(&query_cu, this, false);
2c384610
DS
895 }
896}
897
5f0a03a6
JK
898static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
899 dwarf_query * q);
900
901void
902dwarf_query::query_module_symtab()
903{
904 // Get the symbol table if it's necessary, sufficient, and not already got.
905 if (dbinfo_reqt == dbr_need_dwarf)
906 return;
907
908 module_info *mi = dw.mod_info;
909 if (dbinfo_reqt == dbr_need_symtab)
910 {
911 if (mi->symtab_status == info_unknown)
912 mi->get_symtab(this);
913 if (mi->symtab_status == info_absent)
914 return;
915 }
916
917 func_info *fi = NULL;
918 symbol_table *sym_table = mi->sym_table;
919
920 if (has_function_str)
921 {
922 // Per dwarf_query::assess_dbinfo_reqt()...
923 assert(spec_type == function_alone);
924 if (dw.name_has_wildcard(function_str_val))
925 {
926 // Until we augment the blacklist sufficently...
927 if (function_str_val.find_first_not_of("*?") == string::npos)
928 {
929 // e.g., kernel.function("*")
b530b5b3
LB
930 cerr << _F("Error: Pattern '%s' matches every single "
931 "instruction address in the symbol table,\n"
932 "some of which aren't even functions.\n", function_str_val.c_str()) << endl;
5f0a03a6
JK
933 return;
934 }
2e67a43b 935 symbol_table::iterator_t iter;
1c6b77e5
JS
936 for (iter = sym_table->map_by_addr.begin();
937 iter != sym_table->map_by_addr.end();
2e67a43b 938 ++iter)
5f0a03a6 939 {
1c6b77e5 940 fi = iter->second;
5f0a03a6
JK
941 if (!null_die(&fi->die))
942 continue; // already handled in query_module_dwarf()
943 if (dw.function_name_matches_pattern(fi->name, function_str_val))
944 query_func_info(fi->addr, *fi, this);
945 }
946 }
947 else
948 {
949 fi = sym_table->lookup_symbol(function_str_val);
2867a2a1 950 if (fi && !fi->descriptor && null_die(&fi->die))
5f0a03a6
JK
951 query_func_info(fi->addr, *fi, this);
952 }
953 }
954 else
955 {
956 assert(has_function_num || has_statement_num);
957 // Find the "function" in which the indicated address resides.
958 Dwarf_Addr addr =
959 (has_function_num ? function_num_val : statement_num_val);
576eaefe 960 if (has_plt)
3d372d6b
SC
961 {
962 // Use the raw address from the .plt
963 fi = sym_table->get_first_func();
964 fi->addr = addr;
965 }
966 else
967 fi = sym_table->get_func_containing_address(addr);
968
5f0a03a6
JK
969 if (!fi)
970 {
2713ea24
CM
971 sess.print_warning(_F("address %#" PRIx64 " out of range for module %s",
972 addr, dw.module_name.c_str()));
973 return;
5f0a03a6
JK
974 }
975 if (!null_die(&fi->die))
976 {
977 // addr looks like it's in the compilation unit containing
978 // the indicated function, but query_module_dwarf() didn't
979 // match addr to any compilation unit, so addr must be
980 // above that cu's address range.
2713ea24
CM
981 sess.print_warning(_F("address %#" PRIx64 " maps to no known compilation unit in module %s",
982 addr, dw.module_name.c_str()));
5f0a03a6
JK
983 return;
984 }
985 query_func_info(fi->addr, *fi, this);
986 }
987}
988
989void
990dwarf_query::handle_query_module()
991{
1c6b77e5
JS
992 bool report = dbinfo_reqt == dbr_need_dwarf || !sess.consult_symtab;
993 dw.get_module_dwarf(false, report);
994
995 // prebuild the symbol table to resolve aliases
996 dw.mod_info->get_symtab(this);
997
857bdfd1
JS
998 // reset the dupe-checking for each new module
999 alias_dupes.clear();
7fdd3e2c 1000 inline_dupes.clear();
857bdfd1 1001
5f0a03a6
JK
1002 if (dw.mod_info->dwarf_status == info_present)
1003 query_module_dwarf();
1c6b77e5 1004
5f0a03a6
JK
1005 // Consult the symbol table if we haven't found all we're looking for.
1006 // asm functions can show up in the symbol table but not in dwarf.
1007 if (sess.consult_symtab && !query_done)
1008 query_module_symtab();
1009}
1010
2c384610 1011
7d6d0afc
JS
1012void
1013dwarf_query::parse_function_spec(const string & spec)
bd2b1e68 1014{
1d12a9b2
JS
1015 line_type = ABSOLUTE;
1016 line[0] = line[1] = 0;
1017
91699a70 1018 size_t src_pos, line_pos, dash_pos, scope_pos;
bd2b1e68 1019
7d6d0afc 1020 // look for named scopes
91699a70
JS
1021 scope_pos = spec.rfind("::");
1022 if (scope_pos != string::npos)
bd2b1e68 1023 {
91699a70
JS
1024 tokenize_cxx(spec.substr(0, scope_pos), scopes);
1025 scope_pos += 2;
bd2b1e68 1026 }
91699a70
JS
1027 else
1028 scope_pos = 0;
bd2b1e68 1029
7d6d0afc
JS
1030 // look for a source separator
1031 src_pos = spec.find('@', scope_pos);
1032 if (src_pos == string::npos)
bd2b1e68 1033 {
7d6d0afc
JS
1034 function = spec.substr(scope_pos);
1035 spec_type = function_alone;
bd2b1e68 1036 }
7d6d0afc 1037 else
879eb9e9 1038 {
7d6d0afc 1039 function = spec.substr(scope_pos, src_pos - scope_pos);
7a053d3b 1040
7d6d0afc
JS
1041 // look for a line-number separator
1042 line_pos = spec.find_first_of(":+", src_pos);
1043 if (line_pos == string::npos)
1044 {
1045 file = spec.substr(src_pos + 1);
1046 spec_type = function_and_file;
1047 }
1048 else
1049 {
1050 file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
1051
1052 // classify the line spec
1053 spec_type = function_file_and_line;
1054 if (spec[line_pos] == '+')
1055 line_type = RELATIVE;
1056 else if (spec[line_pos + 1] == '*' &&
1057 spec.length() == line_pos + 2)
1058 line_type = WILDCARD;
1059 else
1060 line_type = ABSOLUTE;
1061
1062 if (line_type != WILDCARD)
1063 try
1064 {
1065 // try to parse either N or N-M
1066 dash_pos = spec.find('-', line_pos + 1);
1067 if (dash_pos == string::npos)
1068 line[0] = line[1] = lex_cast<int>(spec.substr(line_pos + 1));
1069 else
1070 {
1071 line_type = RANGE;
1072 line[0] = lex_cast<int>(spec.substr(line_pos + 1,
1073 dash_pos - line_pos - 1));
1074 line[1] = lex_cast<int>(spec.substr(dash_pos + 1));
1075 }
1076 }
1077 catch (runtime_error & exn)
1078 {
1079 goto bad;
1080 }
1081 }
bd2b1e68
GH
1082 }
1083
7d6d0afc
JS
1084 if (function.empty() ||
1085 (spec_type != function_alone && file.empty()))
bd2b1e68
GH
1086 goto bad;
1087
7d6d0afc 1088 if (sess.verbose > 2)
bd2b1e68 1089 {
b530b5b3
LB
1090 //clog << "parsed '" << spec << "'";
1091 clog << _F("parse '%s'", spec.c_str());
41c262f3 1092
7d6d0afc
JS
1093 if (!scopes.empty())
1094 clog << ", scope '" << scopes[0] << "'";
1095 for (unsigned i = 1; i < scopes.size(); ++i)
1096 clog << "::'" << scopes[i] << "'";
41c262f3 1097
7d6d0afc
JS
1098 clog << ", func '" << function << "'";
1099
1100 if (spec_type != function_alone)
1101 clog << ", file '" << file << "'";
1102
1103 if (spec_type == function_file_and_line)
1104 {
1105 clog << ", line ";
1106 switch (line_type)
1107 {
1108 case ABSOLUTE:
1109 clog << line[0];
1110 break;
1111
1112 case RELATIVE:
1113 clog << "+" << line[0];
1114 break;
1115
1116 case RANGE:
1117 clog << line[0] << " - " << line[1];
1118 break;
1119
1120 case WILDCARD:
1121 clog << "*";
1122 break;
1123 }
1124 }
1125
1126 clog << endl;
bd2b1e68
GH
1127 }
1128
7d6d0afc
JS
1129 return;
1130
1131bad:
b530b5b3 1132 throw semantic_error(_F("malformed specification '%s'", spec.c_str()),
7d6d0afc 1133 base_probe->tok);
bd2b1e68
GH
1134}
1135
05fb3e0c
WF
1136string path_remove_sysroot(const systemtap_session& sess, const string& path)
1137{
1138 size_t pos;
1139 string retval = path;
1140 if (!sess.sysroot.empty() &&
1141 (pos = retval.find(sess.sysroot)) != string::npos)
1142 retval.replace(pos, sess.sysroot.length(), "/");
1143 return retval;
1144}
bd2b1e68 1145
36f9dd1d 1146void
1ffb8bd1 1147dwarf_query::add_probe_point(const string& dw_funcname,
b20febf3 1148 const char* filename,
36f9dd1d 1149 int line,
b20febf3 1150 Dwarf_Die* scope_die,
36f9dd1d
FCE
1151 Dwarf_Addr addr)
1152{
b20febf3 1153 string reloc_section; // base section for relocation purposes
27646582 1154 Dwarf_Addr reloc_addr; // relocated
b20febf3 1155 const string& module = dw.module_name; // "kernel" or other
1ffb8bd1 1156 string funcname = dw_funcname;
36f9dd1d 1157
37ebca01
FCE
1158 assert (! has_absolute); // already handled in dwarf_builder::build()
1159
576eaefe
SC
1160 if (!has_plt)
1161 reloc_addr = dw.relocate_address(addr, reloc_section);
1162 else
1163 {
3d372d6b 1164 // Set the reloc_section but use the plt entry for reloc_addr
576eaefe
SC
1165 dw.relocate_address(addr, reloc_section);
1166 reloc_addr = addr;
1167 }
2930abc7 1168
1ffb8bd1 1169 // If we originally used the linkage name, then let's call it that way
1ffb8bd1
JS
1170 const char* linkage_name;
1171 if (scope_die && startswith (this->function, "_Z")
f450a7e3 1172 && (linkage_name = dwarf_linkage_name (scope_die)))
1ffb8bd1
JS
1173 funcname = linkage_name;
1174
7f9f3386
FCE
1175 if (sess.verbose > 1)
1176 {
b530b5b3 1177 clog << _("probe ") << funcname << "@" << filename << ":" << line;
b20febf3 1178 if (string(module) == TOK_KERNEL)
b530b5b3 1179 clog << _(" kernel");
91af0778 1180 else if (has_module)
b530b5b3 1181 clog << _(" module=") << module;
91af0778 1182 else if (has_process)
b530b5b3 1183 clog << _(" process=") << module;
b20febf3 1184 if (reloc_section != "") clog << " reloc=" << reloc_section;
b20febf3 1185 clog << " pc=0x" << hex << addr << dec;
7f9f3386 1186 }
4baf0e53 1187
27646582 1188 bool bad = dw.blacklisted_p (funcname, filename, line, module,
789448a3 1189 addr, has_return);
b20febf3
FCE
1190 if (sess.verbose > 1)
1191 clog << endl;
7f9f3386 1192
84048984
FCE
1193 if (module == TOK_KERNEL)
1194 {
1195 // PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
1196 reloc_addr = addr - sess.sym_stext;
37ebca01 1197 reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
84048984
FCE
1198 }
1199
b20febf3
FCE
1200 if (! bad)
1201 {
1a0dbc5a 1202 sess.unwindsym_modules.insert (module);
6d0f3f0c
FCE
1203
1204 if (has_process)
1205 {
05fb3e0c 1206 string module_tgt = path_remove_sysroot(sess, module);
6d0f3f0c 1207 results.push_back (new uprobe_derived_probe(funcname, filename, line,
05fb3e0c 1208 module_tgt, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1209 *this, scope_die));
1210 }
1211 else
1212 {
1213 assert (has_kernel || has_module);
1214 results.push_back (new dwarf_derived_probe(funcname, filename, line,
06aca46a 1215 module, reloc_section, addr, reloc_addr,
6d0f3f0c
FCE
1216 *this, scope_die));
1217 }
b20febf3 1218 }
2930abc7
FCE
1219}
1220
5f0a03a6
JK
1221enum dbinfo_reqt
1222dwarf_query::assess_dbinfo_reqt()
1223{
1224 if (has_absolute)
1225 {
1226 // kernel.statement(NUM).absolute
1227 return dbr_none;
1228 }
1229 if (has_inline)
1230 {
1231 // kernel.function("f").inline or module("m").function("f").inline
1232 return dbr_need_dwarf;
1233 }
1234 if (has_function_str && spec_type == function_alone)
1235 {
1236 // kernel.function("f") or module("m").function("f")
1237 return dbr_need_symtab;
1238 }
1239 if (has_statement_num)
1240 {
1241 // kernel.statement(NUM) or module("m").statement(NUM)
1242 // Technically, all we need is the module offset (or _stext, for
1243 // the kernel). But for that we need either the ELF file or (for
1244 // _stext) the symbol table. In either case, the symbol table
1245 // is available, and that allows us to map the NUM (address)
1246 // to a function, which is goodness.
1247 return dbr_need_symtab;
1248 }
1249 if (has_function_num)
1250 {
1251 // kernel.function(NUM) or module("m").function(NUM)
1252 // Need the symbol table so we can back up from NUM to the
1253 // start of the function.
1254 return dbr_need_symtab;
1255 }
1256 // Symbol table tells us nothing about source files or line numbers.
1257 return dbr_need_dwarf;
1258}
2930abc7
FCE
1259
1260
b8da0ad1
FCE
1261// The critical determining factor when interpreting a pattern
1262// string is, perhaps surprisingly: "presence of a lineno". The
1263// presence of a lineno changes the search strategy completely.
1264//
1265// Compare the two cases:
1266//
1267// 1. {statement,function}(foo@file.c:lineno)
1268// - find the files matching file.c
1269// - in each file, find the functions matching foo
1270// - query the file for line records matching lineno
1271// - iterate over the line records,
1272// - and iterate over the functions,
1273// - if(haspc(function.DIE, line.addr))
1274// - if looking for statements: probe(lineno.addr)
1275// - if looking for functions: probe(function.{entrypc,return,etc.})
1276//
1277// 2. {statement,function}(foo@file.c)
1278// - find the files matching file.c
1279// - in each file, find the functions matching foo
1280// - probe(function.{entrypc,return,etc.})
1281//
1282// Thus the first decision we make is based on the presence of a
1283// lineno, and we enter entirely different sets of callbacks
1284// depending on that decision.
1285//
1286// Note that the first case is a generalization fo the second, in that
1287// we could theoretically search through line records for matching
1288// file names (a "table scan" in rdbms lingo). Luckily, file names
1289// are already cached elsewhere, so we can do an "index scan" as an
1290// optimization.
7e1279ea 1291
bd2b1e68 1292static void
4cd232e4 1293query_statement (string const & func,
20e4a32c 1294 char const * file,
4cd232e4 1295 int line,
bcc12710 1296 Dwarf_Die *scope_die,
20e4a32c 1297 Dwarf_Addr stmt_addr,
4cd232e4 1298 dwarf_query * q)
bd2b1e68 1299{
39bcd429
FCE
1300 try
1301 {
cee35f73 1302 q->add_probe_point(func, file ? file : "",
a9b2f3a5 1303 line, scope_die, stmt_addr);
39bcd429
FCE
1304 }
1305 catch (const semantic_error& e)
1306 {
1307 q->sess.print_error (e);
1308 }
bd2b1e68
GH
1309}
1310
6b517475
JS
1311static void
1312query_addr(Dwarf_Addr addr, dwarf_query *q)
1313{
1314 dwflpp &dw = q->dw;
1315
08d1d520
MW
1316 if (q->sess.verbose > 2)
1317 clog << "query_addr 0x" << hex << addr << dec << endl;
6b517475
JS
1318
1319 // First pick which CU contains this address
1320 Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
1321 if (!cudie) // address could be wildly out of range
1322 return;
1323 dw.focus_on_cu(cudie);
1324
1325 // Now compensate for the dw bias
1326 addr -= dw.module_bias;
1327
1328 // Per PR5787, we look up the scope die even for
1329 // statement_num's, for blacklist sensitivity and $var
1330 // resolution purposes.
1331
1332 // Find the scopes containing this address
1333 vector<Dwarf_Die> scopes = dw.getscopes(addr);
1334 if (scopes.empty())
1335 return;
1336
1337 // Look for the innermost containing function
1338 Dwarf_Die *fnscope = NULL;
1339 for (size_t i = 0; i < scopes.size(); ++i)
1340 {
1341 int tag = dwarf_tag(&scopes[i]);
1342 if ((tag == DW_TAG_subprogram && !q->has_inline) ||
1343 (tag == DW_TAG_inlined_subroutine &&
4bda987e 1344 !q->has_call && !q->has_return && !q->has_exported))
6b517475
JS
1345 {
1346 fnscope = &scopes[i];
1347 break;
1348 }
1349 }
1350 if (!fnscope)
1351 return;
1352 dw.focus_on_function(fnscope);
1353
1354 Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
1355
1356 const char *file = dwarf_decl_file(fnscope);
1357 int line;
1358 dwarf_decl_line(fnscope, &line);
1359
1360 // Function probes should reset the addr to the function entry
1361 // and possibly perform prologue searching
1362 if (q->has_function_num)
1363 {
1364 dw.die_entrypc(fnscope, &addr);
1365 if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
1366 (q->sess.prologue_searching || q->has_process)) // PR 6871
1367 {
1368 func_info func;
1369 func.die = *fnscope;
1370 func.name = dw.function_name;
1371 func.decl_file = file;
1372 func.decl_line = line;
1373 func.entrypc = addr;
1374
1375 func_info_map_t funcs(1, func);
1376 dw.resolve_prologue_endings (funcs);
464379bb
FCE
1377 if (q->has_return) // PR13200
1378 {
1379 if (q->sess.verbose > 2)
1380 clog << "ignoring prologue for .return probes" << endl;
1381 }
1382 else
1383 {
1384 if (funcs[0].prologue_end)
1385 addr = funcs[0].prologue_end;
1386 }
6b517475
JS
1387 }
1388 }
1389 else
1390 {
1391 dwarf_line_t address_line(dwarf_getsrc_die(cudie, addr));
1392 if (address_line)
1393 {
1394 file = address_line.linesrc();
1395 line = address_line.lineno();
1396 }
1397
1398 // Verify that a raw address matches the beginning of a
1399 // statement. This is a somewhat lame check that the address
1400 // is at the start of an assembly instruction. Mark probes are in the
1401 // middle of a macro and thus not strictly at a statement beginning.
1402 // Guru mode may override this check.
1403 if (!q->has_mark && (!address_line || address_line.addr() != addr))
1404 {
1405 stringstream msg;
2a97f50b 1406 msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
b530b5b3 1407 addr);
6b517475 1408 if (address_line)
2a97f50b 1409 msg << _F(" (try %#" PRIx64 ")", address_line.addr());
6b517475 1410 else
b530b5b3
LB
1411 msg << _F(" (no line info found for '%s', in module '%s')",
1412 dw.cu_name().c_str(), dw.module_name.c_str());
6b517475
JS
1413 if (! q->sess.guru_mode)
1414 throw semantic_error(msg.str());
2713ea24 1415 else
6b517475
JS
1416 q->sess.print_warning(msg.str());
1417 }
1418 }
1419
1420 // Build a probe at this point
1421 query_statement(dw.function_name, file, line, scope, addr, q);
1422}
1423
8096dd7d
JS
1424static void
1425query_label (string const & func,
1426 char const * label,
1427 char const * file,
1428 int line,
1429 Dwarf_Die *scope_die,
1430 Dwarf_Addr stmt_addr,
1431 dwarf_query * q)
1432{
6b517475
JS
1433 assert (q->has_statement_str || q->has_function_str);
1434
8096dd7d
JS
1435 size_t i = q->results.size();
1436
1437 // weed out functions whose decl_file isn't one of
1438 // the source files that we actually care about
6b517475 1439 if (q->spec_type != function_alone &&
8096dd7d
JS
1440 q->filtered_srcfiles.count(file) == 0)
1441 return;
1442
1443 query_statement(func, file, line, scope_die, stmt_addr, q);
1444
c72aa911
JS
1445 // after the fact, insert the label back into the derivation chain
1446 probe_point::component* ppc =
1447 new probe_point::component(TOK_LABEL, new literal_string (label));
1448 for (; i < q->results.size(); ++i)
1449 {
1450 derived_probe* p = q->results[i];
1451 probe_point* pp = new probe_point(*p->locations[0]);
1452 pp->components.push_back (ppc);
1453 p->base = p->base->create_alias(p->locations[0], pp);
1454 }
8096dd7d
JS
1455}
1456
7e1279ea 1457static void
3e961ba6 1458query_inline_instance_info (inline_instance_info & ii,
7e1279ea
FCE
1459 dwarf_query * q)
1460{
b6581717 1461 try
7e1279ea 1462 {
8f14e444
FCE
1463 assert (! q->has_return); // checked by caller already
1464 if (q->sess.verbose>2)
b530b5b3
LB
1465 clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
1466 ii.entrypc, ii.name.c_str());
8f14e444
FCE
1467 query_statement (ii.name, ii.decl_file, ii.decl_line,
1468 &ii.die, ii.entrypc, q);
7e1279ea 1469 }
b6581717 1470 catch (semantic_error &e)
7e1279ea 1471 {
b6581717 1472 q->sess.print_error (e);
7e1279ea
FCE
1473 }
1474}
1475
1476static void
1477query_func_info (Dwarf_Addr entrypc,
bcc12710 1478 func_info & fi,
7e1279ea
FCE
1479 dwarf_query * q)
1480{
b6581717 1481 try
7e1279ea 1482 {
b6581717
GH
1483 if (q->has_return)
1484 {
1485 // NB. dwarf_derived_probe::emit_registrations will emit a
1486 // kretprobe based on the entrypc in this case.
464379bb
FCE
1487 if (fi.prologue_end != 0 && q->has_return) // PR13200
1488 {
1489 if (q->sess.verbose > 2)
1490 clog << "ignoring prologue for .return probes" << endl;
1491 }
20e4a32c 1492 query_statement (fi.name, fi.decl_file, fi.decl_line,
b6581717
GH
1493 &fi.die, entrypc, q);
1494 }
1495 else
1496 {
35dc8b04 1497 if (fi.prologue_end != 0)
44f75386 1498 {
44f75386
FCE
1499 query_statement (fi.name, fi.decl_file, fi.decl_line,
1500 &fi.die, fi.prologue_end, q);
1501 }
1502 else
1503 {
1504 query_statement (fi.name, fi.decl_file, fi.decl_line,
1505 &fi.die, entrypc, q);
1506 }
b6581717 1507 }
7e1279ea 1508 }
b6581717 1509 catch (semantic_error &e)
7e1279ea 1510 {
b6581717 1511 q->sess.print_error (e);
7e1279ea
FCE
1512 }
1513}
1514
1515
bd4b874d
SC
1516static void
1517query_srcfile_label (const dwarf_line_t& line, void * arg)
1518{
1519 dwarf_query * q = static_cast<dwarf_query *>(arg);
1520
1521 Dwarf_Addr addr = line.addr();
1522
1523 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1524 i != q->filtered_functions.end(); ++i)
1525 if (q->dw.die_has_pc (i->die, addr))
f09d0d1e
JS
1526 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1527 q, query_label);
1528
1529 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1530 i != q->filtered_inlines.end(); ++i)
1531 if (q->dw.die_has_pc (i->die, addr))
1532 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1533 q, query_label);
bd4b874d
SC
1534}
1535
7e1279ea 1536static void
86bf665e 1537query_srcfile_line (const dwarf_line_t& line, void * arg)
7e1279ea
FCE
1538{
1539 dwarf_query * q = static_cast<dwarf_query *>(arg);
1540
86bf665e 1541 Dwarf_Addr addr = line.addr();
4cd232e4 1542
86bf665e 1543 int lineno = line.lineno();
847bf07f 1544
86bf665e 1545 for (func_info_map_t::iterator i = q->filtered_functions.begin();
7e1279ea
FCE
1546 i != q->filtered_functions.end(); ++i)
1547 {
3e961ba6 1548 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1549 {
b0ee93c4 1550 if (q->sess.verbose>3)
b530b5b3 1551 clog << _("function DIE lands on srcfile\n");
4cd232e4 1552 if (q->has_statement_str)
f5958c8f
JS
1553 {
1554 Dwarf_Die scope;
1555 q->dw.inner_die_containing_pc(i->die, addr, scope);
1556 query_statement (i->name, i->decl_file,
1557 lineno, // NB: not q->line !
1558 &scope, addr, q);
1559 }
4cd232e4 1560 else
3e961ba6 1561 query_func_info (i->entrypc, *i, q);
7e1279ea 1562 }
20e4a32c
RM
1563 }
1564
86bf665e 1565 for (inline_instance_map_t::iterator i
897820ca
GH
1566 = q->filtered_inlines.begin();
1567 i != q->filtered_inlines.end(); ++i)
1568 {
3e961ba6 1569 if (q->dw.die_has_pc (i->die, addr))
7e1279ea 1570 {
b0ee93c4 1571 if (q->sess.verbose>3)
b530b5b3 1572 clog << _("inline instance DIE lands on srcfile\n");
897820ca 1573 if (q->has_statement_str)
f5958c8f
JS
1574 {
1575 Dwarf_Die scope;
1576 q->dw.inner_die_containing_pc(i->die, addr, scope);
1577 query_statement (i->name, i->decl_file,
1578 q->line[0], &scope, addr, q);
1579 }
897820ca 1580 else
3e961ba6 1581 query_inline_instance_info (*i, q);
897820ca 1582 }
20e4a32c 1583 }
7e1279ea
FCE
1584}
1585
1586
7fdd3e2c
JS
1587bool
1588inline_instance_info::operator<(const inline_instance_info& other) const
1589{
1590 if (entrypc != other.entrypc)
1591 return entrypc < other.entrypc;
1592
1593 if (decl_line != other.decl_line)
1594 return decl_line < other.decl_line;
1595
1596 int cmp = name.compare(other.name);
1597 if (!cmp)
1598 cmp = strcmp(decl_file, other.decl_file);
1599 return cmp < 0;
1600}
1601
1602
4fa7b22b 1603static int
7e1279ea 1604query_dwarf_inline_instance (Dwarf_Die * die, void * arg)
4fa7b22b
GH
1605{
1606 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475 1607 assert (q->has_statement_str || q->has_function_str);
4bda987e 1608 assert (!q->has_call && !q->has_return && !q->has_exported);
bd2b1e68 1609
39bcd429 1610 try
7a053d3b 1611 {
b0ee93c4 1612 if (q->sess.verbose>2)
b530b5b3 1613 clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
7e1279ea 1614
6b517475
JS
1615 Dwarf_Addr entrypc;
1616 if (q->dw.die_entrypc (die, &entrypc))
1617 {
1618 inline_instance_info inl;
1619 inl.die = *die;
1620 inl.name = q->dw.function_name;
1621 inl.entrypc = entrypc;
1622 q->dw.function_file (&inl.decl_file);
1623 q->dw.function_line (&inl.decl_line);
1624
1625 // make sure that this inline hasn't already
1626 // been matched from a different CU
1627 if (q->inline_dupes.insert(inl).second)
1628 q->filtered_inlines.push_back(inl);
1629 }
7e1279ea
FCE
1630 return DWARF_CB_OK;
1631 }
1632 catch (const semantic_error& e)
1633 {
1634 q->sess.print_error (e);
1635 return DWARF_CB_ABORT;
1636 }
1637}
bb788f9f 1638
7e1279ea 1639static int
2da9cedb 1640query_dwarf_func (Dwarf_Die * func, base_query * bq)
7e1279ea 1641{
2da9cedb 1642 dwarf_query * q = static_cast<dwarf_query *>(bq);
6b517475 1643 assert (q->has_statement_str || q->has_function_str);
bb788f9f 1644
bd25380d
JS
1645 // weed out functions whose decl_file isn't one of
1646 // the source files that we actually care about
6b517475 1647 if (q->spec_type != function_alone &&
bd25380d 1648 q->filtered_srcfiles.count(dwarf_decl_file(func)?:"") == 0)
8096dd7d 1649 return DWARF_CB_OK;
bd25380d 1650
7e1279ea
FCE
1651 try
1652 {
7e1279ea
FCE
1653 q->dw.focus_on_function (func);
1654
7d6d0afc
JS
1655 if (!q->dw.function_scope_matches(q->scopes))
1656 return DWARF_CB_OK;
1657
857bdfd1
JS
1658 // make sure that this function address hasn't
1659 // already been matched under an aliased name
1660 Dwarf_Addr addr;
1661 if (!q->dw.func_is_inline() &&
1662 dwarf_entrypc(func, &addr) == 0 &&
1663 !q->alias_dupes.insert(addr).second)
1664 return DWARF_CB_OK;
1665
4bda987e 1666 if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
7e1279ea 1667 {
4bda987e 1668 if (q->sess.verbose>3)
b530b5b3 1669 clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
4bda987e 1670 q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
7e1279ea 1671 }
8f14e444
FCE
1672 else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
1673 {
1674 q->inlined_non_returnable.insert (q->dw.function_name);
1675 }
396afcee 1676 else if (!q->dw.func_is_inline () && (! q->has_inline))
20e4a32c 1677 {
4bda987e
SC
1678 if (q->has_exported && !q->dw.func_is_exported ())
1679 return DWARF_CB_OK;
6b517475 1680 if (q->sess.verbose>2)
b530b5b3 1681 clog << _F("selected function %s\n", q->dw.function_name.c_str());
6b517475
JS
1682
1683 func_info func;
1684 q->dw.function_die (&func.die);
1685 func.name = q->dw.function_name;
1686 q->dw.function_file (&func.decl_file);
1687 q->dw.function_line (&func.decl_line);
1688
1689 Dwarf_Addr entrypc;
1690 if (q->dw.function_entrypc (&entrypc))
1691 {
1692 func.entrypc = entrypc;
1693 q->filtered_functions.push_back (func);
1694 }
1695 /* else this function is fully inlined, just ignore it */
7e1279ea 1696 }
39bcd429 1697 return DWARF_CB_OK;
bd2b1e68 1698 }
39bcd429 1699 catch (const semantic_error& e)
bd2b1e68 1700 {
39bcd429
FCE
1701 q->sess.print_error (e);
1702 return DWARF_CB_ABORT;
bd2b1e68 1703 }
bd2b1e68
GH
1704}
1705
1706static int
1707query_cu (Dwarf_Die * cudie, void * arg)
1708{
20c6c071 1709 dwarf_query * q = static_cast<dwarf_query *>(arg);
6b517475
JS
1710 assert (q->has_statement_str || q->has_function_str);
1711
85007c04 1712 if (pending_interrupts) return DWARF_CB_ABORT;
7a053d3b 1713
39bcd429 1714 try
bd2b1e68 1715 {
7e1279ea 1716 q->dw.focus_on_cu (cudie);
b5d77020 1717
b0ee93c4 1718 if (false && q->sess.verbose>2)
b530b5b3
LB
1719 clog << _F("focused on CU '%s', in module '%s'\n",
1720 q->dw.cu_name().c_str(), q->dw.module_name.c_str());
d9b516ca 1721
6b517475
JS
1722 q->filtered_srcfiles.clear();
1723 q->filtered_functions.clear();
1724 q->filtered_inlines.clear();
1725
1726 // In this path, we find "abstract functions", record
1727 // information about them, and then (depending on lineno
1728 // matching) possibly emit one or more of the function's
1729 // associated addresses. Unfortunately the control of this
1730 // cannot easily be turned inside out.
1731
1732 if (q->spec_type != function_alone)
39bcd429 1733 {
6b517475
JS
1734 // If we have a pattern string with a filename, we need
1735 // to elaborate the srcfile mask in question first.
1736 q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
1737
1738 // If we have a file pattern and *no* srcfile matches, there's
1739 // no need to look further into this CU, so skip.
1740 if (q->filtered_srcfiles.empty())
1741 return DWARF_CB_OK;
1742 }
e4c58386 1743
6b517475
JS
1744 // Pick up [entrypc, name, DIE] tuples for all the functions
1745 // matching the query, and fill in the prologue endings of them
1746 // all in a single pass.
5898b6e1 1747 int rc = q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
6b517475
JS
1748 if (rc != DWARF_CB_OK)
1749 q->query_done = true;
1750
1751 if ((q->sess.prologue_searching || q->has_process) // PR 6871
1752 && !q->has_statement_str) // PR 2608
1753 if (! q->filtered_functions.empty())
1754 q->dw.resolve_prologue_endings (q->filtered_functions);
464379bb
FCE
1755 // NB: we could skip the resolve_prologue_endings() call here for has_return case (PR13200),
1756 // but don't have to. We can resolve the prologue, just not actually use it in query_addr().
6b517475
JS
1757
1758 if (q->spec_type == function_file_and_line)
1759 {
58b070fb 1760 // .statement(...:NN) often gets mixed up with .function(...:NN)
2713ea24 1761 if (q->has_function_str)
b530b5b3
LB
1762 q->sess.print_warning (_("For probing a particular line, use a "
1763 ".statement() probe, not .function()"),
af2e341f 1764 q->base_probe->tok);
58b070fb 1765
6b517475
JS
1766 // If we have a pattern string with target *line*, we
1767 // have to look at lines in all the matched srcfiles.
1768 void (* callback) (const dwarf_line_t&, void*) =
1769 q->has_label ? query_srcfile_label : query_srcfile_line;
1770 for (set<string>::const_iterator i = q->filtered_srcfiles.begin();
1771 i != q->filtered_srcfiles.end(); ++i)
1772 q->dw.iterate_over_srcfile_lines (i->c_str(), q->line, q->has_statement_str,
1773 q->line_type, callback, q->function, q);
1774 }
1775 else if (q->has_label)
1776 {
1777 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1778 i != q->filtered_functions.end(); ++i)
1779 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1780 q, query_label);
1781
1782 for (inline_instance_map_t::iterator i = q->filtered_inlines.begin();
1783 i != q->filtered_inlines.end(); ++i)
1784 q->dw.iterate_over_labels (&i->die, q->label_val, i->name,
1785 q, query_label);
39bcd429 1786 }
6b517475
JS
1787 else
1788 {
1789 // Otherwise, simply probe all resolved functions.
1790 for (func_info_map_t::iterator i = q->filtered_functions.begin();
1791 i != q->filtered_functions.end(); ++i)
1792 query_func_info (i->entrypc, *i, q);
1793
1794 // And all inline instances (if we're not excluding inlines with ".call")
1795 if (! q->has_call)
1796 for (inline_instance_map_t::iterator i
1797 = q->filtered_inlines.begin(); i != q->filtered_inlines.end(); ++i)
1798 query_inline_instance_info (*i, q);
1799 }
39bcd429 1800 return DWARF_CB_OK;
bd2b1e68 1801 }
39bcd429 1802 catch (const semantic_error& e)
bd2b1e68 1803 {
39bcd429
FCE
1804 q->sess.print_error (e);
1805 return DWARF_CB_ABORT;
bd2b1e68 1806 }
bd2b1e68
GH
1807}
1808
0ce64fb8 1809
4df79aaf
JS
1810void
1811dwarf_query::query_module_functions ()
1812{
1813 try
1814 {
1815 filtered_srcfiles.clear();
1816 filtered_functions.clear();
1817 filtered_inlines.clear();
1818
1819 // Collect all module functions so we know which CUs are interesting
1820 int rc = dw.iterate_single_function(query_dwarf_func, this, function);
1821 if (rc != DWARF_CB_OK)
1822 {
1823 query_done = true;
1824 return;
1825 }
1826
1827 set<void*> used_cus; // by cu->addr
1828 vector<Dwarf_Die> cus;
1829 Dwarf_Die cu_mem;
1830
1831 for (func_info_map_t::iterator i = filtered_functions.begin();
1832 i != filtered_functions.end(); ++i)
1833 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1834 used_cus.insert(cu_mem.addr).second)
1835 cus.push_back(cu_mem);
1836
1837 for (inline_instance_map_t::iterator i = filtered_inlines.begin();
1838 i != filtered_inlines.end(); ++i)
1839 if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
1840 used_cus.insert(cu_mem.addr).second)
1841 cus.push_back(cu_mem);
1842
1843 // Reset the dupes since we didn't actually collect them the first time
1844 alias_dupes.clear();
1845 inline_dupes.clear();
1846
1847 // Run the query again on the individual CUs
1848 for (vector<Dwarf_Die>::iterator i = cus.begin(); i != cus.end(); ++i)
1849 query_cu(&*i, this);
1850 }
1851 catch (const semantic_error& e)
1852 {
1853 sess.print_error (e);
1854 }
1855}
1856
1857
5f0a03a6
JK
1858static void
1859validate_module_elf (Dwfl_Module *mod, const char *name, base_query *q)
1860{
1861 // Validate the machine code in this elf file against the
1862 // session machine. This is important, in case the wrong kind
1863 // of debuginfo is being automagically processed by elfutils.
1864 // While we can tell i686 apart from x86-64, unfortunately
1865 // we can't help confusing i586 vs i686 (both EM_386).
1866
1867 Dwarf_Addr bias;
1868 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
1869 // because dwfl_module_getelf can force costly section relocations
1870 // we don't really need, while either will do for this purpose.
1871 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
1872 ?: dwfl_module_getelf (mod, &bias));
1873
1874 GElf_Ehdr ehdr_mem;
1875 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
86bf665e 1876 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 1877 assert(em);
5f0a03a6
JK
1878 int elf_machine = em->e_machine;
1879 const char* debug_filename = "";
1880 const char* main_filename = "";
1881 (void) dwfl_module_info (mod, NULL, NULL,
1882 NULL, NULL, NULL,
1883 & main_filename,
1884 & debug_filename);
1885 const string& sess_machine = q->sess.architecture;
756c9462
FCE
1886
1887 string expect_machine; // to match sess.machine (i.e., kernel machine)
1888 string expect_machine2;
5f0a03a6 1889
d27e6fd5 1890 // NB: See also the 'uname -m' squashing done in main.cxx.
5f0a03a6
JK
1891 switch (elf_machine)
1892 {
756c9462
FCE
1893 // x86 and ppc are bi-architecture; a 64-bit kernel
1894 // can normally run either 32-bit or 64-bit *userspace*.
1895 case EM_386:
1896 expect_machine = "i?86";
1897 if (! q->has_process) break; // 32-bit kernel/module
1898 /* FALLSTHROUGH */
1899 case EM_X86_64:
1900 expect_machine2 = "x86_64";
1901 break;
1902 case EM_PPC:
756c9462 1903 case EM_PPC64:
5a1c472e 1904 expect_machine = "powerpc";
756c9462 1905 break;
3fe7d888 1906 case EM_S390: expect_machine = "s390"; break;
5f0a03a6 1907 case EM_IA_64: expect_machine = "ia64"; break;
d27e6fd5 1908 case EM_ARM: expect_machine = "arm*"; break;
5f0a03a6
JK
1909 // XXX: fill in some more of these
1910 default: expect_machine = "?"; break;
1911 }
1912
1913 if (! debug_filename) debug_filename = main_filename;
1914 if (! debug_filename) debug_filename = name;
1915
756c9462
FCE
1916 if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
1917 fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
5f0a03a6
JK
1918 {
1919 stringstream msg;
b530b5b3
LB
1920 msg << _F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
1921 expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
1922 sess_machine.c_str(), debug_filename);
5f0a03a6
JK
1923 throw semantic_error(msg.str ());
1924 }
1925
b57082de 1926 if (q->sess.verbose>1)
2a97f50b 1927 clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
b530b5b3
LB
1928 " file %s ELF machine %s|%s (code %d)\n",
1929 q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
1930 q->dw.module_bias, debug_filename, expect_machine.c_str(),
1931 expect_machine2.c_str(), elf_machine);
5f0a03a6 1932}
1d3a40b6 1933
91af0778
FCE
1934
1935
1936static Dwarf_Addr
1937lookup_symbol_address (Dwfl_Module *m, const char* wanted)
1938{
1939 int syments = dwfl_module_getsymtab(m);
1940 assert(syments);
1941 for (int i = 1; i < syments; ++i)
1942 {
1943 GElf_Sym sym;
1944 const char *name = dwfl_module_getsym(m, i, &sym, NULL);
1945 if (name != NULL && strcmp(name, wanted) == 0)
1946 return sym.st_value;
1947 }
1948
1949 return 0;
1950}
1951
1952
1953
bd2b1e68 1954static int
b8da0ad1 1955query_module (Dwfl_Module *mod,
91af0778 1956 void **,
b8da0ad1 1957 const char *name,
6f4c1275 1958 Dwarf_Addr addr,
b8da0ad1 1959 void *arg)
bd2b1e68 1960{
91af0778 1961 base_query *q = static_cast<base_query *>(arg);
bd2b1e68 1962
39bcd429 1963 try
e38d6504 1964 {
91af0778
FCE
1965 module_info* mi = q->sess.module_cache->cache[name];
1966 if (mi == 0)
1967 {
1968 mi = q->sess.module_cache->cache[name] = new module_info(name);
1969
6f4c1275
FCE
1970 mi->mod = mod;
1971 mi->addr = addr;
91af0778 1972
6f4c1275
FCE
1973 const char* debug_filename = "";
1974 const char* main_filename = "";
1975 (void) dwfl_module_info (mod, NULL, NULL,
1976 NULL, NULL, NULL,
1977 & main_filename,
1978 & debug_filename);
1979
1980 if (q->sess.ignore_vmlinux && name == TOK_KERNEL)
91af0778
FCE
1981 {
1982 // report_kernel() in elfutils found vmlinux, but pretend it didn't.
1983 // Given a non-null path, returning 1 means keep reporting modules.
1984 mi->dwarf_status = info_absent;
1985 }
6f4c1275 1986 else if (debug_filename || main_filename)
91af0778 1987 {
6f4c1275
FCE
1988 mi->elf_path = debug_filename ?: main_filename;
1989 }
1990 else if (name == TOK_KERNEL)
1991 {
1992 mi->dwarf_status = info_absent;
91af0778 1993 }
91af0778
FCE
1994 }
1995 // OK, enough of that module_info caching business.
1996
5f0a03a6 1997 q->dw.focus_on_module(mod, mi);
d9b516ca 1998
39bcd429
FCE
1999 // If we have enough information in the pattern to skip a module and
2000 // the module does not match that information, return early.
b8da0ad1 2001 if (!q->dw.module_name_matches(q->module_val))
85007c04 2002 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
0cbbf9d1
FCE
2003
2004 // Don't allow module("*kernel*") type expressions to match the
2005 // elfutils module "kernel", which we refer to in the probe
2006 // point syntax exclusively as "kernel.*".
2007 if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
85007c04 2008 return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
b5d77020 2009
5f0a03a6
JK
2010 if (mod)
2011 validate_module_elf(mod, name, q);
2012 else
91af0778
FCE
2013 assert(q->has_kernel); // and no vmlinux to examine
2014
2015 if (q->sess.verbose>2)
b530b5b3 2016 cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
91af0778
FCE
2017
2018
2019 // Collect a few kernel addresses. XXX: these belong better
2020 // to the sess.module_info["kernel"] struct.
2021 if (q->dw.module_name == TOK_KERNEL)
c931ec8a 2022 {
91af0778
FCE
2023 if (! q->sess.sym_kprobes_text_start)
2024 q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
2025 if (! q->sess.sym_kprobes_text_end)
2026 q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
2027 if (! q->sess.sym_stext)
2028 q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
c931ec8a
FCE
2029 }
2030
47e226ed
SC
2031 // We either have a wildcard or an unresolved library
2032 if (q->has_library && (contains_glob_chars (q->path)
2033 || q->path.find('/') == string::npos))
84c84ac4
SC
2034 // handle .library(GLOB)
2035 q->dw.iterate_over_libraries (&q->query_library_callback, q);
576eaefe
SC
2036 // .plt is translated to .plt.statement(N). We only want to iterate for the
2037 // .plt case
2038 else if (q->has_plt && ! q->has_statement)
2039 q->dw.iterate_over_plt (q, &q->query_plt_callback);
84c84ac4
SC
2040 else
2041 // search the module for matches of the probe point.
2042 q->handle_query_module();
bb788f9f 2043
b8da0ad1 2044 // If we know that there will be no more matches, abort early.
85007c04 2045 if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
b8da0ad1
FCE
2046 return DWARF_CB_ABORT;
2047 else
2048 return DWARF_CB_OK;
7a053d3b 2049 }
39bcd429 2050 catch (const semantic_error& e)
bd2b1e68 2051 {
39bcd429
FCE
2052 q->sess.print_error (e);
2053 return DWARF_CB_ABORT;
bd2b1e68 2054 }
bd2b1e68
GH
2055}
2056
35d4ab18 2057
84c84ac4 2058void
5d5bd369 2059base_query::query_library_callback (void *q, const char *data)
84c84ac4
SC
2060{
2061 base_query *me = (base_query*)q;
5d5bd369 2062 me->query_library (data);
84c84ac4
SC
2063}
2064
2065
2066void
51d6bda3
SC
2067query_one_library (const char *library, dwflpp & dw,
2068 const string user_lib, probe * base_probe, probe_point *base_loc,
2069 vector<derived_probe *> & results)
84c84ac4 2070{
47e226ed 2071 if (dw.function_name_matches_pattern(library, "*" + user_lib))
84c84ac4 2072 {
05fb3e0c
WF
2073 string library_path = find_executable (library, "", dw.sess.sysenv,
2074 "LD_LIBRARY_PATH");
84c84ac4
SC
2075 probe_point* specific_loc = new probe_point(*base_loc);
2076 specific_loc->optional = true;
2077 vector<probe_point::component*> derived_comps;
2078
2079 vector<probe_point::component*>::iterator it;
2080 for (it = specific_loc->components.begin();
2081 it != specific_loc->components.end(); ++it)
2082 if ((*it)->functor == TOK_LIBRARY)
2083 derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
2084 new literal_string(library_path)));
2085 else
2086 derived_comps.push_back(*it);
2087 probe_point* derived_loc = new probe_point(*specific_loc);
2088 derived_loc->components = derived_comps;
2089 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
51d6bda3
SC
2090 derive_probes(dw.sess, new_base, results);
2091 if (dw.sess.verbose > 2)
84c84ac4
SC
2092 clog << _("module=") << library_path;
2093 }
2094}
2095
2096
51d6bda3
SC
2097void
2098dwarf_query::query_library (const char *library)
2099{
2100 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
2101}
2102
576eaefe
SC
2103struct plt_expanding_visitor: public var_expanding_visitor
2104{
2105 plt_expanding_visitor(const string & entry):
2106 entry (entry)
2107 {
2108 }
2109 const string & entry;
2110
2111 void visit_target_symbol (target_symbol* e);
2112};
2113
2114
2115void
2116base_query::query_plt_callback (void *q, const char *entry, size_t address)
2117{
2118 base_query *me = (base_query*)q;
2119 if (me->dw.function_name_matches_pattern (entry, me->plt_val))
2120 me->query_plt (entry, address);
2121}
2122
2123
2124void
2125query_one_plt (const char *entry, long addr, dwflpp & dw,
2126 probe * base_probe, probe_point *base_loc,
2127 vector<derived_probe *> & results)
2128{
2129 probe_point* specific_loc = new probe_point(*base_loc);
2130 specific_loc->optional = true;
2131 vector<probe_point::component*> derived_comps;
2132
2133 if (dw.sess.verbose > 2)
2134 clog << _F("plt entry=%s\n", entry);
2135
2136 // query_module_symtab requires .plt to recognize that it can set the probe at
2137 // a plt entry so we convert process.plt to process.plt.statement
2138 vector<probe_point::component*>::iterator it;
2139 for (it = specific_loc->components.begin();
2140 it != specific_loc->components.end(); ++it)
2141 if ((*it)->functor == TOK_PLT)
3d372d6b
SC
2142 {
2143 derived_comps.push_back(*it);
2144 derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
2145 new literal_number(addr)));
2146 }
576eaefe
SC
2147 else
2148 derived_comps.push_back(*it);
2149 probe_point* derived_loc = new probe_point(*specific_loc);
2150 derived_loc->components = derived_comps;
2151 probe *new_base = base_probe->create_alias(derived_loc, specific_loc);
2152 string e = string(entry);
2153 plt_expanding_visitor pltv (e);
2154 pltv.replace (new_base->body);
2155 derive_probes(dw.sess, new_base, results);
2156}
2157
2158
2159void
2160dwarf_query::query_plt (const char *entry, size_t address)
2161{
2162 query_one_plt (entry, address, dw, base_probe, base_loc, results);
2163}
51d6bda3 2164
435f53a7
FCE
2165// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
2166// but the needed declaration for module_cache is not available there.
2167// Nor for that matter in session.cxx. Only in this CU is that field ever
2168// set (in query_module() above), so we clean it up here too.
2169static void
2170delete_session_module_cache (systemtap_session& s)
2171{
2172 if (s.module_cache) {
2173 if (s.verbose > 3)
b530b5b3 2174 clog << _("deleting module_cache") << endl;
435f53a7
FCE
2175 delete s.module_cache;
2176 s.module_cache = 0;
2177 }
2178}
2179
2180
de688825 2181struct dwarf_var_expanding_visitor: public var_expanding_visitor
35d4ab18 2182{
77de5e9e 2183 dwarf_query & q;
bcc12710 2184 Dwarf_Die *scope_die;
77de5e9e 2185 Dwarf_Addr addr;
8c819921 2186 block *add_block;
2260f4e3 2187 block *add_call_probe; // synthesized from .return probes with saved $vars
8cc799a5 2188 bool add_block_tid, add_call_probe_tid;
af234c40
JS
2189 unsigned saved_longs, saved_strings; // data saved within kretprobes
2190 map<std::string, expression *> return_ts_map;
729455a7 2191 vector<Dwarf_Die> scopes;
b95e2b79 2192 bool visited;
77de5e9e 2193
de688825 2194 dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
af234c40 2195 q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
8cc799a5 2196 add_block_tid(false), add_call_probe_tid(false),
af234c40 2197 saved_longs(0), saved_strings(0), visited(false) {}
277c21bc 2198 expression* gen_mapped_saved_return(expression* e, const string& name);
140be17a 2199 expression* gen_kretprobe_saved_return(expression* e);
a7999c82
JS
2200 void visit_target_symbol_saved_return (target_symbol* e);
2201 void visit_target_symbol_context (target_symbol* e);
d7f3e0c5 2202 void visit_target_symbol (target_symbol* e);
c24447be 2203 void visit_cast_op (cast_op* e);
8cc799a5 2204 void visit_entry_op (entry_op* e);
729455a7 2205private:
bfa7e523 2206 vector<Dwarf_Die>& getcuscope(target_symbol *e);
729455a7 2207 vector<Dwarf_Die>& getscopes(target_symbol *e);
77de5e9e
GH
2208};
2209
2210
de688825 2211unsigned var_expanding_visitor::tick = 0;
77de5e9e 2212
a50de939 2213
74fe61bc 2214var_expanding_visitor::var_expanding_visitor (): op()
a50de939
DS
2215{
2216 // FIXME: for the time being, by default we only support plain '$foo
2217 // = bar', not '+=' or any other op= variant. This is fixable, but a
2218 // bit ugly.
2219 //
2220 // If derived classes desire to add additional operator support, add
2221 // new operators to this list in the derived class constructor.
2222 valid_ops.insert ("=");
2223}
2224
2225
87214add
JS
2226bool
2227var_expanding_visitor::rewrite_lvalue(const token* tok, const std::string& eop,
2228 expression*& lvalue, expression*& rvalue)
77de5e9e 2229{
e57b735a
GH
2230 // Our job would normally be to require() the left and right sides
2231 // into a new assignment. What we're doing is slightly trickier:
2232 // we're pushing a functioncall** onto a stack, and if our left
2233 // child sets the functioncall* for that value, we're going to
2234 // assume our left child was a target symbol -- transformed into a
2235 // set_target_foo(value) call, and it wants to take our right child
2236 // as the argument "value".
2237 //
2238 // This is why some people claim that languages with
2239 // constructor-decomposing case expressions have a leg up on
2240 // visitors.
2241
2242 functioncall *fcall = NULL;
d9b516ca 2243
a50de939 2244 // Let visit_target_symbol know what operator it should handle.
87214add
JS
2245 const string* old_op = op;
2246 op = &eop;
a50de939 2247
e57b735a 2248 target_symbol_setter_functioncalls.push (&fcall);
87214add 2249 replace (lvalue);
e57b735a 2250 target_symbol_setter_functioncalls.pop ();
87214add
JS
2251 replace (rvalue);
2252
2253 op = old_op;
e57b735a
GH
2254
2255 if (fcall != NULL)
77de5e9e 2256 {
e57b735a
GH
2257 // Our left child is informing us that it was a target variable
2258 // and it has been replaced with a set_target_foo() function
2259 // call; we are going to provide that function call -- with the
2260 // right child spliced in as sole argument -- in place of
de688825 2261 // ourselves, in the var expansion we're in the middle of making.
e57b735a 2262
87214add 2263 if (valid_ops.find (eop) == valid_ops.end ())
a50de939
DS
2264 {
2265 // Build up a list of supported operators.
2266 string ops;
2267 std::set<string>::iterator i;
b530b5b3 2268 int valid_ops_size = 0;
a50de939 2269 for (i = valid_ops.begin(); i != valid_ops.end(); i++)
b530b5b3 2270 {
a50de939 2271 ops += " " + *i + ",";
b530b5b3
LB
2272 valid_ops_size++;
2273 }
a50de939
DS
2274 ops.resize(ops.size() - 1); // chop off the last ','
2275
2276 // Throw the error.
1e41115c
LB
2277 throw semantic_error (_F(ngettext("Only the following assign operator is implemented on target variables: %s",
2278 "Only the following assign operators are implemented on target variables: %s",
b530b5b3
LB
2279 valid_ops_size), ops.c_str()), tok);
2280
a50de939 2281 }
e57b735a 2282
87214add
JS
2283 assert (lvalue == fcall);
2284 if (rvalue)
2285 fcall->args.push_back (rvalue);
4ed05b15 2286 provide (fcall);
87214add 2287 return true;
77de5e9e 2288 }
e57b735a 2289 else
87214add
JS
2290 return false;
2291}
2292
2293
2294void
2295var_expanding_visitor::visit_assignment (assignment* e)
2296{
2297 if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
2298 provide (e);
2299}
2300
2301
2302void
2303var_expanding_visitor::visit_pre_crement (pre_crement* e)
2304{
2305 expression *dummy = NULL;
2306 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2307 provide (e);
2308}
2309
2310
2311void
2312var_expanding_visitor::visit_post_crement (post_crement* e)
2313{
2314 expression *dummy = NULL;
2315 if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
2316 provide (e);
2317}
2318
2319
2320void
2321var_expanding_visitor::visit_delete_statement (delete_statement* s)
2322{
2323 string fakeop = "delete";
2324 expression *dummy = NULL;
2325 if (!rewrite_lvalue (s->tok, fakeop, s->value, dummy))
2326 provide (s);
e57b735a 2327}
d9b516ca 2328
d7f3e0c5 2329
30263a73
FCE
2330void
2331var_expanding_visitor::visit_defined_op (defined_op* e)
2332{
2333 bool resolved = true;
2334
2335 defined_ops.push (e);
2336 try {
2337 // NB: provide<>/require<> are NOT typesafe. So even though a defined_op is
2338 // defined with a target_symbol* operand, a subsidiary call may attempt to
2339 // rewrite it to a general expression* instead, and require<> happily
2340 // casts to/from void*, causing possible memory corruption. We use
2341 // expression* here, being the general case of rewritten $variable.
2342 expression *foo1 = e->operand;
2343 foo1 = require (foo1);
2344
c69a87e0 2345 // NB: Formerly, we had some curious cases to consider here, depending on what
30263a73 2346 // various visit_target_symbol() implementations do for successful or
c69a87e0
FCE
2347 // erroneous resolutions. Some would signal a visit_target_symbol failure
2348 // with an exception, with a set flag within the target_symbol, or nothing
2349 // at all.
30263a73 2350 //
c69a87e0
FCE
2351 // Now, failures always have to be signalled with a
2352 // saved_conversion_error being chained to the target_symbol.
2353 // Successes have to result in an attempted rewrite of the
850bfddd 2354 // target_symbol (via provide()).
780f11ff 2355 //
c69a87e0
FCE
2356 // Edna Mode: "no capes". fche: "no exceptions".
2357
30263a73
FCE
2358 // dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
2359 //
2360 // sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
2361 //
2362 // sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
2363 // dwarf probe to take care of it.
2364 // But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
2365 // to pass through @defined() to the synthetic dwarf probe.
780f11ff 2366 //
30263a73
FCE
2367 // utrace: success: rewrites to function; failure: semantic_error
2368 //
850bfddd 2369 // procfs: success: rewrites to function; failure: semantic_error
30263a73
FCE
2370
2371 target_symbol* foo2 = dynamic_cast<target_symbol*> (foo1);
c69a87e0 2372 if (foo2 && foo2->saved_conversion_error) // failing
30263a73 2373 resolved = false;
a45664f4 2374 else if (foo2) // unresolved but not marked failing
b7aedf26 2375 {
780f11ff
JS
2376 // There are some visitors that won't touch certain target_symbols,
2377 // e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
2378 // leave it for now so some other visitor can have a chance.
b7aedf26
JS
2379 e->operand = foo2;
2380 provide (e);
2381 return;
2382 }
30263a73
FCE
2383 else // resolved, rewritten to some other expression type
2384 resolved = true;
780f11ff 2385 } catch (const semantic_error& e) {
c69a87e0 2386 assert (0); // should not happen
30263a73
FCE
2387 }
2388 defined_ops.pop ();
2389
2390 literal_number* ln = new literal_number (resolved ? 1 : 0);
2391 ln->tok = e->tok;
2392 provide (ln);
2393}
2394
2395
5f36109e
JS
2396struct dwarf_pretty_print
2397{
2398 dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
2399 const string& local, bool userspace_p,
2400 const target_symbol& e):
d19a9a82
JS
2401 dw(dw), local(local), scopes(scopes), pc(pc), pointer(NULL),
2402 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2403 {
2404 init_ts (e);
2405 dw.type_die_for_local (scopes, pc, local, ts, &base_type);
2406 }
2407
2408 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
2409 bool userspace_p, const target_symbol& e):
d19a9a82
JS
2410 dw(dw), scopes(1, *scope_die), pc(pc), pointer(NULL),
2411 userspace_p(userspace_p), deref_p(true)
5f36109e
JS
2412 {
2413 init_ts (e);
2414 dw.type_die_for_return (&scopes[0], pc, ts, &base_type);
2415 }
2416
2417 dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
d19a9a82 2418 bool deref_p, bool userspace_p, const target_symbol& e):
5f36109e 2419 dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
d19a9a82 2420 userspace_p(userspace_p), deref_p(deref_p)
5f36109e
JS
2421 {
2422 init_ts (e);
2423 dw.type_die_for_pointer (type_die, ts, &base_type);
2424 }
2425
2426 functioncall* expand ();
ce83ff57 2427 ~dwarf_pretty_print () { delete ts; }
5f36109e
JS
2428
2429private:
2430 dwflpp& dw;
2431 target_symbol* ts;
7d11d8c9 2432 bool print_full;
5f36109e
JS
2433 Dwarf_Die base_type;
2434
2435 string local;
2436 vector<Dwarf_Die> scopes;
2437 Dwarf_Addr pc;
2438
2439 expression* pointer;
2440 Dwarf_Die pointer_type;
2441
d19a9a82 2442 const bool userspace_p, deref_p;
5f36109e
JS
2443
2444 void recurse (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2445 print_format* pf, bool top=false);
600551ca
JS
2446 void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
2447 print_format* pf);
5f36109e 2448 void recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2449 print_format* pf);
5f36109e 2450 void recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2451 print_format* pf, bool top);
5f36109e 2452 void recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2453 print_format* pf, bool top);
5f36109e 2454 void recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2455 print_format* pf, bool top);
5f36109e 2456 void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2457 print_format* pf, int& count);
bbee5bb8 2458 bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
5f36109e
JS
2459
2460 void init_ts (const target_symbol& e);
2461 expression* deref (target_symbol* e);
c55ea10d 2462 bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
5f36109e
JS
2463};
2464
2465
2466void
2467dwarf_pretty_print::init_ts (const target_symbol& e)
2468{
2469 // Work with a new target_symbol so we can modify arguments
2470 ts = new target_symbol (e);
2471
2472 if (ts->addressof)
b530b5b3 2473 throw semantic_error(_("cannot take address of pretty-printed variable"), ts->tok);
5f36109e
JS
2474
2475 if (ts->components.empty() ||
2476 ts->components.back().type != target_symbol::comp_pretty_print)
b530b5b3 2477 throw semantic_error(_("invalid target_symbol for pretty-print"), ts->tok);
7d11d8c9 2478 print_full = ts->components.back().member.length() > 1;
5f36109e
JS
2479 ts->components.pop_back();
2480}
2481
2482
2483functioncall*
2484dwarf_pretty_print::expand ()
2485{
2486 static unsigned tick = 0;
2487
2488 // function pretty_print_X([pointer], [arg1, arg2, ...]) {
7d11d8c9
JS
2489 // try {
2490 // return sprintf("{.foo=...}", (ts)->foo, ...)
2491 // } catch {
2492 // return "ERROR"
2493 // }
5f36109e
JS
2494 // }
2495
2496 // Create the function decl and call.
2497
2498 functiondecl *fdecl = new functiondecl;
2499 fdecl->tok = ts->tok;
2500 fdecl->synthetic = true;
2501 fdecl->name = "_dwarf_pretty_print_" + lex_cast(tick++);
2502 fdecl->type = pe_string;
2503
2504 functioncall* fcall = new functioncall;
2505 fcall->tok = ts->tok;
2506 fcall->function = fdecl->name;
140be17a 2507 fcall->type = pe_string;
5f36109e
JS
2508
2509 // If there's a <pointer>, replace it with a new var and make that
2510 // the first function argument.
2511 if (pointer)
2512 {
2513 vardecl *v = new vardecl;
2514 v->type = pe_long;
2515 v->name = "pointer";
2516 v->tok = ts->tok;
2517 fdecl->formal_args.push_back (v);
2518 fcall->args.push_back (pointer);
2519
2520 symbol* sym = new symbol;
2521 sym->tok = ts->tok;
2522 sym->name = v->name;
5f36109e
JS
2523 pointer = sym;
2524 }
2525
2526 // For each expression argument, replace it with a function argument.
2527 for (unsigned i = 0; i < ts->components.size(); ++i)
2528 if (ts->components[i].type == target_symbol::comp_expression_array_index)
2529 {
2530 vardecl *v = new vardecl;
2531 v->type = pe_long;
2532 v->name = "index" + lex_cast(i);
2533 v->tok = ts->tok;
2534 fdecl->formal_args.push_back (v);
2535 fcall->args.push_back (ts->components[i].expr_index);
2536
2537 symbol* sym = new symbol;
2538 sym->tok = ts->tok;
2539 sym->name = v->name;
5f36109e
JS
2540 ts->components[i].expr_index = sym;
2541 }
2542
2543 // Create the return sprintf.
2544 token* pf_tok = new token(*ts->tok);
2545 pf_tok->content = "sprintf";
2546 print_format* pf = print_format::create(pf_tok);
2547 return_statement* rs = new return_statement;
2548 rs->tok = ts->tok;
2549 rs->value = pf;
5f36109e
JS
2550
2551 // Recurse into the actual values.
7d11d8c9 2552 recurse (&base_type, ts, pf, true);
5f36109e
JS
2553 pf->components = print_format::string_to_components(pf->raw_components);
2554
7d11d8c9
JS
2555 // Create the try-catch net
2556 try_block* tb = new try_block;
2557 tb->tok = ts->tok;
2558 tb->try_block = rs;
2559 tb->catch_error_var = 0;
2560 return_statement* rs2 = new return_statement;
2561 rs2->tok = ts->tok;
2562 rs2->value = new literal_string ("ERROR");
2563 rs2->value->tok = ts->tok;
2564 tb->catch_block = rs2;
2565 fdecl->body = tb;
2566
f8809d54 2567 fdecl->join (dw.sess);
5f36109e
JS
2568 return fcall;
2569}
2570
2571
2572void
2573dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
7d11d8c9 2574 print_format* pf, bool top)
5f36109e
JS
2575{
2576 Dwarf_Die type;
2577 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2578
2579 switch (dwarf_tag(&type))
2580 {
2581 default:
2582 // XXX need a warning?
2583 // throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
2584 // + ") for " + dwarf_type_name(&type), e->tok);
2585 pf->raw_components.append("?");
2586 break;
2587
2588 case DW_TAG_enumeration_type:
2589 case DW_TAG_base_type:
7d11d8c9 2590 recurse_base (&type, e, pf);
5f36109e
JS
2591 break;
2592
2593 case DW_TAG_array_type:
7d11d8c9 2594 recurse_array (&type, e, pf, top);
5f36109e
JS
2595 break;
2596
2597 case DW_TAG_pointer_type:
2598 case DW_TAG_reference_type:
2599 case DW_TAG_rvalue_reference_type:
7d11d8c9 2600 recurse_pointer (&type, e, pf, top);
5f36109e
JS
2601 break;
2602
2603 case DW_TAG_subroutine_type:
c55ea10d 2604 push_deref (pf, "<function>:%p", e);
5f36109e
JS
2605 break;
2606
2607 case DW_TAG_union_type:
5f36109e
JS
2608 case DW_TAG_structure_type:
2609 case DW_TAG_class_type:
7d11d8c9 2610 recurse_struct (&type, e, pf, top);
5f36109e
JS
2611 break;
2612 }
2613}
2614
2615
600551ca
JS
2616// Bit fields are handled as a special-case combination of recurse() and
2617// recurse_base(), only called from recurse_struct_members(). The main
2618// difference is that the value is always printed numerically, even if the
2619// underlying type is a char.
2620void
2621dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
2622 print_format* pf)
2623{
2624 Dwarf_Die type;
2625 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2626
2627 int tag = dwarf_tag(&type);
2628 if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
2629 {
2630 // XXX need a warning?
2631 // throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
2632 // + ") for " + dwarf_type_name(&type), e->tok);
2633 pf->raw_components.append("?");
2634 return;
2635 }
2636
2637 Dwarf_Attribute attr;
2638 Dwarf_Word encoding = (Dwarf_Word) -1;
2639 dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
2640 &encoding);
2641 switch (encoding)
2642 {
2643 case DW_ATE_float:
2644 case DW_ATE_complex_float:
2645 // XXX need a warning?
2646 // throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
2647 // + ") for " + dwarf_type_name(&type), e->tok);
2648 pf->raw_components.append("?");
2649 break;
2650
2651 case DW_ATE_unsigned:
2652 case DW_ATE_unsigned_char:
2653 push_deref (pf, "%u", e);
2654 break;
2655
2656 case DW_ATE_signed:
2657 case DW_ATE_signed_char:
2658 default:
2659 push_deref (pf, "%i", e);
2660 break;
2661 }
2662}
2663
2664
5f36109e
JS
2665void
2666dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2667 print_format* pf)
5f36109e
JS
2668{
2669 Dwarf_Attribute attr;
2670 Dwarf_Word encoding = (Dwarf_Word) -1;
2671 dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
2672 &encoding);
5f36109e
JS
2673 switch (encoding)
2674 {
2675 case DW_ATE_float:
2676 case DW_ATE_complex_float:
2677 // XXX need a warning?
2678 // throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
2679 // + ") for " + dwarf_type_name(type), e->tok);
2680 pf->raw_components.append("?");
5f36109e
JS
2681 break;
2682
2683 case DW_ATE_signed_char:
2684 case DW_ATE_unsigned_char:
941101c1
JS
2685 // Use escapes to make sure that non-printable characters
2686 // don't interrupt our stream (especially '\0' values).
2687 push_deref (pf, "'%#c'", e);
5f36109e
JS
2688 break;
2689
2690 case DW_ATE_unsigned:
c55ea10d 2691 push_deref (pf, "%u", e);
5f36109e
JS
2692 break;
2693
600551ca 2694 case DW_ATE_signed:
5f36109e 2695 default:
c55ea10d 2696 push_deref (pf, "%i", e);
5f36109e
JS
2697 break;
2698 }
5f36109e
JS
2699}
2700
2701
2702void
2703dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2704 print_format* pf, bool top)
5f36109e 2705{
7d11d8c9
JS
2706 if (!top && !print_full)
2707 {
2708 pf->raw_components.append("[...]");
2709 return;
2710 }
2711
5f36109e
JS
2712 Dwarf_Die childtype;
2713 dwarf_attr_die (type, DW_AT_type, &childtype);
bbee5bb8
JS
2714
2715 if (print_chars (&childtype, e, pf))
2716 return;
2717
5f36109e
JS
2718 pf->raw_components.append("[");
2719
2720 // We print the array up to the first 5 elements.
2721 // XXX how can we determine the array size?
2722 // ... for now, just print the first element
64cddf39 2723 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
5f36109e 2724 unsigned i, size = 1;
64cddf39 2725 for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
5f36109e
JS
2726 {
2727 if (i > 0)
2728 pf->raw_components.append(", ");
2729 target_symbol* e2 = new target_symbol(*e);
2730 e2->components.push_back (target_symbol::component(e->tok, i));
7d11d8c9 2731 recurse (&childtype, e2, pf);
5f36109e
JS
2732 }
2733 if (i < size || 1/*XXX until real size is known */)
2734 pf->raw_components.append(", ...");
2735 pf->raw_components.append("]");
2736}
2737
2738
2739void
2740dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2741 print_format* pf, bool top)
5f36109e 2742{
7d11d8c9 2743 // We chase to top-level pointers, but leave the rest alone
d19a9a82 2744 bool void_p = true;
7d11d8c9 2745 Dwarf_Die pointee;
bbee5bb8 2746 if (dwarf_attr_die (type, DW_AT_type, &pointee))
d19a9a82
JS
2747 {
2748 try
2749 {
2750 dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
2751 void_p = false;
2752 }
2753 catch (const semantic_error&) {}
2754 }
2755
2756 if (!void_p)
5f36109e 2757 {
bbee5bb8
JS
2758 if (print_chars (&pointee, e, pf))
2759 return;
2760
2761 if (top)
2762 {
2763 recurse (&pointee, e, pf, top);
2764 return;
2765 }
5f36109e 2766 }
bbee5bb8 2767
c55ea10d 2768 push_deref (pf, "%p", e);
5f36109e
JS
2769}
2770
2771
2772void
2773dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2774 print_format* pf, bool top)
5f36109e 2775{
bdec0e18
JS
2776 if (dwarf_hasattr(type, DW_AT_declaration))
2777 {
a44a7cb5 2778 Dwarf_Die *resolved = dw.declaration_resolve(type);
bdec0e18
JS
2779 if (!resolved)
2780 {
2781 // could be an error, but for now just stub it
2782 // throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
2783 pf->raw_components.append("{...}");
2784 return;
2785 }
2786 type = resolved;
2787 }
2788
5f36109e
JS
2789 int count = 0;
2790 pf->raw_components.append("{");
7d11d8c9
JS
2791 if (top || print_full)
2792 recurse_struct_members (type, e, pf, count);
2793 else
2794 pf->raw_components.append("...");
5f36109e
JS
2795 pf->raw_components.append("}");
2796}
2797
2798
2799void
2800dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
7d11d8c9 2801 print_format* pf, int& count)
5f36109e 2802{
a80f28d8
JS
2803 /* With inheritance, a subclass may mask member names of parent classes, so
2804 * our search among the inheritance tree must be breadth-first rather than
2805 * depth-first (recursive). The type die is still our starting point. When
2806 * we encounter a masked name, just skip it. */
2807 set<string> dupes;
2808 deque<Dwarf_Die> inheritees(1, *type);
2809 for (; !inheritees.empty(); inheritees.pop_front())
2810 {
2811 Dwarf_Die child, childtype;
2812 if (dwarf_child (&inheritees.front(), &child) == 0)
2813 do
2814 {
2815 target_symbol* e2 = e;
5f36109e 2816
a80f28d8
JS
2817 // skip static members
2818 if (dwarf_hasattr(&child, DW_AT_declaration))
2819 continue;
5f36109e 2820
a80f28d8 2821 int tag = dwarf_tag (&child);
5f36109e 2822
a80f28d8
JS
2823 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2824 continue;
5f36109e 2825
a80f28d8 2826 dwarf_attr_die (&child, DW_AT_type, &childtype);
5f36109e 2827
a80f28d8
JS
2828 if (tag == DW_TAG_inheritance)
2829 {
2830 inheritees.push_back(childtype);
2831 continue;
2832 }
5f36109e 2833
a80f28d8
JS
2834 int childtag = dwarf_tag (&childtype);
2835 const char *member = dwarf_diename (&child);
3a147004 2836
a80f28d8
JS
2837 // "_vptr.foo" members are C++ virtual function tables,
2838 // which (generally?) aren't interesting for users.
2839 if (member && startswith(member, "_vptr."))
2840 continue;
3a147004 2841
a80f28d8
JS
2842 // skip inheritance-masked duplicates
2843 if (member && !dupes.insert(member).second)
2844 continue;
64cddf39 2845
a80f28d8
JS
2846 if (++count > 1)
2847 pf->raw_components.append(", ");
64cddf39 2848
a80f28d8
JS
2849 // NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
2850 if (pf->args.size() >= 32)
2851 {
2852 pf->raw_components.append("...");
2853 break;
2854 }
2855
2856 if (member)
2857 {
2858 pf->raw_components.append(".");
2859 pf->raw_components.append(member);
5f36109e 2860
a80f28d8
JS
2861 e2 = new target_symbol(*e);
2862 e2->components.push_back (target_symbol::component(e->tok, member));
2863 }
2864 else if (childtag == DW_TAG_union_type)
2865 pf->raw_components.append("<union>");
2866 else if (childtag == DW_TAG_structure_type)
2867 pf->raw_components.append("<class>");
2868 else if (childtag == DW_TAG_class_type)
2869 pf->raw_components.append("<struct>");
2870 pf->raw_components.append("=");
600551ca
JS
2871
2872 if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset))
2873 recurse_bitfield (&childtype, e2, pf);
2874 else
2875 recurse (&childtype, e2, pf);
5f36109e 2876 }
a80f28d8
JS
2877 while (dwarf_siblingof (&child, &child) == 0);
2878 }
5f36109e
JS
2879}
2880
2881
bbee5bb8
JS
2882bool
2883dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
2884 print_format* pf)
2885{
2886 Dwarf_Die type;
2887 dw.resolve_unqualified_inner_typedie (start_type, &type, e);
2888 const char *name = dwarf_diename (&type);
2889 if (name && (name == string("char") || name == string("unsigned char")))
2890 {
c55ea10d
JS
2891 if (push_deref (pf, "\"%s\"", e))
2892 {
2893 // steal the last arg for a string access
2894 assert (!pf->args.empty());
2895 functioncall* fcall = new functioncall;
2896 fcall->tok = e->tok;
2897 fcall->function = userspace_p ? "user_string2" : "kernel_string2";
2898 fcall->args.push_back (pf->args.back());
2899 expression *err_msg = new literal_string ("<unknown>");
2900 err_msg->tok = e->tok;
2901 fcall->args.push_back (err_msg);
2902 pf->args.back() = fcall;
2903 }
bbee5bb8
JS
2904 return true;
2905 }
2906 return false;
2907}
2908
a5ce5211
MW
2909// PR10601: adapt to kernel-vs-userspace loc2c-runtime
2910static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
f1e8e7e0
MW
2911 + "#define fetch_register k_fetch_register\n"
2912 + "#define store_register k_store_register\n"
2913 + "#define deref kderef\n"
2914 + "#define store_deref store_kderef\n";
a5ce5211
MW
2915
2916static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
f1e8e7e0
MW
2917 + "#define fetch_register u_fetch_register\n"
2918 + "#define store_register u_store_register\n"
2919 + "#define deref uderef\n"
2920 + "#define store_deref store_uderef\n";
a5ce5211
MW
2921
2922#define EMBEDDED_FETCH_DEREF(U) \
f1e8e7e0 2923 (U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
a5ce5211
MW
2924
2925static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
f1e8e7e0
MW
2926 + "#undef fetch_register\n"
2927 + "#undef store_register\n"
2928 + "#undef deref\n"
2929 + "#undef store_deref\n";
bbee5bb8 2930
5f36109e
JS
2931expression*
2932dwarf_pretty_print::deref (target_symbol* e)
2933{
2934 static unsigned tick = 0;
2935
d19a9a82
JS
2936 if (!deref_p)
2937 {
2938 assert (pointer && e->components.empty());
2939 return pointer;
2940 }
2941
5f36109e
JS
2942 // Synthesize a function to dereference the dwarf fields,
2943 // with a pointer parameter that is the base tracepoint variable
2944 functiondecl *fdecl = new functiondecl;
2945 fdecl->synthetic = true;
2946 fdecl->tok = e->tok;
2947 embeddedcode *ec = new embeddedcode;
2948 ec->tok = e->tok;
2949
2950 fdecl->name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
2951 fdecl->body = ec;
2952
2953 // Synthesize a functioncall.
2954 functioncall* fcall = new functioncall;
2955 fcall->tok = e->tok;
2956 fcall->function = fdecl->name;
5f36109e 2957
a5ce5211 2958 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
5f36109e
JS
2959
2960 if (pointer)
2961 {
2962 ec->code += dw.literal_stmt_for_pointer (&pointer_type, e,
2963 false, fdecl->type);
2964
2965 vardecl *v = new vardecl;
2966 v->type = pe_long;
2967 v->name = "pointer";
2968 v->tok = e->tok;
2969 fdecl->formal_args.push_back(v);
2970 fcall->args.push_back(pointer);
2971 }
2972 else if (!local.empty())
2973 ec->code += dw.literal_stmt_for_local (scopes, pc, local, e,
2974 false, fdecl->type);
2975 else
2976 ec->code += dw.literal_stmt_for_return (&scopes[0], pc, e,
2977 false, fdecl->type);
2978
2979 // Any non-literal indexes need to be passed in too.
2980 for (unsigned i = 0; i < e->components.size(); ++i)
2981 if (e->components[i].type == target_symbol::comp_expression_array_index)
2982 {
2983 vardecl *v = new vardecl;
2984 v->type = pe_long;
2985 v->name = "index" + lex_cast(i);
2986 v->tok = e->tok;
2987 fdecl->formal_args.push_back(v);
2988 fcall->args.push_back(e->components[i].expr_index);
2989 }
2990
2991 ec->code += "/* pure */";
2992 ec->code += "/* unprivileged */";
2993
a5ce5211 2994 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e 2995
f8809d54 2996 fdecl->join (dw.sess);
5f36109e
JS
2997 return fcall;
2998}
2999
3000
c55ea10d
JS
3001bool
3002dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
3003 target_symbol* e)
3004{
3005 expression* e2 = NULL;
3006 try
3007 {
3008 e2 = deref (e);
3009 }
3010 catch (const semantic_error&)
3011 {
3012 pf->raw_components.append ("?");
3013 return false;
3014 }
3015 pf->raw_components.append (fmt);
3016 pf->args.push_back (e2);
3017 return true;
3018}
3019
3020
e57b735a 3021void
a7999c82 3022dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
e57b735a 3023{
a7999c82
JS
3024 // Get the full name of the target symbol.
3025 stringstream ts_name_stream;
3026 e->print(ts_name_stream);
3027 string ts_name = ts_name_stream.str();
3028
3029 // Check and make sure we haven't already seen this target
3030 // variable in this return probe. If we have, just return our
3031 // last replacement.
af234c40 3032 map<string, expression *>::iterator i = return_ts_map.find(ts_name);
a7999c82 3033 if (i != return_ts_map.end())
85ecf79a 3034 {
a7999c82
JS
3035 provide (i->second);
3036 return;
3037 }
85ecf79a 3038
70208613
JS
3039 // Attempt the expansion directly first, so if there's a problem with the
3040 // variable we won't have a bogus entry probe lying around. Like in
3041 // saveargs(), we pretend for a moment that we're not in a .return.
3042 bool saved_has_return = q.has_return;
3043 q.has_return = false;
3044 expression *repl = e;
3045 replace (repl);
3046 q.has_return = saved_has_return;
3047 target_symbol* n = dynamic_cast<target_symbol*>(repl);
3048 if (n && n->saved_conversion_error)
3049 {
3050 provide (repl);
3051 return;
3052 }
3053
af234c40
JS
3054 expression *exp;
3055 if (!q.has_process &&
3056 strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
140be17a 3057 exp = gen_kretprobe_saved_return(repl);
af234c40 3058 else
cc9001af 3059 exp = gen_mapped_saved_return(repl, e->sym_name());
af234c40
JS
3060
3061 // Provide the variable to our parent so it can be used as a
3062 // substitute for the target symbol.
3063 provide (exp);
3064
3065 // Remember this replacement since we might be able to reuse
3066 // it later if the same return probe references this target
3067 // symbol again.
3068 return_ts_map[ts_name] = exp;
3069}
3070
3071expression*
70208613 3072dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
277c21bc 3073 const string& name)
af234c40 3074{
a7999c82
JS
3075 // We've got to do several things here to handle target
3076 // variables in return probes.
85ecf79a 3077
a7999c82
JS
3078 // (1) Synthesize two global arrays. One is the cache of the
3079 // target variable and the other contains a thread specific
3080 // nesting level counter. The arrays will look like
3081 // this:
3082 //
3083 // _dwarf_tvar_{name}_{num}
3084 // _dwarf_tvar_{name}_{num}_ctr
3085
3086 string aname = (string("_dwarf_tvar_")
cc9001af 3087 + name
aca66a36 3088 + "_" + lex_cast(tick++));
a7999c82
JS
3089 vardecl* vd = new vardecl;
3090 vd->name = aname;
3091 vd->tok = e->tok;
3092 q.sess.globals.push_back (vd);
3093
3094 string ctrname = aname + "_ctr";
3095 vd = new vardecl;
3096 vd->name = ctrname;
3097 vd->tok = e->tok;
3098 q.sess.globals.push_back (vd);
3099
3100 // (2) Create a new code block we're going to insert at the
3101 // beginning of this probe to get the cached value into a
3102 // temporary variable. We'll replace the target variable
3103 // reference with the temporary variable reference. The code
3104 // will look like this:
3105 //
3106 // _dwarf_tvar_tid = tid()
3107 // _dwarf_tvar_{name}_{num}_tmp
3108 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3109 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3110 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3111 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
3112 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
3113 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
3114
3115 // (2a) Synthesize the tid temporary expression, which will look
3116 // like this:
3117 //
3118 // _dwarf_tvar_tid = tid()
3119 symbol* tidsym = new symbol;
3120 tidsym->name = string("_dwarf_tvar_tid");
3121 tidsym->tok = e->tok;
85ecf79a 3122
a7999c82
JS
3123 if (add_block == NULL)
3124 {
3125 add_block = new block;
3126 add_block->tok = e->tok;
8cc799a5 3127 }
8c819921 3128
8cc799a5
JS
3129 if (!add_block_tid)
3130 {
a7999c82
JS
3131 // Synthesize a functioncall to grab the thread id.
3132 functioncall* fc = new functioncall;
3133 fc->tok = e->tok;
3134 fc->function = string("tid");
8c819921 3135
a7999c82 3136 // Assign the tid to '_dwarf_tvar_tid'.
8c819921
DS
3137 assignment* a = new assignment;
3138 a->tok = e->tok;
3139 a->op = "=";
a7999c82
JS
3140 a->left = tidsym;
3141 a->right = fc;
8c819921
DS
3142
3143 expr_statement* es = new expr_statement;
3144 es->tok = e->tok;
3145 es->value = a;
8c819921 3146 add_block->statements.push_back (es);
8cc799a5 3147 add_block_tid = true;
a7999c82 3148 }
8c819921 3149
a7999c82
JS
3150 // (2b) Synthesize an array reference and assign it to a
3151 // temporary variable (that we'll use as replacement for the
3152 // target variable reference). It will look like this:
3153 //
3154 // _dwarf_tvar_{name}_{num}_tmp
3155 // = _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3156 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3157
3158 arrayindex* ai_tvar_base = new arrayindex;
3159 ai_tvar_base->tok = e->tok;
3160
3161 symbol* sym = new symbol;
3162 sym->name = aname;
3163 sym->tok = e->tok;
3164 ai_tvar_base->base = sym;
3165
3166 ai_tvar_base->indexes.push_back(tidsym);
3167
3168 // We need to create a copy of the array index in its current
3169 // state so we can have 2 variants of it (the original and one
3170 // that post-decrements the second index).
3171 arrayindex* ai_tvar = new arrayindex;
3172 arrayindex* ai_tvar_postdec = new arrayindex;
3173 *ai_tvar = *ai_tvar_base;
3174 *ai_tvar_postdec = *ai_tvar_base;
3175
3176 // Synthesize the
3177 // "_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]" used as the
3178 // second index into the array.
3179 arrayindex* ai_ctr = new arrayindex;
3180 ai_ctr->tok = e->tok;
3181
3182 sym = new symbol;
3183 sym->name = ctrname;
3184 sym->tok = e->tok;
3185 ai_ctr->base = sym;
3186 ai_ctr->indexes.push_back(tidsym);
3187 ai_tvar->indexes.push_back(ai_ctr);
3188
3189 symbol* tmpsym = new symbol;
3190 tmpsym->name = aname + "_tmp";
3191 tmpsym->tok = e->tok;
3192
3193 assignment* a = new assignment;
3194 a->tok = e->tok;
3195 a->op = "=";
3196 a->left = tmpsym;
3197 a->right = ai_tvar;
3198
3199 expr_statement* es = new expr_statement;
3200 es->tok = e->tok;
3201 es->value = a;
3202
3203 add_block->statements.push_back (es);
3204
3205 // (2c) Add a post-decrement to the second array index and
3206 // delete the array value. It will look like this:
3207 //
3208 // delete _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3209 // _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]--]
3210
3211 post_crement* pc = new post_crement;
3212 pc->tok = e->tok;
3213 pc->op = "--";
3214 pc->operand = ai_ctr;
3215 ai_tvar_postdec->indexes.push_back(pc);
3216
3217 delete_statement* ds = new delete_statement;
3218 ds->tok = e->tok;
3219 ds->value = ai_tvar_postdec;
3220
3221 add_block->statements.push_back (ds);
3222
3223 // (2d) Delete the counter value if it is 0. It will look like
3224 // this:
3225 // if (! _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid])
3226 // delete _dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]
3227
3228 ds = new delete_statement;
3229 ds->tok = e->tok;
3230 ds->value = ai_ctr;
3231
3232 unary_expression *ue = new unary_expression;
3233 ue->tok = e->tok;
3234 ue->op = "!";
3235 ue->operand = ai_ctr;
3236
3237 if_statement *ifs = new if_statement;
3238 ifs->tok = e->tok;
3239 ifs->condition = ue;
3240 ifs->thenblock = ds;
3241 ifs->elseblock = NULL;
3242
3243 add_block->statements.push_back (ifs);
3244
3245 // (3) We need an entry probe that saves the value for us in the
3246 // global array we created. Create the entry probe, which will
3247 // look like this:
3248 //
2260f4e3 3249 // probe kernel.function("{function}").call {
a7999c82
JS
3250 // _dwarf_tvar_tid = tid()
3251 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3252 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3253 // = ${param}
3254 // }
3255
2260f4e3 3256 if (add_call_probe == NULL)
a7999c82 3257 {
2260f4e3
FCE
3258 add_call_probe = new block;
3259 add_call_probe->tok = e->tok;
8cc799a5 3260 }
4baf0e53 3261
8cc799a5
JS
3262 if (!add_call_probe_tid)
3263 {
a7999c82
JS
3264 // Synthesize a functioncall to grab the thread id.
3265 functioncall* fc = new functioncall;
3266 fc->tok = e->tok;
3267 fc->function = string("tid");
4baf0e53 3268
a7999c82
JS
3269 // Assign the tid to '_dwarf_tvar_tid'.
3270 assignment* a = new assignment;
8fc05e57
DS
3271 a->tok = e->tok;
3272 a->op = "=";
a7999c82
JS
3273 a->left = tidsym;
3274 a->right = fc;
8fc05e57 3275
a7999c82 3276 expr_statement* es = new expr_statement;
8fc05e57
DS
3277 es->tok = e->tok;
3278 es->value = a;
2260f4e3 3279 add_call_probe = new block(add_call_probe, es);
8cc799a5 3280 add_call_probe_tid = true;
85ecf79a 3281 }
cf2a1f85 3282
a7999c82
JS
3283 // Save the value, like this:
3284 // _dwarf_tvar_{name}_{num}[_dwarf_tvar_tid,
3285 // ++_dwarf_tvar_{name}_{num}_ctr[_dwarf_tvar_tid]]
3286 // = ${param}
3287 arrayindex* ai_tvar_preinc = new arrayindex;
3288 *ai_tvar_preinc = *ai_tvar_base;
3289
3290 pre_crement* preinc = new pre_crement;
3291 preinc->tok = e->tok;
3292 preinc->op = "++";
3293 preinc->operand = ai_ctr;
3294 ai_tvar_preinc->indexes.push_back(preinc);
3295
3296 a = new assignment;
3297 a->tok = e->tok;
3298 a->op = "=";
3299 a->left = ai_tvar_preinc;
3300 a->right = e;
3301
3302 es = new expr_statement;
3303 es->tok = e->tok;
3304 es->value = a;
3305
2260f4e3 3306 add_call_probe = new block(add_call_probe, es);
a7999c82
JS
3307
3308 // (4) Provide the '_dwarf_tvar_{name}_{num}_tmp' variable to
3309 // our parent so it can be used as a substitute for the target
3310 // symbol.
3f803f9e 3311 delete ai_tvar_base;
af234c40
JS
3312 return tmpsym;
3313}
a7999c82 3314
af234c40
JS
3315
3316expression*
140be17a 3317dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
af234c40
JS
3318{
3319 // The code for this is simple.
3320 //
3321 // .call:
3322 // _set_kretprobe_long(index, $value)
3323 //
3324 // .return:
3325 // _get_kretprobe_long(index)
3326 //
3327 // (or s/long/string/ for things like $$parms)
3328
3329 unsigned index;
3330 string setfn, getfn;
3331
140be17a
JS
3332 // We need the caller to predetermine the type of the expression!
3333 switch (e->type)
af234c40 3334 {
140be17a 3335 case pe_string:
af234c40
JS
3336 index = saved_strings++;
3337 setfn = "_set_kretprobe_string";
3338 getfn = "_get_kretprobe_string";
140be17a
JS
3339 break;
3340 case pe_long:
af234c40
JS
3341 index = saved_longs++;
3342 setfn = "_set_kretprobe_long";
3343 getfn = "_get_kretprobe_long";
140be17a
JS
3344 break;
3345 default:
b530b5b3 3346 throw semantic_error(_("unknown type to save in kretprobe"), e->tok);
af234c40
JS
3347 }
3348
3349 // Create the entry code
3350 // _set_kretprobe_{long|string}(index, $value)
3351
3352 if (add_call_probe == NULL)
3353 {
3354 add_call_probe = new block;
3355 add_call_probe->tok = e->tok;
3356 }
3357
3358 functioncall* set_fc = new functioncall;
3359 set_fc->tok = e->tok;
3360 set_fc->function = setfn;
3361 set_fc->args.push_back(new literal_number(index));
3362 set_fc->args.back()->tok = e->tok;
3363 set_fc->args.push_back(e);
3364
3365 expr_statement* set_es = new expr_statement;
3366 set_es->tok = e->tok;
3367 set_es->value = set_fc;
3368
3369 add_call_probe->statements.push_back(set_es);
3370
3371 // Create the return code
3372 // _get_kretprobe_{long|string}(index)
3373
3374 functioncall* get_fc = new functioncall;
3375 get_fc->tok = e->tok;
3376 get_fc->function = getfn;
3377 get_fc->args.push_back(new literal_number(index));
3378 get_fc->args.back()->tok = e->tok;
3379
3380 return get_fc;
a7999c82 3381}
a43ba433 3382
2cb3fe26 3383
a7999c82
JS
3384void
3385dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
3386{
9aa8ffce 3387 if (null_die(scope_die))
a7999c82 3388 return;
2cb3fe26 3389
5f36109e
JS
3390 target_symbol *tsym = new target_symbol(*e);
3391
fde50242
JS
3392 bool pretty = (!e->components.empty() &&
3393 e->components[0].type == target_symbol::comp_pretty_print);
3394 string format = pretty ? "=%s" : "=%#x";
a43ba433 3395
a7999c82
JS
3396 // Convert $$parms to sprintf of a list of parms and active local vars
3397 // which we recursively evaluate
a43ba433 3398
a7999c82
JS
3399 // NB: we synthesize a new token here rather than reusing
3400 // e->tok, because print_format::print likes to use
3401 // its tok->content.
5f36109e 3402 token* pf_tok = new token(*e->tok);
a7999c82 3403 pf_tok->type = tok_identifier;
b393f6f2 3404 pf_tok->content = "sprintf";
2cb3fe26 3405
d5e178c1 3406 print_format* pf = print_format::create(pf_tok);
a7999c82 3407
277c21bc 3408 if (q.has_return && (e->name == "$$return"))
a7999c82 3409 {
277c21bc 3410 tsym->name = "$return";
a7999c82
JS
3411
3412 // Ignore any variable that isn't accessible.
3413 tsym->saved_conversion_error = 0;
3414 expression *texp = tsym;
8b095b45 3415 replace (texp); // NB: throws nothing ...
a7999c82 3416 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3417 {
2cb3fe26 3418
a43ba433
FCE
3419 }
3420 else
3421 {
a7999c82 3422 pf->raw_components += "return";
5f36109e 3423 pf->raw_components += format;
a7999c82
JS
3424 pf->args.push_back(texp);
3425 }
3426 }
3427 else
3428 {
3429 // non-.return probe: support $$parms, $$vars, $$locals
345bbb3d 3430 bool first = true;
a7999c82 3431 Dwarf_Die result;
d48bc7eb
JS
3432 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
3433 for (unsigned i = 0; i < scopes.size(); ++i)
3434 {
3435 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
3436 break; // we don't want file-level variables
3437 if (dwarf_child (&scopes[i], &result) == 0)
3438 do
00cf3709 3439 {
d48bc7eb
JS
3440 switch (dwarf_tag (&result))
3441 {
3442 case DW_TAG_variable:
3443 if (e->name == "$$parms")
3444 continue;
3445 break;
3446 case DW_TAG_formal_parameter:
3447 if (e->name == "$$locals")
3448 continue;
3449 break;
3450
3451 default:
3452 continue;
3453 }
41c262f3 3454
d48bc7eb
JS
3455 const char *diename = dwarf_diename (&result);
3456 if (! diename) continue;
f76427a2 3457
d48bc7eb
JS
3458 if (! first)
3459 pf->raw_components += " ";
3460 pf->raw_components += diename;
fde50242
JS
3461 first = false;
3462
3463 // Write a placeholder for ugly aggregates
3464 Dwarf_Die type;
3465 if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
3466 {
3467 q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
3468 switch (dwarf_tag(&type))
3469 {
3470 case DW_TAG_union_type:
3471 case DW_TAG_structure_type:
3472 case DW_TAG_class_type:
3473 pf->raw_components += "={...}";
3474 continue;
3475
3476 case DW_TAG_array_type:
3477 pf->raw_components += "=[...]";
3478 continue;
3479 }
3480 }
345bbb3d 3481
d48bc7eb
JS
3482 tsym->name = "$";
3483 tsym->name += diename;
41c262f3 3484
d48bc7eb
JS
3485 // Ignore any variable that isn't accessible.
3486 tsym->saved_conversion_error = 0;
3487 expression *texp = tsym;
3488 replace (texp); // NB: throws nothing ...
3489 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
a43ba433 3490 {
d48bc7eb
JS
3491 if (q.sess.verbose>2)
3492 {
e26c2f83 3493 for (const semantic_error *c = tsym->saved_conversion_error;
d48bc7eb
JS
3494 c != 0;
3495 c = c->chain) {
b530b5b3 3496 clog << _("variable location problem: ") << c->what() << endl;
d48bc7eb
JS
3497 }
3498 }
3499
3500 pf->raw_components += "=?";
a43ba433 3501 }
d48bc7eb
JS
3502 else
3503 {
3504 pf->raw_components += format;
3505 pf->args.push_back(texp);
3506 }
a7999c82 3507 }
d48bc7eb
JS
3508 while (dwarf_siblingof (&result, &result) == 0);
3509 }
a7999c82 3510 }
2cb3fe26 3511
a7999c82 3512 pf->components = print_format::string_to_components(pf->raw_components);
140be17a 3513 pf->type = pe_string;
a7999c82
JS
3514 provide (pf);
3515}
3516
2cb3fe26 3517
a7999c82
JS
3518void
3519dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
3520{
cc9001af
MW
3521 assert(e->name.size() > 0
3522 && ((e->name[0] == '$' && e->target_name == "")
3523 || (e->name == "@var" && e->target_name != "")));
a7999c82 3524 visited = true;
30263a73
FCE
3525 bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
3526 // In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
a7999c82 3527
70208613 3528 try
a7999c82 3529 {
c69a87e0
FCE
3530 bool lvalue = is_active_lvalue(e);
3531 if (lvalue && !q.sess.guru_mode)
b3741c9d 3532 throw semantic_error(_("write to target variable not permitted; need stap -g"), e->tok);
2cb3fe26 3533
100a540e 3534 // XXX: process $context vars should be writable
70208613 3535
c69a87e0
FCE
3536 // See if we need to generate a new probe to save/access function
3537 // parameters from a return probe. PR 1382.
3538 if (q.has_return
3539 && !defined_being_checked
277c21bc
JS
3540 && e->name != "$return" // not the special return-value variable handled below
3541 && e->name != "$$return") // nor the other special variable handled below
c69a87e0
FCE
3542 {
3543 if (lvalue)
b530b5b3 3544 throw semantic_error(_("write to target variable not permitted in .return probes"), e->tok);
c69a87e0
FCE
3545 visit_target_symbol_saved_return(e);
3546 return;
3547 }
e57b735a 3548
277c21bc
JS
3549 if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
3550 || (q.has_return && (e->name == "$$return")))
c69a87e0
FCE
3551 {
3552 if (lvalue)
b530b5b3 3553 throw semantic_error(_("cannot write to context variable"), e->tok);
70208613 3554
c69a87e0 3555 if (e->addressof)
b530b5b3 3556 throw semantic_error(_("cannot take address of context variable"), e->tok);
70208613 3557
5f36109e
JS
3558 e->assert_no_components("dwarf", true);
3559
c69a87e0
FCE
3560 visit_target_symbol_context(e);
3561 return;
3562 }
70208613 3563
5f36109e
JS
3564 if (!e->components.empty() &&
3565 e->components.back().type == target_symbol::comp_pretty_print)
3566 {
3567 if (lvalue)
b530b5b3 3568 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 3569
277c21bc 3570 if (q.has_return && (e->name == "$return"))
5f36109e
JS
3571 {
3572 dwarf_pretty_print dpp (q.dw, scope_die, addr,
3573 q.has_process, *e);
3574 dpp.expand()->visit(this);
3575 }
3576 else
3577 {
3578 dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
cc9001af 3579 e->sym_name(),
5f36109e
JS
3580 q.has_process, *e);
3581 dpp.expand()->visit(this);
3582 }
3583 return;
3584 }
3585
c69a87e0
FCE
3586 // Synthesize a function.
3587 functiondecl *fdecl = new functiondecl;
59de45f1 3588 fdecl->synthetic = true;
c69a87e0
FCE
3589 fdecl->tok = e->tok;
3590 embeddedcode *ec = new embeddedcode;
3591 ec->tok = e->tok;
70208613 3592
c69a87e0 3593 string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
cc9001af 3594 + "_" + e->sym_name()
c69a87e0 3595 + "_" + lex_cast(tick++));
70208613 3596
a5ce5211 3597 ec->code += EMBEDDED_FETCH_DEREF(q.has_process);
70208613 3598
277c21bc 3599 if (q.has_return && (e->name == "$return"))
e19fda4e 3600 {
b5a0dd41 3601 ec->code += q.dw.literal_stmt_for_return (scope_die,
e19fda4e 3602 addr,
b4c34c26 3603 e,
e19fda4e
DS
3604 lvalue,
3605 fdecl->type);
3606 }
3607 else
3608 {
b5a0dd41 3609 ec->code += q.dw.literal_stmt_for_local (getscopes(e),
e19fda4e 3610 addr,
cc9001af 3611 e->sym_name(),
b4c34c26 3612 e,
e19fda4e
DS
3613 lvalue,
3614 fdecl->type);
3615 }
3616
1b07c728
FCE
3617 if (! lvalue)
3618 ec->code += "/* pure */";
64211010
DB
3619
3620 ec->code += "/* unprivileged */";
a5ce5211 3621 ec->code += EMBEDDED_FETCH_DEREF_DONE;
c69a87e0
FCE
3622
3623 fdecl->name = fname;
3624 fdecl->body = ec;
70208613 3625
c69a87e0
FCE
3626 // Any non-literal indexes need to be passed in too.
3627 for (unsigned i = 0; i < e->components.size(); ++i)
3628 if (e->components[i].type == target_symbol::comp_expression_array_index)
3629 {
3630 vardecl *v = new vardecl;
3631 v->type = pe_long;
3632 v->name = "index" + lex_cast(i);
3633 v->tok = e->tok;
3634 fdecl->formal_args.push_back(v);
3635 }
70208613 3636
c69a87e0
FCE
3637 if (lvalue)
3638 {
3639 // Modify the fdecl so it carries a single pe_long formal
3640 // argument called "value".
70208613 3641
c69a87e0
FCE
3642 // FIXME: For the time being we only support setting target
3643 // variables which have base types; these are 'pe_long' in
3644 // stap's type vocabulary. Strings and pointers might be
3645 // reasonable, some day, but not today.
70208613 3646
c69a87e0
FCE
3647 vardecl *v = new vardecl;
3648 v->type = pe_long;
3649 v->name = "value";
3650 v->tok = e->tok;
3651 fdecl->formal_args.push_back(v);
3652 }
f8809d54 3653 fdecl->join (q.sess);
70208613 3654
c69a87e0
FCE
3655 // Synthesize a functioncall.
3656 functioncall* n = new functioncall;
3657 n->tok = e->tok;
3658 n->function = fname;
140be17a 3659 n->type = fdecl->type;
70208613 3660
c69a87e0
FCE
3661 // Any non-literal indexes need to be passed in too.
3662 for (unsigned i = 0; i < e->components.size(); ++i)
3663 if (e->components[i].type == target_symbol::comp_expression_array_index)
3664 n->args.push_back(require(e->components[i].expr_index));
70208613 3665
c69a87e0
FCE
3666 if (lvalue)
3667 {
3668 // Provide the functioncall to our parent, so that it can be
3669 // used to substitute for the assignment node immediately above
3670 // us.
3671 assert(!target_symbol_setter_functioncalls.empty());
3672 *(target_symbol_setter_functioncalls.top()) = n;
3673 }
70208613 3674
c69a87e0 3675 provide (n);
66d284f4
FCE
3676 }
3677 catch (const semantic_error& er)
3678 {
9fab2262
JS
3679 // We suppress this error message, and pass the unresolved
3680 // target_symbol to the next pass. We hope that this value ends
3681 // up not being referenced after all, so it can be optimized out
3682 // quietly.
1af1e62d 3683 e->chain (er);
9fab2262 3684 provide (e);
66d284f4 3685 }
77de5e9e
GH
3686}
3687
3688
c24447be
JS
3689void
3690dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
3691{
3692 // Fill in our current module context if needed
3693 if (e->module.empty())
3694 e->module = q.dw.module_name;
3695
3696 var_expanding_visitor::visit_cast_op(e);
3697}
3698
3699
8cc799a5
JS
3700void
3701dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
3702{
3703 expression *repl = e;
3704 if (q.has_return)
3705 {
3706 // expand the operand as if it weren't a return probe
3707 q.has_return = false;
3708 replace (e->operand);
3709 q.has_return = true;
3710
3711 // XXX it would be nice to use gen_kretprobe_saved_return when available,
3712 // but it requires knowing the types already, which is problematic for
3713 // arbitrary expressons.
cc9001af 3714 repl = gen_mapped_saved_return (e->operand, "entry");
8cc799a5
JS
3715 }
3716 provide (repl);
3717}
3718
bfa7e523
MW
3719vector<Dwarf_Die>&
3720dwarf_var_expanding_visitor::getcuscope(target_symbol *e)
3721{
54e9f062
MW
3722 Dwarf_Off cu_off = 0;
3723 const char *cu_name = NULL;
bfa7e523
MW
3724
3725 string prefixed_srcfile = string("*/") + e->cu_name;
3726
3727 Dwarf_Off off = 0;
3728 size_t cuhl;
3729 Dwarf_Off noff;
3730 Dwarf_Off module_bias;
3731 Dwarf *dw = dwfl_module_getdwarf(q.dw.module, &module_bias);
54e9f062 3732 while (dwarf_nextcu (dw, off, &noff, &cuhl, NULL, NULL, NULL) == 0)
bfa7e523
MW
3733 {
3734 Dwarf_Die die_mem;
3735 Dwarf_Die *die;
3736 die = dwarf_offdie (dw, off + cuhl, &die_mem);
54e9f062
MW
3737 const char *die_name = dwarf_diename (die);
3738
3739 if (strcmp (die_name, e->cu_name.c_str()) == 0) // Perfect match.
3740 {
3741 cu_name = die_name;
3742 cu_off = off + cuhl;
3743 break;
3744 }
3745
3746 if (fnmatch(prefixed_srcfile.c_str(), die_name, 0) == 0)
3747 if (cu_name == NULL || strlen (die_name) < strlen (cu_name))
3748 {
3749 cu_name = die_name;
3750 cu_off = off + cuhl;
3751 }
bfa7e523
MW
3752 off = noff;
3753 }
3754
54e9f062 3755 if (cu_name == NULL)
bfa7e523
MW
3756 throw semantic_error ("unable to find CU '" + e->cu_name + "'"
3757 + " while searching for '" + e->target_name + "'",
3758 e->tok);
3759
3760 vector<Dwarf_Die> *cu_scope = new vector<Dwarf_Die>;
54e9f062
MW
3761 Dwarf_Die cu_die;
3762 dwarf_offdie (dw, cu_off, &cu_die);
3763 cu_scope->push_back(cu_die);
bfa7e523
MW
3764 return *cu_scope;
3765}
8cc799a5 3766
729455a7
JS
3767vector<Dwarf_Die>&
3768dwarf_var_expanding_visitor::getscopes(target_symbol *e)
3769{
bfa7e523
MW
3770 // "static globals" can only be found in the top-level CU.
3771 if (e->name == "@var" && e->cu_name != "")
3772 return this->getcuscope(e);
3773
729455a7
JS
3774 if (scopes.empty())
3775 {
f25a9197
CM
3776 if(scope_die != NULL)
3777 scopes = q.dw.getscopes(scope_die);
729455a7 3778 if (scopes.empty())
b530b5b3
LB
3779 //throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
3780 // ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
729455a7
JS
3781 throw semantic_error ("unable to find any scopes containing "
3782 + lex_cast_hex(addr)
3783 + ((scope_die == NULL) ? ""
3784 : (string (" in ")
3785 + (dwarf_diename(scope_die) ?: "<unknown>")
3786 + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
3787 + ")"))
3788 + " while searching for local '"
cc9001af 3789 + e->sym_name() + "'",
729455a7
JS
3790 e->tok);
3791 }
3792 return scopes;
3793}
3794
3795
5f36109e
JS
3796struct dwarf_cast_expanding_visitor: public var_expanding_visitor
3797{
3798 systemtap_session& s;
3799 dwarf_builder& db;
3800
3801 dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
3802 s(s), db(db) {}
3803 void visit_cast_op (cast_op* e);
3804 void filter_special_modules(string& module);
3805};
3806
3807
c4ce66a1
JS
3808struct dwarf_cast_query : public base_query
3809{
946e1a48 3810 cast_op& e;
c4ce66a1 3811 const bool lvalue;
5f36109e
JS
3812 const bool userspace_p;
3813 functioncall*& result;
c4ce66a1 3814
5f36109e
JS
3815 dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
3816 const bool userspace_p, functioncall*& result):
abb41d92 3817 base_query(dw, module), e(e), lvalue(lvalue),
5f36109e 3818 userspace_p(userspace_p), result(result) {}
c4ce66a1
JS
3819
3820 void handle_query_module();
822a6a3d 3821 void query_library (const char *) {}
576eaefe 3822 void query_plt (const char *entry, size_t addr) {}
c4ce66a1
JS
3823};
3824
3825
c4ce66a1
JS
3826void
3827dwarf_cast_query::handle_query_module()
3828{
5f36109e
JS
3829 static unsigned tick = 0;
3830
3831 if (result)
c4ce66a1
JS
3832 return;
3833
ea1e477a 3834 // look for the type in any CU
a44a7cb5
JS
3835 Dwarf_Die* type_die = NULL;
3836 if (startswith(e.type_name, "class "))
3837 {
3838 // normalize to match dwflpp::global_alias_caching_callback
3839 string struct_name = "struct " + e.type_name.substr(6);
3840 type_die = dw.declaration_resolve_other_cus(struct_name);
3841 }
3842 else
3843 type_die = dw.declaration_resolve_other_cus(e.type_name);
3844
3845 // NB: We now index the types as "struct name"/"union name"/etc. instead of
3846 // just "name". But since we didn't require users to be explicit before, and
3847 // actually sort of discouraged it, we must be flexible now. So if a lookup
3848 // fails with a bare name, try augmenting it.
3849 if (!type_die &&
3850 !startswith(e.type_name, "class ") &&
3851 !startswith(e.type_name, "struct ") &&
3852 !startswith(e.type_name, "union ") &&
3853 !startswith(e.type_name, "enum "))
3854 {
3855 type_die = dw.declaration_resolve_other_cus("struct " + e.type_name);
3856 if (!type_die)
3857 type_die = dw.declaration_resolve_other_cus("union " + e.type_name);
3858 if (!type_die)
3859 type_die = dw.declaration_resolve_other_cus("enum " + e.type_name);
3860 }
3861
ea1e477a
JS
3862 if (!type_die)
3863 return;
c4ce66a1 3864
5f36109e
JS
3865 string code;
3866 exp_type type = pe_long;
3867
ea1e477a 3868 try
c4ce66a1 3869 {
ea1e477a
JS
3870 Dwarf_Die cu_mem;
3871 dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
5f36109e
JS
3872
3873 if (!e.components.empty() &&
3874 e.components.back().type == target_symbol::comp_pretty_print)
3875 {
3876 if (lvalue)
b530b5b3 3877 throw semantic_error(_("cannot write to pretty-printed variable"), e.tok);
5f36109e 3878
d19a9a82 3879 dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p, e);
5f36109e
JS
3880 result = dpp.expand();
3881 return;
3882 }
3883
3884 code = dw.literal_stmt_for_pointer (type_die, &e, lvalue, type);
ea1e477a
JS
3885 }
3886 catch (const semantic_error& er)
3887 {
3888 // NB: we can have multiple errors, since a @cast
1af1e62d
JS
3889 // may be attempted using several different modules:
3890 // @cast(ptr, "type", "module1:module2:...")
3891 e.chain (er);
c4ce66a1 3892 }
c4ce66a1 3893
5f36109e
JS
3894 if (code.empty())
3895 return;
c4ce66a1 3896
5f36109e 3897 string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
cc9001af 3898 + "_" + e.sym_name()
5f36109e 3899 + "_" + lex_cast(tick++));
c4ce66a1 3900
5f36109e
JS
3901 // Synthesize a function.
3902 functiondecl *fdecl = new functiondecl;
3903 fdecl->synthetic = true;
3904 fdecl->tok = e.tok;
3905 fdecl->type = type;
3906 fdecl->name = fname;
3907
3908 embeddedcode *ec = new embeddedcode;
3909 ec->tok = e.tok;
3910 fdecl->body = ec;
3911
a5ce5211 3912 ec->code += EMBEDDED_FETCH_DEREF(userspace_p);
5f36109e
JS
3913 ec->code += code;
3914
3915 // Give the fdecl an argument for the pointer we're trying to cast
3916 vardecl *v1 = new vardecl;
3917 v1->type = pe_long;
3918 v1->name = "pointer";
3919 v1->tok = e.tok;
3920 fdecl->formal_args.push_back(v1);
3921
3922 // Any non-literal indexes need to be passed in too.
3923 for (unsigned i = 0; i < e.components.size(); ++i)
3924 if (e.components[i].type == target_symbol::comp_expression_array_index)
3925 {
3926 vardecl *v = new vardecl;
3927 v->type = pe_long;
3928 v->name = "index" + lex_cast(i);
3929 v->tok = e.tok;
3930 fdecl->formal_args.push_back(v);
3931 }
3932
3933 if (lvalue)
3934 {
3935 // Modify the fdecl so it carries a second pe_long formal
3936 // argument called "value".
3937
3938 // FIXME: For the time being we only support setting target
3939 // variables which have base types; these are 'pe_long' in
3940 // stap's type vocabulary. Strings and pointers might be
3941 // reasonable, some day, but not today.
3942
3943 vardecl *v2 = new vardecl;
3944 v2->type = pe_long;
3945 v2->name = "value";
3946 v2->tok = e.tok;
3947 fdecl->formal_args.push_back(v2);
3948 }
3949 else
3950 ec->code += "/* pure */";
3951
3952 ec->code += "/* unprivileged */";
a5ce5211 3953 ec->code += EMBEDDED_FETCH_DEREF_DONE;
5f36109e 3954
f8809d54 3955 fdecl->join (dw.sess);
5f36109e
JS
3956
3957 // Synthesize a functioncall.
3958 functioncall* n = new functioncall;
3959 n->tok = e.tok;
3960 n->function = fname;
5f36109e
JS
3961 n->args.push_back(e.operand);
3962
3963 // Any non-literal indexes need to be passed in too.
3964 for (unsigned i = 0; i < e.components.size(); ++i)
3965 if (e.components[i].type == target_symbol::comp_expression_array_index)
3966 n->args.push_back(e.components[i].expr_index);
3967
3968 result = n;
3969}
c4ce66a1
JS
3970
3971
fb0274bc
JS
3972void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
3973{
d90053e7 3974 // look for "<path/to/header>" or "kernel<path/to/header>"
fb0274bc 3975 // for those cases, build a module including that header
d90053e7 3976 if (module[module.size() - 1] == '>' &&
60d98537 3977 (module[0] == '<' || startswith(module, "kernel<")))
fb0274bc
JS
3978 {
3979 string cached_module;
3980 if (s.use_cache)
3981 {
3982 // see if the cached module exists
a2639cb7 3983 cached_module = find_typequery_hash(s, module);
d105f664 3984 if (!cached_module.empty() && !s.poison_cache)
fb0274bc
JS
3985 {
3986 int fd = open(cached_module.c_str(), O_RDONLY);
3987 if (fd != -1)
3988 {
3989 if (s.verbose > 2)
b530b5b3
LB
3990 //TRANSLATORS: Here we're using a cached module.
3991 clog << _("Pass 2: using cached ") << cached_module << endl;
fb0274bc
JS
3992 module = cached_module;
3993 close(fd);
3994 return;
3995 }
3996 }
3997 }
3998
3999 // no cached module, time to make it
d90053e7 4000 if (make_typequery(s, module) == 0)
fb0274bc 4001 {
e16dc041 4002 // try to save typequery in the cache
fb0274bc 4003 if (s.use_cache)
e16dc041 4004 copy_file(module, cached_module, s.verbose > 2);
fb0274bc
JS
4005 }
4006 }
4007}
4008
4009
c4ce66a1
JS
4010void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
4011{
4012 bool lvalue = is_active_lvalue(e);
4013 if (lvalue && !s.guru_mode)
b3741c9d 4014 throw semantic_error(_("write to @cast context variable not permitted; need stap -g"), e->tok);
c4ce66a1
JS
4015
4016 if (e->module.empty())
4017 e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
4018
5f36109e 4019 functioncall* result = NULL;
8b31197b
JS
4020
4021 // split the module string by ':' for alternatives
4022 vector<string> modules;
4023 tokenize(e->module, modules, ":");
b5a0dd41 4024 bool userspace_p=false; // PR10601
5f36109e 4025 for (unsigned i = 0; !result && i < modules.size(); ++i)
c4ce66a1 4026 {
8b31197b 4027 string& module = modules[i];
fb0274bc 4028 filter_special_modules(module);
abb41d92 4029
c4ce66a1
JS
4030 // NB: This uses '/' to distinguish between kernel modules and userspace,
4031 // which means that userspace modules won't get any PATH searching.
4032 dwflpp* dw;
707bf35e
JS
4033 try
4034 {
b5a0dd41
FCE
4035 userspace_p=is_user_module (module);
4036 if (! userspace_p)
707bf35e
JS
4037 {
4038 // kernel or kernel module target
ae2552da 4039 dw = db.get_kern_dw(s, module);
707bf35e
JS
4040 }
4041 else
4042 {
05fb3e0c 4043 module = find_executable (module, "", s.sysenv); // canonicalize it
707bf35e
JS
4044 dw = db.get_user_dw(s, module);
4045 }
4046 }
4047 catch (const semantic_error& er)
4048 {
4049 /* ignore and go to the next module */
4050 continue;
4051 }
c4ce66a1 4052
5f36109e 4053 dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
51178501 4054 dw->iterate_over_modules(&query_module, &q);
c4ce66a1 4055 }
abb41d92 4056
5f36109e 4057 if (!result)
c4ce66a1 4058 {
946e1a48
JS
4059 // We pass the unresolved cast_op to the next pass, and hope
4060 // that this value ends up not being referenced after all, so
4061 // it can be optimized out quietly.
c4ce66a1
JS
4062 provide (e);
4063 return;
4064 }
4065
c4ce66a1
JS
4066 if (lvalue)
4067 {
4068 // Provide the functioncall to our parent, so that it can be
4069 // used to substitute for the assignment node immediately above
4070 // us.
4071 assert(!target_symbol_setter_functioncalls.empty());
5f36109e 4072 *(target_symbol_setter_functioncalls.top()) = result;
c4ce66a1
JS
4073 }
4074
5f36109e 4075 result->visit (this);
77de5e9e
GH
4076}
4077
4078
b8da0ad1
FCE
4079void
4080dwarf_derived_probe::printsig (ostream& o) const
4081{
4082 // Instead of just printing the plain locations, we add a PC value
4083 // as a comment as a way of telling e.g. apart multiple inlined
4084 // function instances. This is distinct from the verbose/clog
4085 // output, since this part goes into the cache hash calculations.
4086 sole_location()->print (o);
6d0f3f0c 4087 o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
b8da0ad1
FCE
4088 printsig_nested (o);
4089}
4090
4091
4092
dc38c0ae 4093void
b20febf3
FCE
4094dwarf_derived_probe::join_group (systemtap_session& s)
4095{
af234c40
JS
4096 // skip probes which are paired entry-handlers
4097 if (!has_return && (saved_longs || saved_strings))
4098 return;
4099
b20febf3
FCE
4100 if (! s.dwarf_derived_probes)
4101 s.dwarf_derived_probes = new dwarf_derived_probe_group ();
4102 s.dwarf_derived_probes->enroll (this);
4103}
4104
4105
2b69faaf
JS
4106static bool
4107kernel_supports_inode_uprobes(systemtap_session& s)
4108{
4109 // The arch-supports is new to the builtin inode-uprobes, so it makes a
4110 // reasonable indicator of the new API. Else we'll need an autoconf...
64e807c2 4111 // see also buildrun.cxx:kernel_built_uprobs()
2b69faaf
JS
4112 return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
4113 && s.kernel_config["CONFIG_UPROBES"] == "y");
4114}
4115
4116
5261f7ab
DS
4117void
4118check_process_probe_kernel_support(systemtap_session& s)
4119{
4120 // If we've got utrace, we're good to go.
4121 if (s.kernel_config["CONFIG_UTRACE"] == "y")
4122 return;
4123
8c021542
DS
4124 // We don't have utrace. For process probes that aren't
4125 // uprobes-based, we just need the task_finder. The task_finder
b266d318
DS
4126 // needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
4127 // specific autoconf test for its needs.
8c021542
DS
4128 //
4129 // We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
4130 // approximation.
4131 if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
4132 return;
4133
d3e959b0
DS
4134 // For uprobes-based process probes, we need the task_finder plus
4135 // the builtin inode-uprobes.
8c021542
DS
4136 if (s.need_uprobes
4137 && s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
d3e959b0 4138 && kernel_supports_inode_uprobes(s))
8c021542
DS
4139 return;
4140
4141 throw semantic_error (_("process probes not available without kernel CONFIG_UTRACE or CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
5261f7ab
DS
4142}
4143
4144
b20febf3
FCE
4145dwarf_derived_probe::dwarf_derived_probe(const string& funcname,
4146 const string& filename,
4147 int line,
91af0778 4148 // module & section specify a relocation
b20febf3
FCE
4149 // base for <addr>, unless section==""
4150 // (equivalently module=="kernel")
4151 const string& module,
4152 const string& section,
4153 // NB: dwfl_addr is the virtualized
4154 // address for this symbol.
4155 Dwarf_Addr dwfl_addr,
4156 // addr is the section-offset for
4157 // actual relocation.
4158 Dwarf_Addr addr,
4159 dwarf_query& q,
37ebca01 4160 Dwarf_Die* scope_die /* may be null */)
4c5d1300 4161 : derived_probe (q.base_probe, q.base_loc, true /* .components soon rewritten */ ),
b20febf3 4162 module (module), section (section), addr (addr),
63b4fd14 4163 path (q.path),
27dc09b1 4164 has_process (q.has_process),
c9bad430
DS
4165 has_return (q.has_return),
4166 has_maxactive (q.has_maxactive),
c57ea854 4167 has_library (q.has_library),
6b66b9f7 4168 maxactive_val (q.maxactive_val),
b642c901
SC
4169 user_path (q.user_path),
4170 user_lib (q.user_lib),
af234c40 4171 access_vars(false),
c57ea854 4172 saved_longs(0), saved_strings(0),
af234c40 4173 entry_handler(0)
bd2b1e68 4174{
b642c901
SC
4175 if (user_lib.size() != 0)
4176 has_library = true;
4177
6b66b9f7
JS
4178 if (q.has_process)
4179 {
4180 // We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
4181 // ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
4182 // ET_DYN ones do (addr += run-time mmap base address). We tell these apart
4183 // by the incoming section value (".absolute" vs. ".dynamic").
4184 // XXX Assert invariants here too?
2b69faaf
JS
4185
4186 // inode-uprobes needs an offset rather than an absolute VM address.
4187 if (kernel_supports_inode_uprobes(q.dw.sess) &&
4188 section == ".absolute" && addr == dwfl_addr &&
4189 addr >= q.dw.module_start && addr < q.dw.module_end)
4190 this->addr = addr - q.dw.module_start;
6b66b9f7
JS
4191 }
4192 else
4193 {
4194 // Assert kernel relocation invariants
4195 if (section == "" && dwfl_addr != addr) // addr should be absolute
ce0f6648 4196 throw semantic_error (_("missing relocation basis"), tok);
6b66b9f7 4197 if (section != "" && dwfl_addr == addr) // addr should be an offset
b530b5b3 4198 throw semantic_error (_("inconsistent relocation address"), tok);
6b66b9f7 4199 }
2930abc7 4200
21beacc9
FCE
4201 // XXX: hack for strange g++/gcc's
4202#ifndef USHRT_MAX
4203#define USHRT_MAX 32767
4204#endif
4205
606fd9c8 4206 // Range limit maxactive() value
6b66b9f7 4207 if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
b530b5b3
LB
4208 throw semantic_error (_F("maxactive value out of range [0,%s]",
4209 lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
606fd9c8 4210
de688825 4211 // Expand target variables in the probe body
5f0a03a6 4212 if (!null_die(scope_die))
8fc05e57 4213 {
6b66b9f7 4214 // XXX: user-space deref's for q.has_process!
de688825 4215 dwarf_var_expanding_visitor v (q, scope_die, dwfl_addr);
8b095b45 4216 v.replace (this->body);
6b66b9f7
JS
4217 if (!q.has_process)
4218 access_vars = v.visited;
37ebca01
FCE
4219
4220 // If during target-variable-expanding the probe, we added a new block
4221 // of code, add it to the start of the probe.
4222 if (v.add_block)
ba6f838d 4223 this->body = new block(v.add_block, this->body);
2260f4e3
FCE
4224
4225 // If when target-variable-expanding the probe, we need to synthesize a
4226 // sibling function-entry probe. We don't go through the whole probe derivation
4227 // business (PR10642) that could lead to wildcard/alias resolution, or for that
4228 // dwarf-induced duplication.
4229 if (v.add_call_probe)
37ebca01 4230 {
2260f4e3
FCE
4231 assert (q.has_return && !q.has_call);
4232
4233 // We temporarily replace q.base_probe.
4234 statement* old_body = q.base_probe->body;
4235 q.base_probe->body = v.add_call_probe;
4236 q.has_return = false;
4237 q.has_call = true;
af234c40 4238
da23eceb 4239 if (q.has_process)
af234c40
JS
4240 entry_handler = new uprobe_derived_probe (funcname, filename, line,
4241 module, section, dwfl_addr,
4242 addr, q, scope_die);
da23eceb 4243 else
af234c40
JS
4244 entry_handler = new dwarf_derived_probe (funcname, filename, line,
4245 module, section, dwfl_addr,
4246 addr, q, scope_die);
4247
4248 saved_longs = entry_handler->saved_longs = v.saved_longs;
4249 saved_strings = entry_handler->saved_strings = v.saved_strings;
4250
4251 q.results.push_back (entry_handler);
2260f4e3
FCE
4252
4253 q.has_return = true;
4254 q.has_call = false;
4255 q.base_probe->body = old_body;
37ebca01 4256 }
f10534c6
WH
4257 // Save the local variables for listing mode
4258 if (q.sess.listing_mode_vars)
8c67c337 4259 saveargs(q, scope_die, dwfl_addr);
8fc05e57 4260 }
37ebca01 4261 // else - null scope_die - $target variables will produce an error during translate phase
8fc05e57 4262
f10534c6 4263 // PR10820: null scope die, local variables aren't accessible, not necessary to invoke saveargs
0a98fd42 4264
5d23847d 4265 // Reset the sole element of the "locations" vector as a
b20febf3
FCE
4266 // "reverse-engineered" form of the incoming (q.base_loc) probe
4267 // point. This allows a user to see what function / file / line
4268 // number any particular match of the wildcards.
2930abc7 4269
a229fcd7 4270 vector<probe_point::component*> comps;
91af0778
FCE
4271 if (q.has_kernel)
4272 comps.push_back (new probe_point::component(TOK_KERNEL));
4273 else if(q.has_module)
4274 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
4275 else if(q.has_process)
4276 comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
4277 else
4278 assert (0);
b5d77020 4279
db520b00
FCE
4280 string fn_or_stmt;
4281 if (q.has_function_str || q.has_function_num)
4282 fn_or_stmt = "function";
4283 else
4284 fn_or_stmt = "statement";
a229fcd7 4285
b8da0ad1 4286 if (q.has_function_str || q.has_statement_str)
db520b00 4287 {
4cd232e4 4288 string retro_name = funcname;
b20febf3 4289 if (filename != "")
cee35f73 4290 {
fb84c077 4291 retro_name += ("@" + string (filename));
cee35f73 4292 if (line > 0)
aca66a36 4293 retro_name += (":" + lex_cast (line));
cee35f73 4294 }
db520b00
FCE
4295 comps.push_back
4296 (new probe_point::component
4297 (fn_or_stmt, new literal_string (retro_name)));
4298 }
b8da0ad1 4299 else if (q.has_function_num || q.has_statement_num)
db520b00
FCE
4300 {
4301 Dwarf_Addr retro_addr;
4302 if (q.has_function_num)
4303 retro_addr = q.function_num_val;
4304 else
4305 retro_addr = q.statement_num_val;
db520b00
FCE
4306 comps.push_back (new probe_point::component
4307 (fn_or_stmt,
9ea68eb9 4308 new literal_number(retro_addr, true)));
37ebca01
FCE
4309
4310 if (q.has_absolute)
4311 comps.push_back (new probe_point::component (TOK_ABSOLUTE));
a229fcd7
GH
4312 }
4313
b8da0ad1
FCE
4314 if (q.has_call)
4315 comps.push_back (new probe_point::component(TOK_CALL));
4bda987e
SC
4316 if (q.has_exported)
4317 comps.push_back (new probe_point::component(TOK_EXPORTED));
b8da0ad1
FCE
4318 if (q.has_inline)
4319 comps.push_back (new probe_point::component(TOK_INLINE));
db520b00 4320 if (has_return)
b8da0ad1
FCE
4321 comps.push_back (new probe_point::component(TOK_RETURN));
4322 if (has_maxactive)
4323 comps.push_back (new probe_point::component
4324 (TOK_MAXACTIVE, new literal_number(maxactive_val)));
d9b516ca 4325
5d23847d
FCE
4326 // Overwrite it.
4327 this->sole_location()->components = comps;
2930abc7
FCE
4328}
4329
bd2b1e68 4330
0a98fd42 4331void
8c67c337
JS
4332dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
4333 Dwarf_Addr dwfl_addr)
0a98fd42 4334{
9aa8ffce 4335 if (null_die(scope_die))
0a98fd42 4336 return;
0a98fd42 4337
8c67c337 4338 bool verbose = q.sess.verbose > 2;
0a98fd42 4339
8c67c337 4340 if (verbose)
b530b5b3 4341 clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
0a98fd42 4342
8c67c337
JS
4343 if (has_return)
4344 {
4345 /* Only save the return value if it has a type. */
4346 string type_name;
4347 Dwarf_Die type_die;
4348 if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
4349 dwarf_type_name(&type_die, type_name))
4350 args.push_back("$return:"+type_name);
4351
4352 else if (verbose)
b530b5b3
LB
4353 clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
4354 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
8c67c337 4355 }
d87623a1 4356
0a98fd42 4357 Dwarf_Die arg;
4ef35696
JS
4358 vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
4359 for (unsigned i = 0; i < scopes.size(); ++i)
4360 {
4361 if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
4362 break; // we don't want file-level variables
4363 if (dwarf_child (&scopes[i], &arg) == 0)
4364 do
0a98fd42 4365 {
4ef35696
JS
4366 switch (dwarf_tag (&arg))
4367 {
4368 case DW_TAG_variable:
4369 case DW_TAG_formal_parameter:
4370 break;
0a98fd42 4371
4ef35696
JS
4372 default:
4373 continue;
4374 }
0a98fd42 4375
4ef35696
JS
4376 /* Ignore this local if it has no name. */
4377 const char *arg_name = dwarf_diename (&arg);
4378 if (!arg_name)
8c67c337
JS
4379 {
4380 if (verbose)
b530b5b3
LB
4381 clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
4382 lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4383 continue;
4384 }
4ef35696
JS
4385
4386 if (verbose)
b530b5b3
LB
4387 clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
4388 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4389
4390 /* Ignore this local if it has no location (or not at this PC). */
4391 /* NB: It still may not be directly accessible, e.g. if it is an
4392 * aggregate type, implicit_pointer, etc., but the user can later
4393 * figure out how to access the interesting parts. */
4394 Dwarf_Attribute attr_mem;
4395 if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
4396 {
4397 Dwarf_Op *expr;
4398 size_t len;
4399 if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
4400 {
4401 if (verbose)
b530b5b3
LB
4402 clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
4403 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
4ef35696
JS
4404 continue;
4405 }
4406 else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
4407 &len, 1) == 1 && len > 0))
4408 {
4409 if (verbose)
b530b5b3
LB
4410 clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
4411 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
4ef35696
JS
4412 continue;
4413 }
4414 }
4415
4416 /* Ignore this local if it has no type. */
4417 string type_name;
4418 Dwarf_Die type_die;
4419 if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
4420 !dwarf_type_name(&type_die, type_name))
8c67c337
JS
4421 {
4422 if (verbose)
b530b5b3
LB
4423 clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
4424 arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
8c67c337
JS
4425 continue;
4426 }
8c67c337 4427
4ef35696
JS
4428 /* This local looks good -- save it! */
4429 args.push_back("$"+string(arg_name)+":"+type_name);
8c67c337 4430 }
4ef35696
JS
4431 while (dwarf_siblingof (&arg, &arg) == 0);
4432 }
0a98fd42
JS
4433}
4434
4435
4436void
d0bfd2ac 4437dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
0a98fd42 4438{
d0bfd2ac 4439 arg_set.insert(arg_set.end(), args.begin(), args.end());
0a98fd42
JS
4440}
4441
4442
27dc09b1 4443void
42e38653 4444dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
27dc09b1
DB
4445{
4446 if (has_process)
4447 {
4448 // These probes are allowed for unprivileged users, but only in the
4449 // context of processes which they own.
4450 emit_process_owner_assertion (o);
4451 return;
4452 }
4453
4454 // Other probes must contain the default assertion which aborts
4455 // if executed by an unprivileged user.
42e38653 4456 derived_probe::emit_privilege_assertion (o);
27dc09b1
DB
4457}
4458
4459
4460void
4461dwarf_derived_probe::print_dupe_stamp(ostream& o)
4462{
4463 if (has_process)
4464 {
4465 // These probes are allowed for unprivileged users, but only in the
4466 // context of processes which they own.
4467 print_dupe_stamp_unprivileged_process_owner (o);
4468 return;
4469 }
4470
4471 // Other probes must contain the default dupe stamp
4472 derived_probe::print_dupe_stamp (o);
4473}
4474
64211010 4475
7a053d3b 4476void
20c6c071 4477dwarf_derived_probe::register_statement_variants(match_node * root,
27dc09b1 4478 dwarf_builder * dw,
42e38653 4479 privilege_t privilege)
bd2b1e68 4480{
27dc09b1 4481 root
42e38653 4482 ->bind_privilege(privilege)
27dc09b1 4483 ->bind(dw);
54efe513
GH
4484}
4485
7a053d3b 4486void
fd6602a0 4487dwarf_derived_probe::register_function_variants(match_node * root,
27dc09b1 4488 dwarf_builder * dw,
42e38653 4489 privilege_t privilege)
2865d17a 4490{
27dc09b1 4491 root
42e38653 4492 ->bind_privilege(privilege)
27dc09b1 4493 ->bind(dw);
27dc09b1 4494 root->bind(TOK_CALL)
42e38653 4495 ->bind_privilege(privilege)
27dc09b1 4496 ->bind(dw);
4bda987e
SC
4497 root->bind(TOK_EXPORTED)
4498 ->bind_privilege(privilege)
4499 ->bind(dw);
27dc09b1 4500 root->bind(TOK_RETURN)
42e38653 4501 ->bind_privilege(privilege)
27dc09b1 4502 ->bind(dw);
1e035395 4503
f6be7c06
DB
4504 // For process probes / uprobes, .maxactive() is unused.
4505 if (! pr_contains (privilege, pr_stapusr))
1e035395
FCE
4506 {
4507 root->bind(TOK_RETURN)
1e035395
FCE
4508 ->bind_num(TOK_MAXACTIVE)->bind(dw);
4509 }
bd2b1e68
GH
4510}
4511
7a053d3b 4512void
27dc09b1 4513dwarf_derived_probe::register_function_and_statement_variants(
440d9b00 4514 systemtap_session& s,
27dc09b1
DB
4515 match_node * root,
4516 dwarf_builder * dw,
42e38653 4517 privilege_t privilege
27dc09b1 4518)
bd2b1e68
GH
4519{
4520 // Here we match 4 forms:
4521 //
4522 // .function("foo")
4523 // .function(0xdeadbeef)
4524 // .statement("foo")
4525 // .statement(0xdeadbeef)
4526
440d9b00 4527 match_node *fv_root = root->bind_str(TOK_FUNCTION);
42e38653 4528 register_function_variants(fv_root, dw, privilege);
7f02ca94 4529 // ROOT.function("STRING") always gets the .inline and .label variants.
440d9b00 4530 fv_root->bind(TOK_INLINE)
42e38653 4531 ->bind_privilege(privilege)
440d9b00 4532 ->bind(dw);
7f02ca94
JS
4533 fv_root->bind_str(TOK_LABEL)
4534 ->bind_privilege(privilege)
440d9b00
DB
4535 ->bind(dw);
4536
4537 fv_root = root->bind_num(TOK_FUNCTION);
42e38653 4538 register_function_variants(fv_root, dw, privilege);
440d9b00
DB
4539 // ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
4540 if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
4541 {
4542 fv_root->bind(TOK_INLINE)
42e38653 4543 ->bind_privilege(privilege)
440d9b00
DB
4544 ->bind(dw);
4545 }
4546
42e38653
DB
4547 register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
4548 register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
bd2b1e68
GH
4549}
4550
b1615c74
JS
4551void
4552dwarf_derived_probe::register_sdt_variants(systemtap_session& s,
4553 match_node * root,
4554 dwarf_builder * dw)
4555{
4556 root->bind_str(TOK_MARK)
f66bb29a 4557 ->bind_privilege(pr_all)
b1615c74
JS
4558 ->bind(dw);
4559 root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
f66bb29a 4560 ->bind_privilege(pr_all)
b1615c74
JS
4561 ->bind(dw);
4562}
4563
4564void
4565dwarf_derived_probe::register_plt_variants(systemtap_session& s,
4566 match_node * root,
4567 dwarf_builder * dw)
4568{
4569 root->bind(TOK_PLT)
f66bb29a 4570 ->bind_privilege(pr_all)
b1615c74
JS
4571 ->bind(dw);
4572 root->bind_str(TOK_PLT)
f66bb29a 4573 ->bind_privilege(pr_all)
b1615c74
JS
4574 ->bind(dw);
4575 root->bind(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4576 ->bind_privilege(pr_all)
b1615c74
JS
4577 ->bind(dw);
4578 root->bind_str(TOK_PLT)->bind_num(TOK_STATEMENT)
f66bb29a 4579 ->bind_privilege(pr_all)
b1615c74 4580 ->bind(dw);
bd2b1e68
GH
4581}
4582
4583void
c4ce66a1 4584dwarf_derived_probe::register_patterns(systemtap_session& s)
bd2b1e68 4585{
c4ce66a1 4586 match_node* root = s.pattern_root;
bd2b1e68
GH
4587 dwarf_builder *dw = new dwarf_builder();
4588
c4ce66a1
JS
4589 update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
4590 s.code_filters.push_back(filter);
4591
73f52eb4
DB
4592 register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
4593 register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
27dc09b1
DB
4594 root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
4595 ->bind(dw);
2cab6244 4596
7f02ca94
JS
4597 match_node* uprobes[] = {
4598 root->bind(TOK_PROCESS),
4599 root->bind_str(TOK_PROCESS),
4600 root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4601 root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
4602 };
4603 for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
4604 {
f66bb29a 4605 register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
7f02ca94
JS
4606 register_sdt_variants(s, uprobes[i], dw);
4607 register_plt_variants(s, uprobes[i], dw);
4608 }
bd2b1e68
GH
4609}
4610
9020300d
FCE
4611void
4612dwarf_derived_probe::emit_probe_local_init(translator_output * o)
4613{
b95e2b79
MH
4614 if (access_vars)
4615 {
4616 // if accessing $variables, emit bsp cache setup for speeding up
d4670309 4617 o->newline() << "#if defined __ia64__";
d9aed31e 4618 o->newline() << "bspcache(c->unwaddr, c->kregs);";
d4670309 4619 o->newline() << "#endif";
b95e2b79 4620 }
9020300d 4621}
2930abc7 4622
b20febf3 4623// ------------------------------------------------------------------------
46b84a80
DS
4624
4625void
b20febf3 4626dwarf_derived_probe_group::enroll (dwarf_derived_probe* p)
46b84a80 4627{
b20febf3 4628 probes_by_module.insert (make_pair (p->module, p));
b8da0ad1
FCE
4629
4630 // XXX: probes put at the same address should all share a
4631 // single kprobe/kretprobe, and have their handlers executed
4632 // sequentially.
b55bc428
FCE
4633}
4634
7a053d3b 4635void
775d51e5 4636dwarf_derived_probe_group::emit_module_decls (systemtap_session& s)
ec4373ff 4637{
b20febf3 4638 if (probes_by_module.empty()) return;
2930abc7 4639
775d51e5
DS
4640 s.op->newline() << "/* ---- dwarf probes ---- */";
4641
4642 // Warn of misconfigured kernels
f41595cc
FCE
4643 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
4644 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
4645 s.op->newline() << "#endif";
775d51e5 4646 s.op->newline();
f41595cc 4647
f07c3b68 4648 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 4649 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
4650 s.op->newline() << "#endif";
4651
14cf7e42 4652 // Forward decls
2ba1736a 4653 s.op->newline() << "#include \"linux/kprobes-common.h\"";
14cf7e42 4654
b20febf3
FCE
4655 // Forward declare the master entry functions
4656 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4657 s.op->line() << " struct pt_regs *regs);";
4658 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4659 s.op->line() << " struct pt_regs *regs);";
4660
42cb22bd
MH
4661 // Emit an array of kprobe/kretprobe pointers
4662 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
4663 s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
4664 s.op->newline() << "#endif";
4665
b20febf3 4666 // Emit the actual probe list.
606fd9c8
FCE
4667
4668 // NB: we used to plop a union { struct kprobe; struct kretprobe } into
4669 // struct stap_dwarf_probe, but it being initialized data makes it add
4670 // hundreds of bytes of padding per stap_dwarf_probe. (PR5673)
14cf7e42 4671 s.op->newline() << "static struct stap_dwarf_kprobe stap_dwarf_kprobes[" << probes_by_module.size() << "];";
606fd9c8
FCE
4672 // NB: bss!
4673
4c2732a1 4674 s.op->newline() << "static struct stap_dwarf_probe {";
b0986e7a
DS
4675 s.op->newline(1) << "const unsigned return_p:1;";
4676 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 4677 s.op->newline() << "const unsigned optional_p:1;";
b20febf3 4678 s.op->newline() << "unsigned registered_p:1;";
b0986e7a 4679 s.op->newline() << "const unsigned short maxactive_val;";
606fd9c8 4680
af234c40
JS
4681 // data saved in the kretprobe_instance packet
4682 s.op->newline() << "const unsigned short saved_longs;";
4683 s.op->newline() << "const unsigned short saved_strings;";
4684
faea5e16 4685 // Let's find some stats for the embedded strings. Maybe they
606fd9c8
FCE
4686 // are small and uniform enough to justify putting char[MAX]'s into
4687 // the array instead of relocated char*'s.
faea5e16
JS
4688 size_t module_name_max = 0, section_name_max = 0;
4689 size_t module_name_tot = 0, section_name_tot = 0;
606fd9c8
FCE
4690 size_t all_name_cnt = probes_by_module.size(); // for average
4691 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
4692 {
4693 dwarf_derived_probe* p = it->second;
4694#define DOIT(var,expr) do { \
4695 size_t var##_size = (expr) + 1; \
4696 var##_max = max (var##_max, var##_size); \
4697 var##_tot += var##_size; } while (0)
4698 DOIT(module_name, p->module.size());
4699 DOIT(section_name, p->section.size());
606fd9c8
FCE
4700#undef DOIT
4701 }
4702
4703 // Decide whether it's worthwhile to use char[] or char* by comparing
4704 // the amount of average waste (max - avg) to the relocation data size
4705 // (3 native long words).
4706#define CALCIT(var) \
4707 if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
4708 { \
4709 s.op->newline() << "const char " << #var << "[" << var##_name_max << "];"; \
4710 if (s.verbose > 2) clog << "stap_dwarf_probe " << #var \
4711 << "[" << var##_name_max << "]" << endl; \
4712 } \
4713 else \
4714 { \
b0986e7a 4715 s.op->newline() << "const char * const " << #var << ";"; \
606fd9c8
FCE
4716 if (s.verbose > 2) clog << "stap_dwarf_probe *" << #var << endl; \
4717 }
4718
4719 CALCIT(module);
4720 CALCIT(section);
e6fe60e7 4721#undef CALCIT
606fd9c8 4722
b0986e7a 4723 s.op->newline() << "const unsigned long address;";
26e63673 4724 s.op->newline() << "struct stap_probe * const probe;";
c87ae2c1 4725 s.op->newline() << "struct stap_probe * const entry_probe;";
b20febf3
FCE
4726 s.op->newline(-1) << "} stap_dwarf_probes[] = {";
4727 s.op->indent(1);
4728
4729 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
2930abc7 4730 {
b20febf3
FCE
4731 dwarf_derived_probe* p = it->second;
4732 s.op->newline() << "{";
4733 if (p->has_return)
4734 s.op->line() << " .return_p=1,";
c9bad430 4735 if (p->has_maxactive)
606fd9c8
FCE
4736 {
4737 s.op->line() << " .maxactive_p=1,";
4738 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
4739 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
4740 }
af234c40
JS
4741 if (p->saved_longs || p->saved_strings)
4742 {
4743 if (p->saved_longs)
4744 s.op->line() << " .saved_longs=" << p->saved_longs << ",";
4745 if (p->saved_strings)
4746 s.op->line() << " .saved_strings=" << p->saved_strings << ",";
4747 if (p->entry_handler)
c87ae2c1 4748 s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
af234c40 4749 }
b350f56b
JS
4750 if (p->locations[0]->optional)
4751 s.op->line() << " .optional_p=1,";
dc38c256 4752 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
84048984
FCE
4753 s.op->line() << " .module=\"" << p->module << "\",";
4754 s.op->line() << " .section=\"" << p->section << "\",";
faea5e16 4755 s.op->line() << " .probe=" << common_probe_init (p) << ",";
b20febf3 4756 s.op->line() << " },";
2930abc7 4757 }
2930abc7 4758
b20febf3
FCE
4759 s.op->newline(-1) << "};";
4760
4761 // Emit the kprobes callback function
4762 s.op->newline();
4763 s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
4764 s.op->line() << " struct pt_regs *regs) {";
606fd9c8
FCE
4765 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
4766 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
4767 // Check that the index is plausible
4768 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4769 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4770 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4771 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4772 s.op->line() << "];";
6eefe942
MW
4773 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
4774 "_STP_PROBE_HANDLER_KPROBE");
d9aed31e 4775 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
4776
4777 // Make it look like the IP is set as it wouldn't have been replaced
4778 // by a breakpoint instruction when calling real probe handler. Reset
4779 // IP regs on return, so we don't confuse kprobes. PR10458
4780 s.op->newline() << "{";
4781 s.op->indent(1);
d9aed31e 4782 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 4783 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 4784 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 4785 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4786 s.op->newline(-1) << "}";
4787
7baf48e9 4788 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
b20febf3
FCE
4789 s.op->newline() << "return 0;";
4790 s.op->newline(-1) << "}";
4791
4792 // Same for kretprobes
4793 s.op->newline();
af234c40
JS
4794 s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
4795 s.op->line() << " struct pt_regs *regs, int entry) {";
b20febf3 4796 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
606fd9c8
FCE
4797
4798 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
a36378d7 4799 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarf_kprobes)/sizeof(struct stap_dwarf_kprobe);";
606fd9c8
FCE
4800 // Check that the index is plausible
4801 s.op->newline() << "struct stap_dwarf_probe *sdp = &stap_dwarf_probes[";
4802 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
4803 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
4804 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
4805 s.op->line() << "];";
4806
c87ae2c1
JS
4807 s.op->newline() << "struct stap_probe *sp = entry ? sdp->entry_probe : sdp->probe;";
4808 s.op->newline() << "if (sp) {";
4809 s.op->indent(1);
6eefe942
MW
4810 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sp",
4811 "_STP_PROBE_HANDLER_KRETPROBE");
d9aed31e 4812 s.op->newline() << "c->kregs = regs;";
af234c40
JS
4813
4814 // for assisting runtime's backtrace logic and accessing kretprobe data packets
6dceb5c9
MW
4815 s.op->newline() << "c->ips.krp.pi = inst;";
4816 s.op->newline() << "c->ips.krp.pi_longs = sdp->saved_longs;";
6415ddde
MW
4817
4818 // Make it look like the IP is set as it wouldn't have been replaced
4819 // by a breakpoint instruction when calling real probe handler. Reset
4820 // IP regs on return, so we don't confuse kprobes. PR10458
4821 s.op->newline() << "{";
d9aed31e 4822 s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
c87ae2c1
JS
4823 s.op->newline() << "if (entry)";
4824 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
4825 s.op->newline(-1) << "else";
4826 s.op->newline(1) << "SET_REG_IP(regs, (unsigned long)inst->ret_addr);";
4827 s.op->newline(-1) << "(sp->ph) (c);";
259d54c0 4828 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
4829 s.op->newline(-1) << "}";
4830
7baf48e9 4831 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
c87ae2c1 4832 s.op->newline(-1) << "}";
b20febf3
FCE
4833 s.op->newline() << "return 0;";
4834 s.op->newline(-1) << "}";
af234c40
JS
4835
4836 s.op->newline();
4837 s.op->newline() << "static int enter_kretprobe_probe (struct kretprobe_instance *inst,";
4838 s.op->line() << " struct pt_regs *regs) {";
4839 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 0);";
4840 s.op->newline(-1) << "}";
4841
4842 s.op->newline();
4843 s.op->newline() << "static int enter_kretprobe_entry_probe (struct kretprobe_instance *inst,";
4844 s.op->line() << " struct pt_regs *regs) {";
4845 s.op->newline(1) << "return enter_kretprobe_common(inst, regs, 1);";
4846 s.op->newline(-1) << "}";
b642c901 4847
14cf7e42 4848 s.op->newline();
20c6c071 4849}
ec4373ff 4850
20c6c071 4851
dc38c0ae 4852void
b20febf3
FCE
4853dwarf_derived_probe_group::emit_module_init (systemtap_session& s)
4854{
4855 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4856 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 4857 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
a049e342 4858 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
b20febf3 4859 s.op->newline() << "if (relocated_addr == 0) continue;"; // quietly; assume module is absent
26e63673 4860 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b20febf3 4861 s.op->newline() << "if (sdp->return_p) {";
606fd9c8 4862 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
c9bad430 4863 s.op->newline() << "if (sdp->maxactive_p) {";
606fd9c8 4864 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
c9bad430 4865 s.op->newline(-1) << "} else {";
f07c3b68 4866 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
c9bad430 4867 s.op->newline(-1) << "}";
606fd9c8 4868 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
af234c40 4869 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
c87ae2c1 4870 s.op->newline() << "if (sdp->entry_probe) {";
af234c40
JS
4871 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4872 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4873 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4874 s.op->newline(-1) << "}";
4875 s.op->newline() << "#endif";
e4cb375f
MH
4876 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4877 s.op->newline() << "#ifdef __ia64__";
4878 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4879 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4880 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4881 s.op->newline() << "if (rc == 0) {";
4882 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4883 s.op->newline() << "if (rc != 0)";
4884 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4885 s.op->newline(-2) << "}";
4886 s.op->newline() << "#else";
606fd9c8 4887 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
e4cb375f 4888 s.op->newline() << "#endif";
b20febf3 4889 s.op->newline(-1) << "} else {";
e4cb375f 4890 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
606fd9c8
FCE
4891 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4892 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
e4cb375f
MH
4893 s.op->newline() << "#ifdef __ia64__";
4894 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
4895 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4896 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4897 s.op->newline() << "if (rc == 0) {";
4898 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
4899 s.op->newline() << "if (rc != 0)";
4900 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4901 s.op->newline(-2) << "}";
4902 s.op->newline() << "#else";
606fd9c8 4903 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
e4cb375f 4904 s.op->newline() << "#endif";
b20febf3 4905 s.op->newline(-1) << "}";
9063462a
FCE
4906 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
4907 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 4908 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 4909 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) relocated_addr, rc);";
b350f56b 4910 s.op->newline(-1) << "rc = 0;"; // continue with other probes
9063462a
FCE
4911 // XXX: shall we increment numskipped?
4912 s.op->newline(-1) << "}";
4913
4914#if 0 /* pre PR 6749; XXX consider making an option */
c48cb0cc 4915 s.op->newline(1) << "for (j=i-1; j>=0; j--) {"; // partial rollback
b20febf3 4916 s.op->newline(1) << "struct stap_dwarf_probe *sdp2 = & stap_dwarf_probes[j];";
606fd9c8
FCE
4917 s.op->newline() << "struct stap_dwarf_kprobe *kp2 = & stap_dwarf_kprobes[j];";
4918 s.op->newline() << "if (sdp2->return_p) unregister_kretprobe (&kp2->u.krp);";
4919 s.op->newline() << "else unregister_kprobe (&kp2->u.kp);";
e4cb375f
MH
4920 s.op->newline() << "#ifdef __ia64__";
4921 s.op->newline() << "unregister_kprobe (&kp2->dummy);";
4922 s.op->newline() << "#endif";
c48cb0cc
FCE
4923 // NB: we don't have to clear sdp2->registered_p, since the module_exit code is
4924 // not run for this early-abort case.
4925 s.op->newline(-1) << "}";
4926 s.op->newline() << "break;"; // don't attempt to register any more probes
b20febf3 4927 s.op->newline(-1) << "}";
9063462a
FCE
4928#endif
4929
b20febf3
FCE
4930 s.op->newline() << "else sdp->registered_p = 1;";
4931 s.op->newline(-1) << "}"; // for loop
dc38c0ae
DS
4932}
4933
4934
b4be7cbc
FCE
4935void
4936dwarf_derived_probe_group::emit_module_refresh (systemtap_session& s)
4937{
4938 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
4939 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
4940 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
4941 s.op->newline() << "unsigned long relocated_addr = _stp_kmodule_relocate (sdp->module, sdp->section, sdp->address);";
4942 s.op->newline() << "int rc;";
4943
4944 // new module arrived?
4945 s.op->newline() << "if (sdp->registered_p == 0 && relocated_addr != 0) {";
4946 s.op->newline(1) << "if (sdp->return_p) {";
4947 s.op->newline(1) << "kp->u.krp.kp.addr = (void *) relocated_addr;";
4948 s.op->newline() << "if (sdp->maxactive_p) {";
4949 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
4950 s.op->newline(-1) << "} else {";
4951 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
4952 s.op->newline(-1) << "}";
4953 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe_probe;";
4954 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)";
4955 s.op->newline() << "if (sdp->entry_probe) {";
4956 s.op->newline(1) << "kp->u.krp.entry_handler = &enter_kretprobe_entry_probe;";
4957 s.op->newline() << "kp->u.krp.data_size = sdp->saved_longs * sizeof(int64_t) + ";
4958 s.op->newline() << " sdp->saved_strings * MAXSTRINGLEN;";
4959 s.op->newline(-1) << "}";
4960 s.op->newline() << "#endif";
4961 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4962 s.op->newline() << "#ifdef __ia64__";
4963 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
4964 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4965 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4966 s.op->newline() << "if (rc == 0) {";
4967 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
4968 s.op->newline() << "if (rc != 0)";
4969 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4970 s.op->newline(-2) << "}";
4971 s.op->newline() << "#else";
4972 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
4973 s.op->newline() << "#endif";
4974 s.op->newline(-1) << "} else {";
4975 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
4976 s.op->newline(1) << "kp->u.kp.addr = (void *) relocated_addr;";
4977 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe_probe;";
4978 s.op->newline() << "#ifdef __ia64__";
4979 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
4980 s.op->newline() << "kp->dummy.pre_handler = NULL;";
4981 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
4982 s.op->newline() << "if (rc == 0) {";
4983 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
4984 s.op->newline() << "if (rc != 0)";
4985 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
4986 s.op->newline(-2) << "}";
4987 s.op->newline() << "#else";
4988 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
4989 s.op->newline() << "#endif";
4990 s.op->newline(-1) << "}";
4991 s.op->newline() << "if (rc == 0) sdp->registered_p = 1;";
4992
4993 // old module disappeared?
4994 s.op->newline(-1) << "} else if (sdp->registered_p == 1 && relocated_addr == 0) {";
4995 s.op->newline(1) << "if (sdp->return_p) {";
4996 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
4997 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
4998 s.op->newline() << "#ifdef STP_TIMING";
4999 s.op->newline() << "if (kp->u.krp.nmissed)";
5000 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
5001 s.op->newline(-1) << "#endif";
5002 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
5003 s.op->newline() << "#ifdef STP_TIMING";
5004 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
5005 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/2 on '%s': %lu\\n\", sdp->probe->pp, kp->u.krp.kp.nmissed);";
5006 s.op->newline(-1) << "#endif";
5007 s.op->newline(-1) << "} else {";
5008 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
5009 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
5010 s.op->newline() << "#ifdef STP_TIMING";
5011 s.op->newline() << "if (kp->u.kp.nmissed)";
5012 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
5013 s.op->newline(-1) << "#endif";
5014 s.op->newline(-1) << "}";
5015 s.op->newline() << "#if defined(__ia64__)";
5016 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5017 s.op->newline() << "#endif";
5018 s.op->newline() << "sdp->registered_p = 0;";
5019 s.op->newline(-1) << "}";
5020
5021 s.op->newline(-1) << "}"; // for loop
5022}
5023
5024
5025
5026
46b84a80 5027void
b20febf3 5028dwarf_derived_probe_group::emit_module_exit (systemtap_session& s)
46b84a80 5029{
42cb22bd
MH
5030 //Unregister kprobes by batch interfaces.
5031 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
5032 s.op->newline() << "j = 0;";
5033 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5034 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5035 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5036 s.op->newline() << "if (! sdp->registered_p) continue;";
5037 s.op->newline() << "if (!sdp->return_p)";
5038 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.kp;";
5039 s.op->newline(-2) << "}";
5040 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5041 s.op->newline() << "j = 0;";
5042 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5043 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5044 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5045 s.op->newline() << "if (! sdp->registered_p) continue;";
5046 s.op->newline() << "if (sdp->return_p)";
5047 s.op->newline(1) << "stap_unreg_kprobes[j++] = &kp->u.krp;";
5048 s.op->newline(-2) << "}";
5049 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes, j);";
e4cb375f
MH
5050 s.op->newline() << "#ifdef __ia64__";
5051 s.op->newline() << "j = 0;";
5052 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5053 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
5054 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
5055 s.op->newline() << "if (! sdp->registered_p) continue;";
5056 s.op->newline() << "stap_unreg_kprobes[j++] = &kp->dummy;";
5057 s.op->newline(-1) << "}";
5058 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes, j);";
5059 s.op->newline() << "#endif";
42cb22bd
MH
5060 s.op->newline() << "#endif";
5061
b20febf3
FCE
5062 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
5063 s.op->newline(1) << "struct stap_dwarf_probe *sdp = & stap_dwarf_probes[i];";
a36378d7 5064 s.op->newline() << "struct stap_dwarf_kprobe *kp = & stap_dwarf_kprobes[i];";
b20febf3
FCE
5065 s.op->newline() << "if (! sdp->registered_p) continue;";
5066 s.op->newline() << "if (sdp->return_p) {";
42cb22bd 5067 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5068 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
42cb22bd 5069 s.op->newline() << "#endif";
606fd9c8 5070 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
73209876
FCE
5071 s.op->newline() << "#ifdef STP_TIMING";
5072 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 5073 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kretprobe/1 on '%s': %d\\n\", sdp->probe->pp, kp->u.krp.nmissed);";
73209876 5074 s.op->newline(-1) << "#endif";
606fd9c8 5075 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
73209876
FCE
5076 s.op->newline() << "#ifdef STP_TIMING";
5077 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 5078 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 5079 s.op->newline(-1) << "#endif";
557fb7a8 5080 s.op->newline(-1) << "} else {";
42cb22bd 5081 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
606fd9c8 5082 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
42cb22bd 5083 s.op->newline() << "#endif";
606fd9c8 5084 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
73209876
FCE
5085 s.op->newline() << "#ifdef STP_TIMING";
5086 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 5087 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
73209876 5088 s.op->newline(-1) << "#endif";
b20febf3 5089 s.op->newline(-1) << "}";
e4cb375f
MH
5090 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
5091 s.op->newline() << "unregister_kprobe (&kp->dummy);";
5092 s.op->newline() << "#endif";
b20febf3
FCE
5093 s.op->newline() << "sdp->registered_p = 0;";
5094 s.op->newline(-1) << "}";
46b84a80
DS
5095}
5096
272c9036
WF
5097static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
5098{
5099 string::size_type pos;
5100 string::size_type lastPos = str.find_first_not_of(" ", 0);
5101 string::size_type nextAt = str.find("@", lastPos);
5102 while (lastPos != string::npos)
5103 {
5104 pos = nextAt + 1;
5105 nextAt = str.find("@", pos);
5106 if (nextAt == string::npos)
5107 pos = string::npos;
5108 else
5109 pos = str.rfind(" ", nextAt);
5110
5111 tokens.push_back(str.substr(lastPos, pos - lastPos));
5112 lastPos = str.find_first_not_of(" ", pos);
5113 }
5114}
8aabf152 5115
8aabf152 5116
aff5d390 5117struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
7a05f484 5118{
ae1418f0 5119 enum regwidths {QI, QIh, HI, SI, DI};
f83336a5
FCE
5120 sdt_uprobe_var_expanding_visitor(systemtap_session& s,
5121 int elf_machine,
5122 const string & process_name,
a794dbeb 5123 const string & provider_name,
aff5d390 5124 const string & probe_name,
71e5e13d 5125 stap_sdt_probe_type probe_type,
aff5d390 5126 const string & arg_string,
8aabf152 5127 int ac):
332ba7e7 5128 session (s), elf_machine (elf_machine), process_name (process_name),
71e5e13d
SC
5129 provider_name (provider_name), probe_name (probe_name),
5130 probe_type (probe_type), arg_count ((unsigned) ac)
a8ec7719 5131 {
f83336a5
FCE
5132 /* Register name mapping table depends on the elf machine of this particular
5133 probe target process/file, not upon the host. So we can't just
5134 #ifdef _i686_ etc. */
ae1418f0
FCE
5135
5136#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
f83336a5 5137 if (elf_machine == EM_X86_64) {
46a94997
SC
5138 DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
5139 DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
5140 DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
5141 DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
5142 DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
5143 DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
5144 DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
5145 DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
5146 DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
5147 DRI ("%sil", 4, QI);
5148 DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
5149 DRI ("%dil", 5, QI);
5150 DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
5151 DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
5152 DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
5153 DRI ("%r8b", 8, QI);
5154 DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
5155 DRI ("%r9b", 9, QI);
5156 DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
5157 DRI ("%r10b", 10, QI);
5158 DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
5159 DRI ("%r11b", 11, QI);
5160 DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
5161 DRI ("%r12b", 12, QI);
5162 DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
5163 DRI ("%r13b", 13, QI);
5164 DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
5165 DRI ("%r14b", 14, QI);
5166 DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
5167 DRI ("%r15b", 15, QI);
f83336a5 5168 } else if (elf_machine == EM_386) {
46a94997
SC
5169 DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
5170 DRI ("%ah", 0, QIh);
5171 DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
5172 DRI ("%ch", 1, QIh);
5173 DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
5174 DRI ("%dh", 2, QIh);
5175 DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
5176 DRI ("%bh", 3, QIh);
5177 DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
5178 DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
5179 DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
5180 DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
0491c523 5181 } else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
46a94997
SC
5182 DRI ("%r0", 0, DI);
5183 DRI ("%r1", 1, DI);
5184 DRI ("%r2", 2, DI);
5185 DRI ("%r3", 3, DI);
5186 DRI ("%r4", 4, DI);
5187 DRI ("%r5", 5, DI);
5188 DRI ("%r6", 6, DI);
5189 DRI ("%r7", 7, DI);
5190 DRI ("%r8", 8, DI);
5191 DRI ("%r9", 9, DI);
5192 DRI ("%r10", 10, DI);
5193 DRI ("%r11", 11, DI);
5194 DRI ("%r12", 12, DI);
5195 DRI ("%r13", 13, DI);
5196 DRI ("%r14", 14, DI);
5197 DRI ("%r15", 15, DI);
5198 DRI ("%r16", 16, DI);
5199 DRI ("%r17", 17, DI);
5200 DRI ("%r18", 18, DI);
5201 DRI ("%r19", 19, DI);
5202 DRI ("%r20", 20, DI);
5203 DRI ("%r21", 21, DI);
5204 DRI ("%r22", 22, DI);
5205 DRI ("%r23", 23, DI);
5206 DRI ("%r24", 24, DI);
5207 DRI ("%r25", 25, DI);
5208 DRI ("%r26", 26, DI);
5209 DRI ("%r27", 27, DI);
5210 DRI ("%r28", 28, DI);
5211 DRI ("%r29", 29, DI);
5212 DRI ("%r30", 30, DI);
5213 DRI ("%r31", 31, DI);
8aabf152 5214 // PR11821: unadorned register "names" without -mregnames
46a94997
SC
5215 DRI ("0", 0, DI);
5216 DRI ("1", 1, DI);
5217 DRI ("2", 2, DI);
5218 DRI ("3", 3, DI);
5219 DRI ("4", 4, DI);
5220 DRI ("5", 5, DI);
5221 DRI ("6", 6, DI);
5222 DRI ("7", 7, DI);
5223 DRI ("8", 8, DI);
5224 DRI ("9", 9, DI);
5225 DRI ("10", 10, DI);
5226 DRI ("11", 11, DI);
5227 DRI ("12", 12, DI);
5228 DRI ("13", 13, DI);
5229 DRI ("14", 14, DI);
5230 DRI ("15", 15, DI);
5231 DRI ("16", 16, DI);
5232 DRI ("17", 17, DI);
5233 DRI ("18", 18, DI);
5234 DRI ("19", 19, DI);
5235 DRI ("20", 20, DI);
5236 DRI ("21", 21, DI);
5237 DRI ("22", 22, DI);
5238 DRI ("23", 23, DI);
5239 DRI ("24", 24, DI);
5240 DRI ("25", 25, DI);
5241 DRI ("26", 26, DI);
5242 DRI ("27", 27, DI);
5243 DRI ("28", 28, DI);
5244 DRI ("29", 29, DI);
5245 DRI ("30", 30, DI);
5246 DRI ("31", 31, DI);
14900130 5247 } else if (elf_machine == EM_S390) {
46a94997
SC
5248 DRI ("%r0", 0, DI);
5249 DRI ("%r1", 1, DI);
5250 DRI ("%r2", 2, DI);
5251 DRI ("%r3", 3, DI);
5252 DRI ("%r4", 4, DI);
5253 DRI ("%r5", 5, DI);
5254 DRI ("%r6", 6, DI);
5255 DRI ("%r7", 7, DI);
5256 DRI ("%r8", 8, DI);
5257 DRI ("%r9", 9, DI);
5258 DRI ("%r10", 10, DI);
5259 DRI ("%r11", 11, DI);
5260 DRI ("%r12", 12, DI);
5261 DRI ("%r13", 13, DI);
5262 DRI ("%r14", 14, DI);
5263 DRI ("%r15", 15, DI);
272c9036
WF
5264 } else if (elf_machine == EM_ARM) {
5265 DRI ("r0", 0, SI);
5266 DRI ("r1", 1, SI);
5267 DRI ("r2", 2, SI);
5268 DRI ("r3", 3, SI);
5269 DRI ("r4", 4, SI);
5270 DRI ("r5", 5, SI);
5271 DRI ("r6", 6, SI);
5272 DRI ("r7", 7, SI);
5273 DRI ("r8", 8, SI);
5274 DRI ("r9", 9, SI);
5275 DRI ("sl", 10, SI);
5276 DRI ("fp", 11, SI);
5277 DRI ("ip", 12, SI);
5278 DRI ("sp", 13, SI);
5279 DRI ("lr", 14, SI);
5280 DRI ("pc", 15, SI);
14900130 5281 } else if (arg_count) {
8aabf152 5282 /* permit this case; just fall back to dwarf */
f83336a5 5283 }
ae1418f0 5284#undef DRI
f83336a5 5285
ebbd2b45 5286 need_debug_info = false;
88e39987 5287 if (probe_type == uprobe3_type)
272c9036
WF
5288 {
5289 sdt_v3_tokenize(arg_string, arg_tokens);
5290 assert(arg_count <= 12);
5291 }
88e39987 5292 else
272c9036
WF
5293 {
5294 tokenize(arg_string, arg_tokens, " ");
5295 assert(arg_count <= 10);
5296 }
a8ec7719 5297 }
8aabf152 5298
f83336a5 5299 systemtap_session& session;
332ba7e7 5300 int elf_machine;
aff5d390 5301 const string & process_name;
a794dbeb 5302 const string & provider_name;
aff5d390 5303 const string & probe_name;
71e5e13d 5304 stap_sdt_probe_type probe_type;
8aabf152 5305 unsigned arg_count;
aff5d390 5306 vector<string> arg_tokens;
46a94997 5307 map<string, pair<unsigned,int> > dwarf_regs;
ebbd2b45 5308 bool need_debug_info;
aff5d390
SC
5309
5310 void visit_target_symbol (target_symbol* e);
6ef331c8
SC
5311 void visit_target_symbol_arg (target_symbol* e);
5312 void visit_target_symbol_context (target_symbol* e);
40a0c64e 5313 void visit_cast_op (cast_op* e);
aff5d390
SC
5314};
5315
7a05f484
SC
5316
5317void
6ef331c8 5318sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
7a05f484 5319{
6ef331c8 5320 if (e->addressof)
b530b5b3 5321 throw semantic_error(_("cannot take address of context variable"), e->tok);
6ef331c8
SC
5322
5323 if (e->name == "$$name")
7a05f484 5324 {
6ef331c8
SC
5325 literal_string *myname = new literal_string (probe_name);
5326 myname->tok = e->tok;
5327 provide(myname);
5328 return;
5329 }
7a05f484 5330
6ef331c8
SC
5331 else if (e->name == "$$provider")
5332 {
5333 literal_string *myname = new literal_string (provider_name);
5334 myname->tok = e->tok;
5335 provide(myname);
5336 return;
5337 }
a794dbeb 5338
6ef331c8
SC
5339 else if (e->name == "$$vars" || e->name == "$$parms")
5340 {
5341 e->assert_no_components("sdt", true);
6ef331c8
SC
5342
5343 // Convert $$vars to sprintf of a list of vars which we recursively evaluate
5344 // NB: we synthesize a new token here rather than reusing
5345 // e->tok, because print_format::print likes to use
5346 // its tok->content.
5347 token* pf_tok = new token(*e->tok);
5348 pf_tok->content = "sprintf";
63ea4244 5349
6ef331c8
SC
5350 print_format* pf = print_format::create(pf_tok);
5351
5352 for (unsigned i = 1; i <= arg_count; ++i)
5353 {
5354 if (i > 1)
5355 pf->raw_components += " ";
5356 target_symbol *tsym = new target_symbol;
5357 tsym->tok = e->tok;
5358 tsym->name = "$arg" + lex_cast(i);
5359 pf->raw_components += tsym->name;
5360 tsym->components = e->components;
5361
5362 expression *texp = require (tsym);
5363 if (!e->components.empty() &&
5364 e->components[0].type == target_symbol::comp_pretty_print)
5365 pf->raw_components += "=%s";
5366 else
5367 pf->raw_components += "=%#x";
5368 pf->args.push_back(texp);
5369 }
5370
5371 pf->components = print_format::string_to_components(pf->raw_components);
5372 provide (pf);
5373 }
5374 else
5375 assert(0); // shouldn't get here
5376}
5377
5378
5379void
5380sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
5381{
5382 try
5383 {
8aabf152 5384 unsigned argno = 0; // the N in $argN
c69a87e0 5385 try
aff5d390 5386 {
5ecaa5a7 5387 if (startswith(e->name, "$arg"))
8aabf152 5388 argno = lex_cast<unsigned>(e->name.substr(4));
aff5d390 5389 }
c69a87e0 5390 catch (const runtime_error& f) // non-integral $arg suffix: e.g. $argKKKSDF
aff5d390 5391 {
8aabf152 5392 argno = 0;
aff5d390 5393 }
5ecaa5a7 5394
8aabf152
FCE
5395 if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
5396 argno < 1 || argno > arg_count) // a $argN with out-of-range N
aff5d390 5397 {
8aabf152
FCE
5398 // NB: Either
5399 // 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
5400 // 2) uprobe2_type $FOO (no probe args)
5401 // both of which get resolved later.
5402 need_debug_info = true;
5403 provide(e);
5404 return;
aff5d390 5405 }
277c21bc 5406
8aabf152
FCE
5407 assert (arg_tokens.size() >= argno);
5408 string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
c57ea854 5409
8aabf152
FCE
5410 // Now we try to parse this thing, which is an assembler operand
5411 // expression. If we can't, we warn, back down to need_debug_info
b874bd52 5412 // and hope for the best. Here is the syntax for a few architectures.
9859b766 5413 // Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
8095a157
FCE
5414 //
5415 // literal reg reg reg + base+index*size+offset
b874bd52 5416 // indirect offset
8095a157 5417 // x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S)
b874bd52
SC
5418 // power iN R (R) N(R)
5419 // ia64 N rR [r16]
5420 // s390 N %rR 0(rR) N(r15)
5421 // arm #N rR [rR] [rR, #N]
5422
8aabf152
FCE
5423 expression* argexpr = 0; // filled in in case of successful parse
5424
5425 string percent_regnames;
5426 string regnames;
5427 vector<string> matches;
71e5e13d 5428 long precision;
8aabf152
FCE
5429 int rc;
5430
40fe32e0
SC
5431 // Parse the leading length
5432
5433 if (asmarg.find('@') != string::npos)
5434 {
5435 precision = lex_cast<int>(asmarg.substr(0, asmarg.find('@')));
5436 asmarg = asmarg.substr(asmarg.find('@')+1);
5437 }
71e5e13d
SC
5438 else
5439 {
5440 // V1/V2 do not have precision field so default to signed long
5441 // V3 asm does not have precision field so default to unsigned long
5442 if (probe_type == uprobe3_type)
5443 precision = sizeof(long); // this is an asm probe
5444 else
5445 precision = -sizeof(long);
5446 }
40fe32e0 5447
8aabf152
FCE
5448 // test for a numeric literal.
5449 // Only accept (signed) decimals throughout. XXX
5450
5451 // PR11821. NB: on powerpc, literals are not prefixed with $,
5452 // so this regex does not match. But that's OK, since without
5453 // -mregnames, we can't tell them apart from register numbers
5454 // anyway. With -mregnames, we could, if gcc somehow
5455 // communicated to us the presence of that option, but alas it
5456 // doesn't. http://gcc.gnu.org/PR44995.
272c9036 5457 rc = regexp_match (asmarg, "^[i\\$#][-]?[0-9][0-9]*$", matches);
8aabf152
FCE
5458 if (! rc)
5459 {
75a371ce
JS
5460 string sn = matches[0].substr(1);
5461 int64_t n;
5462 try
5463 {
5464 // We have to pay attention to the size & sign, as gcc sometimes
5465 // propagates constants that don't quite match, like a negative
5466 // value to fill an unsigned type.
5467 switch (precision)
5468 {
5469 case -1: n = lex_cast< int8_t>(sn); break;
5470 case 1: n = lex_cast< uint8_t>(sn); break;
5471 case -2: n = lex_cast< int16_t>(sn); break;
5472 case 2: n = lex_cast<uint16_t>(sn); break;
5473 case -4: n = lex_cast< int32_t>(sn); break;
5474 case 4: n = lex_cast<uint32_t>(sn); break;
5475 default:
5476 case -8: n = lex_cast< int64_t>(sn); break;
5477 case 8: n = lex_cast<uint64_t>(sn); break;
5478 }
5479 }
5480 catch (std::runtime_error&)
5481 {
5482 goto not_matched;
5483 }
5484 literal_number* ln = new literal_number(n);
8aabf152
FCE
5485 ln->tok = e->tok;
5486 argexpr = ln;
5487 goto matched;
5488 }
5489
14900130
SC
5490 if (dwarf_regs.empty())
5491 goto not_matched;
d5b83cee 5492
8aabf152
FCE
5493 // Build regex pieces out of the known dwarf_regs. We keep two separate
5494 // lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
5495 // and ones with no prefix (and thus only usable in unambiguous contexts).
46a94997 5496 for (map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.begin(); ri != dwarf_regs.end(); ri++)
8aabf152
FCE
5497 {
5498 string regname = ri->first;
5499 assert (regname != "");
5500 regnames += string("|")+regname;
5501 if (regname[0]=='%')
5502 percent_regnames += string("|")+regname;
5503 }
5504 // clip off leading |
5505 regnames = regnames.substr(1);
272c9036
WF
5506 if (percent_regnames != "")
5507 percent_regnames = percent_regnames.substr(1);
8aabf152
FCE
5508
5509 // test for REGISTER
5510 // NB: Because PR11821, we must use percent_regnames here.
272c9036 5511 if (elf_machine == EM_PPC || elf_machine == EM_PPC64 || elf_machine == EM_ARM)
9109f487
SC
5512 rc = regexp_match (asmarg, string("^(")+regnames+string(")$"), matches);
5513 else
332ba7e7 5514 rc = regexp_match (asmarg, string("^(")+percent_regnames+string(")$"), matches);
8aabf152
FCE
5515 if (! rc)
5516 {
5517 string regname = matches[1];
46a94997
SC
5518 map<string,pair<unsigned,int> >::iterator ri = dwarf_regs.find (regname);
5519 if (ri != dwarf_regs.end()) // known register
8aabf152
FCE
5520 {
5521 embedded_expr *get_arg1 = new embedded_expr;
19c22e1f 5522 string width_adjust;
46a94997 5523 switch (ri->second.second)
19c22e1f 5524 {
892ec39a
SC
5525 case QI: width_adjust = ") & 0xff)"; break;
5526 case QIh: width_adjust = ">>8) & 0xff)"; break;
46a94997 5527 case HI:
71e5e13d 5528 // preserve 16 bit register signness
892ec39a
SC
5529 width_adjust = ") & 0xffff)";
5530 if (precision < 0)
55b377f4 5531 width_adjust += " << 48 >> 48";
ac8a78aa
SC
5532 break;
5533 case SI:
5534 // preserve 32 bit register signness
892ec39a
SC
5535 width_adjust = ") & 0xffffffff)";
5536 if (precision < 0)
55b377f4 5537 width_adjust += " << 32 >> 32";
19c22e1f 5538 break;
892ec39a 5539 default: width_adjust = "))";
19c22e1f 5540 }
55b377f4
SC
5541 string type = "";
5542 if (probe_type == uprobe3_type)
5543 type = (precision < 0
5544 ? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
5545 type = type + "((";
8aabf152
FCE
5546 get_arg1->tok = e->tok;
5547 get_arg1->code = string("/* unprivileged */ /* pure */")
892ec39a 5548 + string(" ((int64_t)") + type
8aabf152
FCE
5549 + (is_user_module (process_name)
5550 ? string("u_fetch_register(")
5551 : string("k_fetch_register("))
46a94997 5552 + lex_cast(dwarf_regs[regname].first) + string("))")
19c22e1f 5553 + width_adjust;
8aabf152
FCE
5554 argexpr = get_arg1;
5555 goto matched;
5556 }
5557 // invalid register name, fall through
5558 }
40fe32e0 5559
272c9036 5560 int reg, offset1;
e5b7b83f 5561 // test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
40fe32e0 5562 // NB: Despite PR11821, we can use regnames here, since the parentheses
e5b7b83f 5563 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
272c9036
WF
5564 // On ARM test for [REGISTER, OFFSET]
5565 if (elf_machine == EM_ARM)
5566 {
5567 rc = regexp_match (asmarg, string("^\\[(")+regnames+string("), #([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?\\]$"), matches);
5568 reg = 1;
5569 offset1 = 2;
5570 }
5571 else
5572 {
5573 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string(")[)]$"), matches);
5574 reg = 4;
5575 offset1 = 1;
5576 }
8aabf152
FCE
5577 if (! rc)
5578 {
e5b7b83f 5579 string regname;
8aabf152 5580 int64_t disp = 0;
272c9036
WF
5581 if (matches[reg].length())
5582 regname = matches[reg];
8095a157
FCE
5583 if (dwarf_regs.find (regname) == dwarf_regs.end())
5584 goto not_matched;
5585
272c9036 5586 for (int i=offset1; i <= (offset1 + 2); i++)
e5b7b83f
SC
5587 if (matches[i].length())
5588 try
5589 {
5590 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5591 }
8aabf152
FCE
5592 catch (const runtime_error& f) // unparseable offset
5593 {
5594 goto not_matched; // can't just 'break' out of
5595 // this case or use a sentinel
5596 // value, unfortunately
5597 }
5598
8aabf152 5599 // synthesize user_long(%{fetch_register(R)%} + D)
8aabf152
FCE
5600 embedded_expr *get_arg1 = new embedded_expr;
5601 get_arg1->tok = e->tok;
5602 get_arg1->code = string("/* unprivileged */ /* pure */")
5603 + (is_user_module (process_name)
5604 ? string("u_fetch_register(")
5605 : string("k_fetch_register("))
46a94997 5606 + lex_cast(dwarf_regs[regname].first) + string(")");
8aabf152 5607 // XXX: may we ever need to cast that to a narrower type?
40fe32e0 5608
8aabf152
FCE
5609 literal_number* inc = new literal_number(disp);
5610 inc->tok = e->tok;
40fe32e0 5611
8aabf152
FCE
5612 binary_expression *be = new binary_expression;
5613 be->tok = e->tok;
5614 be->left = get_arg1;
5615 be->op = "+";
5616 be->right = inc;
40fe32e0 5617
8aabf152 5618 functioncall *fc = new functioncall;
40fe32e0
SC
5619 switch (precision)
5620 {
7f6ce9ab
SC
5621 case 1: case -1:
5622 fc->function = "user_int8"; break;
5623 case 2:
5624 fc->function = "user_uint16"; break;
5625 case -2:
5626 fc->function = "user_int16"; break;
5627 case 4:
5628 fc->function = "user_uint32"; break;
5629 case -4:
5630 fc->function = "user_int32"; break;
5631 case 8: case -8:
5632 fc->function = "user_int64"; break;
40fe32e0
SC
5633 default: fc->function = "user_long";
5634 }
8aabf152
FCE
5635 fc->tok = e->tok;
5636 fc->args.push_back(be);
366af4e7 5637
8aabf152
FCE
5638 argexpr = fc;
5639 goto matched;
5640 }
8095a157
FCE
5641
5642 // test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
5643 // NB: Despite PR11821, we can use regnames here, since the parentheses
5644 // make things unambiguous. (Note: gdb/stap-probe.c also parses this)
0f7b51d6 5645 rc = regexp_match (asmarg, string("^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](")+regnames+string("),(")+regnames+string(")(,[1248])?[)]$"), matches);
8095a157
FCE
5646 if (! rc)
5647 {
5648 string baseregname;
5649 string indexregname;
5650 int64_t disp = 0;
5651 short scale = 1;
5652
5653 if (matches[6].length())
5654 try
5655 {
5656 scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
5657 // We could verify that scale is one of 1,2,4,8,
5658 // but it doesn't really matter. An erroneous
5659 // address merely results in run-time errors.
8aabf152 5660 }
8095a157
FCE
5661 catch (const runtime_error &f) // unparseable scale
5662 {
5663 goto not_matched;
5664 }
5665
5666 if (matches[4].length())
5667 baseregname = matches[4];
5668 if (dwarf_regs.find (baseregname) == dwarf_regs.end())
5669 goto not_matched;
5670
5671 if (matches[5].length())
5672 indexregname = matches[5];
5673 if (dwarf_regs.find (indexregname) == dwarf_regs.end())
5674 goto not_matched;
5675
f7719b3d 5676 for (int i = 1; i <= 3; i++) // up to three OFFSET terms
8095a157
FCE
5677 if (matches[i].length())
5678 try
5679 {
5680 disp += lex_cast<int64_t>(matches[i]); // should decode positive/negative hex/decimal
5681 }
5682 catch (const runtime_error& f) // unparseable offset
5683 {
5684 goto not_matched; // can't just 'break' out of
5685 // this case or use a sentinel
5686 // value, unfortunately
5687 }
5688
5689 // synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
5690
5691 embedded_expr *get_arg1 = new embedded_expr;
5692 string regfn = is_user_module (process_name)
5693 ? string("u_fetch_register")
5694 : string("k_fetch_register"); // NB: in practice sdt.h probes are for userspace only
5695
5696 get_arg1->tok = e->tok;
5697 get_arg1->code = string("/* unprivileged */ /* pure */")
5698 + regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
5699 + string("+(")
5700 + regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
5701 + string("*")
5702 + lex_cast(scale)
5703 + string(")");
5704
5705 // NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
5706 literal_number* inc = new literal_number(disp);
5707 inc->tok = e->tok;
5708
5709 binary_expression *be = new binary_expression;
5710 be->tok = e->tok;
5711 be->left = get_arg1;
5712 be->op = "+";
5713 be->right = inc;
5714
5715 functioncall *fc = new functioncall;
5716 switch (precision)
5717 {
5718 case 1: case -1:
5719 fc->function = "user_int8"; break;
5720 case 2:
5721 fc->function = "user_uint16"; break;
5722 case -2:
5723 fc->function = "user_int16"; break;
5724 case 4:
5725 fc->function = "user_uint32"; break;
5726 case -4:
5727 fc->function = "user_int32"; break;
5728 case 8: case -8:
5729 fc->function = "user_int64"; break;
5730 default: fc->function = "user_long";
5731 }
5732 fc->tok = e->tok;
5733 fc->args.push_back(be);
5734
5735 argexpr = fc;
5736 goto matched;
8aabf152
FCE
5737 }
5738
8aabf152
FCE
5739
5740 not_matched:
5741 // The asmarg operand was not recognized. Back down to dwarf.
5742 if (! session.suppress_warnings)
84fef8ee
FCE
5743 {
5744 if (probe_type == UPROBE3_TYPE)
5745 session.print_warning (_F("Can't parse SDT_V3 operand '%s'", asmarg.c_str()), e->tok);
5746 else // must be *PROBE2; others don't get asm operands
5747 session.print_warning (_F("Downgrading SDT_V2 probe argument to dwarf, can't parse '%s'",
5748 asmarg.c_str()), e->tok);
5749 }
8aabf152
FCE
5750 assert (argexpr == 0);
5751 need_debug_info = true;
5752 provide (e);
5753 return;
366af4e7 5754
8aabf152
FCE
5755 matched:
5756 assert (argexpr != 0);
366af4e7
RM
5757
5758 if (session.verbose > 2)
1e41115c 5759 //TRANSLATORS: We're mapping the operand to a new expression*.
b530b5b3 5760 clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
366af4e7 5761
aff5d390 5762 if (e->components.empty()) // We have a scalar
8aabf152
FCE
5763 {
5764 if (e->addressof)
b530b5b3 5765 throw semantic_error(_("cannot take address of sdt variable"), e->tok);
8aabf152
FCE
5766 provide (argexpr);
5767 return;
5768 }
5769 else // $var->foo
5770 {
5771 cast_op *cast = new cast_op;
5772 cast->name = "@cast";
5773 cast->tok = e->tok;
5774 cast->operand = argexpr;
5775 cast->components = e->components;
5776 cast->type_name = probe_name + "_arg" + lex_cast(argno);
5777 cast->module = process_name;
5778 cast->visit(this);
5779 return;
5780 }
366af4e7 5781
8aabf152 5782 /* NOTREACHED */
aff5d390
SC
5783 }
5784 catch (const semantic_error &er)
5785 {
5786 e->chain (er);
5787 provide (e);
5788 }
5789}
5790
5791
6ef331c8
SC
5792void
5793sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
5794{
5795 try
5796 {
49131a6d
MW
5797 assert(e->name.size() > 0
5798 && ((e->name[0] == '$' && e->target_name == "")
5799 || (e->name == "@var" && e->target_name != "")));
6ef331c8
SC
5800
5801 if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
5802 visit_target_symbol_context (e);
5803 else
5804 visit_target_symbol_arg (e);
5805 }
5806 catch (const semantic_error &er)
5807 {
5808 e->chain (er);
5809 provide (e);
5810 }
5811}
5812
5813
40a0c64e
JS
5814void
5815sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
5816{
5817 // Fill in our current module context if needed
5818 if (e->module.empty())
5819 e->module = process_name;
5820
5821 var_expanding_visitor::visit_cast_op(e);
5822}
5823
5824
576eaefe
SC
5825void
5826plt_expanding_visitor::visit_target_symbol (target_symbol *e)
5827{
5828 try
5829 {
5830 if (e->name == "$$name")
5831 {
5832 literal_string *myname = new literal_string (entry);
5833 myname->tok = e->tok;
5834 provide(myname);
5835 return;
5836 }
3d69c03f
JS
5837
5838 // variable not found -> throw a semantic error
5839 // (only to be caught right away, but this may be more complex later...)
5840 string alternatives = "$$name";
5841 throw semantic_error(_F("unable to find plt variable '%s' (alternatives: %s)",
5842 e->name.c_str(), alternatives.c_str()), e->tok);
576eaefe
SC
5843 }
5844 catch (const semantic_error &er)
5845 {
5846 e->chain (er);
5847 provide (e);
5848 }
5849}
5850
5851
edce5b67
JS
5852struct sdt_query : public base_query
5853{
5854 sdt_query(probe * base_probe, probe_point * base_loc,
5855 dwflpp & dw, literal_map_t const & params,
51d6bda3 5856 vector<derived_probe *> & results, const string user_lib);
edce5b67 5857
51d6bda3 5858 void query_library (const char *data);
576eaefe 5859 void query_plt (const char *entry, size_t addr) {}
edce5b67
JS
5860 void handle_query_module();
5861
5862private:
15284963 5863 stap_sdt_probe_type probe_type;
d61ea602 5864 enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
edce5b67
JS
5865 probe * base_probe;
5866 probe_point * base_loc;
6846cfc8 5867 literal_map_t const & params;
edce5b67 5868 vector<derived_probe *> & results;
a794dbeb
FCE
5869 string pp_mark;
5870 string pp_provider;
51d6bda3 5871 string user_lib;
edce5b67
JS
5872
5873 set<string> probes_handled;
5874
5875 Elf_Data *pdata;
5876 size_t probe_scn_offset;
5877 size_t probe_scn_addr;
aff5d390 5878 uint64_t arg_count;
40fe32e0 5879 GElf_Addr base;
c57ea854 5880 GElf_Addr pc;
aff5d390 5881 string arg_string;
edce5b67 5882 string probe_name;
a794dbeb 5883 string provider_name;
79a0ca08 5884 Dwarf_Addr semaphore;
edce5b67
JS
5885
5886 bool init_probe_scn();
6b51ee12 5887 bool get_next_probe();
c57ea854
SC
5888 void iterate_over_probe_entries();
5889 void handle_probe_entry();
edce5b67 5890
40fe32e0
SC
5891 static void setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len);
5892 void setup_note_probe_entry (int type, const char *data, size_t len);
5893
edce5b67 5894 void convert_probe(probe *base);
4ddb6dd0 5895 void record_semaphore(vector<derived_probe *> & results, unsigned start);
c72aa911 5896 probe* convert_location();
40fe32e0 5897 bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
c57ea854
SC
5898 bool have_debuginfo_uprobe(bool need_debug_info)
5899 {return probe_type == uprobe1_type
40fe32e0 5900 || ((probe_type == uprobe2_type || probe_type == uprobe3_type)
c57ea854 5901 && need_debug_info);}
40fe32e0 5902 bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
edce5b67
JS
5903};
5904
5905
5906sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
5907 dwflpp & dw, literal_map_t const & params,
51d6bda3 5908 vector<derived_probe *> & results, const string user_lib):
d61ea602
JS
5909 base_query(dw, params), probe_type(unknown_probe_type),
5910 probe_loc(unknown_section), base_probe(base_probe),
74fe61bc
LB
5911 base_loc(base_loc), params(params), results(results), user_lib(user_lib),
5912 probe_scn_offset(0), probe_scn_addr(0), arg_count(0), base(0), pc(0),
5913 semaphore(0)
edce5b67 5914{
a794dbeb
FCE
5915 assert(get_string_param(params, TOK_MARK, pp_mark));
5916 get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
5917
ef428667
FCE
5918 // PR10245: permit usage of dtrace-y "-" separator in marker name;
5919 // map it to double-underscores.
5920 size_t pos = 0;
5921 while (1) // there may be more than one
5922 {
a794dbeb 5923 size_t i = pp_mark.find("-", pos);
ef428667 5924 if (i == string::npos) break;
a794dbeb 5925 pp_mark.replace (i, 1, "__");
ef428667
FCE
5926 pos = i+1; // resume searching after the inserted __
5927 }
a794dbeb
FCE
5928
5929 // XXX: same for pp_provider?
edce5b67
JS
5930}
5931
5932
5933void
c57ea854 5934sdt_query::handle_probe_entry()
edce5b67 5935{
c57ea854
SC
5936 if (! have_uprobe()
5937 && !probes_handled.insert(probe_name).second)
edce5b67
JS
5938 return;
5939
5940 if (sess.verbose > 3)
c57ea854 5941 {
b530b5b3
LB
5942 //TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
5943 //TRANSLATORS: is matched to.
5944 clog << _F("matched probe_name %s probe type ", probe_name.c_str());
c57ea854
SC
5945 switch (probe_type)
5946 {
5947 case uprobe1_type:
5948 clog << "uprobe1 at 0x" << hex << pc << dec << endl;
5949 break;
5950 case uprobe2_type:
5951 clog << "uprobe2 at 0x" << hex << pc << dec << endl;
5952 break;
40fe32e0
SC
5953 case uprobe3_type:
5954 clog << "uprobe3 at 0x" << hex << pc << dec << endl;
5955 break;
d61ea602
JS
5956 default:
5957 clog << "unknown!" << endl;
5958 break;
c57ea854
SC
5959 }
5960 }
edce5b67 5961
c57ea854
SC
5962 // Extend the derivation chain
5963 probe *new_base = convert_location();
5964 probe_point *new_location = new_base->locations[0];
5965
c57ea854
SC
5966 bool need_debug_info = false;
5967
7d395255
JS
5968 // We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
5969 // or dwfl_module_getelf(...). We only need it for the machine type, which
5970 // should be the same. The bias is used for relocating debuginfoless probes,
5971 // though, so that must come from the possibly-prelinked ELF file, not DWARF.
c57ea854 5972 Dwarf_Addr bias;
7d395255 5973 Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
c57ea854 5974
1cc41cd6
DS
5975 /* Figure out the architecture of this particular ELF file. The
5976 dwarfless register-name mappings depend on it. */
5977 GElf_Ehdr ehdr_mem;
5978 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
5979 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
d8f31d0a 5980 assert(em);
1cc41cd6
DS
5981 int elf_machine = em->e_machine;
5982 sdt_uprobe_var_expanding_visitor svv (sess, elf_machine, module_val,
5983 provider_name, probe_name,
5984 probe_type, arg_string, arg_count);
5985 svv.replace (new_base->body);
5986 need_debug_info = svv.need_debug_info;
c57ea854
SC
5987
5988 unsigned i = results.size();
edce5b67 5989
1cc41cd6
DS
5990 // XXX: why not derive_probes() in the uprobes case too?
5991 literal_map_t params;
5992 for (unsigned i = 0; i < new_location->components.size(); ++i)
5993 {
5994 probe_point::component *c = new_location->components[i];
5995 params[c->functor] = c->arg;
5996 }
c57ea854 5997
1cc41cd6
DS
5998 dwarf_query q(new_base, new_location, dw, params, results, "", "");
5999 q.has_mark = true; // enables mid-statement probing
30263a73 6000
1cc41cd6
DS
6001 // V2 probes need dwarf info in case of a variable reference
6002 if (have_debuginfo_uprobe(need_debug_info))
6003 dw.iterate_over_modules(&query_module, &q);
6004 else if (have_debuginfoless_uprobe())
6005 {
6006 string section;
6007 Dwarf_Addr reloc_addr = q.statement_num_val + bias;
6008 if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
6009 {
6010 dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
6011 section = ".dynamic";
6012 }
6013 else
6014 section = ".absolute";
edce5b67 6015
1cc41cd6
DS
6016 uprobe_derived_probe* p =
6017 new uprobe_derived_probe ("", "", 0,
6018 path_remove_sysroot(sess,q.module_val),
6019 section,
6020 q.statement_num_val, reloc_addr, q, 0);
6021 p->saveargs (arg_count);
6022 results.push_back (p);
c57ea854 6023 }
487bf4e2 6024 sess.unwindsym_modules.insert (dw.module_name);
c57ea854
SC
6025 record_semaphore(results, i);
6026}
edce5b67 6027
4ddb6dd0 6028
c57ea854
SC
6029void
6030sdt_query::handle_query_module()
6031{
6032 if (!init_probe_scn())
6033 return;
edce5b67 6034
c57ea854
SC
6035 if (sess.verbose > 3)
6036 clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
edce5b67 6037
40fe32e0
SC
6038 if (probe_loc == note_section)
6039 {
6040 GElf_Shdr shdr_mem;
6041 GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
6042
6043 if (shdr)
6044 base = shdr->sh_addr;
6045 else
6046 base = 0;
6047 dw.iterate_over_notes ((void*) this, &sdt_query::setup_note_probe_entry_callback);
6048 }
d61ea602 6049 else if (probe_loc == probe_section)
40fe32e0 6050 iterate_over_probe_entries ();
edce5b67
JS
6051}
6052
6053
6054bool
6055sdt_query::init_probe_scn()
6056{
448a86b7 6057 Elf* elf;
edce5b67 6058 GElf_Shdr shdr_mem;
40fe32e0
SC
6059
6060 GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
6061 if (shdr)
6062 {
6063 probe_loc = note_section;
6064 return true;
6065 }
edce5b67 6066
448a86b7 6067 shdr = dw.get_section (".probes", &shdr_mem, &elf);
fea74777 6068 if (shdr)
edce5b67 6069 {
fea74777
SC
6070 pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
6071 probe_scn_offset = 0;
6072 probe_scn_addr = shdr->sh_addr;
6073 assert (pdata != NULL);
6074 if (sess.verbose > 4)
ce0f6648
LB
6075 clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
6076 << pdata->d_size << endl;
40fe32e0 6077 probe_loc = probe_section;
fea74777 6078 return true;
edce5b67 6079 }
fea74777 6080 else
edce5b67 6081 return false;
edce5b67
JS
6082}
6083
40fe32e0
SC
6084void
6085sdt_query::setup_note_probe_entry_callback (void *object, int type, const char *data, size_t len)
6086{
6087 sdt_query *me = (sdt_query*)object;
6088 me->setup_note_probe_entry (type, data, len);
6089}
6090
6091
6092void
6093sdt_query::setup_note_probe_entry (int type, const char *data, size_t len)
6094{
6095 // if (nhdr.n_namesz == sizeof _SDT_NOTE_NAME
6096 // && !memcmp (data->d_buf + name_off,
6097 // _SDT_NOTE_NAME, sizeof _SDT_NOTE_NAME))
6098
6099 // probes are in the .note.stapsdt section
6100#define _SDT_NOTE_TYPE 3
6101 if (type != _SDT_NOTE_TYPE)
6102 return;
6103
6104 union
6105 {
6106 Elf64_Addr a64[3];
6107 Elf32_Addr a32[3];
6108 } buf;
6109 Dwarf_Addr bias;
6110 Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
6111 Elf_Data dst =
6112 {
6113 &buf, ELF_T_ADDR, EV_CURRENT,
6114 gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
6115 };
6116 assert (dst.d_size <= sizeof buf);
6117
6118 if (len < dst.d_size + 3)
6119 return;
6120
6121 Elf_Data src =
6122 {
6123 (void *) data, ELF_T_ADDR, EV_CURRENT,
6124 dst.d_size, 0, 0
6125 };
6126
6127 if (gelf_xlatetom (elf, &dst, &src,
6128 elf_getident (elf, NULL)[EI_DATA]) == NULL)
6129 printf ("gelf_xlatetom: %s", elf_errmsg (-1));
6130
6131 probe_type = uprobe3_type;
6132 const char * provider = data + dst.d_size;
3f803f9e 6133
40fe32e0 6134 const char *name = (const char*)memchr (provider, '\0', data + len - provider);
3f803f9e
CM
6135 if(name++ == NULL)
6136 return;
6137
6138 const char *args = (const char*)memchr (name, '\0', data + len - name);
6139 if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
6140 return;
6141
6142 provider_name = provider;
6143 probe_name = name;
6144 arg_string = args;
40fe32e0
SC
6145
6146 // Did we find a matching probe?
6147 if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
6148 && ((pp_provider == "")
6149 || dw.function_name_matches_pattern (provider_name, pp_provider))))
6150 return;
6151
40fe32e0
SC
6152 arg_count = 0;
6153 for (unsigned i = 0; i < arg_string.length(); i++)
272c9036 6154 if (arg_string[i] == '@')
40fe32e0 6155 arg_count += 1;
40fe32e0
SC
6156
6157 GElf_Addr base_ref;
6158 if (gelf_getclass (elf) == ELFCLASS32)
6159 {
6160 pc = buf.a32[0];
6161 base_ref = buf.a32[1];
6162 semaphore = buf.a32[2];
6163 }
6164 else
6165 {
6166 pc = buf.a64[0];
6167 base_ref = buf.a64[1];
6168 semaphore = buf.a64[2];
6169 }
6170
6171 semaphore += base - base_ref;
6172 pc += base - base_ref;
6173
7d395255
JS
6174 // The semaphore also needs the ELF bias added now, so
6175 // record_semaphore can properly relocate it later.
6176 semaphore += bias;
6177
40fe32e0 6178 if (sess.verbose > 4)
b530b5b3 6179 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
6180
6181 handle_probe_entry();
6182}
6183
6184
c57ea854
SC
6185void
6186sdt_query::iterate_over_probe_entries()
edce5b67 6187{
c57ea854 6188 // probes are in the .probe section
edce5b67
JS
6189 while (probe_scn_offset < pdata->d_size)
6190 {
aff5d390
SC
6191 stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
6192 stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
15284963 6193 probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
1cc41cd6 6194 if (! have_uprobe())
edce5b67
JS
6195 {
6196 // Unless this is a mangled .probes section, this happens
6197 // because the name of the probe comes first, followed by
6198 // the sentinel.
6199 if (sess.verbose > 5)
b530b5b3 6200 clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
edce5b67
JS
6201 probe_scn_offset += sizeof(__uint32_t);
6202 continue;
6203 }
aff5d390
SC
6204 if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
6205 {
6206 pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
1cc41cd6 6207 if (pbe_v1->type_b != uprobe1_type)
aff5d390
SC
6208 continue;
6209 }
6210
1cc41cd6 6211 if (probe_type == uprobe1_type)
aff5d390 6212 {
79a0ca08 6213 if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6214 return;
79a0ca08 6215 semaphore = 0;
aff5d390 6216 probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
a794dbeb 6217 provider_name = ""; // unknown
1cc41cd6
DS
6218 pc = pbe_v1->arg;
6219 arg_count = 0;
aff5d390
SC
6220 probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
6221 }
08b5a50c 6222 else if (probe_type == uprobe2_type)
aff5d390 6223 {
79a0ca08 6224 if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
c57ea854 6225 return;
79a0ca08 6226 semaphore = pbe_v2->semaphore;
aff5d390 6227 probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
a794dbeb 6228 provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
aff5d390
SC
6229 arg_count = pbe_v2->arg_count;
6230 pc = pbe_v2->pc;
6231 if (pbe_v2->arg_string)
6232 arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
79a0ca08
SC
6233 // skip over pbe_v2, probe_name text and provider text
6234 probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
6235 probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
aff5d390 6236 }
edce5b67 6237 if (sess.verbose > 4)
b530b5b3 6238 clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
aff5d390 6239 << "@0x" << hex << pc << dec << endl;
edce5b67 6240
a794dbeb
FCE
6241 if (dw.function_name_matches_pattern (probe_name, pp_mark)
6242 && ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
c57ea854 6243 handle_probe_entry ();
edce5b67 6244 }
edce5b67
JS
6245}
6246
6247
6846cfc8 6248void
4ddb6dd0 6249sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
6846cfc8 6250{
a794dbeb
FCE
6251 for (unsigned i=0; i<2; i++) {
6252 // prefer with-provider symbol; look without provider prefix for backward compatibility only
6253 string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
6254 // XXX: multiple addresses?
6255 if (sess.verbose > 2)
b530b5b3 6256 clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
a794dbeb 6257
79a0ca08
SC
6258 Dwarf_Addr addr;
6259 if (this->semaphore)
6260 addr = this->semaphore;
6261 else
6262 addr = lookup_symbol_address(dw.module, semaphore.c_str());
a794dbeb
FCE
6263 if (addr)
6264 {
7d395255 6265 if (dwfl_module_relocations (dw.module) > 0)
a794dbeb
FCE
6266 dwfl_module_relocate_address (dw.module, &addr);
6267 // XXX: relocation basis?
6268 for (unsigned i = start; i < results.size(); ++i)
6269 results[i]->sdt_semaphore_addr = addr;
6270 if (sess.verbose > 2)
b530b5b3 6271 clog << _(", found at 0x") << hex << addr << dec << endl;
a794dbeb
FCE
6272 return;
6273 }
6274 else
6275 if (sess.verbose > 2)
b530b5b3 6276 clog << _(", not found") << endl;
a794dbeb 6277 }
6846cfc8
SC
6278}
6279
6280
edce5b67
JS
6281void
6282sdt_query::convert_probe (probe *base)
6283{
6284 block *b = new block;
6285 b->tok = base->body->tok;
6286
edce5b67
JS
6287 // Generate: if (arg1 != mark("label")) next;
6288 functioncall *fc = new functioncall;
bbafcb1e 6289 fc->function = "ulong_arg";
edce5b67 6290 fc->tok = b->tok;
bbafcb1e 6291 literal_number* num = new literal_number(1);
edce5b67
JS
6292 num->tok = b->tok;
6293 fc->args.push_back(num);
6294
6295 functioncall *fcus = new functioncall;
6296 fcus->function = "user_string";
6297 fcus->type = pe_string;
6298 fcus->tok = b->tok;
6299 fcus->args.push_back(fc);
6300
6301 if_statement *is = new if_statement;
6302 is->thenblock = new next_statement;
6303 is->elseblock = NULL;
6304 is->tok = b->tok;
63ea4244 6305 is->thenblock->tok = b->tok;
edce5b67
JS
6306 comparison *be = new comparison;
6307 be->op = "!=";
6308 be->tok = b->tok;
6309 be->left = fcus;
6310 be->right = new literal_string(probe_name);
63ea4244 6311 be->right->tok = b->tok;
edce5b67
JS
6312 is->condition = be;
6313 b->statements.push_back(is);
6314
6315 // Now replace the body
6316 b->statements.push_back(base->body);
6317 base->body = b;
6318}
6319
6320
c72aa911
JS
6321probe*
6322sdt_query::convert_location ()
edce5b67 6323{
c72aa911 6324 probe_point* specific_loc = new probe_point(*base_loc);
662539d9 6325 vector<probe_point::component*> derived_comps;
edce5b67 6326
662539d9
JS
6327 vector<probe_point::component*>::iterator it;
6328 for (it = specific_loc->components.begin();
6329 it != specific_loc->components.end(); ++it)
6330 if ((*it)->functor == TOK_PROCESS)
6331 {
1cc41cd6
DS
6332 // copy the process name
6333 derived_comps.push_back(*it);
662539d9
JS
6334 }
6335 else if ((*it)->functor == TOK_LIBRARY)
6336 {
1cc41cd6
DS
6337 // copy the library name for process probes
6338 derived_comps.push_back(*it);
662539d9
JS
6339 }
6340 else if ((*it)->functor == TOK_PROVIDER)
6341 {
6342 // replace the possibly wildcarded arg with the specific provider name
6343 *it = new probe_point::component(TOK_PROVIDER,
6344 new literal_string(provider_name));
6345 }
6346 else if ((*it)->functor == TOK_MARK)
c72aa911
JS
6347 {
6348 // replace the possibly wildcarded arg with the specific marker name
662539d9
JS
6349 *it = new probe_point::component(TOK_MARK,
6350 new literal_string(probe_name));
a794dbeb 6351
aff5d390
SC
6352 if (sess.verbose > 3)
6353 switch (probe_type)
6354 {
6355 case uprobe1_type:
b530b5b3 6356 clog << _("probe_type == uprobe1, use statement addr: 0x")
aff5d390
SC
6357 << hex << pc << dec << endl;
6358 break;
6359 case uprobe2_type:
b530b5b3 6360 clog << _("probe_type == uprobe2, use statement addr: 0x")
aff5d390
SC
6361 << hex << pc << dec << endl;
6362 break;
40fe32e0 6363 case uprobe3_type:
b530b5b3 6364 clog << _("probe_type == uprobe3, use statement addr: 0x")
40fe32e0
SC
6365 << hex << pc << dec << endl;
6366 break;
aff5d390 6367 default:
b530b5b3
LB
6368 clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
6369 pp_mark.c_str()) << endl;
aff5d390
SC
6370 }
6371
c72aa911
JS
6372 switch (probe_type)
6373 {
aff5d390
SC
6374 case uprobe1_type:
6375 case uprobe2_type:
40fe32e0 6376 case uprobe3_type:
c72aa911 6377 // process("executable").statement(probe_arg)
662539d9
JS
6378 derived_comps.push_back
6379 (new probe_point::component(TOK_STATEMENT,
6380 new literal_number(pc, true)));
c72aa911
JS
6381 break;
6382
a794dbeb 6383 default: // deprecated
c72aa911 6384 // process("executable").function("*").label("_stapprobe1_MARK_NAME")
662539d9
JS
6385 derived_comps.push_back
6386 (new probe_point::component(TOK_FUNCTION,
6387 new literal_string("*")));
6388 derived_comps.push_back
c72aa911 6389 (new probe_point::component(TOK_LABEL,
a794dbeb 6390 new literal_string("_stapprobe1_" + pp_mark)));
c72aa911
JS
6391 break;
6392 }
6393 }
edce5b67 6394
662539d9
JS
6395 probe_point* derived_loc = new probe_point(*specific_loc);
6396 derived_loc->components = derived_comps;
c72aa911 6397 return base_probe->create_alias(derived_loc, specific_loc);
edce5b67
JS
6398}
6399
6400
51d6bda3
SC
6401void
6402sdt_query::query_library (const char *library)
6403{
6404 query_one_library (library, dw, user_lib, base_probe, base_loc, results);
6405}
6406
6407
20c6c071 6408void
5227f1ea 6409dwarf_builder::build(systemtap_session & sess,
7a053d3b 6410 probe * base,
20c6c071 6411 probe_point * location,
86bf665e 6412 literal_map_t const & parameters,
20c6c071
GH
6413 vector<derived_probe *> & finished_results)
6414{
b20febf3
FCE
6415 // NB: the kernel/user dwlfpp objects are long-lived.
6416 // XXX: but they should be per-session, as this builder object
6417 // may be reused if we try to cross-instrument multiple targets.
84048984 6418
7a24d422 6419 dwflpp* dw = 0;
6d5d594e 6420 literal_map_t filled_parameters = parameters;
7a24d422 6421
7a24d422 6422 string module_name;
ae2552da
FCE
6423 if (has_null_param (parameters, TOK_KERNEL))
6424 {
6425 dw = get_kern_dw(sess, "kernel");
6426 }
6427 else if (get_param (parameters, TOK_MODULE, module_name))
b8da0ad1 6428 {
c523a015
LB
6429 size_t dash_pos = 0;
6430 while((dash_pos=module_name.find('-'))!=string::npos)
6431 module_name.replace(int(dash_pos),1,"_");
6432 filled_parameters[TOK_MODULE] = new literal_string(module_name);
37001baa
FCE
6433 // NB: glob patterns get expanded later, during the offline
6434 // elfutils module listing.
ae2552da 6435 dw = get_kern_dw(sess, module_name);
b8da0ad1 6436 }
6d5d594e 6437 else if (get_param (parameters, TOK_PROCESS, module_name) || has_null_param(parameters, TOK_PROCESS))
84c84ac4 6438 {
05fb3e0c 6439 module_name = sess.sysroot + module_name;
6d5d594e
LB
6440 if(has_null_param(filled_parameters, TOK_PROCESS))
6441 {
6442 wordexp_t words;
6443 int rc = wordexp(sess.cmd.c_str(), &words, WRDE_NOCMD|WRDE_UNDEF);
6444 if(rc || words.we_wordc <= 0)
6445 throw semantic_error(_("unspecified process probe is invalid without a -c COMMAND"));
05fb3e0c 6446 module_name = sess.sysroot + words.we_wordv[0];
6d5d594e
LB
6447 filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
6448 // in the case of TOK_MARK we need to modify locations as well
6449 if(location->components[0]->functor==TOK_PROCESS &&
6450 location->components[0]->arg == 0)
6451 location->components[0]->arg = new literal_string(module_name);
6452 wordfree (& words);
6453 }
5750ecc6 6454
37001baa
FCE
6455 // PR6456 process("/bin/*") glob handling
6456 if (contains_glob_chars (module_name))
6457 {
6458 // Expand glob via rewriting the probe-point process("....")
6459 // parameter, asserted to be the first one.
6460
6461 assert (location->components.size() > 0);
6462 assert (location->components[0]->functor == TOK_PROCESS);
6463 assert (location->components[0]->arg);
6464 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6465 assert (lit);
6466
6467 // Evaluate glob here, and call derive_probes recursively with each match.
6468 glob_t the_blob;
6469 int rc = glob (module_name.c_str(), 0, NULL, & the_blob);
b530b5b3
LB
6470 if (rc)
6471 throw semantic_error (_F("glob %s error (%s)", module_name.c_str(), lex_cast(rc).c_str() ));
37001baa
FCE
6472 for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
6473 {
e19ebcf7 6474 assert_no_interrupts();
37001baa
FCE
6475
6476 const char* globbed = the_blob.gl_pathv[i];
6477 struct stat st;
6478
6479 if (access (globbed, X_OK) == 0
6480 && stat (globbed, &st) == 0
6481 && S_ISREG (st.st_mode)) // see find_executable()
6482 {
7977a734
FCE
6483 // Need to call canonicalize here, in order to path-expand
6484 // patterns like process("stap*"). Otherwise it may go through
6485 // to the next round of expansion as ("stap"), leading to a $PATH
6486 // search that's not consistent with the glob search already done.
6487
6488 char *cf = canonicalize_file_name (globbed);
6489 if (cf) globbed = cf;
6490
37001baa
FCE
6491 // synthesize a new probe_point, with the glob-expanded string
6492 probe_point *pp = new probe_point (*location);
5750ecc6
FCE
6493 // PR13338: quote results to prevent recursion
6494 string eglobbed = escape_glob_chars (globbed);
6495
6496 if (sess.verbose > 1)
6497 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6498 module_name.c_str(), eglobbed.c_str()) << endl;
05fb3e0c 6499 string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
5750ecc6 6500
37001baa 6501 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6502 new literal_string (eglobbed_tgt));
37001baa
FCE
6503 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6504 pp->components[0] = ppc;
6505
7977a734
FCE
6506 probe* new_probe = new probe (*base, pp);
6507
6508 // We override "optional = true" here, as if the
6509 // wildcarded probe point was given a "?" suffix.
6510
6511 // This is because wildcard probes will be expected
6512 // by users to apply only to some subset of the
6513 // matching binaries, in the sense of "any", rather
6514 // than "all", sort of similarly how
6515 // module("*").function("...") patterns work.
6516
6517 derive_probes (sess, new_probe, finished_results,
6518 true /* NB: not location->optional */ );
37001baa
FCE
6519 }
6520 }
6521
6522 globfree (& the_blob);
6523 return; // avoid falling through
6524 }
6525
5750ecc6
FCE
6526 // PR13338: unquote glob results
6527 module_name = unescape_glob_chars (module_name);
05fb3e0c 6528 user_path = find_executable (module_name, "", sess.sysenv); // canonicalize it
d1bcbe71
RH
6529
6530 // if the executable starts with "#!", we look for the interpreter of the script
6531 {
6532 ifstream script_file (user_path.c_str () );
6533
6534 if (script_file.good ())
6535 {
6536 string line;
6537
6538 getline (script_file, line);
6539
6540 if (line.compare (0, 2, "#!") == 0)
6541 {
6542 string path_head = line.substr(2);
6543
6544 // remove white spaces at the beginning of the string
6545 size_t p2 = path_head.find_first_not_of(" \t");
6546
6547 if (p2 != string::npos)
6548 {
6549 string path = path_head.substr(p2);
6550
6551 // remove white spaces at the end of the string
6552 p2 = path.find_last_not_of(" \t\n");
6553 if (string::npos != p2)
6554 path.erase(p2+1);
6555
8e13c1a1
RH
6556 // handle "#!/usr/bin/env" redirect
6557 size_t offset = 0;
6558 if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
6559 {
6560 offset = sizeof("/bin/env")-1;
6561 }
6562 else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
6563 {
6564 offset = sizeof("/usr/bin/env")-1;
6565 }
6566
6567 if (offset != 0)
6568 {
6569 size_t p3 = path.find_first_not_of(" \t", offset);
6570
6571 if (p3 != string::npos)
6572 {
6573 string env_path = path.substr(p3);
05fb3e0c
WF
6574 user_path = find_executable (env_path, sess.sysroot,
6575 sess.sysenv);
8e13c1a1
RH
6576 }
6577 }
6578 else
6579 {
05fb3e0c 6580 user_path = find_executable (path, sess.sysroot, sess.sysenv);
8e13c1a1 6581 }
d1bcbe71
RH
6582
6583 struct stat st;
6584
6585 if (access (user_path.c_str(), X_OK) == 0
6586 && stat (user_path.c_str(), &st) == 0
6587 && S_ISREG (st.st_mode)) // see find_executable()
6588 {
6589 if (sess.verbose > 1)
b530b5b3
LB
6590 clog << _F("Expanded process(\"%s\") to process(\"%s\")",
6591 module_name.c_str(), user_path.c_str()) << endl;
d1bcbe71
RH
6592
6593 assert (location->components.size() > 0);
6594 assert (location->components[0]->functor == TOK_PROCESS);
6595 assert (location->components[0]->arg);
6596 literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
6597 assert (lit);
6598
6599 // synthesize a new probe_point, with the expanded string
6600 probe_point *pp = new probe_point (*location);
05fb3e0c 6601 string user_path_tgt = path_remove_sysroot(sess, user_path);
d1bcbe71 6602 probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
05fb3e0c 6603 new literal_string (user_path_tgt.c_str()));
d1bcbe71
RH
6604 ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
6605 pp->components[0] = ppc;
6606
6607 probe* new_probe = new probe (*base, pp);
6608
6609 derive_probes (sess, new_probe, finished_results);
6610
6611 script_file.close();
6612 return;
6613 }
6614 }
6615 }
6616 }
6617 script_file.close();
6618 }
6619
47e226ed 6620 if (get_param (parameters, TOK_LIBRARY, user_lib)
378d78b5 6621 && user_lib.length() && ! contains_glob_chars (user_lib))
47e226ed
SC
6622 {
6623 module_name = find_executable (user_lib, sess.sysroot, sess.sysenv,
6624 "LD_LIBRARY_PATH");
6625 if (module_name.find('/') == string::npos)
6626 // We didn't find user_lib so use iterate_over_libraries
6627 module_name = user_path;
6628 }
63b4fd14 6629 else
b642c901 6630 module_name = user_path; // canonicalize it
d0a7f5a9 6631
2b69faaf
JS
6632 if (kernel_supports_inode_uprobes(sess))
6633 {
64e807c2 6634 // XXX: autoconf this?
2b69faaf
JS
6635 if (has_null_param(parameters, TOK_RETURN))
6636 throw semantic_error
6637 (_("process return probes not available with inode-based uprobes"));
6638 }
f4000852
MW
6639 // There is a similar check in pass 4 (buildrun), but it is
6640 // needed here too to make sure alternatives for optional
6641 // (? or !) process probes are disposed and/or alternatives
6642 // are selected.
5261f7ab 6643 check_process_probe_kernel_support(sess);
e34d5d13 6644
7a24d422
FCE
6645 // user-space target; we use one dwflpp instance per module name
6646 // (= program or shared library)
707bf35e 6647 dw = get_user_dw(sess, module_name);
c8959a29 6648 }
20c6c071 6649
5896cd05 6650 if (sess.verbose > 3)
b530b5b3 6651 clog << _F("dwarf_builder::build for %s", module_name.c_str()) << endl;
5896cd05 6652
a794dbeb
FCE
6653 string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
6654 if (get_param(parameters, TOK_MARK, dummy_mark_name))
f28a8c28 6655 {
d8f31d0a 6656 assert(dw);
51d6bda3 6657 sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
edce5b67
JS
6658 dw->iterate_over_modules(&query_module, &sdtq);
6659 return;
7a05f484 6660 }
20c6c071 6661
8f14e444 6662 unsigned results_pre = finished_results.size();
6d5d594e 6663 dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
7a24d422
FCE
6664
6665 // XXX: kernel.statement.absolute is a special case that requires no
6666 // dwfl processing. This code should be in a separate builder.
7a24d422 6667 if (q.has_kernel && q.has_absolute)
37ebca01 6668 {
4baf0e53 6669 // assert guru mode for absolute probes
37ebca01
FCE
6670 if (! q.base_probe->privileged)
6671 {
e3bbc038 6672 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"),
edce5b67 6673 q.base_probe->tok);
37ebca01
FCE
6674 }
6675
6676 // For kernel.statement(NUM).absolute probe points, we bypass
6677 // all the debuginfo stuff: We just wire up a
6678 // dwarf_derived_probe right here and now.
4baf0e53 6679 dwarf_derived_probe* p =
b8da0ad1
FCE
6680 new dwarf_derived_probe ("", "", 0, "kernel", "",
6681 q.statement_num_val, q.statement_num_val,
6682 q, 0);
37ebca01 6683 finished_results.push_back (p);
1a0dbc5a 6684 sess.unwindsym_modules.insert ("kernel");
37ebca01
FCE
6685 return;
6686 }
6687
51178501 6688 dw->iterate_over_modules(&query_module, &q);
8f14e444
FCE
6689
6690
6691 // PR11553 special processing: .return probes requested, but
6692 // some inlined function instances matched.
6693 unsigned i_n_r = q.inlined_non_returnable.size();
6694 unsigned results_post = finished_results.size();
6695 if (i_n_r > 0)
6696 {
6697 if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
6698 {
6699 string quicklist;
6700 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6701 it != q.inlined_non_returnable.end();
6702 it++)
6703 {
6704 quicklist += " " + (*it);
6705 if (quicklist.size() > 80) // heuristic, don't make an overlong report line
6706 {
6707 quicklist += " ...";
6708 break;
6709 }
6710 }
c57ea854 6711
b530b5b3
LB
6712 sess.print_warning (_F(ngettext("cannot probe .return of %u inlined function %s",
6713 "cannot probe .return of %u inlined functions %s",
6714 quicklist.size()), i_n_r, quicklist.c_str()));
8f14e444
FCE
6715 // There will be also a "no matches" semantic error generated.
6716 }
6717 if (sess.verbose > 1)
b530b5b3
LB
6718 clog << _F(ngettext("skipped .return probe of %u inlined function",
6719 "skipped .return probe of %u inlined functions", i_n_r), i_n_r) << endl;
8f14e444
FCE
6720 if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
6721 {
6722 for (set<string>::iterator it = q.inlined_non_returnable.begin();
6723 it != q.inlined_non_returnable.end();
6724 it++)
6725 clog << (*it) << " ";
6726 clog << endl;
6727 }
6728 } // i_n_r > 0
5f0a03a6
JK
6729}
6730
6731symbol_table::~symbol_table()
6732{
c9efa5c9 6733 delete_map(map_by_addr);
5f0a03a6
JK
6734}
6735
6736void
2867a2a1 6737symbol_table::add_symbol(const char *name, bool weak, bool descriptor,
822a6a3d 6738 Dwarf_Addr addr, Dwarf_Addr */*high_addr*/)
5f0a03a6 6739{
ab91b232
JK
6740#ifdef __powerpc__
6741 // Map ".sys_foo" to "sys_foo".
6742 if (name[0] == '.')
6743 name++;
6744#endif
5f0a03a6
JK
6745 func_info *fi = new func_info();
6746 fi->addr = addr;
6747 fi->name = name;
ab91b232 6748 fi->weak = weak;
2867a2a1 6749 fi->descriptor = descriptor;
5f0a03a6
JK
6750 map_by_name[fi->name] = fi;
6751 // TODO: Use a multimap in case there are multiple static
6752 // functions with the same name?
1c6b77e5 6753 map_by_addr.insert(make_pair(addr, fi));
5f0a03a6
JK
6754}
6755
6756enum info_status
6757symbol_table::read_symbols(FILE *f, const string& path)
6758{
6759 // Based on do_kernel_symbols() in runtime/staprun/symbols.c
6760 int ret;
2e67a43b
TM
6761 char *name = 0;
6762 char *mod = 0;
5f0a03a6
JK
6763 char type;
6764 unsigned long long addr;
6765 Dwarf_Addr high_addr = 0;
6766 int line = 0;
6767
6768 // %as (non-POSIX) mallocs space for the string and stores its address.
6769 while ((ret = fscanf(f, "%llx %c %as [%as", &addr, &type, &name, &mod)) > 0)
6770 {
2e67a43b
TM
6771 auto_free free_name(name);
6772 auto_free free_mod(mod);
5f0a03a6
JK
6773 line++;
6774 if (ret < 3)
6775 {
3d372d6b 6776 cerr << _F("Symbol table error: Line %d of symbol list from %s is not in correct format: address type name [module]\n",
b530b5b3 6777 line, path.c_str());
5f0a03a6
JK
6778 // Caller should delete symbol_table object.
6779 return info_absent;
6780 }
2e67a43b 6781 else if (ret > 3)
5f0a03a6
JK
6782 {
6783 // Modules are loaded above the kernel, so if we're getting
6784 // modules, we're done.
2e67a43b 6785 break;
5f0a03a6 6786 }
ab91b232 6787 if (type == 'T' || type == 't' || type == 'W')
2867a2a1 6788 add_symbol(name, (type == 'W'), false, (Dwarf_Addr) addr, &high_addr);
5f0a03a6
JK
6789 }
6790
1c6b77e5 6791 if (map_by_addr.size() < 1)
5f0a03a6 6792 {
3d372d6b 6793 cerr << _F("Symbol table error: %s contains no function symbols.\n",
b530b5b3 6794 path.c_str()) << endl;
5f0a03a6
JK
6795 return info_absent;
6796 }
6797 return info_present;
6798}
6799
6800// NB: This currently unused. We use get_from_elf() instead because
6801// that gives us raw addresses -- which we need for modules -- whereas
6802// nm provides the address relative to the beginning of the section.
6803enum info_status
83ca3872 6804symbol_table::read_from_elf_file(const string &path,
2713ea24 6805 systemtap_session &sess)
5f0a03a6 6806{
58502ae4
JS
6807 vector<string> cmd;
6808 cmd.push_back("/usr/bin/nm");
6809 cmd.push_back("-n");
6810 cmd.push_back("--defined-only");
6811 cmd.push_back("path");
6812
5f0a03a6 6813 FILE *f;
58502ae4
JS
6814 int child_fd;
6815 pid_t child = stap_spawn_piped(sess.verbose, cmd, NULL, &child_fd);
6816 if (child <= 0 || !(f = fdopen(child_fd, "r")))
5f0a03a6 6817 {
58502ae4 6818 // nm failures are detected by stap_waitpid
3d372d6b 6819 cerr << _F("Internal error reading symbol table from %s -- %s\n",
b530b5b3 6820 path.c_str(), strerror(errno));
5f0a03a6
JK
6821 return info_absent;
6822 }
6823 enum info_status status = read_symbols(f, path);
58502ae4 6824 if (fclose(f) || stap_waitpid(sess.verbose, child))
5f0a03a6 6825 {
2713ea24
CM
6826 if (status == info_present)
6827 sess.print_warning("nm cannot read symbol table from " + path);
5f0a03a6
JK
6828 return info_absent;
6829 }
6830 return status;
6831}
6832
6833enum info_status
83ca3872 6834symbol_table::read_from_text_file(const string& path,
2713ea24 6835 systemtap_session &sess)
5f0a03a6
JK
6836{
6837 FILE *f = fopen(path.c_str(), "r");
6838 if (!f)
6839 {
2713ea24 6840 sess.print_warning("cannot read symbol table from " + path + " -- " + strerror(errno));
5f0a03a6
JK
6841 return info_absent;
6842 }
6843 enum info_status status = read_symbols(f, path);
6844 (void) fclose(f);
6845 return status;
6846}
6847
46f7b6be 6848void
f98c6346 6849symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
46f7b6be
JK
6850{
6851#ifdef __powerpc__
6852 /*
6853 * The .opd section contains function descriptors that can look
6854 * just like function entry points. For example, there's a function
6855 * descriptor called "do_exit" that links to the entry point ".do_exit".
6856 * Reject all symbols in .opd.
6857 */
6858 opd_section = SHN_UNDEF;
6859 Dwarf_Addr bias;
6860 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
6861 ?: dwfl_module_getelf (mod, &bias));
6862 Elf_Scn* scn = 0;
6863 size_t shstrndx;
6864
6865 if (!elf)
6866 return;
fcc30d6d 6867 if (elf_getshdrstrndx (elf, &shstrndx) != 0)
46f7b6be
JK
6868 return;
6869 while ((scn = elf_nextscn(elf, scn)) != NULL)
6870 {
6871 GElf_Shdr shdr_mem;
6872 GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
6873 if (!shdr)
6874 continue;
6875 const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
6876 if (!strcmp(name, ".opd"))
6877 {
6878 opd_section = elf_ndxscn(scn);
6879 return;
6880 }
6881 }
6882#endif
6883}
6884
6885bool
6886symbol_table::reject_section(GElf_Word section)
6887{
6888 if (section == SHN_UNDEF)
6889 return true;
6890#ifdef __powerpc__
6891 if (section == opd_section)
6892 return true;
6893#endif
6894 return false;
6895}
6896
5f0a03a6
JK
6897enum info_status
6898symbol_table::get_from_elf()
6899{
6900 Dwarf_Addr high_addr = 0;
6901 Dwfl_Module *mod = mod_info->mod;
6902 int syments = dwfl_module_getsymtab(mod);
6903 assert(syments);
46f7b6be 6904 prepare_section_rejection(mod);
5f0a03a6
JK
6905 for (int i = 1; i < syments; ++i)
6906 {
6907 GElf_Sym sym;
ab91b232
JK
6908 GElf_Word section;
6909 const char *name = dwfl_module_getsym(mod, i, &sym, &section);
2867a2a1 6910 if (name && GELF_ST_TYPE(sym.st_info) == STT_FUNC)
ab91b232 6911 add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
2867a2a1 6912 reject_section(section), sym.st_value, &high_addr);
5f0a03a6
JK
6913 }
6914 return info_present;
6915}
6916
5f0a03a6
JK
6917func_info *
6918symbol_table::get_func_containing_address(Dwarf_Addr addr)
6919{
1c6b77e5
JS
6920 iterator_t iter = map_by_addr.upper_bound(addr);
6921 if (iter == map_by_addr.begin())
5f0a03a6 6922 return NULL;
2e67a43b 6923 else
1c6b77e5 6924 return (--iter)->second;
5f0a03a6
JK
6925}
6926
3d372d6b
SC
6927func_info *
6928symbol_table::get_first_func()
6929{
6930 iterator_t iter = map_by_addr.begin();
6931 return (iter)->second;
6932}
6933
5f0a03a6
JK
6934func_info *
6935symbol_table::lookup_symbol(const string& name)
6936{
6937 map<string, func_info*>::iterator i = map_by_name.find(name);
6938 if (i == map_by_name.end())
6939 return NULL;
6940 return i->second;
6941}
6942
6943Dwarf_Addr
6944symbol_table::lookup_symbol_address(const string& name)
6945{
6946 func_info *fi = lookup_symbol(name);
6947 if (fi)
6948 return fi->addr;
6949 return 0;
6950}
6951
ab91b232
JK
6952// This is the kernel symbol table. The kernel macro cond_syscall creates
6953// a weak symbol for each system call and maps it to sys_ni_syscall.
6954// For system calls not implemented elsewhere, this weak symbol shows up
6955// in the kernel symbol table. Following the precedent of dwarfful stap,
6956// we refuse to consider such symbols. Here we delete them from our
6957// symbol table.
6958// TODO: Consider generalizing this and/or making it part of blacklist
6959// processing.
6960void
6961symbol_table::purge_syscall_stubs()
6962{
6963 Dwarf_Addr stub_addr = lookup_symbol_address("sys_ni_syscall");
6964 if (stub_addr == 0)
6965 return;
1c6b77e5 6966 range_t purge_range = map_by_addr.equal_range(stub_addr);
2e67a43b
TM
6967 for (iterator_t iter = purge_range.first;
6968 iter != purge_range.second;
1c6b77e5 6969 )
ab91b232 6970 {
1c6b77e5 6971 func_info *fi = iter->second;
2e67a43b 6972 if (fi->weak && fi->name != "sys_ni_syscall")
ab91b232 6973 {
2e67a43b 6974 map_by_name.erase(fi->name);
1c6b77e5 6975 map_by_addr.erase(iter++);
2e67a43b 6976 delete fi;
2e67a43b 6977 }
1c6b77e5
JS
6978 else
6979 iter++;
ab91b232
JK
6980 }
6981}
6982
5f0a03a6
JK
6983void
6984module_info::get_symtab(dwarf_query *q)
6985{
6986 systemtap_session &sess = q->sess;
6987
1c6b77e5
JS
6988 if (symtab_status != info_unknown)
6989 return;
6990
5f0a03a6
JK
6991 sym_table = new symbol_table(this);
6992 if (!elf_path.empty())
6993 {
2713ea24
CM
6994 if (name == TOK_KERNEL && !sess.kernel_symtab_path.empty())
6995 sess.print_warning("reading symbol table from " + elf_path + " -- ignoring " + sess.kernel_symtab_path.c_str());
5f0a03a6
JK
6996 symtab_status = sym_table->get_from_elf();
6997 }
6998 else
6999 {
7000 assert(name == TOK_KERNEL);
7001 if (sess.kernel_symtab_path.empty())
7002 {
7003 symtab_status = info_absent;
3d372d6b 7004 cerr << _("Error: Cannot find vmlinux.\n"
b530b5b3 7005 " Consider using --kmap instead of --kelf.")
5f0a03a6
JK
7006 << endl;;
7007 }
7008 else
7009 {
7010 symtab_status =
83ca3872 7011 sym_table->read_from_text_file(sess.kernel_symtab_path, sess);
5f0a03a6
JK
7012 if (symtab_status == info_present)
7013 {
7014 sess.sym_kprobes_text_start =
7015 sym_table->lookup_symbol_address("__kprobes_text_start");
7016 sess.sym_kprobes_text_end =
7017 sym_table->lookup_symbol_address("__kprobes_text_end");
7018 sess.sym_stext = sym_table->lookup_symbol_address("_stext");
5f0a03a6
JK
7019 }
7020 }
7021 }
7022 if (symtab_status == info_absent)
7023 {
7024 delete sym_table;
7025 sym_table = NULL;
7026 return;
7027 }
7028
ab91b232
JK
7029 if (name == TOK_KERNEL)
7030 sym_table->purge_syscall_stubs();
5f0a03a6
JK
7031}
7032
1c6b77e5
JS
7033// update_symtab reconciles data between the elf symbol table and the dwarf
7034// function enumeration. It updates the symbol table entries with the dwarf
7035// die that describes the function, which also signals to query_module_symtab
7036// that a statement probe isn't needed. In return, it also adds aliases to the
7037// function table for names that share the same addr/die.
7038void
7039module_info::update_symtab(cu_function_cache_t *funcs)
7040{
7041 if (!sym_table)
7042 return;
7043
7044 cu_function_cache_t new_funcs;
7045
7046 for (cu_function_cache_t::iterator func = funcs->begin();
7047 func != funcs->end(); func++)
7048 {
7049 // optimization: inlines will never be in the symbol table
7050 if (dwarf_func_inline(&func->second) != 0)
7051 continue;
7052
1ffb8bd1
JS
7053 // XXX We may want to make additional efforts to match mangled elf names
7054 // to dwarf too. MIPS_linkage_name can help, but that's sometimes
7055 // missing, so we may also need to try matching by address. See also the
7056 // notes about _Z in dwflpp::iterate_over_functions().
7057
1c6b77e5
JS
7058 func_info *fi = sym_table->lookup_symbol(func->first);
7059 if (!fi)
7060 continue;
7061
7062 // iterate over all functions at the same address
7063 symbol_table::range_t er = sym_table->map_by_addr.equal_range(fi->addr);
7064 for (symbol_table::iterator_t it = er.first; it != er.second; ++it)
7065 {
7066 // update this function with the dwarf die
7067 it->second->die = func->second;
7068
7069 // if this function is a new alias, then
7070 // save it to merge into the function cache
7071 if (it->second != fi)
b7478964 7072 new_funcs.insert(make_pair(it->second->name, it->second->die));
1c6b77e5
JS
7073 }
7074 }
7075
7076 // add all discovered aliases back into the function cache
7077 // NB: this won't replace any names that dwarf may have already found
7078 funcs->insert(new_funcs.begin(), new_funcs.end());
7079}
7080
5f0a03a6
JK
7081module_info::~module_info()
7082{
7083 if (sym_table)
7084 delete sym_table;
b55bc428
FCE
7085}
7086
935447c8 7087// ------------------------------------------------------------------------
888af770 7088// user-space probes
935447c8
DS
7089// ------------------------------------------------------------------------
7090
935447c8 7091
888af770 7092struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
935447c8 7093{
89ba3085
FCE
7094private:
7095 string make_pbm_key (uprobe_derived_probe* p) {
cfcab6c7 7096 return p->path + "|" + p->module + "|" + p->section + "|" + lex_cast(p->pid);
89ba3085
FCE
7097 }
7098
cfcab6c7
JS
7099 void emit_module_maxuprobes (systemtap_session& s);
7100
2b69faaf
JS
7101 // Using our own utrace-based uprobes
7102 void emit_module_utrace_decls (systemtap_session& s);
7103 void emit_module_utrace_init (systemtap_session& s);
7104 void emit_module_utrace_exit (systemtap_session& s);
7105
7106 // Using the upstream inode-based uprobes
7107 void emit_module_inode_decls (systemtap_session& s);
7108 void emit_module_inode_init (systemtap_session& s);
7109 void emit_module_inode_exit (systemtap_session& s);
7110
935447c8 7111public:
888af770 7112 void emit_module_decls (systemtap_session& s);
935447c8
DS
7113 void emit_module_init (systemtap_session& s);
7114 void emit_module_exit (systemtap_session& s);
7115};
7116
7117
888af770
FCE
7118void
7119uprobe_derived_probe::join_group (systemtap_session& s)
7120{
7121 if (! s.uprobe_derived_probes)
7122 s.uprobe_derived_probes = new uprobe_derived_probe_group ();
7123 s.uprobe_derived_probes->enroll (this);
93646f4d 7124 enable_task_finder(s);
a96d1db0 7125
8a03658e 7126 // Ask buildrun.cxx to build extra module if needed, and
d3e959b0
DS
7127 // signal staprun to load that module. If we're using the builtin
7128 // inode-uprobes, we still need to know that it is required.
8a03658e 7129 s.need_uprobes = true;
a96d1db0
DN
7130}
7131
888af770 7132
c0f84e7b
SC
7133void
7134uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
7135{
7136 dwarf_derived_probe::getargs(arg_set);
7137 arg_set.insert(arg_set.end(), args.begin(), args.end());
7138}
7139
7140
7141void
7142uprobe_derived_probe::saveargs(int nargs)
7143{
7144 for (int i = 1; i <= nargs; i++)
7145 args.push_back("$arg" + lex_cast (i) + ":long");
7146}
7147
7148
2865d17a 7149void
42e38653 7150uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
2865d17a
DB
7151{
7152 // These probes are allowed for unprivileged users, but only in the
7153 // context of processes which they own.
7154 emit_process_owner_assertion (o);
7155}
7156
7157
888af770 7158struct uprobe_builder: public derived_probe_builder
a96d1db0 7159{
888af770 7160 uprobe_builder() {}
2b69faaf 7161 virtual void build(systemtap_session & sess,
a96d1db0
DN
7162 probe * base,
7163 probe_point * location,
86bf665e 7164 literal_map_t const & parameters,
a96d1db0
DN
7165 vector<derived_probe *> & finished_results)
7166 {
888af770 7167 int64_t process, address;
a96d1db0 7168
2b69faaf
JS
7169 if (kernel_supports_inode_uprobes(sess))
7170 throw semantic_error (_("absolute process probes not available with inode-based uprobes"));
7171
888af770 7172 bool b1 = get_param (parameters, TOK_PROCESS, process);
ced347a9 7173 (void) b1;
888af770 7174 bool b2 = get_param (parameters, TOK_STATEMENT, address);
ced347a9 7175 (void) b2;
888af770
FCE
7176 bool rr = has_null_param (parameters, TOK_RETURN);
7177 assert (b1 && b2); // by pattern_root construction
a96d1db0 7178
0973d815 7179 finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
a96d1db0
DN
7180 }
7181};
7182
7183
7184void
cfcab6c7 7185uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
a96d1db0 7186{
43241c44
FCE
7187 // We'll probably need at least this many:
7188 unsigned minuprobes = probes.size();
7189 // .. but we don't want so many that .bss is inflated (PR10507):
7190 unsigned uprobesize = 64;
7191 unsigned maxuprobesmem = 10*1024*1024; // 10 MB
7192 unsigned maxuprobes = maxuprobesmem / uprobesize;
7193
aaf7ffe8
FCE
7194 // Let's choose a value on the geometric middle. This should end up
7195 // between minuprobes and maxuprobes. It's OK if this number turns
7196 // out to be < minuprobes or > maxuprobes. At worst, we get a
7197 // run-time error of one kind (too few: missed uprobe registrations)
7198 // or another (too many: vmalloc errors at module load time).
7199 unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
43241c44 7200
6d0f3f0c 7201 s.op->newline() << "#ifndef MAXUPROBES";
43241c44 7202 s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
6d0f3f0c 7203 s.op->newline() << "#endif";
cfcab6c7
JS
7204}
7205
7206
7207void
7208uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
7209{
7210 if (probes.empty()) return;
7211 s.op->newline() << "/* ---- utrace uprobes ---- */";
7212 // If uprobes isn't in the kernel, pull it in from the runtime.
7213
7214 s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
7215 s.op->newline() << "#include <linux/uprobes.h>";
7216 s.op->newline() << "#else";
2ba1736a 7217 s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
cfcab6c7
JS
7218 s.op->newline() << "#endif";
7219 s.op->newline() << "#ifndef UPROBES_API_VERSION";
7220 s.op->newline() << "#define UPROBES_API_VERSION 1";
7221 s.op->newline() << "#endif";
7222
7223 emit_module_maxuprobes (s);
a96d1db0 7224
cc52276b 7225 // Forward decls
2ba1736a 7226 s.op->newline() << "#include \"linux/uprobes-common.h\"";
cc52276b 7227
5e112f92
FCE
7228 // In .bss, the shared pool of uprobe/uretprobe structs. These are
7229 // too big to embed in the initialized .data stap_uprobe_spec array.
cc52276b
WC
7230 // XXX: consider a slab cache or somesuch for stap_uprobes
7231 s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
5e112f92 7232 s.op->newline() << "DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
a96d1db0 7233
89ba3085
FCE
7234 s.op->assert_0_indent();
7235
89ba3085
FCE
7236 // Assign task-finder numbers as we build up the stap_uprobe_tf table.
7237 // This means we process probes[] in two passes.
7238 map <string,unsigned> module_index;
7239 unsigned module_index_ctr = 0;
7240
cc52276b
WC
7241 // not const since embedded task_finder_target struct changes
7242 s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
89ba3085
FCE
7243 s.op->indent(1);
7244 for (unsigned i=0; i<probes.size(); i++)
7245 {
7246 uprobe_derived_probe *p = probes[i];
7247 string pbmkey = make_pbm_key (p);
7248 if (module_index.find (pbmkey) == module_index.end())
7249 {
7250 module_index[pbmkey] = module_index_ctr++;
7251
7252 s.op->newline() << "{";
7253 // NB: it's essential that make_pbm_key() use all of and
7254 // only the same fields as we're about to emit.
7255 s.op->line() << " .finder={";
7256 if (p->pid != 0)
68910c97
JK
7257 s.op->line() << " .pid=" << p->pid << ",";
7258
7259 if (p->section == "") // .statement(addr).absolute
7260 s.op->line() << " .callback=&stap_uprobe_process_found,";
89ba3085
FCE
7261 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7262 {
7263 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7264 s.op->line() << " .callback=&stap_uprobe_process_found,";
7265 }
68910c97 7266 else if (p->section != ".absolute") // ET_DYN
89ba3085 7267 {
4ad95bbc
SC
7268 if (p->has_library)
7269 s.op->line() << " .procname=\"" << p->path << "\", ";
89ba3085
FCE
7270 s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
7271 s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
19d91f6c 7272 s.op->line() << " .callback=&stap_uprobe_process_munmap,";
89ba3085 7273 }
89ba3085 7274 s.op->line() << " },";
68910c97
JK
7275 if (p->module != "")
7276 s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
89ba3085
FCE
7277 s.op->line() << " },";
7278 }
c57ea854 7279 else
822a6a3d 7280 { } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
89ba3085
FCE
7281 }
7282 s.op->newline(-1) << "};";
7283
7284 s.op->assert_0_indent();
7285
cc52276b
WC
7286 // NB: read-only structure
7287 s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
a96d1db0 7288 s.op->indent(1);
888af770
FCE
7289 for (unsigned i =0; i<probes.size(); i++)
7290 {
7291 uprobe_derived_probe* p = probes[i];
7292 s.op->newline() << "{";
89ba3085
FCE
7293 string key = make_pbm_key (p);
7294 unsigned value = module_index[key];
759e1d76
FCE
7295 if (value != 0)
7296 s.op->line() << " .tfi=" << value << ",";
6b66b9f7 7297 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
faea5e16 7298 s.op->line() << " .probe=" << common_probe_init (p) << ",";
4ddb6dd0 7299
038c38c6 7300 if (p->sdt_semaphore_addr != 0)
63b4fd14 7301 s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
038c38c6 7302 << hex << p->sdt_semaphore_addr << dec << "ULL,";
4ddb6dd0
JS
7303
7304 if (p->has_return)
7305 s.op->line() << " .return_p=1,";
888af770
FCE
7306 s.op->line() << " },";
7307 }
7308 s.op->newline(-1) << "};";
a96d1db0 7309
89ba3085
FCE
7310 s.op->assert_0_indent();
7311
48e685da 7312 s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
888af770 7313 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
89ba3085 7314 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
7315 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
7316 "_STP_PROBE_HANDLER_UPROBE");
0e090c74 7317 s.op->newline() << "if (sup->spec_index < 0 || "
6e895029
DS
7318 << "sup->spec_index >= " << probes.size() << ") {";
7319 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7320 << "): %s\", sup->spec_index, c->probe_point);";
6e895029
DS
7321 s.op->newline() << "atomic_dec (&c->busy);";
7322 s.op->newline() << "goto probe_epilogue;";
7323 s.op->newline(-1) << "}";
d9aed31e 7324 s.op->newline() << "c->uregs = regs;";
92c25572 7325 s.op->newline() << "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
6415ddde
MW
7326
7327 // Make it look like the IP is set as it would in the actual user
7328 // task when calling real probe handler. Reset IP regs on return, so
7329 // we don't confuse uprobes. PR10458
7330 s.op->newline() << "{";
7331 s.op->indent(1);
d9aed31e 7332 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
259d54c0 7333 s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
26e63673 7334 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7335 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7336 s.op->newline(-1) << "}";
7337
7baf48e9 7338 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
888af770 7339 s.op->newline(-1) << "}";
a96d1db0 7340
48e685da 7341 s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
888af770 7342 s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
89ba3085 7343 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6eefe942
MW
7344 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sups->probe",
7345 "_STP_PROBE_HANDLER_URETPROBE");
6dceb5c9 7346 s.op->newline() << "c->ips.ri = inst;";
0e090c74 7347 s.op->newline() << "if (sup->spec_index < 0 || "
0d5561a5
DS
7348 << "sup->spec_index >= " << probes.size() << ") {";
7349 s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
0e090c74 7350 << "): %s\", sup->spec_index, c->probe_point);";
0d5561a5
DS
7351 s.op->newline() << "atomic_dec (&c->busy);";
7352 s.op->newline() << "goto probe_epilogue;";
7353 s.op->newline(-1) << "}";
7354
d9aed31e 7355 s.op->newline() << "c->uregs = regs;";
92c25572 7356 s.op->newline() << "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
6415ddde
MW
7357
7358 // Make it look like the IP is set as it would in the actual user
7359 // task when calling real probe handler. Reset IP regs on return, so
7360 // we don't confuse uprobes. PR10458
7361 s.op->newline() << "{";
7362 s.op->indent(1);
d9aed31e 7363 s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
5e562a69 7364 s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
26e63673 7365 s.op->newline() << "(*sups->probe->ph) (c);";
259d54c0 7366 s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
6415ddde
MW
7367 s.op->newline(-1) << "}";
7368
7baf48e9 7369 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
a96d1db0
DN
7370 s.op->newline(-1) << "}";
7371
89ba3085 7372 s.op->newline();
2ba1736a 7373 s.op->newline() << "#include \"linux/uprobes-common.c\"";
6d0f3f0c 7374 s.op->newline();
888af770 7375}
935447c8
DS
7376
7377
888af770 7378void
2b69faaf 7379uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
935447c8 7380{
888af770 7381 if (probes.empty()) return;
935447c8 7382
2b69faaf 7383 s.op->newline() << "/* ---- utrace uprobes ---- */";
935447c8 7384
01b05e2e 7385 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92
FCE
7386 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
7387 s.op->newline() << "sup->spec_index = -1;"; // free slot
80b4ad8b
FCE
7388 // NB: we assume the rest of the struct (specificaly, sup->up) is
7389 // initialized to zero. This is so that we can use
7390 // sup->up->kdata = NULL for "really free!" PR 6829.
5e112f92
FCE
7391 s.op->newline(-1) << "}";
7392 s.op->newline() << "mutex_init (& stap_uprobes_lock);";
935447c8 7393
89ba3085
FCE
7394 // Set up the task_finders
7395 s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
7396 s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
c57ea854 7397 s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
89ba3085 7398 s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
935447c8 7399
5e112f92
FCE
7400 // NB: if (rc), there is no need (XXX: nor any way) to clean up any
7401 // finders already registered, since mere registration does not
7402 // cause any utrace or memory allocation actions. That happens only
7403 // later, once the task finder engine starts running. So, for a
7404 // partial initialization requiring unwind, we need do nothing.
7405 s.op->newline() << "if (rc) break;";
a7a68293 7406
888af770
FCE
7407 s.op->newline(-1) << "}";
7408}
d0ea46ce 7409
d0a7f5a9 7410
888af770 7411void
2b69faaf 7412uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
888af770
FCE
7413{
7414 if (probes.empty()) return;
2b69faaf 7415 s.op->newline() << "/* ---- utrace uprobes ---- */";
e56e51c9 7416
6d0f3f0c
FCE
7417 // NB: there is no stap_unregister_task_finder_target call;
7418 // important stuff like utrace cleanups are done by
d41d451c
FCE
7419 // __stp_task_finder_cleanup() via stap_stop_task_finder().
7420 //
7421 // This function blocks until all callbacks are completed, so there
7422 // is supposed to be no possibility of any registration-related code starting
7423 // to run in parallel with our shutdown here. So we don't need to protect the
7424 // stap_uprobes[] array with the mutex.
d0a7f5a9 7425
01b05e2e 7426 s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
5e112f92 7427 s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
89ba3085 7428 s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
6d0f3f0c 7429 s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
3568f1dd 7430
8faa1fc5 7431 // PR10655: decrement that ENABLED semaphore
c116c31b 7432 s.op->newline() << "if (sup->sdt_sem_address) {";
8faa1fc5
FCE
7433 s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
7434 s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
7435 s.op->newline() << "struct task_struct *tsk;";
7436 s.op->newline() << "rcu_read_lock();";
6846cfc8 7437
86229a55
DS
7438 // Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
7439 // that the pid is always in the global namespace, not in any
7440 // private namespace.
8faa1fc5 7441 s.op->newline() << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)";
86229a55
DS
7442 // We'd like to call find_task_by_pid_ns() here, but it isn't
7443 // exported. So, we call what it calls...
7444 s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
8faa1fc5
FCE
7445 s.op->newline() << "#else";
7446 s.op->newline() << " tsk = find_task_by_pid (pid);";
7447 s.op->newline() << "#endif /* 2.6.24 */";
8faa1fc5
FCE
7448
7449 s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
3c5b8e2b 7450 s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
63b4fd14 7451 s.op->newline(1) << "sdt_semaphore --;";
903b9fcd 7452 s.op->newline() << "#ifdef DEBUG_UPROBES";
c116c31b 7453 s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
903b9fcd 7454 s.op->newline() << "#endif";
3c5b8e2b 7455 s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
93c84191 7456 s.op->newline(-1) << "}";
8faa1fc5
FCE
7457 // XXX: need to analyze possibility of race condition
7458 s.op->newline(-1) << "}";
7459 s.op->newline() << "rcu_read_unlock();";
7460 s.op->newline(-1) << "}";
6846cfc8 7461
3568f1dd
FCE
7462 s.op->newline() << "if (sups->return_p) {";
7463 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
89ba3085 7464 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 7465 s.op->newline() << "#endif";
80b4ad8b
FCE
7466 // NB: PR6829 does not change that we still need to unregister at
7467 // *this* time -- when the script as a whole exits.
3568f1dd
FCE
7468 s.op->newline() << "unregister_uretprobe (& sup->urp);";
7469 s.op->newline(-1) << "} else {";
7470 s.op->newline(1) << "#ifdef DEBUG_UPROBES";
8faa1fc5 7471 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
7472 s.op->newline() << "#endif";
7473 s.op->newline() << "unregister_uprobe (& sup->up);";
7474 s.op->newline(-1) << "}";
935447c8 7475
6d0f3f0c 7476 s.op->newline() << "sup->spec_index = -1;";
935447c8 7477
3568f1dd
FCE
7478 // XXX: uprobe missed counts?
7479
6d0f3f0c 7480 s.op->newline(-1) << "}";
935447c8 7481
5e112f92 7482 s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
935447c8
DS
7483}
7484
2b69faaf
JS
7485
7486void
7487uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
7488{
7489 if (probes.empty()) return;
7490 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 7491 emit_module_maxuprobes (s);
2ba1736a 7492 s.op->newline() << "#include \"linux/uprobes-inode.c\"";
2b69faaf
JS
7493
7494 // Write the probe handler.
7495 s.op->newline() << "static int enter_inode_uprobe "
7496 << "(struct uprobe_consumer *inst, struct pt_regs *regs) {";
cfcab6c7
JS
7497 s.op->newline(1) << "struct stapiu_consumer *sup = "
7498 << "container_of(inst, struct stapiu_consumer, consumer);";
fe5acded
JS
7499 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sup->probe",
7500 "_STP_PROBE_HANDLER_UPROBE");
3bff6634
JS
7501 s.op->newline() << "c->uregs = regs;";
7502 s.op->newline() << "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
2b69faaf
JS
7503 // XXX: Can't set SET_REG_IP; we don't actually know the relocated address.
7504 // ... In some error cases, uprobes itself calls uprobes_get_bkpt_addr().
7505 s.op->newline() << "(*sup->probe->ph) (c);";
7ee95b6b 7506 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
2b69faaf
JS
7507 s.op->newline() << "return 0;";
7508 s.op->newline(-1) << "}";
7509 s.op->assert_0_indent();
7510
7511 // Index of all the modules for which we need inodes.
7512 map<string, unsigned> module_index;
7513 unsigned module_index_ctr = 0;
7514
7515 // Discover and declare targets for each unique path.
cfcab6c7 7516 s.op->newline() << "static struct stapiu_target "
2b69faaf
JS
7517 << "stap_inode_uprobe_targets[] = {";
7518 s.op->indent(1);
7519 for (unsigned i=0; i<probes.size(); i++)
7520 {
7521 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
7522 const string key = make_pbm_key(p);
7523 if (module_index.find (key) == module_index.end())
2b69faaf 7524 {
cfcab6c7
JS
7525 module_index[key] = module_index_ctr++;
7526 s.op->newline() << "{";
7527 s.op->line() << " .finder={";
7528 if (p->pid != 0)
7529 s.op->line() << " .pid=" << p->pid << ",";
7530
7531 if (p->section == "") // .statement(addr).absolute XXX?
7532 s.op->line() << " .callback=&stapiu_process_found,";
7533 else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
7534 {
7535 s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
7536 s.op->line() << " .callback=&stapiu_process_found,";
7537 }
7538 else if (p->section != ".absolute") // ET_DYN
7539 {
7540 if (p->has_library)
7541 s.op->line() << " .procname=\"" << p->path << "\", ";
7542 s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
7543 s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
7544 s.op->line() << " .callback=&stapiu_process_munmap,";
7545 }
7546 s.op->line() << " },";
7547 s.op->line() << " .filename=" << lex_cast_qstring(p->module) << ",";
7548 s.op->line() << " },";
2b69faaf
JS
7549 }
7550 }
7551 s.op->newline(-1) << "};";
7552 s.op->assert_0_indent();
7553
7554 // Declare the actual probes.
cfcab6c7 7555 s.op->newline() << "static struct stapiu_consumer "
2b69faaf
JS
7556 << "stap_inode_uprobe_consumers[] = {";
7557 s.op->indent(1);
7558 for (unsigned i=0; i<probes.size(); i++)
7559 {
7560 uprobe_derived_probe *p = probes[i];
cfcab6c7
JS
7561 unsigned index = module_index[make_pbm_key(p)];
7562 s.op->newline() << "{";
7563 s.op->line() << " .consumer={ .handler=enter_inode_uprobe },";
7564 s.op->line() << " .target=&stap_inode_uprobe_targets[" << index << "],";
7565 s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
7566 if (p->sdt_semaphore_addr)
7567 s.op->line() << " .sdt_sem_offset=(loff_t)0x"
7568 << hex << p->sdt_semaphore_addr << dec << "ULL,";
7569 s.op->line() << " .probe=" << common_probe_init (p) << ",";
7570 s.op->line() << " },";
2b69faaf
JS
7571 }
7572 s.op->newline(-1) << "};";
7573 s.op->assert_0_indent();
7574}
7575
7576
7577void
7578uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
7579{
7580 if (probes.empty()) return;
7581 s.op->newline() << "/* ---- inode uprobes ---- */";
b0f614a0
DS
7582 // Let stapiu_init() handle reporting errors by setting probe_point
7583 // to NULL.
7584 s.op->newline() << "probe_point = NULL;";
cfcab6c7 7585 s.op->newline() << "rc = stapiu_init ("
2b69faaf
JS
7586 << "stap_inode_uprobe_targets, "
7587 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
7588 << "stap_inode_uprobe_consumers, "
7589 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
7590}
7591
7592
7593void
7594uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
7595{
7596 if (probes.empty()) return;
7597 s.op->newline() << "/* ---- inode uprobes ---- */";
cfcab6c7 7598 s.op->newline() << "stapiu_exit ("
2b69faaf
JS
7599 << "stap_inode_uprobe_targets, "
7600 << "ARRAY_SIZE(stap_inode_uprobe_targets), "
7601 << "stap_inode_uprobe_consumers, "
7602 << "ARRAY_SIZE(stap_inode_uprobe_consumers));";
7603}
7604
7605
7606void
7607uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
7608{
7609 if (kernel_supports_inode_uprobes (s))
7610 emit_module_inode_decls (s);
7611 else
7612 emit_module_utrace_decls (s);
7613}
7614
7615
7616void
7617uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
7618{
7619 if (kernel_supports_inode_uprobes (s))
7620 emit_module_inode_init (s);
7621 else
7622 emit_module_utrace_init (s);
7623}
7624
7625
7626void
7627uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
7628{
7629 if (kernel_supports_inode_uprobes (s))
7630 emit_module_inode_exit (s);
7631 else
7632 emit_module_utrace_exit (s);
7633}
7634
7635
e6fe60e7
AM
7636// ------------------------------------------------------------------------
7637// Kprobe derived probes
7638// ------------------------------------------------------------------------
7639
4627ed58 7640static const string TOK_KPROBE("kprobe");
935447c8 7641
bae55db9 7642struct kprobe_derived_probe: public derived_probe
d0ea46ce 7643{
bae55db9
JS
7644 kprobe_derived_probe (probe *base,
7645 probe_point *location,
7646 const string& name,
7647 int64_t stmt_addr,
7648 bool has_return,
7649 bool has_statement,
7650 bool has_maxactive,
b642c901
SC
7651 bool has_path,
7652 bool has_library,
7653 long maxactive_val,
7654 const string& path,
7655 const string& library
bae55db9
JS
7656 );
7657 string symbol_name;
7658 Dwarf_Addr addr;
7659 bool has_return;
7660 bool has_statement;
7661 bool has_maxactive;
b642c901
SC
7662 bool has_path;
7663 bool has_library;
bae55db9 7664 long maxactive_val;
b642c901
SC
7665 string path;
7666 string library;
bae55db9
JS
7667 bool access_var;
7668 void printsig (std::ostream &o) const;
7669 void join_group (systemtap_session& s);
7670};
d0ea46ce 7671
bae55db9
JS
7672struct kprobe_derived_probe_group: public derived_probe_group
7673{
7674private:
7675 multimap<string,kprobe_derived_probe*> probes_by_module;
7676 typedef multimap<string,kprobe_derived_probe*>::iterator p_b_m_iterator;
d0ea46ce 7677
bae55db9
JS
7678public:
7679 void enroll (kprobe_derived_probe* probe);
7680 void emit_module_decls (systemtap_session& s);
7681 void emit_module_init (systemtap_session& s);
7682 void emit_module_exit (systemtap_session& s);
7683};
d0ea46ce 7684
e6fe60e7
AM
7685kprobe_derived_probe::kprobe_derived_probe (probe *base,
7686 probe_point *location,
b6371390 7687 const string& name,
e6fe60e7 7688 int64_t stmt_addr,
b6371390
JS
7689 bool has_return,
7690 bool has_statement,
7691 bool has_maxactive,
b642c901
SC
7692 bool has_path,
7693 bool has_library,
7694 long maxactive_val,
7695 const string& path,
7696 const string& library
b6371390 7697 ):
4c5d1300 7698 derived_probe (base, location, true /* .components soon rewritten */ ),
e6fe60e7 7699 symbol_name (name), addr (stmt_addr),
b6371390 7700 has_return (has_return), has_statement (has_statement),
b642c901
SC
7701 has_maxactive (has_maxactive), has_path (has_path),
7702 has_library (has_library),
7703 maxactive_val (maxactive_val),
7704 path (path), library (library)
e6fe60e7
AM
7705{
7706 this->tok = base->tok;
7707 this->access_var = false;
d0ea46ce 7708
e6fe60e7
AM
7709#ifndef USHRT_MAX
7710#define USHRT_MAX 32767
7711#endif
d0ea46ce 7712
46856d8d
JS
7713 // Expansion of $target variables in the probe body produces an error during
7714 // translate phase, since we're not using debuginfo
d0ea46ce 7715
e6fe60e7 7716 vector<probe_point::component*> comps;
46856d8d 7717 comps.push_back (new probe_point::component(TOK_KPROBE));
e6fe60e7 7718
46856d8d
JS
7719 if (has_statement)
7720 {
9ea68eb9
JS
7721 comps.push_back (new probe_point::component(TOK_STATEMENT,
7722 new literal_number(addr, true)));
46856d8d
JS
7723 comps.push_back (new probe_point::component(TOK_ABSOLUTE));
7724 }
7725 else
7726 {
7727 size_t pos = name.find(':');
7728 if (pos != string::npos)
d0ea46ce 7729 {
46856d8d
JS
7730 string module = name.substr(0, pos);
7731 string function = name.substr(pos + 1);
7732 comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
7733 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
7734 }
7735 else
7736 comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
46856d8d 7737 }
d0ea46ce 7738
b6371390
JS
7739 if (has_return)
7740 comps.push_back (new probe_point::component(TOK_RETURN));
7741 if (has_maxactive)
7742 comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
d0ea46ce 7743
e6fe60e7
AM
7744 this->sole_location()->components = comps;
7745}
d0ea46ce 7746
e6fe60e7
AM
7747void kprobe_derived_probe::printsig (ostream& o) const
7748{
7749 sole_location()->print (o);
7750 o << " /* " << " name = " << symbol_name << "*/";
7751 printsig_nested (o);
7752}
d0ea46ce 7753
e6fe60e7
AM
7754void kprobe_derived_probe::join_group (systemtap_session& s)
7755{
d0ea46ce 7756
e6fe60e7
AM
7757 if (! s.kprobe_derived_probes)
7758 s.kprobe_derived_probes = new kprobe_derived_probe_group ();
7759 s.kprobe_derived_probes->enroll (this);
d0ea46ce 7760
e6fe60e7 7761}
d0ea46ce 7762
e6fe60e7
AM
7763void kprobe_derived_probe_group::enroll (kprobe_derived_probe* p)
7764{
7765 probes_by_module.insert (make_pair (p->symbol_name, p));
7766 // probes of same symbol should share single kprobe/kretprobe
7767}
d0ea46ce 7768
e6fe60e7
AM
7769void
7770kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
7771{
7772 if (probes_by_module.empty()) return;
d0ea46ce 7773
e6fe60e7 7774 s.op->newline() << "/* ---- kprobe-based probes ---- */";
d0ea46ce 7775
e6fe60e7
AM
7776 // Warn of misconfigured kernels
7777 s.op->newline() << "#if ! defined(CONFIG_KPROBES)";
7778 s.op->newline() << "#error \"Need CONFIG_KPROBES!\"";
7779 s.op->newline() << "#endif";
7780 s.op->newline();
d0ea46ce 7781
f07c3b68 7782 s.op->newline() << "#ifndef KRETACTIVE";
1ee6b5fc 7783 s.op->newline() << "#define KRETACTIVE (max(15,6*(int)num_possible_cpus()))";
f07c3b68
FCE
7784 s.op->newline() << "#endif";
7785
e6fe60e7 7786 // Forward declare the master entry functions
88747011 7787 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7 7788 s.op->line() << " struct pt_regs *regs);";
88747011 7789 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7 7790 s.op->line() << " struct pt_regs *regs);";
d0ea46ce 7791
e6fe60e7
AM
7792 // Emit an array of kprobe/kretprobe pointers
7793 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
c9116e99 7794 s.op->newline() << "static void * stap_unreg_kprobes2[" << probes_by_module.size() << "];";
e6fe60e7 7795 s.op->newline() << "#endif";
d0ea46ce 7796
e6fe60e7 7797 // Emit the actual probe list.
d0ea46ce 7798
e6fe60e7
AM
7799 s.op->newline() << "static struct stap_dwarfless_kprobe {";
7800 s.op->newline(1) << "union { struct kprobe kp; struct kretprobe krp; } u;";
7801 s.op->newline() << "#ifdef __ia64__";
7802 s.op->newline() << "struct kprobe dummy;";
7803 s.op->newline() << "#endif";
7804 s.op->newline(-1) << "} stap_dwarfless_kprobes[" << probes_by_module.size() << "];";
7805 // NB: bss!
d0ea46ce 7806
e6fe60e7
AM
7807 s.op->newline() << "static struct stap_dwarfless_probe {";
7808 s.op->newline(1) << "const unsigned return_p:1;";
7809 s.op->newline() << "const unsigned maxactive_p:1;";
b350f56b 7810 s.op->newline() << "const unsigned optional_p:1;";
e6fe60e7
AM
7811 s.op->newline() << "unsigned registered_p:1;";
7812 s.op->newline() << "const unsigned short maxactive_val;";
935447c8 7813
e6fe60e7
AM
7814 // Function Names are mostly small and uniform enough to justify putting
7815 // char[MAX]'s into the array instead of relocated char*'s.
935447c8 7816
faea5e16
JS
7817 size_t symbol_string_name_max = 0;
7818 size_t symbol_string_name_tot = 0;
e6fe60e7 7819 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
6270adc1 7820 {
e6fe60e7
AM
7821 kprobe_derived_probe* p = it->second;
7822#define DOIT(var,expr) do { \
7823 size_t var##_size = (expr) + 1; \
7824 var##_max = max (var##_max, var##_size); \
7825 var##_tot += var##_size; } while (0)
e6fe60e7
AM
7826 DOIT(symbol_string_name, p->symbol_name.size());
7827#undef DOIT
6270adc1
MH
7828 }
7829
e6fe60e7
AM
7830#define CALCIT(var) \
7831 s.op->newline() << "const char " << #var << "[" << var##_name_max << "] ;";
935447c8 7832
e6fe60e7
AM
7833 CALCIT(symbol_string);
7834#undef CALCIT
6270adc1 7835
bd659351 7836 s.op->newline() << "unsigned long address;";
26e63673 7837 s.op->newline() << "struct stap_probe * const probe;";
e6fe60e7
AM
7838 s.op->newline(-1) << "} stap_dwarfless_probes[] = {";
7839 s.op->indent(1);
6270adc1 7840
e6fe60e7
AM
7841 for (p_b_m_iterator it = probes_by_module.begin(); it != probes_by_module.end(); it++)
7842 {
7843 kprobe_derived_probe* p = it->second;
7844 s.op->newline() << "{";
7845 if (p->has_return)
7846 s.op->line() << " .return_p=1,";
6270adc1 7847
e6fe60e7
AM
7848 if (p->has_maxactive)
7849 {
7850 s.op->line() << " .maxactive_p=1,";
7851 assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
7852 s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
7853 }
6270adc1 7854
b350f56b
JS
7855 if (p->locations[0]->optional)
7856 s.op->line() << " .optional_p=1,";
7857
e6fe60e7 7858 if (p->has_statement)
c8d9d15e 7859 s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
e6fe60e7 7860 else
c8d9d15e 7861 s.op->line() << " .symbol_string=\"" << p->symbol_name << "\",";
5d67b47c 7862
faea5e16 7863 s.op->line() << " .probe=" << common_probe_init (p) << ",";
e6fe60e7 7864 s.op->line() << " },";
935447c8
DS
7865 }
7866
e6fe60e7 7867 s.op->newline(-1) << "};";
5d67b47c 7868
e6fe60e7
AM
7869 // Emit the kprobes callback function
7870 s.op->newline();
88747011 7871 s.op->newline() << "static int enter_kprobe2_probe (struct kprobe *inst,";
e6fe60e7
AM
7872 s.op->line() << " struct pt_regs *regs) {";
7873 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7874 s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7875 // Check that the index is plausible
7876 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7877 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7878 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7879 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7880 s.op->line() << "];";
6eefe942
MW
7881 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7882 "_STP_PROBE_HANDLER_KPROBE");
d9aed31e 7883 s.op->newline() << "c->kregs = regs;";
6415ddde
MW
7884
7885 // Make it look like the IP is set as it wouldn't have been replaced
7886 // by a breakpoint instruction when calling real probe handler. Reset
7887 // IP regs on return, so we don't confuse kprobes. PR10458
7888 s.op->newline() << "{";
7889 s.op->indent(1);
d9aed31e 7890 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 7891 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
26e63673 7892 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7893 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7894 s.op->newline(-1) << "}";
7895
7baf48e9 7896 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
e6fe60e7
AM
7897 s.op->newline() << "return 0;";
7898 s.op->newline(-1) << "}";
935447c8 7899
e6fe60e7
AM
7900 // Same for kretprobes
7901 s.op->newline();
88747011 7902 s.op->newline() << "static int enter_kretprobe2_probe (struct kretprobe_instance *inst,";
e6fe60e7
AM
7903 s.op->line() << " struct pt_regs *regs) {";
7904 s.op->newline(1) << "struct kretprobe *krp = inst->rp;";
935447c8 7905
e6fe60e7
AM
7906 // NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
7907 s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_dwarfless_kprobes)/sizeof(struct stap_dwarfless_kprobe);";
7908 // Check that the index is plausible
7909 s.op->newline() << "struct stap_dwarfless_probe *sdp = &stap_dwarfless_probes[";
7910 s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
7911 s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
7912 // XXX: it would be nice to give a more verbose error though; BUG_ON later?
7913 s.op->line() << "];";
935447c8 7914
6eefe942
MW
7915 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
7916 "_STP_PROBE_HANDLER_KRETPROBE");
d9aed31e 7917 s.op->newline() << "c->kregs = regs;";
6dceb5c9 7918 s.op->newline() << "c->ips.krp.pi = inst;"; // for assisting runtime's backtrace logic
6415ddde
MW
7919
7920 // Make it look like the IP is set as it wouldn't have been replaced
7921 // by a breakpoint instruction when calling real probe handler. Reset
7922 // IP regs on return, so we don't confuse kprobes. PR10458
7923 s.op->newline() << "{";
7924 s.op->indent(1);
d9aed31e 7925 s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
259d54c0 7926 s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->rp->kp.addr);";
26e63673 7927 s.op->newline() << "(*sdp->probe->ph) (c);";
259d54c0 7928 s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
6415ddde
MW
7929 s.op->newline(-1) << "}";
7930
7baf48e9 7931 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
e6fe60e7
AM
7932 s.op->newline() << "return 0;";
7933 s.op->newline(-1) << "}";
bd659351 7934
03a4ec63 7935 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7936 s.op->newline() << "static int kprobe_resolve(void *data, const char *name,";
7937 s.op->newline() << " struct module *owner,";
7938 s.op->newline() << " unsigned long val) {";
7939 s.op->newline(1) << "int i;";
fc1d2aa2
MW
7940 s.op->newline() << "int *p = (int *) data;";
7941 s.op->newline() << "for (i=0; i<" << probes_by_module.size()
7942 << " && *p > 0; i++) {";
bd659351
MW
7943 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7944 s.op->newline() << "if (! sdp->address)";
fc1d2aa2 7945 s.op->newline(1) << "if (strcmp(sdp->symbol_string, name) == 0) {";
bd659351 7946 s.op->newline(1) << "sdp->address = val;";
fc1d2aa2
MW
7947 s.op->newline() << "(*p)--;";
7948 s.op->newline(-1) << "}";
7949 s.op->newline(-2) << "}";
7950 s.op->newline() << "return (p > 0) ? 0 : -1;";
bd659351 7951 s.op->newline(-1) << "}";
03a4ec63 7952 s.op->newline() << "#endif";
935447c8
DS
7953}
7954
e6fe60e7 7955
6270adc1 7956void
e6fe60e7 7957kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
6270adc1 7958{
03a4ec63 7959 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
fc1d2aa2
MW
7960 s.op->newline() << "{";
7961 s.op->newline(1) << "int p = 0;";
7962 s.op->newline() << "for (i = 0; i < " << probes_by_module.size() << "; i++) {";
7963 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
7964 s.op->newline() << "if (! sdp->address)";
7965 s.op->newline(1) << "p++;";
7966 s.op->newline(-2) << "}";
7967 s.op->newline() << "kallsyms_on_each_symbol(kprobe_resolve, &p);";
7968 s.op->newline(-1) << "}";
03a4ec63 7969 s.op->newline() << "#endif";
bd659351 7970
e6fe60e7 7971 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
c8d9d15e 7972 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
e6fe60e7 7973 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
c8d9d15e 7974 s.op->newline() << "void *addr = (void *) sdp->address;";
03a4ec63
MW
7975 s.op->newline() << "const char *symbol_name = addr ? NULL : sdp->symbol_string;";
7976
7977 s.op->newline() << "#ifdef STAPCONF_KALLSYMS_ON_EACH_SYMBOL";
bd659351
MW
7978 s.op->newline() << "if (! addr) {";
7979 s.op->newline(1) << "sdp->registered_p = 0;";
9319b767
MW
7980 s.op->newline() << "if (!sdp->optional_p)";
7981 s.op->newline(1) << "_stp_warn (\"probe %s registration error (symbol not found)\", probe_point);";
7982 s.op->newline(-1) << "continue;";
bd659351 7983 s.op->newline(-1) << "}";
03a4ec63
MW
7984 s.op->newline() << "#endif";
7985
26e63673 7986 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
e6fe60e7 7987 s.op->newline() << "if (sdp->return_p) {";
c8d9d15e 7988 s.op->newline(1) << "kp->u.krp.kp.addr = addr;";
766cee5f 7989 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 7990 s.op->newline() << "kp->u.krp.kp.symbol_name = (char *) symbol_name;";
766cee5f 7991 s.op->newline() << "#endif";
e6fe60e7
AM
7992 s.op->newline() << "if (sdp->maxactive_p) {";
7993 s.op->newline(1) << "kp->u.krp.maxactive = sdp->maxactive_val;";
7994 s.op->newline(-1) << "} else {";
f07c3b68 7995 s.op->newline(1) << "kp->u.krp.maxactive = KRETACTIVE;";
e6fe60e7 7996 s.op->newline(-1) << "}";
88747011 7997 s.op->newline() << "kp->u.krp.handler = &enter_kretprobe2_probe;";
e6fe60e7
AM
7998 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
7999 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8000 s.op->newline() << "kp->dummy.addr = kp->u.krp.kp.addr;";
766cee5f 8001 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8002 s.op->newline() << "kp->dummy.symbol_name = kp->u.krp.kp.symbol_name;";
766cee5f 8003 s.op->newline() << "#endif";
c8d9d15e 8004 s.op->newline() << "kp->dummy.pre_handler = NULL;";
e6fe60e7
AM
8005 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8006 s.op->newline() << "if (rc == 0) {";
8007 s.op->newline(1) << "rc = register_kretprobe (& kp->u.krp);";
8008 s.op->newline() << "if (rc != 0)";
8009 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8010 s.op->newline(-2) << "}";
8011 s.op->newline() << "#else";
8012 s.op->newline() << "rc = register_kretprobe (& kp->u.krp);";
8013 s.op->newline() << "#endif";
8014 s.op->newline(-1) << "} else {";
8015 // to ensure safeness of bspcache, always use aggr_kprobe on ia64
c8d9d15e 8016 s.op->newline(1) << "kp->u.kp.addr = addr;";
766cee5f 8017 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
03a4ec63 8018 s.op->newline() << "kp->u.kp.symbol_name = (char *) symbol_name;";
766cee5f 8019 s.op->newline() << "#endif";
88747011 8020 s.op->newline() << "kp->u.kp.pre_handler = &enter_kprobe2_probe;";
e6fe60e7 8021 s.op->newline() << "#ifdef __ia64__";
e6fe60e7 8022 s.op->newline() << "kp->dummy.pre_handler = NULL;";
c8d9d15e 8023 s.op->newline() << "kp->dummy.addr = kp->u.kp.addr;";
766cee5f 8024 s.op->newline() << "#ifdef STAPCONF_KPROBE_SYMBOL_NAME";
c8d9d15e 8025 s.op->newline() << "kp->dummy.symbol_name = kp->u.kp.symbol_name;";
766cee5f 8026 s.op->newline() << "#endif";
e6fe60e7
AM
8027 s.op->newline() << "rc = register_kprobe (& kp->dummy);";
8028 s.op->newline() << "if (rc == 0) {";
8029 s.op->newline(1) << "rc = register_kprobe (& kp->u.kp);";
8030 s.op->newline() << "if (rc != 0)";
8031 s.op->newline(1) << "unregister_kprobe (& kp->dummy);";
8032 s.op->newline(-2) << "}";
8033 s.op->newline() << "#else";
8034 s.op->newline() << "rc = register_kprobe (& kp->u.kp);";
8035 s.op->newline() << "#endif";
8036 s.op->newline(-1) << "}";
8037 s.op->newline() << "if (rc) {"; // PR6749: tolerate a failed register_*probe.
8038 s.op->newline(1) << "sdp->registered_p = 0;";
b350f56b 8039 s.op->newline() << "if (!sdp->optional_p)";
50b6acf7 8040 s.op->newline(1) << "_stp_warn (\"probe %s (address 0x%lx) registration error (rc %d)\", probe_point, (unsigned long) addr, rc);";
b350f56b 8041 s.op->newline(-1) << "rc = 0;"; // continue with other probes
e6fe60e7
AM
8042 // XXX: shall we increment numskipped?
8043 s.op->newline(-1) << "}";
6270adc1 8044
e6fe60e7
AM
8045 s.op->newline() << "else sdp->registered_p = 1;";
8046 s.op->newline(-1) << "}"; // for loop
6270adc1
MH
8047}
8048
b4be7cbc 8049
e6fe60e7
AM
8050void
8051kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
935447c8 8052{
e6fe60e7
AM
8053 //Unregister kprobes by batch interfaces.
8054 s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
8055 s.op->newline() << "j = 0;";
8056 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8057 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8058 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8059 s.op->newline() << "if (! sdp->registered_p) continue;";
8060 s.op->newline() << "if (!sdp->return_p)";
c9116e99 8061 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.kp;";
e6fe60e7 8062 s.op->newline(-2) << "}";
c9116e99 8063 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8064 s.op->newline() << "j = 0;";
8065 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8066 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8067 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8068 s.op->newline() << "if (! sdp->registered_p) continue;";
8069 s.op->newline() << "if (sdp->return_p)";
c9116e99 8070 s.op->newline(1) << "stap_unreg_kprobes2[j++] = &kp->u.krp;";
e6fe60e7 8071 s.op->newline(-2) << "}";
c9116e99 8072 s.op->newline() << "unregister_kretprobes((struct kretprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8073 s.op->newline() << "#ifdef __ia64__";
8074 s.op->newline() << "j = 0;";
8075 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8076 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8077 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8078 s.op->newline() << "if (! sdp->registered_p) continue;";
c9116e99 8079 s.op->newline() << "stap_unreg_kprobes2[j++] = &kp->dummy;";
e6fe60e7 8080 s.op->newline(-1) << "}";
c9116e99 8081 s.op->newline() << "unregister_kprobes((struct kprobe **)stap_unreg_kprobes2, j);";
e6fe60e7
AM
8082 s.op->newline() << "#endif";
8083 s.op->newline() << "#endif";
3e3bd7b6 8084
e6fe60e7
AM
8085 s.op->newline() << "for (i=0; i<" << probes_by_module.size() << "; i++) {";
8086 s.op->newline(1) << "struct stap_dwarfless_probe *sdp = & stap_dwarfless_probes[i];";
8087 s.op->newline() << "struct stap_dwarfless_kprobe *kp = & stap_dwarfless_kprobes[i];";
8088 s.op->newline() << "if (! sdp->registered_p) continue;";
8089 s.op->newline() << "if (sdp->return_p) {";
8090 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8091 s.op->newline(1) << "unregister_kretprobe (&kp->u.krp);";
8092 s.op->newline() << "#endif";
8093 s.op->newline() << "atomic_add (kp->u.krp.nmissed, & skipped_count);";
8094 s.op->newline() << "#ifdef STP_TIMING";
8095 s.op->newline() << "if (kp->u.krp.nmissed)";
26e63673 8096 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
8097 s.op->newline(-1) << "#endif";
8098 s.op->newline() << "atomic_add (kp->u.krp.kp.nmissed, & skipped_count);";
8099 s.op->newline() << "#ifdef STP_TIMING";
8100 s.op->newline() << "if (kp->u.krp.kp.nmissed)";
26e63673 8101 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
8102 s.op->newline(-1) << "#endif";
8103 s.op->newline(-1) << "} else {";
8104 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES)";
8105 s.op->newline(1) << "unregister_kprobe (&kp->u.kp);";
8106 s.op->newline() << "#endif";
8107 s.op->newline() << "atomic_add (kp->u.kp.nmissed, & skipped_count);";
8108 s.op->newline() << "#ifdef STP_TIMING";
8109 s.op->newline() << "if (kp->u.kp.nmissed)";
26e63673 8110 s.op->newline(1) << "_stp_warn (\"Skipped due to missed kprobe on '%s': %lu\\n\", sdp->probe->pp, kp->u.kp.nmissed);";
e6fe60e7
AM
8111 s.op->newline(-1) << "#endif";
8112 s.op->newline(-1) << "}";
8113 s.op->newline() << "#if !defined(STAPCONF_UNREGISTER_KPROBES) && defined(__ia64__)";
8114 s.op->newline() << "unregister_kprobe (&kp->dummy);";
8115 s.op->newline() << "#endif";
8116 s.op->newline() << "sdp->registered_p = 0;";
8117 s.op->newline(-1) << "}";
f8a968bc
JS
8118}
8119
e6fe60e7 8120struct kprobe_builder: public derived_probe_builder
3c1b3d06 8121{
9fdf787d
DS
8122private:
8123 bool cache_initialized;
8124 vector<string> function_name_cache;
8125
8126 void load_function_name_cache(systemtap_session & sess);
8127
8128public:
8129 kprobe_builder(): cache_initialized(false) {}
8130
8131 void build_no_more (systemtap_session &s)
8132 {
8133 if (! function_name_cache.empty())
8134 {
8135 if (s.verbose > 3)
8136 clog << _("kprobe_builder releasing cache") << endl;
8137 function_name_cache.clear();
8138 }
8139 }
8140
e6fe60e7
AM
8141 virtual void build(systemtap_session & sess,
8142 probe * base,
8143 probe_point * location,
8144 literal_map_t const & parameters,
8145 vector<derived_probe *> & finished_results);
8146};
3c1b3d06
FCE
8147
8148
9fdf787d
DS
8149void
8150kprobe_builder::load_function_name_cache(systemtap_session &sess)
8151{
8152 if (! cache_initialized)
8153 {
8154 cache_initialized = true;
8155 string system_map_path = sess.kernel_build_tree + "/System.map";
8156 ifstream system_map;
8157
8158 system_map.open(system_map_path.c_str(), ifstream::in);
8159 if (! system_map.is_open())
8160 {
8161 string system_map_path2 = "/boot/System.map-" + sess.kernel_release;
8162
8163 system_map.clear();
8164 system_map.open(system_map_path2.c_str(), ifstream::in);
8165 if (! system_map.is_open())
8166 {
8167 if (sess.verbose > 3)
8168 //TRANSLATORS: specific path cannot be opened
8169 clog << system_map_path << _(" and ")
8170 << system_map_path2 << _(" cannot be opened: ")
8171 << strerror(errno) << endl;
8172 return;
8173 }
8174 }
8175
8176 string address, type, name;
8177 do
8178 {
8179 system_map >> address >> type >> name;
8180
8181 if (sess.verbose > 3)
8182 clog << "'" << address << "' '" << type << "' '" << name
8183 << "'" << endl;
8184
8185 // 'T'/'t' are text code symbols
8186 if (type != "t" && type != "T")
8187 continue;
8188
8189 // FIXME: better things to do here - look for _stext before
8190 // remembering symbols. Also:
8191 // - stop remembering names at ???
8192 // - what about __kprobes_text_start/__kprobes_text_end?
8193 function_name_cache.push_back(name);
8194 }
8195 while (! system_map.eof());
8196 system_map.close();
8197 }
8198}
8199
79189b84 8200void
05fb3e0c 8201kprobe_builder::build(systemtap_session & sess,
e6fe60e7
AM
8202 probe * base,
8203 probe_point * location,
8204 literal_map_t const & parameters,
8205 vector<derived_probe *> & finished_results)
79189b84 8206{
e6fe60e7 8207 string function_string_val, module_string_val;
05fb3e0c 8208 string path, library, path_tgt, library_tgt;
b6371390
JS
8209 int64_t statement_num_val = 0, maxactive_val = 0;
8210 bool has_function_str, has_module_str, has_statement_num;
8211 bool has_absolute, has_return, has_maxactive;
b642c901 8212 bool has_path, has_library;
79189b84 8213
b6371390
JS
8214 has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
8215 has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
8216 has_return = has_null_param (parameters, TOK_RETURN);
8217 has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
8218 has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
8219 has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
b642c901
SC
8220 has_path = get_param (parameters, TOK_PROCESS, path);
8221 has_library = get_param (parameters, TOK_LIBRARY, library);
8222
8223 if (has_path)
05fb3e0c
WF
8224 {
8225 path = find_executable (path, sess.sysroot, sess.sysenv);
8226 path_tgt = path_remove_sysroot(sess, path);
8227 }
b642c901 8228 if (has_library)
05fb3e0c
WF
8229 {
8230 library = find_executable (library, sess.sysroot, sess.sysenv,
8231 "LD_LIBRARY_PATH");
8232 library_tgt = path_remove_sysroot(sess, library);
8233 }
c57ea854 8234
b6371390 8235 if (has_function_str)
6fb70fb7 8236 {
9fdf787d
DS
8237 if (has_module_str)
8238 {
8239 function_string_val = module_string_val + ":" + function_string_val;
8240 derived_probe *dp
8241 = new kprobe_derived_probe (base, location, function_string_val,
8242 0, has_return, has_statement_num,
8243 has_maxactive, has_path, has_library,
8244 maxactive_val, path_tgt, library_tgt);
8245 finished_results.push_back (dp);
8246 }
8247 else
8248 {
8249 load_function_name_cache(sess);
86758d5f 8250
9fdf787d
DS
8251 // Search function name list for matching names
8252 for (vector<string>::const_iterator it = function_name_cache.begin();
8253 it != function_name_cache.end(); it++)
8254 {
8255 // Below, "rc" has negative polarity: zero iff matching.
8256 int rc = fnmatch(function_string_val.c_str(), (*it).c_str(), 0);
8257 if (! rc)
8258 {
8259 derived_probe *dp
8260 = new kprobe_derived_probe (base, location, *it,
8261 0, has_return,
8262 has_statement_num,
8263 has_maxactive, has_path,
8264 has_library, maxactive_val,
8265 path_tgt, library_tgt);
8266 finished_results.push_back (dp);
8267 }
8268 }
8269 }
6fb70fb7 8270 }
e6fe60e7 8271 else
b6371390
JS
8272 {
8273 // assert guru mode for absolute probes
8274 if ( has_statement_num && has_absolute && !base->privileged )
e3bbc038 8275 throw semantic_error (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
b6371390
JS
8276
8277 finished_results.push_back (new kprobe_derived_probe (base,
8278 location, "",
8279 statement_num_val,
8280 has_return,
8281 has_statement_num,
8282 has_maxactive,
b642c901
SC
8283 has_path,
8284 has_library,
8285 maxactive_val,
05fb3e0c
WF
8286 path_tgt,
8287 library_tgt));
96b030fe 8288 }
79189b84
JS
8289}
8290
dd225250
PS
8291// ------------------------------------------------------------------------
8292// Hardware breakpoint based probes.
8293// ------------------------------------------------------------------------
8294
8295static const string TOK_HWBKPT("data");
8296static const string TOK_HWBKPT_WRITE("write");
8297static const string TOK_HWBKPT_RW("rw");
8298static const string TOK_LENGTH("length");
8299
8300#define HWBKPT_READ 0
8301#define HWBKPT_WRITE 1
8302#define HWBKPT_RW 2
8303struct hwbkpt_derived_probe: public derived_probe
8304{
8305 hwbkpt_derived_probe (probe *base,
8306 probe_point *location,
8307 uint64_t addr,
8308 string symname,
8309 unsigned int len,
8310 bool has_only_read_access,
8311 bool has_only_write_access,
8312 bool has_rw_access
8313 );
8314 Dwarf_Addr hwbkpt_addr;
8315 string symbol_name;
8316 unsigned int hwbkpt_access,hwbkpt_len;
8317
8318 void printsig (std::ostream &o) const;
8319 void join_group (systemtap_session& s);
8320};
8321
8322struct hwbkpt_derived_probe_group: public derived_probe_group
8323{
dd225250 8324private:
dac77b80 8325 vector<hwbkpt_derived_probe*> hwbkpt_probes;
dd225250
PS
8326
8327public:
8328 void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
8329 void emit_module_decls (systemtap_session& s);
8330 void emit_module_init (systemtap_session& s);
8331 void emit_module_exit (systemtap_session& s);
8332};
8333
8334hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
9ea68eb9
JS
8335 probe_point *location,
8336 uint64_t addr,
8337 string symname,
8338 unsigned int len,
8339 bool has_only_read_access,
8340 bool has_only_write_access,
822a6a3d 8341 bool):
4c5d1300 8342 derived_probe (base, location, true /* .components soon rewritten */ ),
dd225250
PS
8343 hwbkpt_addr (addr),
8344 symbol_name (symname),
8345 hwbkpt_len (len)
8346{
8347 this->tok = base->tok;
8348
8349 vector<probe_point::component*> comps;
8350 comps.push_back (new probe_point::component(TOK_KERNEL));
8351
8352 if (hwbkpt_addr)
9ea68eb9
JS
8353 comps.push_back (new probe_point::component (TOK_HWBKPT,
8354 new literal_number(hwbkpt_addr, true)));
8355 else if (symbol_name.size())
8356 comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
dd225250
PS
8357
8358 comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
8359
8360 if (has_only_read_access)
9ea68eb9 8361 this->hwbkpt_access = HWBKPT_READ ;
dd225250
PS
8362//TODO add code for comps.push_back for read, since this flag is not for x86
8363
8364 else
9ea68eb9
JS
8365 {
8366 if (has_only_write_access)
8367 {
8368 this->hwbkpt_access = HWBKPT_WRITE ;
8369 comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
8370 }
8371 else
8372 {
8373 this->hwbkpt_access = HWBKPT_RW ;
8374 comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
8375 }
8376 }
dd225250
PS
8377
8378 this->sole_location()->components = comps;
8379}
8380
8381void hwbkpt_derived_probe::printsig (ostream& o) const
8382{
8383 sole_location()->print (o);
8384 printsig_nested (o);
8385}
8386
8387void hwbkpt_derived_probe::join_group (systemtap_session& s)
8388{
dac77b80
FCE
8389 if (! s.hwbkpt_derived_probes)
8390 s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
dd225250
PS
8391 s.hwbkpt_derived_probes->enroll (this, s);
8392}
8393
8394void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session& s)
8395{
dac77b80
FCE
8396 hwbkpt_probes.push_back (p);
8397
8398 unsigned max_hwbkpt_probes_by_arch = 0;
8399 if (s.architecture == "i386" || s.architecture == "x86_64")
8400 max_hwbkpt_probes_by_arch = 4;
8401 else if (s.architecture == "s390")
8402 max_hwbkpt_probes_by_arch = 1;
8403
c57ea854 8404 if (hwbkpt_probes.size() >= max_hwbkpt_probes_by_arch)
2713ea24 8405 s.print_warning (_F("Too many hardware breakpoint probes requested for %s (%zu vs. %u)",
b530b5b3 8406 s.architecture.c_str(), hwbkpt_probes.size(), max_hwbkpt_probes_by_arch));
dd225250
PS
8407}
8408
8409void
8410hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
8411{
dac77b80 8412 if (hwbkpt_probes.empty()) return;
dd225250
PS
8413
8414 s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
8415
8416 s.op->newline() << "#include <linux/perf_event.h>";
8417 s.op->newline() << "#include <linux/hw_breakpoint.h>";
8418 s.op->newline();
8419
8420 // Forward declare the master entry functions
8421 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8422 s.op->line() << " int nmi,";
8423 s.op->line() << " struct perf_sample_data *data,";
8424 s.op->line() << " struct pt_regs *regs);";
79189b84 8425
dd225250
PS
8426 // Emit the actual probe list.
8427
8428 s.op->newline() << "static struct perf_event_attr ";
dac77b80 8429 s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8430
8431 s.op->newline() << "static struct perf_event **";
dac77b80 8432 s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
dd225250
PS
8433 s.op->newline() << "static struct stap_hwbkpt_probe {";
8434 s.op->newline() << "int registered_p:1;";
43650b10 8435// registered_p = 0 signifies a probe that is unregistered (or failed)
dd225250
PS
8436// registered_p = 1 signifies a probe that got registered successfully
8437
faea5e16 8438 // Symbol Names are mostly small and uniform enough
dd225250 8439 // to justify putting const char*.
dac77b80 8440 s.op->newline() << "const char * const symbol;";
dd225250
PS
8441
8442 s.op->newline() << "const unsigned long address;";
8443 s.op->newline() << "uint8_t atype;";
bb0a4e12 8444 s.op->newline() << "unsigned int len;";
26e63673 8445 s.op->newline() << "struct stap_probe * const probe;";
dd225250
PS
8446 s.op->newline() << "} stap_hwbkpt_probes[] = {";
8447 s.op->indent(1);
8448
dac77b80 8449 for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
dd225250 8450 {
dac77b80 8451 hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
dd225250 8452 s.op->newline() << "{";
dd225250
PS
8453 if (p->symbol_name.size())
8454 s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
8455 else
8456 s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
8457 switch(p->hwbkpt_access){
8458 case HWBKPT_READ:
8459 s.op->line() << " .atype=HW_BREAKPOINT_R ,";
bb0a4e12 8460 break;
dd225250
PS
8461 case HWBKPT_WRITE:
8462 s.op->line() << " .atype=HW_BREAKPOINT_W ,";
bb0a4e12 8463 break;
dd225250
PS
8464 case HWBKPT_RW:
8465 s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
bb0a4e12 8466 break;
dd225250
PS
8467 };
8468 s.op->line() << " .len=" << p->hwbkpt_len << ",";
faea5e16 8469 s.op->line() << " .probe=" << common_probe_init (p) << ",";
dd225250 8470 s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
dd225250
PS
8471 s.op->line() << " },";
8472 }
dac77b80 8473 s.op->newline(-1) << "};";
dd225250
PS
8474
8475 // Emit the hwbkpt callback function
8476 s.op->newline() ;
8477 s.op->newline() << "static int enter_hwbkpt_probe (struct perf_event *bp,";
8478 s.op->line() << " int nmi,";
8479 s.op->line() << " struct perf_sample_data *data,";
8480 s.op->line() << " struct pt_regs *regs) {";
dac77b80
FCE
8481 s.op->newline(1) << "unsigned int i;";
8482 s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return -1;";
8483 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
8484 s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8485 // XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
8486 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) {";
8487 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = &stap_hwbkpt_probes[i];";
6eefe942
MW
8488 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "sdp->probe",
8489 "_STP_PROBE_HANDLER_HWBKPT");
d9aed31e
MW
8490 s.op->newline() << "if (user_mode(regs)) {";
8491 s.op->newline(1)<< "c->probe_flags |= _STP_PROBE_STATE_USER_MODE;";
8492 s.op->newline() << "c->uregs = regs;";
8493 s.op->newline(-1) << "} else {";
8494 s.op->newline(1) << "c->kregs = regs;";
8495 s.op->newline(-1) << "}";
26e63673 8496 s.op->newline() << "(*sdp->probe->ph) (c);";
7baf48e9 8497 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
dac77b80 8498 s.op->newline(-1) << "}";
dd225250
PS
8499 s.op->newline(-1) << "}";
8500 s.op->newline() << "return 0;";
dac77b80 8501 s.op->newline(-1) << "}";
dd225250
PS
8502}
8503
8504void
8505hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
8506{
dac77b80 8507 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250
PS
8508 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
8509 s.op->newline() << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
8510 s.op->newline() << "void *addr = (void *) sdp->address;";
8511 s.op->newline() << "const char *hwbkpt_symbol_name = addr ? NULL : sdp->symbol;";
dac77b80
FCE
8512 s.op->newline() << "hw_breakpoint_init(hp);";
8513 s.op->newline() << "if (addr)";
8514 s.op->newline(1) << "hp->bp_addr = (unsigned long) addr;";
8515 s.op->newline(-1) << "else { ";
8516 s.op->newline(1) << "hp->bp_addr = kallsyms_lookup_name(hwbkpt_symbol_name);";
8517 s.op->newline() << "if (!hp->bp_addr) { ";
26e63673 8518 s.op->newline(1) << "_stp_warn(\"Probe %s registration skipped: invalid symbol %s \",sdp->probe->pp,hwbkpt_symbol_name);";
dac77b80
FCE
8519 s.op->newline() << "continue;";
8520 s.op->newline(-1) << "}";
8521 s.op->newline(-1) << "}";
8522 s.op->newline() << "hp->bp_type = sdp->atype;";
8523
8524 // On x86 & x86-64, hp->bp_len is not just a number but a macro/enum (!?!).
c57ea854 8525 if (s.architecture == "i386" || s.architecture == "x86_64" )
dac77b80
FCE
8526 {
8527 s.op->newline() << "switch(sdp->len) {";
8528 s.op->newline() << "case 1:";
8529 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_1;";
8530 s.op->newline() << "break;";
8531 s.op->newline(-1) << "case 2:";
8532 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_2;";
8533 s.op->newline() << "break;";
8534 s.op->newline(-1) << "case 3:";
8535 s.op->newline() << "case 4:";
8536 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_4;";
8537 s.op->newline() << "break;";
8538 s.op->newline(-1) << "case 5:";
8539 s.op->newline() << "case 6:";
8540 s.op->newline() << "case 7:";
8541 s.op->newline() << "case 8:";
8542 s.op->newline() << "default:"; // XXX: could instead reject
8543 s.op->newline(1) << "hp->bp_len = HW_BREAKPOINT_LEN_8;";
8544 s.op->newline() << "break;";
8545 s.op->newline(-1) << "}";
8546 }
8547 else // other architectures presumed straightforward
8548 s.op->newline() << "hp->bp_len = sdp->len;";
8549
26e63673 8550 s.op->newline() << "probe_point = sdp->probe->pp;"; // for error messages
b273669e
MW
8551 s.op->newline() << "#ifdef STAPCONF_HW_BREAKPOINT_CONTEXT";
8552 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe, NULL);";
8553 s.op->newline() << "#else";
dac77b80 8554 s.op->newline() << "stap_hwbkpt_ret_array[i] = register_wide_hw_breakpoint(hp, (void *)&enter_hwbkpt_probe);";
b273669e 8555 s.op->newline() << "#endif";
43650b10 8556 s.op->newline() << "rc = 0;";
dac77b80 8557 s.op->newline() << "if (IS_ERR(stap_hwbkpt_ret_array[i])) {";
43650b10
WC
8558 s.op->newline(1) << "rc = PTR_ERR(stap_hwbkpt_ret_array[i]);";
8559 s.op->newline() << "stap_hwbkpt_ret_array[i] = 0;";
8560 s.op->newline(-1) << "}";
217ef1f4
WC
8561 s.op->newline() << "if (rc) {";
8562 s.op->newline(1) << "_stp_warn(\"Hwbkpt probe %s: registration error %d, addr %p, name %s\", probe_point, rc, addr, hwbkpt_symbol_name);";
43650b10 8563 s.op->newline() << "sdp->registered_p = 0;";
dac77b80 8564 s.op->newline(-1) << "}";
dd225250 8565 s.op->newline() << " else sdp->registered_p = 1;";
dd225250
PS
8566 s.op->newline(-1) << "}"; // for loop
8567}
8568
8569void
8570hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
8571{
8572 //Unregister hwbkpt probes.
dac77b80 8573 s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
dd225250 8574 s.op->newline(1) << "struct stap_hwbkpt_probe *sdp = & stap_hwbkpt_probes[i];";
dac77b80
FCE
8575 s.op->newline() << "if (sdp->registered_p == 0) continue;";
8576 s.op->newline() << "unregister_wide_hw_breakpoint(stap_hwbkpt_ret_array[i]);";
dd225250
PS
8577 s.op->newline() << "sdp->registered_p = 0;";
8578 s.op->newline(-1) << "}";
8579}
8580
8581struct hwbkpt_builder: public derived_probe_builder
8582{
8583 hwbkpt_builder() {}
8584 virtual void build(systemtap_session & sess,
8585 probe * base,
8586 probe_point * location,
8587 literal_map_t const & parameters,
8588 vector<derived_probe *> & finished_results);
8589};
8590
8591void
8592hwbkpt_builder::build(systemtap_session & sess,
8593 probe * base,
8594 probe_point * location,
8595 literal_map_t const & parameters,
8596 vector<derived_probe *> & finished_results)
8597{
8598 string symbol_str_val;
8599 int64_t hwbkpt_address, len;
8600 bool has_addr, has_symbol_str, has_write, has_rw, has_len;
8601
b47f3a55 8602 if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
b530b5b3 8603 throw semantic_error (_("CONFIG_PERF_EVENTS not available on this kernel"),
b47f3a55
FCE
8604 location->components[0]->tok);
8605 if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
b530b5b3 8606 throw semantic_error (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
b47f3a55
FCE
8607 location->components[0]->tok);
8608
dd225250
PS
8609 has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
8610 has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
8611 has_len = get_param (parameters, TOK_LENGTH, len);
8612 has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
8613 has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
8614
8615 if (!has_len)
8616 len = 1;
8617
8618 if (has_addr)
8619 finished_results.push_back (new hwbkpt_derived_probe (base,
8620 location,
8621 hwbkpt_address,
8622 "",len,0,
8623 has_write,
8624 has_rw));
5d8a0aea 8625 else if (has_symbol_str)
dd225250
PS
8626 finished_results.push_back (new hwbkpt_derived_probe (base,
8627 location,
8628 0,
8629 symbol_str_val,len,0,
8630 has_write,
8631 has_rw));
5d8a0aea
FCE
8632 else
8633 assert (0);
dd225250 8634}
342d3f96 8635
0a6f5a3f
JS
8636// ------------------------------------------------------------------------
8637// statically inserted kernel-tracepoint derived probes
8638// ------------------------------------------------------------------------
8639
6fb70fb7 8640struct tracepoint_arg
79189b84 8641{
ad370dcc 8642 string name, c_type, typecast;
dcaa1a65 8643 bool usable, used, isptr;
f8a968bc 8644 Dwarf_Die type_die;
dcaa1a65 8645 tracepoint_arg(): usable(false), used(false), isptr(false) {}
6fb70fb7 8646};
79189b84 8647
0a6f5a3f
JS
8648struct tracepoint_derived_probe: public derived_probe
8649{
79189b84
JS
8650 tracepoint_derived_probe (systemtap_session& s,
8651 dwflpp& dw, Dwarf_Die& func_die,
8652 const string& tracepoint_name,
8653 probe* base_probe, probe_point* location);
bc9a523d 8654
79189b84 8655 systemtap_session& sess;
6fb70fb7
JS
8656 string tracepoint_name, header;
8657 vector <struct tracepoint_arg> args;
bc9a523d 8658
6fb70fb7 8659 void build_args(dwflpp& dw, Dwarf_Die& func_die);
d0bfd2ac 8660 void getargs (std::list<std::string> &arg_set) const;
79189b84 8661 void join_group (systemtap_session& s);
3e3bd7b6 8662 void print_dupe_stamp(ostream& o);
0a6f5a3f 8663};
79189b84
JS
8664
8665
0a6f5a3f 8666struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
79189b84 8667{
79189b84
JS
8668 void emit_module_decls (systemtap_session& s);
8669 void emit_module_init (systemtap_session& s);
8670 void emit_module_exit (systemtap_session& s);
0a6f5a3f 8671};
79189b84 8672
bc9a523d 8673
f8a968bc
JS
8674struct tracepoint_var_expanding_visitor: public var_expanding_visitor
8675{
8676 tracepoint_var_expanding_visitor(dwflpp& dw, const string& probe_name,
8677 vector <struct tracepoint_arg>& args):
8678 dw (dw), probe_name (probe_name), args (args) {}
8679 dwflpp& dw;
8680 const string& probe_name;
8681 vector <struct tracepoint_arg>& args;
bc9a523d 8682
f8a968bc
JS
8683 void visit_target_symbol (target_symbol* e);
8684 void visit_target_symbol_arg (target_symbol* e);
8685 void visit_target_symbol_context (target_symbol* e);
8686};
79189b84
JS
8687
8688
f8a968bc
JS
8689void
8690tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
75ead1f7 8691{
cc9001af 8692 string argname = e->sym_name();
75ead1f7 8693
f8a968bc
JS
8694 // search for a tracepoint parameter matching this name
8695 tracepoint_arg *arg = NULL;
8696 for (unsigned i = 0; i < args.size(); ++i)
dcaa1a65 8697 if (args[i].usable && args[i].name == argname)
f8a968bc
JS
8698 {
8699 arg = &args[i];
8700 arg->used = true;
8701 break;
8702 }
75ead1f7 8703
f8a968bc
JS
8704 if (arg == NULL)
8705 {
8706 stringstream alternatives;
8707 for (unsigned i = 0; i < args.size(); ++i)
8708 alternatives << " $" << args[i].name;
046e7190 8709 alternatives << " $$name $$parms $$vars";
75ead1f7 8710
f8a968bc
JS
8711 // We hope that this value ends up not being referenced after all, so it
8712 // can be optimized out quietly.
b530b5b3
LB
8713 throw semantic_error(_F("unable to find tracepoint variable '%s' (alternatives: %s)",
8714 e->name.c_str(), alternatives.str().c_str()), e->tok);
f8a968bc
JS
8715 // NB: we can have multiple errors, since a target variable
8716 // may be expanded in several different contexts:
8717 // trace ("*") { $foo->bar }
f8a968bc 8718 }
75ead1f7 8719
f8a968bc 8720 // make sure we're not dereferencing base types
dc5a09fc 8721 if (!arg->isptr)
d19a9a82 8722 e->assert_no_components("tracepoint", true);
75ead1f7 8723
f8a968bc
JS
8724 // we can only write to dereferenced fields, and only if guru mode is on
8725 bool lvalue = is_active_lvalue(e);
8726 if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
b3741c9d 8727 throw semantic_error(_F("write to tracepoint variable '%s' not permitted; need stap -g", e->name.c_str()), e->tok);
c69a87e0 8728
ad370dcc
JS
8729 // XXX: if a struct/union arg is passed by value, then writing to its fields
8730 // is also meaningless until you dereference past a pointer member. It's
8731 // harder to detect and prevent that though...
75ead1f7 8732
f8a968bc
JS
8733 if (e->components.empty())
8734 {
03c75a4a 8735 if (e->addressof)
b530b5b3 8736 throw semantic_error(_("cannot take address of tracepoint variable"), e->tok);
a45664f4 8737
3e3bd7b6 8738 // Just grab the value from the probe locals
a45664f4
JS
8739 symbol* sym = new symbol;
8740 sym->tok = e->tok;
8741 sym->name = "__tracepoint_arg_" + arg->name;
8742 provide (sym);
f8a968bc
JS
8743 }
8744 else
8745 {
5f36109e
JS
8746 // make a copy of the original as a bare target symbol for the tracepoint
8747 // value, which will be passed into the dwarf dereferencing code
8748 target_symbol* e2 = deep_copy_visitor::deep_copy(e);
8749 e2->components.clear();
8750
8751 if (e->components.back().type == target_symbol::comp_pretty_print)
8752 {
8753 if (lvalue)
b530b5b3 8754 throw semantic_error(_("cannot write to pretty-printed variable"), e->tok);
5f36109e 8755
d19a9a82 8756 dwarf_pretty_print dpp(dw, &arg->type_die, e2, arg->isptr, false, *e);
5f36109e
JS
8757 dpp.expand()->visit (this);
8758 return;
8759 }
8760
f8a968bc
JS
8761 // Synthesize a function to dereference the dwarf fields,
8762 // with a pointer parameter that is the base tracepoint variable
8763 functiondecl *fdecl = new functiondecl;
59de45f1 8764 fdecl->synthetic = true;
f8a968bc
JS
8765 fdecl->tok = e->tok;
8766 embeddedcode *ec = new embeddedcode;
8767 ec->tok = e->tok;
75ead1f7 8768
f8a968bc 8769 string fname = (string(lvalue ? "_tracepoint_tvar_set" : "_tracepoint_tvar_get")
cc9001af 8770 + "_" + e->sym_name()
aca66a36 8771 + "_" + lex_cast(tick++));
75ead1f7 8772
f8a968bc
JS
8773 fdecl->name = fname;
8774 fdecl->body = ec;
75ead1f7 8775
a5ce5211 8776 ec->code += EMBEDDED_FETCH_DEREF(false);
c69a87e0 8777 ec->code += dw.literal_stmt_for_pointer (&arg->type_die, e,
f8a968bc 8778 lvalue, fdecl->type);
75ead1f7 8779
f8a968bc
JS
8780 // Give the fdecl an argument for the raw tracepoint value
8781 vardecl *v1 = new vardecl;
8782 v1->type = pe_long;
8783 v1->name = "pointer";
8784 v1->tok = e->tok;
8785 fdecl->formal_args.push_back(v1);
75ead1f7 8786
6fda2dff
JS
8787 // Any non-literal indexes need to be passed in too.
8788 for (unsigned i = 0; i < e->components.size(); ++i)
8789 if (e->components[i].type == target_symbol::comp_expression_array_index)
8790 {
8791 vardecl *v = new vardecl;
8792 v->type = pe_long;
aca66a36 8793 v->name = "index" + lex_cast(i);
6fda2dff
JS
8794 v->tok = e->tok;
8795 fdecl->formal_args.push_back(v);
8796 }
8797
f8a968bc
JS
8798 if (lvalue)
8799 {
8800 // Modify the fdecl so it carries a pe_long formal
8801 // argument called "value".
75ead1f7 8802
f8a968bc
JS
8803 // FIXME: For the time being we only support setting target
8804 // variables which have base types; these are 'pe_long' in
8805 // stap's type vocabulary. Strings and pointers might be
8806 // reasonable, some day, but not today.
8807
8808 vardecl *v2 = new vardecl;
8809 v2->type = pe_long;
8810 v2->name = "value";
8811 v2->tok = e->tok;
8812 fdecl->formal_args.push_back(v2);
8813 }
8814 else
8815 ec->code += "/* pure */";
8816
64211010 8817 ec->code += "/* unprivileged */";
a5ce5211 8818 ec->code += EMBEDDED_FETCH_DEREF_DONE;
aff5d390 8819
f8809d54 8820 fdecl->join (dw.sess);
75ead1f7 8821
f8a968bc
JS
8822 // Synthesize a functioncall.
8823 functioncall* n = new functioncall;
8824 n->tok = e->tok;
8825 n->function = fname;
6fda2dff
JS
8826 n->args.push_back(require(e2));
8827
8828 // Any non-literal indexes need to be passed in too.
8829 for (unsigned i = 0; i < e->components.size(); ++i)
8830 if (e->components[i].type == target_symbol::comp_expression_array_index)
8831 n->args.push_back(require(e->components[i].expr_index));
75ead1f7 8832
f8a968bc
JS
8833 if (lvalue)
8834 {
8835 // Provide the functioncall to our parent, so that it can be
8836 // used to substitute for the assignment node immediately above
8837 // us.
8838 assert(!target_symbol_setter_functioncalls.empty());
8839 *(target_symbol_setter_functioncalls.top()) = n;
8840 }
75ead1f7 8841
f8a968bc
JS
8842 provide (n);
8843 }
75ead1f7
JS
8844}
8845
8846
f8a968bc
JS
8847void
8848tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
0a6f5a3f 8849{
03c75a4a 8850 if (e->addressof)
b530b5b3 8851 throw semantic_error(_("cannot take address of context variable"), e->tok);
03c75a4a 8852
f8a968bc 8853 if (is_active_lvalue (e))
b530b5b3 8854 throw semantic_error(_F("write to tracepoint '%s' not permitted", e->name.c_str()), e->tok);
0a6f5a3f 8855
277c21bc 8856 if (e->name == "$$name")
f8a968bc 8857 {
5f36109e
JS
8858 e->assert_no_components("tracepoint");
8859
bfdaad1e
DS
8860 // Synthesize an embedded expression.
8861 embedded_expr *expr = new embedded_expr;
8862 expr->tok = e->tok;
8863 expr->code = string("/* string */ /* pure */ ")
6dceb5c9 8864 + string("c->ips.tracepoint_name ? c->ips.tracepoint_name : \"\"");
bfdaad1e 8865 provide (expr);
f8a968bc 8866 }
277c21bc 8867 else if (e->name == "$$vars" || e->name == "$$parms")
f8a968bc 8868 {
5f36109e
JS
8869 e->assert_no_components("tracepoint", true);
8870
f8a968bc
JS
8871 token* pf_tok = new token(*e->tok);
8872 pf_tok->content = "sprintf";
0a6f5a3f 8873
d5e178c1 8874 print_format* pf = print_format::create(pf_tok);
0a6f5a3f 8875
f8a968bc 8876 for (unsigned i = 0; i < args.size(); ++i)
b278033a 8877 {
dcaa1a65
JS
8878 if (!args[i].usable)
8879 continue;
f8a968bc
JS
8880 if (i > 0)
8881 pf->raw_components += " ";
8882 pf->raw_components += args[i].name;
3e3bd7b6 8883 target_symbol *tsym = new target_symbol;
f8a968bc 8884 tsym->tok = e->tok;
277c21bc 8885 tsym->name = "$" + args[i].name;
5f36109e 8886 tsym->components = e->components;
b278033a 8887
f8a968bc
JS
8888 // every variable should always be accessible!
8889 tsym->saved_conversion_error = 0;
8890 expression *texp = require (tsym); // NB: throws nothing ...
14a97852
JS
8891 if (tsym->saved_conversion_error) // ... but this is how we know it happened.
8892 {
8893 if (dw.sess.verbose>2)
e26c2f83 8894 for (const semantic_error *c = tsym->saved_conversion_error;
14a97852 8895 c != 0; c = c->chain)
b530b5b3 8896 clog << _("variable location problem: ") << c->what() << endl;
14a97852
JS
8897 pf->raw_components += "=?";
8898 continue;
8899 }
b278033a 8900
5f36109e
JS
8901 if (!e->components.empty() &&
8902 e->components[0].type == target_symbol::comp_pretty_print)
8903 pf->raw_components += "=%s";
8904 else
8905 pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
f8a968bc
JS
8906 pf->args.push_back(texp);
8907 }
0a6f5a3f 8908
f8a968bc
JS
8909 pf->components = print_format::string_to_components(pf->raw_components);
8910 provide (pf);
b278033a 8911 }
f8a968bc
JS
8912 else
8913 assert(0); // shouldn't get here
0a6f5a3f
JS
8914}
8915
0a6f5a3f 8916void
f8a968bc 8917tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
0a6f5a3f 8918{
aff5d390 8919 try
c69a87e0 8920 {
8fa5f271
MW
8921 assert(e->name.size() > 0
8922 && ((e->name[0] == '$' && e->target_name == "")
8923 || (e->name == "@var" && e->target_name != "")));
aff5d390 8924
277c21bc 8925 if (e->name == "$$name" || e->name == "$$parms" || e->name == "$$vars")
c69a87e0 8926 visit_target_symbol_context (e);
8fa5f271
MW
8927 else if (e->name == "@var")
8928 throw semantic_error(_("cannot use @var DWARF variables in tracepoints"), e->tok);
c69a87e0
FCE
8929 else
8930 visit_target_symbol_arg (e);
8931 }
8932 catch (const semantic_error &er)
8933 {
1af1e62d 8934 e->chain (er);
c69a87e0
FCE
8935 provide (e);
8936 }
0a6f5a3f
JS
8937}
8938
8939
8940
79189b84
JS
8941tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
8942 dwflpp& dw, Dwarf_Die& func_die,
8943 const string& tracepoint_name,
8944 probe* base, probe_point* loc):
4c5d1300 8945 derived_probe (base, loc, true /* .components soon rewritten */),
79189b84 8946 sess (s), tracepoint_name (tracepoint_name)
56894e91 8947{
79189b84
JS
8948 // create synthetic probe point name; preserve condition
8949 vector<probe_point::component*> comps;
8950 comps.push_back (new probe_point::component (TOK_KERNEL));
8951 comps.push_back (new probe_point::component (TOK_TRACE, new literal_string (tracepoint_name)));
8952 this->sole_location()->components = comps;
8953
6fb70fb7
JS
8954 // fill out the available arguments in this tracepoint
8955 build_args(dw, func_die);
56894e91 8956
6fb70fb7
JS
8957 // determine which header defined this tracepoint
8958 string decl_file = dwarf_decl_file(&func_die);
d4393459
FCE
8959 header = decl_file;
8960
8961#if 0 /* This convention is not enforced. */
6fb70fb7
JS
8962 size_t header_pos = decl_file.rfind("trace/");
8963 if (header_pos == string::npos)
8964 throw semantic_error ("cannot parse header location for tracepoint '"
8965 + tracepoint_name + "' in '"
8966 + decl_file + "'");
8967 header = decl_file.substr(header_pos);
d4393459 8968#endif
56894e91 8969
6fb70fb7
JS
8970 // tracepoints from FOO_event_types.h should really be included from FOO.h
8971 // XXX can dwarf tell us the include hierarchy? it would be better to
8972 // ... walk up to see which one was directly included by tracequery.c
3c1b3d06 8973 // XXX: see also PR9993.
d4393459 8974 size_t header_pos = header.find("_event_types");
6fb70fb7
JS
8975 if (header_pos != string::npos)
8976 header.erase(header_pos, 12);
56894e91 8977
f8a968bc
JS
8978 // Now expand the local variables in the probe body
8979 tracepoint_var_expanding_visitor v (dw, name, args);
8b095b45 8980 v.replace (this->body);
a45664f4
JS
8981 for (unsigned i = 0; i < args.size(); i++)
8982 if (args[i].used)
8983 {
8984 vardecl* v = new vardecl;
8985 v->name = "__tracepoint_arg_" + args[i].name;
8986 v->tok = this->tok;
58701b78 8987 v->set_arity(0, this->tok);
a45664f4 8988 v->type = pe_long;
69aa668e 8989 v->synthetic = true;
a45664f4
JS
8990 this->locals.push_back (v);
8991 }
56894e91 8992
79189b84 8993 if (sess.verbose > 2)
ce0f6648 8994 clog << "tracepoint-based " << name << " tracepoint='" << tracepoint_name << "'" << endl;
79189b84 8995}
dc38c0ae 8996
56894e91 8997
f8a968bc 8998static bool
dcaa1a65 8999resolve_tracepoint_arg_type(tracepoint_arg& arg)
46b84a80 9000{
d19a9a82 9001 Dwarf_Die type;
dcaa1a65 9002 switch (dwarf_tag(&arg.type_die))
b20febf3 9003 {
f8a968bc
JS
9004 case DW_TAG_typedef:
9005 case DW_TAG_const_type:
9006 case DW_TAG_volatile_type:
9007 // iterate on the referent type
3d1ad340 9008 return (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die)
dcaa1a65 9009 && resolve_tracepoint_arg_type(arg));
f8a968bc 9010 case DW_TAG_base_type:
a52d2ac0 9011 case DW_TAG_enumeration_type:
f8a968bc 9012 // base types will simply be treated as script longs
dcaa1a65 9013 arg.isptr = false;
f8a968bc
JS
9014 return true;
9015 case DW_TAG_pointer_type:
dcaa1a65
JS
9016 // pointers can be treated as script longs,
9017 // and if we know their type, they can also be dereferenced
d19a9a82
JS
9018 type = arg.type_die;
9019 while (dwarf_attr_die(&arg.type_die, DW_AT_type, &arg.type_die))
9020 {
9021 // It still might be a non-type, e.g. const void,
9022 // so we need to strip away all qualifiers.
9023 int tag = dwarf_tag(&arg.type_die);
9024 if (tag != DW_TAG_typedef &&
9025 tag != DW_TAG_const_type &&
9026 tag != DW_TAG_volatile_type)
9027 {
9028 arg.isptr = true;
9029 break;
9030 }
9031 }
9032 if (!arg.isptr)
9033 arg.type_die = type;
ad370dcc
JS
9034 arg.typecast = "(intptr_t)";
9035 return true;
9036 case DW_TAG_structure_type:
9037 case DW_TAG_union_type:
9038 // for structs/unions which are passed by value, we turn it into
9039 // a pointer that can be dereferenced.
9040 arg.isptr = true;
9041 arg.typecast = "(intptr_t)&";
dcaa1a65 9042 return true;
f8a968bc
JS
9043 default:
9044 // should we consider other types too?
9045 return false;
b20febf3 9046 }
56894e91
JS
9047}
9048
9049
9050void
822a6a3d 9051tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
56894e91 9052{
6fb70fb7
JS
9053 Dwarf_Die arg;
9054 if (dwarf_child(&func_die, &arg) == 0)
9055 do
9056 if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
9057 {
9058 // build a tracepoint_arg for this parameter
9059 tracepoint_arg tparg;
23d106b9 9060 tparg.name = dwarf_diename(&arg);
56894e91 9061
6fb70fb7 9062 // read the type of this parameter
3d1ad340 9063 if (!dwarf_attr_die (&arg, DW_AT_type, &tparg.type_die)
f1c8f8a5 9064 || !dwarf_type_name(&tparg.type_die, tparg.c_type))
ce0f6648
LB
9065 throw semantic_error (_F("cannot get type of parameter '%s' of tracepoint '%s'",
9066 tparg.name.c_str(), tracepoint_name.c_str()));
a68f81a2 9067
dcaa1a65 9068 tparg.usable = resolve_tracepoint_arg_type(tparg);
6fb70fb7
JS
9069 args.push_back(tparg);
9070 if (sess.verbose > 4)
a52d2ac0
JS
9071 clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' %s",
9072 tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
9073 tparg.usable ? "ok" : "unavailable") << endl;
6fb70fb7
JS
9074 }
9075 while (dwarf_siblingof(&arg, &arg) == 0);
56894e91
JS
9076}
9077
dc38c0ae 9078void
d0bfd2ac 9079tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
dc38c0ae 9080{
dcaa1a65
JS
9081 for (unsigned i = 0; i < args.size(); ++i)
9082 if (args[i].usable)
d0bfd2ac 9083 arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
dc38c0ae
DS
9084}
9085
79189b84
JS
9086void
9087tracepoint_derived_probe::join_group (systemtap_session& s)
197a4d62 9088{
79189b84
JS
9089 if (! s.tracepoint_derived_probes)
9090 s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
9091 s.tracepoint_derived_probes->enroll (this);
9092}
e38d6504 9093
56894e91 9094
197a4d62 9095void
3e3bd7b6 9096tracepoint_derived_probe::print_dupe_stamp(ostream& o)
56894e91 9097{
3e3bd7b6
JS
9098 for (unsigned i = 0; i < args.size(); i++)
9099 if (args[i].used)
9100 o << "__tracepoint_arg_" << args[i].name << endl;
197a4d62 9101}
56894e91 9102
3e3bd7b6 9103
c9ccb642 9104static vector<string> tracepoint_extra_decls (systemtap_session& s, const string& header)
47dd066d 9105{
3c1b3d06
FCE
9106 vector<string> they_live;
9107 // PR 9993
9108 // XXX: may need this to be configurable
d4393459 9109 they_live.push_back ("#include <linux/skbuff.h>");
9e0cd21a
FCE
9110
9111 // PR11649: conditional extra header
9112 // for kvm tracepoints in 2.6.33ish
9113 if (s.kernel_config["CONFIG_KVM"] != string("")) {
d4393459
FCE
9114 they_live.push_back ("#include <linux/kvm_host.h>");
9115 }
9116
50b72692 9117 if (header.find("xfs") != string::npos && s.kernel_config["CONFIG_XFS_FS"] != string("")) {
d4393459 9118 they_live.push_back ("#define XFS_BIG_BLKNOS 1");
88637c31
FCE
9119 if (s.kernel_source_tree != "")
9120 they_live.push_back ("#include \"fs/xfs/xfs_types.h\""); // in kernel-source tree
d4393459
FCE
9121 they_live.push_back ("struct xfs_mount;");
9122 they_live.push_back ("struct xfs_inode;");
9123 they_live.push_back ("struct xfs_buf;");
9124 they_live.push_back ("struct xfs_bmbt_irec;");
c2cf1b87 9125 they_live.push_back ("struct xfs_trans;");
9e0cd21a 9126 }
d4393459 9127
50b72692 9128 if (header.find("nfs") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
d4393459
FCE
9129 they_live.push_back ("struct rpc_task;");
9130 }
9131
9132 they_live.push_back ("#include <asm/cputime.h>");
9133
c2cf1b87
FCE
9134 // linux 3.0
9135 they_live.push_back ("struct cpu_workqueue_struct;");
9136
50b72692 9137 if (header.find("ext4") != string::npos && s.kernel_config["CONFIG_EXT4_FS"] != string(""))
c2cf1b87
FCE
9138 if (s.kernel_source_tree != "")
9139 they_live.push_back ("#include \"fs/ext4/ext4.h\""); // in kernel-source tree
9140
50b72692
HP
9141 if (header.find("ext3") != string::npos && s.kernel_config["CONFIG_EXT3_FS"] != string(""))
9142 they_live.push_back ("struct ext3_reserve_window_node;");
9143
3c1b3d06
FCE
9144 return they_live;
9145}
47dd066d
WC
9146
9147
9148void
79189b84 9149tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
47dd066d 9150{
79189b84
JS
9151 if (probes.empty())
9152 return;
47dd066d 9153
96b030fe
JS
9154 s.op->newline() << "/* ---- tracepoint probes ---- */";
9155 s.op->newline();
79189b84 9156
47dd066d 9157
a4b9c3b3
FCE
9158 // We create a MODULE_aux_N.c file for each tracepoint header, to allow them
9159 // to be separately compiled. That's because kernel tracepoint headers sometimes
9160 // conflict. PR13155.
9161
9162 map<string,translator_output*> per_header_aux;
9163 // GC NB: the translator_output* structs are owned/retained by the systemtap_session.
47dd066d 9164
6fb70fb7
JS
9165 for (unsigned i = 0; i < probes.size(); ++i)
9166 {
9167 tracepoint_derived_probe *p = probes[i];
75ae2ec9 9168 string header = p->header;
5f73a260 9169
a4b9c3b3
FCE
9170 // We cache the auxiliary output files on a per-header basis. We don't
9171 // need one aux file per tracepoint, only one per tracepoint-header.
9172 translator_output *tpop = per_header_aux[header];
9173 if (tpop == 0)
9174 {
9175 tpop = s.op_create_auxiliary();
9176 per_header_aux[header] = tpop;
9177
9178 // PR9993: Add extra headers to work around undeclared types in individual
9179 // include/trace/foo.h files
9180 const vector<string>& extra_decls = tracepoint_extra_decls (s, header);
9181 for (unsigned z=0; z<extra_decls.size(); z++)
9182 tpop->newline() << extra_decls[z] << "\n";
720c435f 9183
a4b9c3b3
FCE
9184 // strip include/ substring, the same way as done in get_tracequery_module()
9185 size_t root_pos = header.rfind("include/");
9186 header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
bfffa443
FCE
9187
9188 tpop->newline() << "#include <linux/tracepoint.h>" << endl;
a4b9c3b3 9189 tpop->newline() << "#include <" << header << ">";
720c435f 9190
a4b9c3b3
FCE
9191 // Starting in 2.6.35, at the same time NOARGS was added, the callback
9192 // always has a void* as the first parameter. PR11599
9193 tpop->newline() << "#ifdef DECLARE_TRACE_NOARGS";
9194 tpop->newline() << "#define STAP_TP_DATA , NULL";
9195 tpop->newline() << "#define STAP_TP_PROTO void *cb_data"
9196 << " __attribute__ ((unused))";
9197 if (!p->args.empty())
9198 tpop->line() << ",";
9199 tpop->newline() << "#else";
9200 tpop->newline() << "#define STAP_TP_DATA";
9201 tpop->newline() << "#define STAP_TP_PROTO";
9202 if (p->args.empty())
9203 tpop->line() << " void";
9204 tpop->newline() << "#endif";
720c435f
JS
9205
9206 tpop->newline() << "#define intptr_t long";
a4b9c3b3
FCE
9207 }
9208
720c435f
JS
9209 // collect the args that are actually in use
9210 vector<const tracepoint_arg*> used_args;
6fb70fb7 9211 for (unsigned j = 0; j < p->args.size(); ++j)
720c435f
JS
9212 if (p->args[j].used)
9213 used_args.push_back(&p->args[j]);
9214
a4b9c3b3
FCE
9215 // forward-declare the generated-side tracepoint callback
9216 tpop->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9217 tpop->indent(2);
9218 if (used_args.empty())
9219 tpop->line() << "void";
9220 for (unsigned j = 0; j < used_args.size(); ++j)
6fb70fb7
JS
9221 {
9222 if (j > 0)
a4b9c3b3
FCE
9223 tpop->line() << ", ";
9224 tpop->line() << "int64_t";
6fb70fb7 9225 }
720c435f
JS
9226 tpop->line() << ");";
9227 tpop->indent(-2);
5f73a260 9228
a4b9c3b3
FCE
9229 // define the generated-side tracepoint callback - in the main translator-output
9230 s.op->newline() << "void enter_real_tracepoint_probe_" << i << "(";
720c435f
JS
9231 s.op->indent(2);
9232 if (used_args.empty())
9233 s.op->newline() << "void";
9234 for (unsigned j = 0; j < used_args.size(); ++j)
a4b9c3b3 9235 {
a4b9c3b3
FCE
9236 if (j > 0)
9237 s.op->line() << ", ";
720c435f 9238 s.op->newline() << "int64_t __tracepoint_arg_" << used_args[j]->name;
6fb70fb7 9239 }
5f73a260
JS
9240 s.op->newline() << ")";
9241 s.op->newline(-2) << "{";
26e63673 9242 s.op->newline(1) << "struct stap_probe * const probe = "
faea5e16 9243 << common_probe_init (p) << ";";
6eefe942
MW
9244 common_probe_entryfn_prologue (s.op, "STAP_SESSION_RUNNING", "probe",
9245 "_STP_PROBE_HANDLER_TRACEPOINT");
6dceb5c9 9246 s.op->newline() << "c->ips.tracepoint_name = "
c12d974f
FCE
9247 << lex_cast_qstring (p->tracepoint_name)
9248 << ";";
720c435f
JS
9249 for (unsigned j = 0; j < used_args.size(); ++j)
9250 {
9251 s.op->newline() << "c->probe_locals." << p->name
0386bbcf 9252 << "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
720c435f
JS
9253 << " = __tracepoint_arg_" << used_args[j]->name << ";";
9254 }
26e63673 9255 s.op->newline() << "(*probe->ph) (c);";
7baf48e9 9256 common_probe_entryfn_epilogue (s.op, true, s.suppress_handler_errors);
6fb70fb7 9257 s.op->newline(-1) << "}";
47dd066d 9258
a4b9c3b3 9259 // define the real tracepoint callback function
720c435f 9260 tpop->newline() << "static void enter_tracepoint_probe_" << i << "(";
a4b9c3b3
FCE
9261 tpop->newline(2) << "STAP_TP_PROTO";
9262 for (unsigned j = 0; j < p->args.size(); ++j)
9263 {
9264 if (j > 0)
9265 tpop->line() << ", ";
9266 tpop->newline() << p->args[j].c_type << " __tracepoint_arg_" << p->args[j].name;
9267 }
9268 tpop->newline() << ")";
9269 tpop->newline(-2) << "{";
720c435f
JS
9270 tpop->newline(1) << "enter_real_tracepoint_probe_" << i << "(";
9271 tpop->indent(2);
9272 for (unsigned j = 0; j < used_args.size(); ++j)
9273 {
9274 if (j > 0)
9275 tpop->line() << ", ";
9276 tpop->newline() << "(int64_t)" << used_args[j]->typecast
9277 << "__tracepoint_arg_" << used_args[j]->name;
9278 }
9279 tpop->newline() << ");";
9280 tpop->newline(-3) << "}";
a4b9c3b3
FCE
9281
9282
96b030fe 9283 // emit normalized registration functions
720c435f 9284 tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9285 tpop->newline(1) << "return register_trace_" << p->tracepoint_name
5f73a260 9286 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3 9287 tpop->newline(-1) << "}";
47dd066d 9288
86758d5f
JS
9289 // NB: we're not prepared to deal with unreg failures. However, failures
9290 // can only occur if the tracepoint doesn't exist (yet?), or if we
9291 // weren't even registered. The former should be OKed by the initial
9292 // registration call, and the latter is safe to ignore.
720c435f 9293 tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
a4b9c3b3 9294 tpop->newline(1) << "(void) unregister_trace_" << p->tracepoint_name
5f73a260 9295 << "(enter_tracepoint_probe_" << i << " STAP_TP_DATA);";
a4b9c3b3
FCE
9296 tpop->newline(-1) << "}";
9297 tpop->newline();
5f73a260 9298
720c435f
JS
9299 // declare normalized registration functions
9300 s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
9301 s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
5f73a260 9302
a4b9c3b3 9303 tpop->assert_0_indent();
af304783
DS
9304 }
9305
96b030fe
JS
9306 // emit an array of registration functions for easy init/shutdown
9307 s.op->newline() << "static struct stap_tracepoint_probe {";
9308 s.op->newline(1) << "int (*reg)(void);";
86758d5f 9309 s.op->newline(0) << "void (*unreg)(void);";
96b030fe
JS
9310 s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
9311 s.op->indent(1);
9312 for (unsigned i = 0; i < probes.size(); ++i)
9313 {
9314 s.op->newline () << "{";
9315 s.op->line() << " .reg=&register_tracepoint_probe_" << i << ",";
9316 s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
9317 s.op->line() << " },";
9318 }
9319 s.op->newline(-1) << "};";
9320 s.op->newline();
47dd066d
WC
9321}
9322
9323
79189b84
JS
9324void
9325tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
47dd066d 9326{
79189b84
JS
9327 if (probes.size () == 0)
9328 return;
47dd066d 9329
79189b84 9330 s.op->newline() << "/* init tracepoint probes */";
96b030fe
JS
9331 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
9332 s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
9333 s.op->newline() << "if (rc) {";
9334 s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
9335 s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
9336 s.op->newline(-1) << "break;"; // don't attempt to register any more probes
9337 s.op->newline(-1) << "}";
9338 s.op->newline(-1) << "}";
47dd066d 9339
bc9a523d
FCE
9340 // This would be technically proper (on those autoconf-detectable
9341 // kernels that include this function in tracepoint.h), however we
9342 // already make several calls to synchronze_sched() during our
9343 // shutdown processes.
47dd066d 9344
bc9a523d
FCE
9345 // s.op->newline() << "if (rc)";
9346 // s.op->newline(1) << "tracepoint_synchronize_unregister();";
9347 // s.op->indent(-1);
79189b84 9348}
47dd066d
WC
9349
9350
79189b84
JS
9351void
9352tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
47dd066d 9353{
79189b84
JS
9354 if (probes.empty())
9355 return;
47dd066d 9356
96b030fe
JS
9357 s.op->newline() << "/* deregister tracepoint probes */";
9358 s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
9359 s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
9360 s.op->indent(-1);
47dd066d 9361
bc9a523d 9362 // Not necessary: see above.
47dd066d 9363
bc9a523d 9364 // s.op->newline() << "tracepoint_synchronize_unregister();";
79189b84 9365}
b20febf3 9366
47dd066d 9367
75ead1f7 9368struct tracepoint_query : public base_query
47dd066d 9369{
75ead1f7
JS
9370 tracepoint_query(dwflpp & dw, const string & tracepoint,
9371 probe * base_probe, probe_point * base_loc,
9372 vector<derived_probe *> & results):
9373 base_query(dw, "*"), tracepoint(tracepoint),
9374 base_probe(base_probe), base_loc(base_loc),
9375 results(results) {}
47dd066d 9376
75ead1f7 9377 const string& tracepoint;
47dd066d 9378
75ead1f7
JS
9379 probe * base_probe;
9380 probe_point * base_loc;
9381 vector<derived_probe *> & results;
f982c59b 9382 set<string> probed_names;
47dd066d 9383
75ead1f7
JS
9384 void handle_query_module();
9385 int handle_query_cu(Dwarf_Die * cudie);
9386 int handle_query_func(Dwarf_Die * func);
822a6a3d 9387 void query_library (const char *) {}
576eaefe 9388 void query_plt (const char *entry, size_t addr) {}
b20febf3 9389
75ead1f7
JS
9390 static int tracepoint_query_cu (Dwarf_Die * cudie, void * arg);
9391 static int tracepoint_query_func (Dwarf_Die * func, base_query * query);
9392};
47dd066d
WC
9393
9394
9395void
75ead1f7 9396tracepoint_query::handle_query_module()
47dd066d 9397{
75ead1f7 9398 // look for the tracepoints in each CU
337b7c44 9399 dw.iterate_over_cus(tracepoint_query_cu, this, false);
47dd066d
WC
9400}
9401
9402
75ead1f7
JS
9403int
9404tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
47dd066d 9405{
75ead1f7 9406 dw.focus_on_cu (cudie);
47dd066d 9407
75ead1f7
JS
9408 // look at each function to see if it's a tracepoint
9409 string function = "stapprobe_" + tracepoint;
9410 return dw.iterate_over_functions (tracepoint_query_func, this, function);
47dd066d
WC
9411}
9412
9413
75ead1f7
JS
9414int
9415tracepoint_query::handle_query_func(Dwarf_Die * func)
47dd066d 9416{
75ead1f7 9417 dw.focus_on_function (func);
47dd066d 9418
60d98537 9419 assert(startswith(dw.function_name, "stapprobe_"));
75ead1f7 9420 string tracepoint_instance = dw.function_name.substr(10);
f982c59b
JS
9421
9422 // check for duplicates -- sometimes tracepoint headers may be indirectly
9423 // included in more than one of our tracequery modules.
9424 if (!probed_names.insert(tracepoint_instance).second)
9425 return DWARF_CB_OK;
9426
79189b84
JS
9427 derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
9428 tracepoint_instance,
9429 base_probe, base_loc);
9430 results.push_back (dp);
75ead1f7 9431 return DWARF_CB_OK;
47dd066d
WC
9432}
9433
9434
75ead1f7
JS
9435int
9436tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, void * arg)
47dd066d 9437{
75ead1f7 9438 tracepoint_query * q = static_cast<tracepoint_query *>(arg);
85007c04 9439 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9440 return q->handle_query_cu(cudie);
47dd066d
WC
9441}
9442
9443
75ead1f7
JS
9444int
9445tracepoint_query::tracepoint_query_func (Dwarf_Die * func, base_query * query)
47dd066d 9446{
75ead1f7 9447 tracepoint_query * q = static_cast<tracepoint_query *>(query);
85007c04 9448 if (pending_interrupts) return DWARF_CB_ABORT;
75ead1f7 9449 return q->handle_query_func(func);
47dd066d
WC
9450}
9451
9452
0a6f5a3f 9453struct tracepoint_builder: public derived_probe_builder
47dd066d 9454{
0a6f5a3f
JS
9455private:
9456 dwflpp *dw;
9457 bool init_dw(systemtap_session& s);
c9ccb642
FCE
9458 void get_tracequery_modules(systemtap_session& s,
9459 const vector<string>& headers,
9460 vector<string>& modules);
47dd066d 9461
0a6f5a3f 9462public:
47dd066d 9463
0a6f5a3f
JS
9464 tracepoint_builder(): dw(0) {}
9465 ~tracepoint_builder() { delete dw; }
47dd066d 9466
0a6f5a3f
JS
9467 void build_no_more (systemtap_session& s)
9468 {
9469 if (dw && s.verbose > 3)
b530b5b3 9470 clog << _("tracepoint_builder releasing dwflpp") << endl;
0a6f5a3f
JS
9471 delete dw;
9472 dw = NULL;
435f53a7
FCE
9473
9474 delete_session_module_cache (s);
0a6f5a3f 9475 }
47dd066d 9476
0a6f5a3f
JS
9477 void build(systemtap_session& s,
9478 probe *base, probe_point *location,
9479 literal_map_t const& parameters,
9480 vector<derived_probe*>& finished_results);
9481};
47dd066d 9482
47dd066d 9483
c9ccb642 9484
2a0e62a8 9485// Create (or cache) one or more tracequery .o modules, based upon the
c9ccb642
FCE
9486// tracepoint-related header files given. Return the generated or cached
9487// modules[].
9488
9489void
9490tracepoint_builder::get_tracequery_modules(systemtap_session& s,
9491 const vector<string>& headers,
9492 vector<string>& modules)
0a6f5a3f 9493{
c95eddf7 9494 if (s.verbose > 2)
55e50c24 9495 {
ce0f6648 9496 clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
55e50c24
JS
9497 for (size_t i = 0; i < headers.size(); ++i)
9498 clog << " " << headers[i] << endl;
9499 }
c95eddf7 9500
2a0e62a8
JS
9501 map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
9502 // Map the headers to cache .o names. Note that this has side-effects of
c9ccb642
FCE
9503 // creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
9504 // so we prefer not to repeat this.
9505 vector<string> uncached_headers;
9506 for (size_t i=0; i<headers.size(); i++)
2a0e62a8 9507 headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
c9ccb642
FCE
9508
9509 // They may be in the cache already.
9510 if (s.use_cache && !s.poison_cache)
9511 for (size_t i=0; i<headers.size(); i++)
9512 {
9513 // see if the cached module exists
2a0e62a8 9514 const string& tracequery_path = headers_cache_obj[headers[i]];
c9ccb642
FCE
9515 if (!tracequery_path.empty() && file_exists(tracequery_path))
9516 {
9517 if (s.verbose > 2)
9518 clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
47dd066d 9519
c252fca2
JS
9520 // an empty file is a cached failure
9521 if (get_file_size(tracequery_path) > 0)
9522 modules.push_back (tracequery_path);
c9ccb642
FCE
9523 }
9524 else
9525 uncached_headers.push_back(headers[i]);
9526 }
9527 else
9528 uncached_headers = headers;
f982c59b 9529
c9ccb642
FCE
9530 // If we have nothing left to search for, quit
9531 if (uncached_headers.empty()) return;
55e50c24 9532
c9ccb642 9533 map<string,string> headers_tracequery_src; // header -> C-source code mapping
55e50c24 9534
c9ccb642
FCE
9535 // We could query several subsets of headers[] to make this go
9536 // faster, but let's KISS and do one at a time.
9537 for (size_t i=0; i<uncached_headers.size(); i++)
55e50c24 9538 {
c9ccb642
FCE
9539 const string& header = uncached_headers[i];
9540
9541 // create a tracequery source file
9542 ostringstream osrc;
9543
9544 // PR9993: Add extra headers to work around undeclared types in individual
9545 // include/trace/foo.h files
9546 vector<string> short_decls = tracepoint_extra_decls(s, header);
9547
9548 // add each requested tracepoint header
75ae2ec9 9549 size_t root_pos = header.rfind("include/");
832f100d 9550 short_decls.push_back(string("#include <") +
75ae2ec9 9551 ((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
d4393459 9552 string(">"));
f982c59b 9553
c9ccb642
FCE
9554 osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
9555 osrc << "#include <linux/tracepoint.h>" << endl;
832f100d
JS
9556
9557 // the kernel has changed this naming a few times, previously TPPROTO,
9558 // TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
9559 osrc << "#ifndef PARAMS" << endl;
9560 osrc << "#define PARAMS(args...) args" << endl;
9561 osrc << "#endif" << endl;
9562
c9ccb642
FCE
9563 // override DECLARE_TRACE to synthesize probe functions for us
9564 osrc << "#undef DECLARE_TRACE" << endl;
9565 osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
9566 osrc << " void stapprobe_##name(proto) {}" << endl;
832f100d 9567
c9ccb642
FCE
9568 // 2.6.35 added the NOARGS variant, but it's the same for us
9569 osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
9570 osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
9571 osrc << " DECLARE_TRACE(name, void, )" << endl;
832f100d
JS
9572
9573 // 2.6.38 added the CONDITION variant, which can also just redirect
9574 osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
9575 osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
9576 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
9577
c9ccb642
FCE
9578 // older tracepoints used DEFINE_TRACE, so redirect that too
9579 osrc << "#undef DEFINE_TRACE" << endl;
9580 osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
832f100d
JS
9581 osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
9582
c9ccb642
FCE
9583 // add the specified decls/#includes
9584 for (unsigned z=0; z<short_decls.size(); z++)
9585 osrc << "#undef TRACE_INCLUDE_FILE\n"
9586 << "#undef TRACE_INCLUDE_PATH\n"
9587 << short_decls[z] << "\n";
9588
9589 // finish up the module source
9590 osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
47dd066d 9591
c9ccb642
FCE
9592 // save the source file away
9593 headers_tracequery_src[header] = osrc.str();
55e50c24 9594 }
f982c59b 9595
c9ccb642 9596 // now build them all together
2a0e62a8 9597 map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
47dd066d 9598
c9ccb642 9599 // now plop them into the cache
b278033a 9600 if (s.use_cache)
c9ccb642
FCE
9601 for (size_t i=0; i<uncached_headers.size(); i++)
9602 {
9603 const string& header = uncached_headers[i];
2a0e62a8
JS
9604 const string& tracequery_obj = tracequery_objs[header];
9605 const string& tracequery_path = headers_cache_obj[header];
9606 if (tracequery_obj !="" && file_exists(tracequery_obj))
c9ccb642 9607 {
2a0e62a8 9608 copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
c9ccb642
FCE
9609 modules.push_back (tracequery_path);
9610 }
c252fca2
JS
9611 else
9612 // cache an empty file for failures
9613 copy_file("/dev/null", tracequery_path, s.verbose > 2);
c9ccb642 9614 }
f982c59b
JS
9615}
9616
9617
d4393459 9618
f982c59b
JS
9619bool
9620tracepoint_builder::init_dw(systemtap_session& s)
9621{
9622 if (dw != NULL)
9623 return true;
9624
9625 vector<string> tracequery_modules;
55e50c24 9626 vector<string> system_headers;
f982c59b
JS
9627
9628 glob_t trace_glob;
d4393459
FCE
9629
9630 // find kernel_source_tree
9631 if (s.kernel_source_tree == "")
f982c59b 9632 {
d4393459
FCE
9633 unsigned found;
9634 DwflPtr dwfl_ptr = setup_dwfl_kernel ("kernel", &found, s);
9635 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
9636 if (found)
9637 {
9638 Dwarf_Die *cudie = 0;
9639 Dwarf_Addr bias;
9640 while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
9641 {
e19ebcf7 9642 assert_no_interrupts();
d4393459
FCE
9643 Dwarf_Attribute attr;
9644 const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
9645 if (name)
9646 {
61f1a63b 9647 if (s.verbose > 2)
b530b5b3 9648 clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
61f1a63b 9649
d4393459
FCE
9650 s.kernel_source_tree = name;
9651 break; // skip others; modern Kbuild uses same comp_dir for them all
9652 }
9653 }
9654 }
9655 }
9656
9657 // prefixes
9658 vector<string> glob_prefixes;
9659 glob_prefixes.push_back (s.kernel_build_tree);
9660 if (s.kernel_source_tree != "")
9661 glob_prefixes.push_back (s.kernel_source_tree);
9662
9663 // suffixes
9664 vector<string> glob_suffixes;
9665 glob_suffixes.push_back("include/trace/events/*.h");
9666 glob_suffixes.push_back("include/trace/*.h");
9667 glob_suffixes.push_back("arch/x86/kvm/*trace.h");
f89ff3e2 9668 glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
d4393459
FCE
9669
9670 // compute cartesian product
9671 vector<string> globs;
9672 for (unsigned i=0; i<glob_prefixes.size(); i++)
9673 for (unsigned j=0; j<glob_suffixes.size(); j++)
9674 globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
9675
8aa43b8d 9676 set<string> duped_headers;
d4393459
FCE
9677 for (unsigned z = 0; z < globs.size(); z++)
9678 {
9679 string glob_str = globs[z];
9680 if (s.verbose > 3)
b530b5b3 9681 clog << _("Checking tracepoint glob ") << glob_str << endl;
d4393459 9682
067cc66f
CM
9683 int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
9684 if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
9685 throw runtime_error("Error globbing tracepoint");
9686
f982c59b
JS
9687 for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
9688 {
9689 string header(trace_glob.gl_pathv[i]);
9690
9691 // filter out a few known "internal-only" headers
60d98537
JS
9692 if (endswith(header, "/define_trace.h") ||
9693 endswith(header, "/ftrace.h") ||
9694 endswith(header, "/trace_events.h") ||
9695 endswith(header, "_event_types.h"))
f982c59b
JS
9696 continue;
9697
8aa43b8d
JS
9698 // skip identical headers from the build and source trees.
9699 size_t root_pos = header.rfind("include/");
9700 if (root_pos != string::npos &&
9701 !duped_headers.insert(header.substr(root_pos + 8)).second)
9702 continue;
9703
55e50c24 9704 system_headers.push_back(header);
f982c59b
JS
9705 }
9706 globfree(&trace_glob);
9707 }
9708
c9ccb642
FCE
9709 // Build tracequery modules
9710 get_tracequery_modules(s, system_headers, tracequery_modules);
55e50c24 9711
f982c59b
JS
9712 // TODO: consider other sources of tracepoint headers too, like from
9713 // a command-line parameter or some environment or .systemtaprc
47dd066d 9714
59c11f91 9715 dw = new dwflpp(s, tracequery_modules, true);
0a6f5a3f
JS
9716 return true;
9717}
47dd066d 9718
0a6f5a3f
JS
9719void
9720tracepoint_builder::build(systemtap_session& s,
9721 probe *base, probe_point *location,
9722 literal_map_t const& parameters,
9723 vector<derived_probe*>& finished_results)
9724{
9725 if (!init_dw(s))
9726 return;
47dd066d 9727
75ead1f7
JS
9728 string tracepoint;
9729 assert(get_param (parameters, TOK_TRACE, tracepoint));
47dd066d 9730
75ead1f7 9731 tracepoint_query q(*dw, tracepoint, base, location, finished_results);
51178501 9732 dw->iterate_over_modules(&query_module, &q);
47dd066d 9733}
47dd066d 9734
e6fe60e7 9735
b55bc428 9736// ------------------------------------------------------------------------
bd2b1e68 9737// Standard tapset registry.
b55bc428
FCE
9738// ------------------------------------------------------------------------
9739
7a053d3b 9740void
f8220a7b 9741register_standard_tapsets(systemtap_session & s)
b55bc428 9742{
47e0478e 9743 register_tapset_been(s);
93646f4d 9744 register_tapset_itrace(s);
dd0e4fa7 9745 register_tapset_mark(s);
7a212aa8 9746 register_tapset_procfs(s);
912e8c59 9747 register_tapset_timers(s);
8d9609f5 9748 register_tapset_netfilter(s);
b84779a5 9749 register_tapset_utrace(s);
b98a8d73 9750
7a24d422 9751 // dwarf-based kprobe/uprobe parts
c4ce66a1 9752 dwarf_derived_probe::register_patterns(s);
30a279be 9753
888af770
FCE
9754 // XXX: user-space starter set
9755 s.pattern_root->bind_num(TOK_PROCESS)
9756 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
f66bb29a 9757 ->bind_privilege(pr_all)
888af770
FCE
9758 ->bind(new uprobe_builder ());
9759 s.pattern_root->bind_num(TOK_PROCESS)
9760 ->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
f66bb29a 9761 ->bind_privilege(pr_all)
888af770
FCE
9762 ->bind(new uprobe_builder ());
9763
0a6f5a3f
JS
9764 // kernel tracepoint probes
9765 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
9766 ->bind(new tracepoint_builder());
9767
e6fe60e7
AM
9768 // Kprobe based probe
9769 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
9770 ->bind(new kprobe_builder());
9771 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9772 ->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
9773 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9774 ->bind(new kprobe_builder());
b6371390
JS
9775 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9776 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
9777 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9778 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
b6371390
JS
9779 s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
9780 ->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
9781 ->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
e6fe60e7
AM
9782 s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
9783 ->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
dd225250
PS
9784
9785 //Hwbkpt based probe
b47f3a55
FCE
9786 // NB: we formerly registered the probe point types only if the kernel configuration
9787 // allowed it. However, we get better error messages if we allow probes to resolve.
9788 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9789 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9790 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
9791 ->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9792 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9793 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9794 s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
9795 ->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9796 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9797 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder());
9798 s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
9799 ->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder());
9800 // length supported with address only, not symbol names
83ea76b1
WC
9801
9802 //perf event based probe
4763f713 9803 register_tapset_perf(s);
b55bc428 9804}
dc38c0ae
DS
9805
9806
b20febf3
FCE
9807vector<derived_probe_group*>
9808all_session_groups(systemtap_session& s)
dc38c0ae 9809{
b20febf3 9810 vector<derived_probe_group*> g;
912e8c59
JS
9811
9812#define DOONE(x) \
9813 if (s. x##_derived_probes) \
9814 g.push_back ((derived_probe_group*)(s. x##_derived_probes))
ab655cf8
DS
9815
9816 // Note that order *is* important here. We want to make sure we
9817 // register (actually run) begin probes before any other probe type
9818 // is run. Similarly, when unregistering probes, we want to
9819 // unregister (actually run) end probes after every other probe type
9820 // has be unregistered. To do the latter,
9821 // c_unparser::emit_module_exit() will run this list backwards.
b20febf3
FCE
9822 DOONE(be);
9823 DOONE(dwarf);
888af770 9824 DOONE(uprobe);
b20febf3
FCE
9825 DOONE(timer);
9826 DOONE(profile);
9827 DOONE(mark);
0a6f5a3f 9828 DOONE(tracepoint);
e6fe60e7 9829 DOONE(kprobe);
dd225250 9830 DOONE(hwbkpt);
83ea76b1 9831 DOONE(perf);
b20febf3 9832 DOONE(hrtimer);
ce82316f 9833 DOONE(procfs);
8d9609f5 9834 DOONE(netfilter);
935447c8
DS
9835
9836 // Another "order is important" item. We want to make sure we
9837 // "register" the dummy task_finder probe group after all probe
9838 // groups that use the task_finder.
9839 DOONE(utrace);
a96d1db0 9840 DOONE(itrace);
935447c8 9841 DOONE(task_finder);
b20febf3
FCE
9842#undef DOONE
9843 return g;
46b84a80 9844}
73267b89
JS
9845
9846/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 3.892992 seconds and 5 git commands to generate.