1dbg(3)                     Erlang Module Definition                     dbg(3)
2
3
4

NAME

6       dbg - The Text Based Trace Facility
7

DESCRIPTION

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

EXPORTS

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 | file
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 Type is file, then the second parameter should be a  filename
700              specifying a file where all the traces are printed.
701
702              If an error is returned, it can either be due to a tracer server
703              already running ({error,already_started}) or due to the Handler‐
704              Fun throwing an exception.
705
706              To start a similar tracer on a remote node, use tracer/3.
707
708       tracer(Nodename, Type, Data) -> {ok, Nodename} | {error, Reason}
709
710              Types:
711
712                 Nodename = atom()
713
714              This  function  is equivalent to tracer/2, but acts on the given
715              node. A tracer is started on the node (Nodename) and the node is
716              added to the list of traced nodes.
717
718          Note:
719              This  function  is  not  equivalent  to  n/1. While n/1 starts a
720              process tracer  which  redirects  all  trace  information  to  a
721              process  tracer on the local node (i.e. the trace control node),
722              tracer/3 starts a tracer of any type which is independent of the
723              tracer on the trace control node.
724
725
726              For details, see tracer/2.
727
728       trace_port(Type, Parameters) -> fun()
729
730              Types:
731
732                 Type = ip | file
733                 Parameters = Filename | WrapFilesSpec | IPPortSpec
734                 Filename = string() | [string()] | atom()
735                 WrapFilesSpec  =  {Filename, wrap, Suffix} | {Filename, wrap,
736                 Suffix,  WrapSize}  |  {Filename,  wrap,  Suffix,   WrapSize,
737                 WrapCnt}
738                 Suffix = string()
739                 WrapSize = integer() >= 0 | {time, WrapTime}
740                 WrapTime = integer() >= 1
741                 WrapCnt = integer() >= 1
742                 IpPortSpec = PortNumber | {PortNumber, QueSize}
743                 PortNumber = integer()
744                 QueSize = integer()
745
746              This function creates a trace port generating fun. The fun takes
747              no arguments and returns a newly opened trace port.  The  return
748              value  from  this  function is suitable as a second parameter to
749              tracer/2, i.e. dbg:tracer(port, dbg:trace_port(ip, 4711)).
750
751              A trace port is an Erlang port to a dynamically linked in driver
752              that  handles  trace  messages directly, without the overhead of
753              sending them as messages in the Erlang virtual machine.
754
755              Two trace drivers are currently implemented, the file and the ip
756              trace drivers. The file driver sends all trace messages into one
757              or several binary files, from where they later  can  be  fetched
758              and  processed  with  the trace_client/2 function. The ip driver
759              opens a TCP/IP port where it listens  for  connections.  When  a
760              client  (preferably started by calling trace_client/2 on another
761              Erlang node) connects, all trace messages are sent over  the  IP
762              network for further processing by the remote client.
763
764              Using  a trace port significantly lowers the overhead imposed by
765              using tracing.
766
767              The file trace driver expects a filename or a wrap files  speci‐
768              fication  as  parameter. A file is written with a high degree of
769              buffering, why all trace messages are not guaranteed to be saved
770              in  the file in case of a system crash. That is the price to pay
771              for low tracing overhead.
772
773              A wrap files specification is used to limit the disk space  con‐
774              sumed  by the trace. The trace is written to a limited number of
775              files each with a limited size. The actual filenames  are  File‐
776              name  ++  SeqCnt  ++  Suffix,  where  SeqCnt counts as a decimal
777              string from 0 to WrapCnt and then around again from  0.  When  a
778              trace  term  written  to  the  current file makes it longer than
779              WrapSize, that file is closed, if the number of  files  in  this
780              wrap trace is as many as WrapCnt the oldest file is deleted then
781              a new file is opened to become the current. Thus,  when  a  wrap
782              trace  has  been  stopped, there are at most WrapCnt trace files
783              saved with a size of at least WrapSize (but  not  much  bigger),
784              except  for  the last file that might even be empty. The default
785              values are WrapSize = 128*1024 and WrapCnt = 8.
786
787              The SeqCnt values in the  filenames  are  all  in  the  range  0
788              through  WrapCnt with a gap in the circular sequence. The gap is
789              needed to find the end of the trace.
790
791              If the WrapSize is specified as {time,  WrapTime},  the  current
792              file  is  closed  when  it has been open more than WrapTime mil‐
793              liseconds, regardless of it being empty or not.
794
795              The ip trace driver has a queue of QueSize messages  waiting  to
796              be  delivered.  If the driver cannot deliver messages as fast as
797              they are produced by the runtime system, a  special  message  is
798              sent,  which  indicates how many messages that are dropped. That
799              message  will  arrive  at  the  handler  function  specified  in
800              trace_client/3  as  the tuple {drop, N} where N is the number of
801              consecutive messages dropped. In case of heavy  tracing,  drop's
802              are likely to occur, and they surely occur if no client is read‐
803              ing the trace messages. The default value of QueSize is 200.
804
805       flush_trace_port()
806
807              Equivalent to flush_trace_port(node()).
808
809       flush_trace_port(Nodename) -> ok | {error, Reason}
810
811              Equivalent to trace_port_control(Nodename,flush).
812
813       trace_port_control(Operation)
814
815              Equivalent to trace_port_control(node(),Operation).
816
817       trace_port_control(Nodename,Operation) -> ok | {ok, Result}  |  {error,
818       Reason}
819
820              Types:
821
822                 Nodename = atom()
823
824              This  function  is  used to do a control operation on the active
825              trace port driver on the given node (Nodename). Which operations
826              are allowed as well as their return values depend on which trace
827              driver is used.
828
829              Returns either ok or {ok, Result} if the operation was  success‐
830              ful, or {error, Reason} if the current tracer is a process or if
831              it is a port not supporting the operation.
832
833              The allowed values for Operation are:
834
835                flush:
836                  This function is used to flush the internal buffers held  by
837                  a  trace  port  driver. Currently only the file trace driver
838                  supports this operation. Returns ok.
839
840                get_listen_port:
841                  Returns {ok, IpPort} where IpPort is the IP port number used
842                  by  the  driver listen socket. Only the ip trace driver sup‐
843                  ports this operation.
844
845       trace_client(Type, Parameters) -> pid()
846
847              Types:
848
849                 Type = ip | file | follow_file
850                 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
851                 Filename = string() | [string()] | atom()
852                 WrapFilesSpec = see trace_port/2
853                 Suffix = string()
854                 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
855                 PortNumber = integer()
856                 Hostname = string()
857
858              This function starts a trace client that reads the  output  cre‐
859              ated  by  a  trace port driver and handles it in mostly the same
860              way as a tracer process created by the tracer/0 function.
861
862              If Type is file, the client reads all trace messages  stored  in
863              the  file  named Filename or specified by WrapFilesSpec (must be
864              the same as used when creating the trace, see trace_port/2)  and
865              let's  the  default  handler function format the messages on the
866              console. This is one way to interpret the data stored in a  file
867              by the file trace port driver.
868
869              If  Type is follow_file, the client behaves as in the file case,
870              but keeps trying to read (and process) more data from  the  file
871              until  stopped  by stop_trace_client/1. WrapFilesSpec is not al‐
872              lowed as second argument for this Type.
873
874              If Type is ip, the client connects to the TCP/IP port PortNumber
875              on  the  host Hostname, from where it reads trace messages until
876              the TCP/IP connection is closed. If no  Hostname  is  specified,
877              the local host is assumed.
878
879              As  an example, one can let trace messages be sent over the net‐
880              work to another Erlang node (preferably not distributed),  where
881              the formatting occurs:
882
883              On  the  node  stack  there's  an  Erlang node ant@stack, in the
884              shell, type the following:
885
886              ant@stack> dbg:tracer(port, dbg:trace_port(ip,4711)).
887              <0.17.0>
888              ant@stack> dbg:p(self(), send).
889              {ok,1}
890
891              All trace messages are now sent to the trace port driver,  which
892              in  turn  listens for connections on the TCP/IP port 4711. If we
893              want to see the messages on another node, preferably on  another
894              host, we do like this:
895
896              -> dbg:trace_client(ip, {"stack", 4711}).
897              <0.42.0>
898
899              If  we  now send a message from the shell on the node ant@stack,
900              where all sends from the shell are traced:
901
902              ant@stack> self() ! hello.
903              hello
904
905              The following will appear  at  the  console  on  the  node  that
906              started the trace client:
907
908              (<0.23.0>) <0.23.0> ! hello
909              (<0.23.0>) <0.22.0> ! {shell_rep,<0.23.0>,{value,hello,[],[]}}
910
911              The  last  line  is generated due to internal message passing in
912              the Erlang shell. The process id's will vary.
913
914       trace_client(Type, Parameters, HandlerSpec) -> pid()
915
916              Types:
917
918                 Type = ip | file | follow_file
919                 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
920                 Filename = string() | [string()] | atom()
921                 WrapFilesSpec = see trace_port/2
922                 Suffix = string()
923                 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
924                 PortNumber = integer()
925                 Hostname = string()
926                 HandlerSpec = {HandlerFun, InitialData}
927                 HandlerFun = fun() (two arguments)
928                 InitialData = term()
929
930              This function works exactly as trace_client/2, but allows you to
931              write  your  own  handler  function.  The handler function works
932              mostly as the one described in tracer/2, but will also  have  to
933              be  prepared  to  handle  trace  messages of the form {drop, N},
934              where N is the number of dropped  messages.  This  pseudo  trace
935              message will only occur if the ip trace driver is used.
936
937              For  trace type file, the pseudo trace message end_of_trace will
938              appear at the end of the trace. The return value from  the  han‐
939              dler function is in this case ignored.
940
941       stop_trace_client(Pid) -> ok
942
943              Types:
944
945                 Pid = pid()
946
947              This  function shuts down a previously started trace client. The
948              Pid argument is the process id returned from the  trace_client/2
949              or trace_client/3 call.
950
951       get_tracer()
952
953              Equivalent to get_tracer(node()).
954
955       get_tracer(Nodename) -> {ok, Tracer}
956
957              Types:
958
959                 Nodename = atom()
960                 Tracer = port() | pid() | {module(), term()}
961
962              Returns  the  process,  port or tracer module to which all trace
963              messages are sent.
964
965       stop() -> ok
966
967              Stops the dbg server, clears all trace flags for all  processes,
968              clears  all  trace patterns for all functions, clears trace pat‐
969              terns for send/receive, shuts down all trace clients, and closes
970              all trace ports.
971

