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