1dbg(3) Erlang Module Definition dbg(3)
2
3
4
6 dbg - The Text Based Trace Facility
7
9 This module implements a text based interface to the trace/3 and the
10 trace_pattern/2 BIFs. It makes it possible to trace functions, pro‐
11 cesses, ports and messages.
12
13 To quickly get started on tracing function calls you can use the fol‐
14 lowing code in the Erlang shell:
15
16 1> dbg:tracer(). %% Start the default trace message receiver
17 {ok,<0.36.0>}
18 2> dbg:p(all, c). %% Setup call (c) tracing on all processes
19 {ok,[{matched,nonode@nohost,26}]}
20 3> dbg:tp(lists, seq, x). %% Setup an exception return trace (x) on lists:seq
21 {ok,[{matched,nonode@nohost,2},{saved,x}]}
22 4> lists:seq(1,10).
23 (<0.34.0>) call lists:seq(1,10)
24 (<0.34.0>) returned from lists:seq/2 -> [1,2,3,4,5,6,7,8,9,10]
25 [1,2,3,4,5,6,7,8,9,10]
26
27
28 For more examples of how to use dbg from the Erlang shell, see the sim‐
29 ple example section.
30
31 The utilities are also suitable to use in system testing on large sys‐
32 tems, where other tools have too much impact on the system performance.
33 Some primitive support for sequential tracing is also included, see the
34 advanced topics section.
35
37 fun2ms(LiteralFun) -> MatchSpec
38
39 Types:
40
41 LiteralFun = fun() literal
42 MatchSpec = term()
43
44 Pseudo function that by means of a parse_transform translates
45 the literal fun() typed as parameter in the function call to a
46 match specification as described in the match_spec manual of
47 ERTS users guide. (With literal I mean that the fun() needs to
48 textually be written as the parameter of the function, it cannot
49 be held in a variable which in turn is passed to the function).
50
51 The parse transform is implemented in the module ms_transform
52 and the source must include the file ms_transform.hrl in STDLIB
53 for this pseudo function to work. Failing to include the hrl
54 file in the source will result in a runtime error, not a compile
55 time ditto. The include file is easiest included by adding the
56 line -include_lib("stdlib/include/ms_transform.hrl"). to the
57 source file.
58
59 The fun() is very restricted, it can take only a single parame‐
60 ter (the parameter list to match), a sole variable or a list. It
61 needs to use the is_XXX guard tests and one cannot use language
62 constructs that have no representation in a match_spec (like if,
63 case, receive etc). The return value from the fun will be the
64 return value of the resulting match_spec.
65
66 Example:
67
68 1> dbg:fun2ms(fun([M,N]) when N > 3 -> return_trace() end).
69 [{['$1','$2'],[{'>','$2',3}],[{return_trace}]}]
70
71 Variables from the environment can be imported, so that this
72 works:
73
74 2> X=3.
75 3
76 3> dbg:fun2ms(fun([M,N]) when N > X -> return_trace() end).
77 [{['$1','$2'],[{'>','$2',{const,3}}],[{return_trace}]}]
78
79 The imported variables will be replaced by match_spec const ex‐
80 pressions, which is consistent with the static scoping for Er‐
81 lang fun()s. Local or global function calls cannot be in the
82 guard or body of the fun however. Calls to builtin match_spec
83 functions of course is allowed:
84
85 4> dbg:fun2ms(fun([M,N]) when N > X, is_atomm(M) -> return_trace() end).
86 Error: fun containing local erlang function calls ('is_atomm' called in guard)\
87 cannot be translated into match_spec
88 {error,transform_error}
89 5> dbg:fun2ms(fun([M,N]) when N > X, is_atom(M) -> return_trace() end).
90 [{['$1','$2'],[{'>','$2',{const,3}},{is_atom,'$1'}],[{return_trace}]}]
91
92 As you can see by the example, the function can be called from
93 the shell too. The fun() needs to be literally in the call when
94 used from the shell as well. Other means than the parse_trans‐
95 form are used in the shell case, but more or less the same re‐
96 strictions apply (the exception being records, as they are not
97 handled by the shell).
98
99 Warning:
100 If the parse_transform is not applied to a module which calls
101 this pseudo function, the call will fail in runtime (with a
102 badarg). The module dbg actually exports a function with this
103 name, but it should never really be called except for when using
104 the function in the shell. If the parse_transform is properly
105 applied by including the ms_transform.hrl header file, compiled
106 code will never call the function, but the function call is re‐
107 placed by a literal match_spec.
108
109
110 More information is provided by the ms_transform manual page in
111 STDLIB.
112
113 h() -> ok
114
115 h stands for help. Gives a list of items for brief online help.
116
117 h(Item) -> ok
118
119 Types:
120
121 Item = atom()
122
123 h stands for help. Gives a brief help text for functions in the
124 dbg module. The available items can be listed with dbg:h/0.
125
126 p(Item) -> {ok, MatchDesc} | {error, term()}
127
128 Equivalent to p(Item, [m]).
129
130 p(Item, Flags) -> {ok, MatchDesc} | {error, term()}
131
132 Types:
133
134 MatchDesc = [MatchNum]
135 MatchNum = {matched, node(), integer()} | {matched, node(),
136 0, RPCError}
137 RPCError = term()
138
139 p stands for process. Traces Item in accordance to the value
140 specified by Flags. The variation of Item is listed below:
141
142 pid() or port():
143 The corresponding process or port is traced. The process or
144 port may be a remote process or port (on another Erlang
145 node). The node must be in the list of traced nodes (see n/1
146 and tracer/3).
147
148 all:
149 All processes and ports in the system as well as all pro‐
150 cesses and ports created hereafter are to be traced.
151
152 processes:
153 All processes in the system as well as all processes created
154 hereafter are to be traced.
155
156 ports:
157 All ports in the system as well as all ports created here‐
158 after are to be traced.
159
160 new:
161 All processes and ports created after the call is are to be
162 traced.
163
164 new_processes:
165 All processes created after the call is are to be traced.
166
167 new_ports:
168 All ports created after the call is are to be traced.
169
170 existing:
171 All existing processes and ports are traced.
172
173 existing_processes:
174 All existing processes are traced.
175
176 existing_ports:
177 All existing ports are traced.
178
179 atom():
180 The process or port with the corresponding registered name
181 is traced. The process or port may be a remote process (on
182 another Erlang node). The node must be added with the n/1 or
183 tracer/3 function.
184
185 integer():
186 The process <0.Item.0> is traced.
187
188 {X, Y, Z}:
189 The process <X.Y.Z> is traced.
190
191 string():
192 If the Item is a string "<X.Y.Z>" as returned from
193 pid_to_list/1, the process <X.Y.Z> is traced.
194
195 When enabling an Item that represents a group of processes, the
196 Item is enabled on all nodes added with the n/1 or tracer/3
197 function.
198
199 Flags can be a single atom, or a list of flags. The available
200 flags are:
201
202 s (send):
203 Traces the messages the process or port sends.
204
205 r (receive):
206 Traces the messages the process or port receives.
207
208 m (messages):
209 Traces the messages the process or port receives and sends.
210
211 c (call):
212 Traces global function calls for the process according to
213 the trace patterns set in the system (see tp/2).
214
215 p (procs):
216 Traces process related events to the process.
217
218 ports:
219 Traces port related events to the port.
220
221 sos (set on spawn):
222 Lets all processes created by the traced process inherit the
223 trace flags of the traced process.
224
225 sol (set on link):
226 Lets another process, P2, inherit the trace flags of the
227 traced process whenever the traced process links to P2.
228
229 sofs (set on first spawn):
230 This is the same as sos, but only for the first process
231 spawned by the traced process.
232
233 sofl (set on first link):
234 This is the same as sol, but only for the first call to
235 link/1 by the traced process.
236
237 all:
238 Sets all flags except silent.
239
240 clear:
241 Clears all flags.
242
243 The list can also include any of the flags allowed in er‐
244 lang:trace/3
245
246 The function returns either an error tuple or a tuple {ok,
247 List}. The List consists of specifications of how many processes
248 and ports that matched (in the case of a pure pid() exactly 1).
249 The specification of matched processes is {matched, Node, N}. If
250 the remote processor call, rpc, to a remote node fails, the rpc
251 error message is delivered as a fourth argument and the number
252 of matched processes are 0. Note that the result {ok, List} may
253 contain a list where rpc calls to one, several or even all nodes
254 failed.
255
256 c(Mod, Fun, Args)
257
258 Equivalent to c(Mod, Fun, Args, all).
259
260 c(Mod, Fun, Args, Flags)
261
262 c stands for call. Evaluates the expression apply(Mod, Fun,
263 Args) with the trace flags in Flags set. This is a convenient
264 way to trace processes from the Erlang shell.
265
266 i() -> ok
267
268 i stands for information. Displays information about all traced
269 processes and ports.
270
271 tp(Module,MatchSpec)
272
273 Same as tp({Module, '_', '_'}, MatchSpec)
274
275 tp(Module,Function,MatchSpec)
276
277 Same as tp({Module, Function, '_'}, MatchSpec)
278
279 tp(Module, Function, Arity, MatchSpec)
280
281 Same as tp({Module, Function, Arity}, MatchSpec)
282
283 tp({Module, Function, Arity}, MatchSpec) -> {ok, MatchDesc} | {error,
284 term()}
285
286 Types:
287
288 Module = atom() | '_'
289 Function = atom() | '_'
290 Arity = integer() |'_'
291 MatchSpec = integer() | Built-inAlias | [] | match_spec()
292 Built-inAlias = x | c | cx
293 MatchDesc = [MatchInfo]
294 MatchInfo = {saved, integer()} | MatchNum
295 MatchNum = {matched, node(), integer()} | {matched, node(),
296 0, RPCError}
297
298 tp stands for trace pattern. This function enables call trace
299 for one or more functions. All exported functions matching the
300 {Module, Function, Arity} argument will be concerned, but the
301 match_spec() may further narrow down the set of function calls
302 generating trace messages.
303
304 For a description of the match_spec() syntax, please turn to the
305 User's guide part of the online documentation for the runtime
306 system (erts). The chapter Match Specifications in Erlang ex‐
307 plains the general match specification "language". The most com‐
308 mon generic match specifications used can be found as Built-inA‐
309 lias', see ltp/0 below for details.
310
311 The Module, Function and/or Arity parts of the tuple may be
312 specified as the atom '_' which is a "wild-card" matching all
313 modules/functions/arities. Note, if the Module is specified as
314 '_', the Function and Arity parts have to be specified as '_'
315 too. The same holds for the Functions relation to the Arity.
316
317 All nodes added with n/1 or tracer/3 will be affected by this
318 call, and if Module is not '_' the module will be loaded on all
319 nodes.
320
321 The function returns either an error tuple or a tuple {ok,
322 List}. The List consists of specifications of how many functions
323 that matched, in the same way as the processes and ports are
324 presented in the return value of p/2.
325
326 There may be a tuple {saved, N} in the return value, if the
327 MatchSpec is other than []. The integer N may then be used in
328 subsequent calls to this function and will stand as an "alias"
329 for the given expression. There are also a couple of built-in
330 aliases for common expressions, see ltp/0 below for details.
331
332 If an error is returned, it can be due to errors in compilation
333 of the match specification. Such errors are presented as a list
334 of tuples {error, string()} where the string is a textual expla‐
335 nation of the compilation error. An example:
336
337 (x@y)4> dbg:tp({dbg,ltp,0},[{[],[],[{message, two, arguments}, {noexist}]}]).
338 {error,
339 [{error,"Special form 'message' called with wrong number of
340 arguments in {message,two,arguments}."},
341 {error,"Function noexist/1 does_not_exist."}]}
342
343 tpl(Module,MatchSpec)
344
345 Same as tpl({Module, '_', '_'}, MatchSpec)
346
347 tpl(Module,Function,MatchSpec)
348
349 Same as tpl({Module, Function, '_'}, MatchSpec)
350
351 tpl(Module, Function, Arity, MatchSpec)
352
353 Same as tpl({Module, Function, Arity}, MatchSpec)
354
355 tpl({Module, Function, Arity}, MatchSpec) -> {ok, MatchDesc} | {error,
356 term()}
357
358 tpl stands for trace pattern local. This function works as tp/2,
359 but enables tracing for local calls (and local functions) as
360 well as for global calls (and functions).
361
362 tpe(Event, MatchSpec) -> {ok, MatchDesc} | {error, term()}
363
364 Types:
365
366 Event = send | 'receive'
367 MatchSpec = integer() | Built-inAlias | [] | match_spec()
368 Built-inAlias = x | c | cx
369 MatchDesc = [MatchInfo]
370 MatchInfo = {saved, integer()} | MatchNum
371 MatchNum = {matched, node(), 1} | {matched, node(), 0, RPCEr‐
372 ror}
373
374 tpe stands for trace pattern event. This function associates a
375 match specification with trace event send or 'receive'. By de‐
376 fault all executed send and 'receive' events are traced if en‐
377 abled for a process. A match specification can be used to filter
378 traced events based on sender, receiver and/or message content.
379
380 For a description of the match_spec() syntax, please turn to the
381 User's guide part of the online documentation for the runtime
382 system (erts). The chapter Match Specifications in Erlang ex‐
383 plains the general match specification "language".
384
385 For send, the matching is done on the list [Receiver, Msg]. Re‐
386 ceiver is the process or port identity of the receiver and Msg
387 is the message term. The pid of the sending process can be ac‐
388 cessed with the guard function self/0.
389
390 For 'receive', the matching is done on the list [Node, Sender,
391 Msg]. Node is the node name of the sender. Sender is the process
392 or port identity of the sender, or the atom undefined if the
393 sender is not known (which may be the case for remote senders).
394 Msg is the message term. The pid of the receiving process can be
395 accessed with the guard function self/0.
396
397 All nodes added with n/1 or tracer/3 will be affected by this
398 call.
399
400 The return value is the same as for tp/2. The number of matched
401 events are never larger than 1 as tpe/2 does not accept any form
402 of wildcards for argument Event.
403
404 ctp()
405
406 Same as ctp({'_', '_', '_'})
407
408 ctp(Module)
409
410 Same as ctp({Module, '_', '_'})
411
412 ctp(Module, Function)
413
414 Same as ctp({Module, Function, '_'})
415
416 ctp(Module, Function, Arity)
417
418 Same as ctp({Module, Function, Arity})
419
420 ctp({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
421
422 Types:
423
424 Module = atom() | '_'
425 Function = atom() | '_'
426 Arity = integer() | '_'
427 MatchDesc = [MatchNum]
428 MatchNum = {matched, node(), integer()} | {matched, node(),
429 0, RPCError}
430
431 ctp stands for clear trace pattern. This function disables call
432 tracing on the specified functions. The semantics of the parame‐
433 ter is the same as for the corresponding function specification
434 in tp/2 or tpl/2. Both local and global call trace is disabled.
435
436 The return value reflects how many functions that matched, and
437 is constructed as described in tp/2. No tuple {saved, N} is how‐
438 ever ever returned (for obvious reasons).
439
440 ctpl()
441
442 Same as ctpl({'_', '_', '_'})
443
444 ctpl(Module)
445
446 Same as ctpl({Module, '_', '_'})
447
448 ctpl(Module, Function)
449
450 Same as ctpl({Module, Function, '_'})
451
452 ctpl(Module, Function, Arity)
453
454 Same as ctpl({Module, Function, Arity})
455
456 ctpl({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
457
458 ctpl stands for clear trace pattern local. This function works
459 as ctp/1, but only disables tracing set up with tpl/2 (not with
460 tp/2).
461
462 ctpg()
463
464 Same as ctpg({'_', '_', '_'})
465
466 ctpg(Module)
467
468 Same as ctpg({Module, '_', '_'})
469
470 ctpg(Module, Function)
471
472 Same as ctpg({Module, Function, '_'})
473
474 ctpg(Module, Function, Arity)
475
476 Same as ctpg({Module, Function, Arity})
477
478 ctpg({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
479
480 ctpg stands for clear trace pattern global. This function works
481 as ctp/1, but only disables tracing set up with tp/2 (not with
482 tpl/2).
483
484 ctpe(Event) -> {ok, MatchDesc} | {error, term()}
485
486 Types:
487
488 Event = send | 'receive'
489 MatchDesc = [MatchNum]
490 MatchNum = {matched, node(), 1} | {matched, node(), 0, RPCEr‐
491 ror}
492
493 ctpe stands for clear trace pattern event. This function clears
494 match specifications for the specified trace event (send or 're‐
495 ceive'). It will revert back to the default behavior of tracing
496 all triggered events.
497
498 The return value follow the same style as for ctp/1.
499
500 ltp() -> ok
501
502 ltp stands for list trace patterns. Use this function to recall
503 all match specifications previously used in the session (i. e.
504 previously saved during calls to tp/2, and built-in match speci‐
505 fications. This is very useful, as a complicated match_spec can
506 be quite awkward to write. Note that the match specifications
507 are lost if stop/0 is called.
508
509 Match specifications used can be saved in a file (if a read-
510 write file system is present) for use in later debugging ses‐
511 sions, see wtp/1 and rtp/1
512
513 There are three built-in trace patterns: exception_trace,
514 caller_trace and caller_exception_trace (or x, c and cx respec‐
515 tively). Exception trace sets a trace which will show function
516 names, parameters, return values and exceptions thrown from
517 functions. Caller traces display function names, parameters and
518 information about which function called it. An example using a
519 built-in alias:
520
521 (x@y)4> dbg:tp(lists,sort,cx).
522 {ok,[{matched,nonode@nohost,2},{saved,cx}]}
523 (x@y)4> lists:sort([2,1]).
524 (<0.32.0>) call lists:sort([2,1]) ({erl_eval,do_apply,5})
525 (<0.32.0>) returned from lists:sort/1 -> [1,2]
526 [1,2]
527
528 dtp() -> ok
529
530 dtp stands for delete trace patterns. Use this function to "for‐
531 get" all match specifications saved during calls to tp/2. This
532 is useful when one wants to restore other match specifications
533 from a file with rtp/1. Use dtp/1 to delete specific saved match
534 specifications.
535
536 dtp(N) -> ok
537
538 Types:
539
540 N = integer()
541
542 dtp stands for delete trace pattern. Use this function to "for‐
543 get" a specific match specification saved during calls to tp/2.
544
545 wtp(Name) -> ok | {error, IOError}
546
547 Types:
548
549 Name = string()
550 IOError = term()
551
552 wtp stands for write trace patterns. This function will save all
553 match specifications saved during the session (during calls to
554 tp/2) and built-in match specifications in a text file with the
555 name designated by Name. The format of the file is textual, why
556 it can be edited with an ordinary text editor, and then restored
557 with rtp/1.
558
559 Each match spec in the file ends with a full stop (.) and new
560 (syntactically correct) match specifications can be added to the
561 file manually.
562
563 The function returns ok or an error tuple where the second ele‐
564 ment contains the I/O error that made the writing impossible.
565
566 rtp(Name) -> ok | {error, Error}
567
568 Types:
569
570 Name = string()
571 Error = term()
572
573 rtp stands for read trace patterns. This function reads match
574 specifications from a file (possibly) generated by the wtp/1
575 function. It checks the syntax of all match specifications and
576 verifies that they are correct. The error handling principle is
577 "all or nothing", i. e. if some of the match specifications are
578 wrong, none of the specifications are added to the list of saved
579 match specifications for the running system.
580
581 The match specifications in the file are merged with the current
582 match specifications, so that no duplicates are generated. Use
583 ltp/0 to see what numbers were assigned to the specifications
584 from the file.
585
586 The function will return an error, either due to I/O problems
587 (like a non existing or non readable file) or due to file format
588 problems. The errors from a bad format file are in a more or
589 less textual format, which will give a hint to what's causing
590 the problem.
591
592 n(Nodename) -> {ok, Nodename} | {error, Reason}
593
594 Types:
595
596 Nodename = atom()
597 Reason = term()
598
599 n stands for node. The dbg server keeps a list of nodes where
600 tracing should be performed. Whenever a tp/2 call or a p/2 call
601 is made, it is executed for all nodes in this list including the
602 local node (except for p/2 with a specific pid() or port() as
603 first argument, in which case the command is executed only on
604 the node where the designated process or port resides).
605
606 This function adds a remote node (Nodename) to the list of nodes
607 where tracing is performed. It starts a tracer process on the
608 remote node, which will send all trace messages to the tracer
609 process on the local node (via the Erlang distribution). If no
610 tracer process is running on the local node, the error reason
611 no_local_tracer is returned. The tracer process on the local
612 node must be started with the tracer/0/2 function.
613
614 If Nodename is the local node, the error reason cant_add_lo‐
615 cal_node is returned.
616
617 If a trace port (see trace_port/2) is running on the local node,
618 remote nodes cannot be traced with a tracer process. The error
619 reason cant_trace_remote_pid_to_local_port is returned. A trace
620 port can however be started on the remote node with the tracer/3
621 function.
622
623 The function will also return an error if the node Nodename is
624 not reachable.
625
626 cn(Nodename) -> ok
627
628 Types:
629
630 Nodename = atom()
631
632 cn stands for clear node. Clears a node from the list of traced
633 nodes. Subsequent calls to tp/2 and p/2 will not consider that
634 node, but tracing already activated on the node will continue to
635 be in effect.
636
637 Returns ok, cannot fail.
638
639 ln() -> ok
640
641 ln stands for list nodes. Shows the list of traced nodes on the
642 console.
643
644 tracer() -> {ok, pid()} | {error, already_started}
645
646 This function starts a server on the local node that will be the
647 recipient of all trace messages. All subsequent calls to p/2
648 will result in messages sent to the newly started trace server.
649
650 A trace server started in this way will simply display the trace
651 messages in a formatted way in the Erlang shell (i. e. use
652 io:format). See tracer/2 for a description of how the trace mes‐
653 sage handler can be customized.
654
655 To start a similar tracer on a remote node, use n/1.
656
657 tracer(Type, Data) -> {ok, pid()} | {error, Error}
658
659 Types:
660
661 Type = port | process | module
662 Data = PortGenerator | HandlerSpec | ModuleSpec
663 PortGenerator = fun() (no arguments)
664 Error = term()
665 HandlerSpec = {HandlerFun, InitialData}
666 HandlerFun = fun() (two arguments)
667 ModuleSpec = fun() (no arguments) | {TracerModule, Tracer‐
668 State}
669 TracerModule = atom()
670 InitialData = TracerState = term()
671
672 This function starts a tracer server with additional parameters
673 on the local node. The first parameter, the Type, indicates if
674 trace messages should be handled by a receiving process
675 (process), by a tracer port (port) or by a tracer module (mod‐
676 ule). For a description about tracer ports see trace_port/2 and
677 for a tracer modules see erl_tracer.
678
679 If Type is process, a message handler function can be specified
680 (HandlerSpec). The handler function, which should be a fun tak‐
681 ing two arguments, will be called for each trace message, with
682 the first argument containing the message as it is and the sec‐
683 ond argument containing the return value from the last invoca‐
684 tion of the fun. The initial value of the second parameter is
685 specified in the InitialData part of the HandlerSpec. The Han‐
686 dlerFun may choose any appropriate action to take when invoked,
687 and can save a state for the next invocation by returning it.
688
689 If Type is port, then the second parameter should be a fun which
690 takes no arguments and returns a newly opened trace port when
691 called. Such a fun is preferably generated by calling
692 trace_port/2.
693
694 if Type is module, then the second parameter should be either a
695 tuple describing the erl_tracer module to be used for tracing
696 and the state to be used for that tracer module or a fun return‐
697 ing the same tuple.
698
699 If an error is returned, it can either be due to a tracer server
700 already running ({error,already_started}) or due to the Handler‐
701 Fun throwing an exception.
702
703 To start a similar tracer on a remote node, use tracer/3.
704
705 tracer(Nodename, Type, Data) -> {ok, Nodename} | {error, Reason}
706
707 Types:
708
709 Nodename = atom()
710
711 This function is equivalent to tracer/2, but acts on the given
712 node. A tracer is started on the node (Nodename) and the node is
713 added to the list of traced nodes.
714
715 Note:
716 This function is not equivalent to n/1. While n/1 starts a
717 process tracer which redirects all trace information to a
718 process tracer on the local node (i.e. the trace control node),
719 tracer/3 starts a tracer of any type which is independent of the
720 tracer on the trace control node.
721
722
723 For details, see tracer/2.
724
725 trace_port(Type, Parameters) -> fun()
726
727 Types:
728
729 Type = ip | file
730 Parameters = Filename | WrapFilesSpec | IPPortSpec
731 Filename = string() | [string()] | atom()
732 WrapFilesSpec = {Filename, wrap, Suffix} | {Filename, wrap,
733 Suffix, WrapSize} | {Filename, wrap, Suffix, WrapSize,
734 WrapCnt}
735 Suffix = string()
736 WrapSize = integer() >= 0 | {time, WrapTime}
737 WrapTime = integer() >= 1
738 WrapCnt = integer() >= 1
739 IpPortSpec = PortNumber | {PortNumber, QueSize}
740 PortNumber = integer()
741 QueSize = integer()
742
743 This function creates a trace port generating fun. The fun takes
744 no arguments and returns a newly opened trace port. The return
745 value from this function is suitable as a second parameter to
746 tracer/2, i.e. dbg:tracer(port, dbg:trace_port(ip, 4711)).
747
748 A trace port is an Erlang port to a dynamically linked in driver
749 that handles trace messages directly, without the overhead of
750 sending them as messages in the Erlang virtual machine.
751
752 Two trace drivers are currently implemented, the file and the ip
753 trace drivers. The file driver sends all trace messages into one
754 or several binary files, from where they later can be fetched
755 and processed with the trace_client/2 function. The ip driver
756 opens a TCP/IP port where it listens for connections. When a
757 client (preferably started by calling trace_client/2 on another
758 Erlang node) connects, all trace messages are sent over the IP
759 network for further processing by the remote client.
760
761 Using a trace port significantly lowers the overhead imposed by
762 using tracing.
763
764 The file trace driver expects a filename or a wrap files speci‐
765 fication as parameter. A file is written with a high degree of
766 buffering, why all trace messages are not guaranteed to be saved
767 in the file in case of a system crash. That is the price to pay
768 for low tracing overhead.
769
770 A wrap files specification is used to limit the disk space con‐
771 sumed by the trace. The trace is written to a limited number of
772 files each with a limited size. The actual filenames are File‐
773 name ++ SeqCnt ++ Suffix, where SeqCnt counts as a decimal
774 string from 0 to WrapCnt and then around again from 0. When a
775 trace term written to the current file makes it longer than
776 WrapSize, that file is closed, if the number of files in this
777 wrap trace is as many as WrapCnt the oldest file is deleted then
778 a new file is opened to become the current. Thus, when a wrap
779 trace has been stopped, there are at most WrapCnt trace files
780 saved with a size of at least WrapSize (but not much bigger),
781 except for the last file that might even be empty. The default
782 values are WrapSize = 128*1024 and WrapCnt = 8.
783
784 The SeqCnt values in the filenames are all in the range 0
785 through WrapCnt with a gap in the circular sequence. The gap is
786 needed to find the end of the trace.
787
788 If the WrapSize is specified as {time, WrapTime}, the current
789 file is closed when it has been open more than WrapTime mil‐
790 liseconds, regardless of it being empty or not.
791
792 The ip trace driver has a queue of QueSize messages waiting to
793 be delivered. If the driver cannot deliver messages as fast as
794 they are produced by the runtime system, a special message is
795 sent, which indicates how many messages that are dropped. That
796 message will arrive at the handler function specified in
797 trace_client/3 as the tuple {drop, N} where N is the number of
798 consecutive messages dropped. In case of heavy tracing, drop's
799 are likely to occur, and they surely occur if no client is read‐
800 ing the trace messages. The default value of QueSize is 200.
801
802 flush_trace_port()
803
804 Equivalent to flush_trace_port(node()).
805
806 flush_trace_port(Nodename) -> ok | {error, Reason}
807
808 Equivalent to trace_port_control(Nodename,flush).
809
810 trace_port_control(Operation)
811
812 Equivalent to trace_port_control(node(),Operation).
813
814 trace_port_control(Nodename,Operation) -> ok | {ok, Result} | {error,
815 Reason}
816
817 Types:
818
819 Nodename = atom()
820
821 This function is used to do a control operation on the active
822 trace port driver on the given node (Nodename). Which operations
823 are allowed as well as their return values depend on which trace
824 driver is used.
825
826 Returns either ok or {ok, Result} if the operation was success‐
827 ful, or {error, Reason} if the current tracer is a process or if
828 it is a port not supporting the operation.
829
830 The allowed values for Operation are:
831
832 flush:
833 This function is used to flush the internal buffers held by
834 a trace port driver. Currently only the file trace driver
835 supports this operation. Returns ok.
836
837 get_listen_port:
838 Returns {ok, IpPort} where IpPort is the IP port number used
839 by the driver listen socket. Only the ip trace driver sup‐
840 ports this operation.
841
842 trace_client(Type, Parameters) -> pid()
843
844 Types:
845
846 Type = ip | file | follow_file
847 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
848 Filename = string() | [string()] | atom()
849 WrapFilesSpec = see trace_port/2
850 Suffix = string()
851 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
852 PortNumber = integer()
853 Hostname = string()
854
855 This function starts a trace client that reads the output cre‐
856 ated by a trace port driver and handles it in mostly the same
857 way as a tracer process created by the tracer/0 function.
858
859 If Type is file, the client reads all trace messages stored in
860 the file named Filename or specified by WrapFilesSpec (must be
861 the same as used when creating the trace, see trace_port/2) and
862 let's the default handler function format the messages on the
863 console. This is one way to interpret the data stored in a file
864 by the file trace port driver.
865
866 If Type is follow_file, the client behaves as in the file case,
867 but keeps trying to read (and process) more data from the file
868 until stopped by stop_trace_client/1. WrapFilesSpec is not al‐
869 lowed as second argument for this Type.
870
871 If Type is ip, the client connects to the TCP/IP port PortNumber
872 on the host Hostname, from where it reads trace messages until
873 the TCP/IP connection is closed. If no Hostname is specified,
874 the local host is assumed.
875
876 As an example, one can let trace messages be sent over the net‐
877 work to another Erlang node (preferably not distributed), where
878 the formatting occurs:
879
880 On the node stack there's an Erlang node ant@stack, in the
881 shell, type the following:
882
883 ant@stack> dbg:tracer(port, dbg:trace_port(ip,4711)).
884 <0.17.0>
885 ant@stack> dbg:p(self(), send).
886 {ok,1}
887
888 All trace messages are now sent to the trace port driver, which
889 in turn listens for connections on the TCP/IP port 4711. If we
890 want to see the messages on another node, preferably on another
891 host, we do like this:
892
893 -> dbg:trace_client(ip, {"stack", 4711}).
894 <0.42.0>
895
896 If we now send a message from the shell on the node ant@stack,
897 where all sends from the shell are traced:
898
899 ant@stack> self() ! hello.
900 hello
901
902 The following will appear at the console on the node that
903 started the trace client:
904
905 (<0.23.0>) <0.23.0> ! hello
906 (<0.23.0>) <0.22.0> ! {shell_rep,<0.23.0>,{value,hello,[],[]}}
907
908 The last line is generated due to internal message passing in
909 the Erlang shell. The process id's will vary.
910
911 trace_client(Type, Parameters, HandlerSpec) -> pid()
912
913 Types:
914
915 Type = ip | file | follow_file
916 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
917 Filename = string() | [string()] | atom()
918 WrapFilesSpec = see trace_port/2
919 Suffix = string()
920 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
921 PortNumber = integer()
922 Hostname = string()
923 HandlerSpec = {HandlerFun, InitialData}
924 HandlerFun = fun() (two arguments)
925 InitialData = term()
926
927 This function works exactly as trace_client/2, but allows you to
928 write your own handler function. The handler function works
929 mostly as the one described in tracer/2, but will also have to
930 be prepared to handle trace messages of the form {drop, N},
931 where N is the number of dropped messages. This pseudo trace
932 message will only occur if the ip trace driver is used.
933
934 For trace type file, the pseudo trace message end_of_trace will
935 appear at the end of the trace. The return value from the han‐
936 dler function is in this case ignored.
937
938 stop_trace_client(Pid) -> ok
939
940 Types:
941
942 Pid = pid()
943
944 This function shuts down a previously started trace client. The
945 Pid argument is the process id returned from the trace_client/2
946 or trace_client/3 call.
947
948 get_tracer()
949
950 Equivalent to get_tracer(node()).
951
952 get_tracer(Nodename) -> {ok, Tracer}
953
954 Types:
955
956 Nodename = atom()
957 Tracer = port() | pid() | {module(), term()}
958
959 Returns the process, port or tracer module to which all trace
960 messages are sent.
961
962 stop() -> ok
963
964 Stops the dbg server and clears all trace flags for all pro‐
965 cesses and all local trace patterns for all functions. Also
966 shuts down all trace clients and closes all trace ports.
967
968 Note that no global trace patterns are affected by this func‐
969 tion.
970
971 stop_clear() -> ok
972
973 Same as stop/0, but also clears all trace patterns on global
974 functions calls.
975
977 The simplest way of tracing from the Erlang shell is to use dbg:c/3 or
978 dbg:c/4, e.g. tracing the function dbg:get_tracer/0:
979
980 (tiger@durin)84> dbg:c(dbg,get_tracer,[]).
981 (<0.154.0>) <0.152.0> ! {<0.154.0>,{get_tracer,tiger@durin}}
982 (<0.154.0>) out {dbg,req,1}
983 (<0.154.0>) << {dbg,{ok,<0.153.0>}}
984 (<0.154.0>) in {dbg,req,1}
985 (<0.154.0>) << timeout
986 {ok,<0.153.0>}
987 (tiger@durin)85>
988
989 Another way of tracing from the shell is to explicitly start a tracer
990 and then set the trace flags of your choice on the processes you want
991 to trace, e.g. trace messages and process events:
992
993 (tiger@durin)66> Pid = spawn(fun() -> receive {From,Msg} -> From ! Msg end end).
994 <0.126.0>
995 (tiger@durin)67> dbg:tracer().
996 {ok,<0.128.0>}
997 (tiger@durin)68> dbg:p(Pid,[m,procs]).
998 {ok,[{matched,tiger@durin,1}]}
999 (tiger@durin)69> Pid ! {self(),hello}.
1000 (<0.126.0>) << {<0.116.0>,hello}
1001 {<0.116.0>,hello}
1002 (<0.126.0>) << timeout
1003 (<0.126.0>) <0.116.0> ! hello
1004 (<0.126.0>) exit normal
1005 (tiger@durin)70> flush().
1006 Shell got hello
1007 ok
1008 (tiger@durin)71>
1009
1010 If you set the call trace flag, you also have to set a trace pattern
1011 for the functions you want to trace:
1012
1013 (tiger@durin)77> dbg:tracer().
1014 {ok,<0.142.0>}
1015 (tiger@durin)78> dbg:p(all,call).
1016 {ok,[{matched,tiger@durin,3}]}
1017 (tiger@durin)79> dbg:tp(dbg,get_tracer,0,[]).
1018 {ok,[{matched,tiger@durin,1}]}
1019 (tiger@durin)80> dbg:get_tracer().
1020 (<0.116.0>) call dbg:get_tracer()
1021 {ok,<0.143.0>}
1022 (tiger@durin)81> dbg:tp(dbg,get_tracer,0,[{'_',[],[{return_trace}]}]).
1023 {ok,[{matched,tiger@durin,1},{saved,1}]}
1024 (tiger@durin)82> dbg:get_tracer().
1025 (<0.116.0>) call dbg:get_tracer()
1026 (<0.116.0>) returned from dbg:get_tracer/0 -> {ok,<0.143.0>}
1027 {ok,<0.143.0>}
1028 (tiger@durin)83>
1029
1031 The dbg module is primarily targeted towards tracing through the er‐
1032 lang:trace/3 function. It is sometimes desired to trace messages in a
1033 more delicate way, which can be done with the help of the seq_trace
1034 module.
1035
1036 seq_trace implements sequential tracing (known in the AXE10 world, and
1037 sometimes called "forlopp tracing"). dbg can interpret messages gener‐
1038 ated from seq_trace and the same tracer function for both types of
1039 tracing can be used. The seq_trace messages can even be sent to a trace
1040 port for further analysis.
1041
1042 As a match specification can turn on sequential tracing, the combina‐
1043 tion of dbg and seq_trace can be quite powerful. This brief example
1044 shows a session where sequential tracing is used:
1045
1046 1> dbg:tracer().
1047 {ok,<0.30.0>}
1048 2> {ok, Tracer} = dbg:get_tracer().
1049 {ok,<0.31.0>}
1050 3> seq_trace:set_system_tracer(Tracer).
1051 false
1052 4> dbg:tp(dbg, get_tracer, 0, [{[],[],[{set_seq_token, send, true}]}]).
1053 {ok,[{matched,nonode@nohost,1},{saved,1}]}
1054 5> dbg:p(all,call).
1055 {ok,[{matched,nonode@nohost,22}]}
1056 6> dbg:get_tracer(), seq_trace:set_token([]).
1057 (<0.25.0>) call dbg:get_tracer()
1058 SeqTrace [0]: (<0.25.0>) <0.30.0> ! {<0.25.0>,get_tracer} [Serial: {2,4}]
1059 SeqTrace [0]: (<0.30.0>) <0.25.0> ! {dbg,{ok,<0.31.0>}} [Serial: {4,5}]
1060 {1,0,5,<0.30.0>,4}
1061
1062 This session sets the system_tracer to the same process as the ordinary
1063 tracer process (i. e. <0.31.0>) and sets the trace pattern for the
1064 function dbg:get_tracer to one that has the action of setting a sequen‐
1065 tial token. When the function is called by a traced process (all pro‐
1066 cesses are traced in this case), the process gets "contaminated" by the
1067 token and seq_trace messages are sent both for the server request and
1068 the response. The seq_trace:set_token([]) after the call clears the
1069 seq_trace token, why no messages are sent when the answer propagates
1070 via the shell to the console port. The output would otherwise have been
1071 more noisy.
1072
1074 When tracing function calls on a group leader process (an IO process),
1075 there is risk of causing a deadlock. This will happen if a group leader
1076 process generates a trace message and the tracer process, by calling
1077 the trace handler function, sends an IO request to the same group
1078 leader. The problem can only occur if the trace handler prints to tty
1079 using an io function such as format/2. Note that when dbg:p(all,call)
1080 is called, IO processes are also traced. Here's an example:
1081
1082 %% Using a default line editing shell
1083 1> dbg:tracer(process, {fun(Msg,_) -> io:format("~p~n", [Msg]), 0 end, 0}).
1084 {ok,<0.37.0>}
1085 2> dbg:p(all, [call]).
1086 {ok,[{matched,nonode@nohost,25}]}
1087 3> dbg:tp(mymod,[{'_',[],[]}]).
1088 {ok,[{matched,nonode@nohost,0},{saved,1}]}
1089 4> mymod: % TAB pressed here
1090 %% -- Deadlock --
1091
1092 Here's another example:
1093
1094 %% Using a shell without line editing (oldshell)
1095 1> dbg:tracer(process).
1096 {ok,<0.31.0>}
1097 2> dbg:p(all, [call]).
1098 {ok,[{matched,nonode@nohost,25}]}
1099 3> dbg:tp(lists,[{'_',[],[]}]).
1100 {ok,[{matched,nonode@nohost,0},{saved,1}]}
1101 % -- Deadlock --
1102
1103 The reason we get a deadlock in the first example is because when TAB
1104 is pressed to expand the function name, the group leader (which handles
1105 character input) calls mymod:module_info(). This generates a trace mes‐
1106 sage which, in turn, causes the tracer process to send an IO request to
1107 the group leader (by calling io:format/2). We end up in a deadlock.
1108
1109 In the second example we use the default trace handler function. This
1110 handler prints to tty by sending IO requests to the user process. When
1111 Erlang is started in oldshell mode, the shell process will have user as
1112 its group leader and so will the tracer process in this example. Since
1113 user calls functions in lists we end up in a deadlock as soon as the
1114 first IO request is sent.
1115
1116 Here are a few suggestions for how to avoid deadlock:
1117
1118 * Don't trace the group leader of the tracer process. If tracing has
1119 been switched on for all processes, call dbg:p(TracerGLPid,clear)
1120 to stop tracing the group leader (TracerGLPid). process_info(Trac‐
1121 erPid,group_leader) tells you which process this is (TracerPid is
1122 returned from dbg:get_tracer/0).
1123
1124 * Don't trace the user process if using the default trace handler
1125 function.
1126
1127 * In your own trace handler function, call erlang:display/1 instead
1128 of an io function or, if user is not used as group leader, print to
1129 user instead of the default group leader. Example: io:for‐
1130 mat(user,Str,Args).
1131
1132Ericsson AB runtime_tools 1.17 dbg(3)