SIMPLE EXAMPLES - TRACING FROM THE SHELL

973       The  simplest way of tracing from the Erlang shell is to use dbg:c/3 or
974       dbg:c/4, e.g. tracing the function dbg:get_tracer/0:
975
976       (tiger@durin)84> dbg:c(dbg,get_tracer,[]).
977       (<0.154.0>) <0.152.0> ! {<0.154.0>,{get_tracer,tiger@durin}}
978       (<0.154.0>) out {dbg,req,1}
979       (<0.154.0>) << {dbg,{ok,<0.153.0>}}
980       (<0.154.0>) in {dbg,req,1}
981       (<0.154.0>) << timeout
982       {ok,<0.153.0>}
983       (tiger@durin)85>
984
985       Another way of tracing from the shell is to explicitly start  a  tracer
986       and  then  set the trace flags of your choice on the processes you want
987       to trace, e.g. trace messages and process events:
988
989       (tiger@durin)66> Pid = spawn(fun() -> receive {From,Msg} -> From ! Msg end end).
990       <0.126.0>
991       (tiger@durin)67> dbg:tracer().
992       {ok,<0.128.0>}
993       (tiger@durin)68> dbg:p(Pid,[m,procs]).
994       {ok,[{matched,tiger@durin,1}]}
995       (tiger@durin)69> Pid ! {self(),hello}.
996       (<0.126.0>) << {<0.116.0>,hello}
997       {<0.116.0>,hello}
998       (<0.126.0>) << timeout
999       (<0.126.0>) <0.116.0> ! hello
1000       (<0.126.0>) exit normal
1001       (tiger@durin)70> flush().
1002       Shell got hello
1003       ok
1004       (tiger@durin)71>
1005
1006       If you set the call trace flag, you also have to set  a  trace  pattern
1007       for the functions you want to trace:
1008
1009       (tiger@durin)77> dbg:tracer().
1010       {ok,<0.142.0>}
1011       (tiger@durin)78> dbg:p(all,call).
1012       {ok,[{matched,tiger@durin,3}]}
1013       (tiger@durin)79> dbg:tp(dbg,get_tracer,0,[]).
1014       {ok,[{matched,tiger@durin,1}]}
1015       (tiger@durin)80> dbg:get_tracer().
1016       (<0.116.0>) call dbg:get_tracer()
1017       {ok,<0.143.0>}
1018       (tiger@durin)81> dbg:tp(dbg,get_tracer,0,[{'_',[],[{return_trace}]}]).
1019       {ok,[{matched,tiger@durin,1},{saved,1}]}
1020       (tiger@durin)82> dbg:get_tracer().
1021       (<0.116.0>) call dbg:get_tracer()
1022       (<0.116.0>) returned from dbg:get_tracer/0 -> {ok,<0.143.0>}
1023       {ok,<0.143.0>}
1024       (tiger@durin)83>
1025

