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