ADVANCED TOPICS - COMBINING WITH SEQ_TRACE

1027       The  dbg  module  is primarily targeted towards tracing through the er‐
1028       lang:trace/3 function. It is sometimes desired to trace messages  in  a
1029       more  delicate  way,  which  can be done with the help of the seq_trace
1030       module.
1031
1032       seq_trace implements sequential tracing (known in the AXE10 world,  and
1033       sometimes  called "forlopp tracing"). dbg can interpret messages gener‐
1034       ated from seq_trace and the same tracer  function  for  both  types  of
1035       tracing can be used. The seq_trace messages can even be sent to a trace
1036       port for further analysis.
1037
1038       As a match specification can turn on sequential tracing,  the  combina‐
1039       tion  of  dbg  and  seq_trace can be quite powerful. This brief example
1040       shows a session where sequential tracing is used:
1041
1042       1> dbg:tracer().
1043       {ok,<0.30.0>}
1044       2> {ok, Tracer} = dbg:get_tracer().
1045       {ok,<0.31.0>}
1046       3> seq_trace:set_system_tracer(Tracer).
1047       false
1048       4> dbg:tp(dbg, get_tracer, 0, [{[],[],[{set_seq_token, send, true}]}]).
1049       {ok,[{matched,nonode@nohost,1},{saved,1}]}
1050       5> dbg:p(all,call).
1051       {ok,[{matched,nonode@nohost,22}]}
1052       6> dbg:get_tracer(), seq_trace:set_token([]).
1053       (<0.25.0>) call dbg:get_tracer()
1054       SeqTrace [0]: (<0.25.0>) <0.30.0> ! {<0.25.0>,get_tracer} [Serial: {2,4}]
1055       SeqTrace [0]: (<0.30.0>) <0.25.0> ! {dbg,{ok,<0.31.0>}} [Serial: {4,5}]
1056       {1,0,5,<0.30.0>,4}
1057
1058       This session sets the system_tracer to the same process as the ordinary
1059       tracer  process  (i.  e.  <0.31.0>)  and sets the trace pattern for the
1060       function dbg:get_tracer to one that has the action of setting a sequen‐
1061       tial  token.  When the function is called by a traced process (all pro‐
1062       cesses are traced in this case), the process gets "contaminated" by the
1063       token  and  seq_trace messages are sent both for the server request and
1064       the response. The seq_trace:set_token([]) after  the  call  clears  the
1065       seq_trace  token,  why  no messages are sent when the answer propagates
1066       via the shell to the console port. The output would otherwise have been
1067       more noisy.
1068

NOTE OF CAUTION

1070       When  tracing function calls on a group leader process (an IO process),
1071       there is risk of causing a deadlock. This will happen if a group leader
1072       process  generates  a  trace message and the tracer process, by calling
1073       the trace handler function, sends an  IO  request  to  the  same  group
1074       leader.  The  problem can only occur if the trace handler prints to tty
1075       using an io function such as format/2. Note that  when  dbg:p(all,call)
1076       is called, IO processes are also traced. Here's an example:
1077
1078       %% Using a default line editing shell
1079       1> dbg:tracer(process, {fun(Msg,_) -> io:format("~p~n", [Msg]), 0 end, 0}).
1080       {ok,<0.37.0>}
1081       2> dbg:p(all, [call]).
1082       {ok,[{matched,nonode@nohost,25}]}
1083       3> dbg:tp(mymod,[{'_',[],[]}]).
1084       {ok,[{matched,nonode@nohost,0},{saved,1}]}
1085       4> mymod: % TAB pressed here
1086       %% -- Deadlock --
1087
1088       Here's another example:
1089
1090       %% Using a shell without line editing (oldshell)
1091       1> dbg:tracer(process).
1092       {ok,<0.31.0>}
1093       2> dbg:p(all, [call]).
1094       {ok,[{matched,nonode@nohost,25}]}
1095       3> dbg:tp(lists,[{'_',[],[]}]).
1096       {ok,[{matched,nonode@nohost,0},{saved,1}]}
1097       % -- Deadlock --
1098
1099       The  reason  we get a deadlock in the first example is because when TAB
1100       is pressed to expand the function name, the group leader (which handles
1101       character input) calls mymod:module_info(). This generates a trace mes‐
1102       sage which, in turn, causes the tracer process to send an IO request to
1103       the group leader (by calling io:format/2). We end up in a deadlock.
1104
1105       In  the  second example we use the default trace handler function. This
1106       handler prints to tty by sending IO requests to the user process.  When
1107       Erlang is started in oldshell mode, the shell process will have user as
1108       its group leader and so will the tracer process in this example.  Since
1109       user  calls  functions  in lists we end up in a deadlock as soon as the
1110       first IO request is sent.
1111
1112       Here are a few suggestions for how to avoid deadlock:
1113
1114         * Don't trace the group leader of the tracer process. If tracing  has
1115           been  switched  on for all processes, call dbg:p(TracerGLPid,clear)
1116           to stop tracing the group leader (TracerGLPid).  process_info(Trac‐
1117           erPid,group_leader)  tells  you which process this is (TracerPid is
1118           returned from dbg:get_tracer/0).
1119
1120         * Don't trace the user process if using  the  default  trace  handler
1121           function.
1122
1123         * In  your  own trace handler function, call erlang:display/1 instead
1124           of an io function or, if user is not used as group leader, print to
1125           user   instead  of  the  default  group  leader.  Example:  io:for‐
1126           mat(user,Str,Args).
1127
1128Ericsson AB                    runtime_tools 2.0                        dbg(3)
Impressum