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              Gives a list of items for brief online help.
116
117       h(Item) -> ok
118
119              Types:
120
121                 Item = atom()
122
123              Gives a brief help text for functions in  the  dbg  module.  The
124              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              Traces Item in accordance to the value specified by  Flags.  The
140              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              Evaluates  the  expression  apply(Mod, Fun, Args) with the trace
263              flags in Flags set. This is a convenient way to trace  processes
264              from the Erlang shell.
265
266       i() -> ok
267
268              Displays information about all traced processes and ports.
269
270       tp(Module,MatchSpec)
271
272              Same as tp({Module, '_', '_'}, MatchSpec)
273
274       tp(Module,Function,MatchSpec)
275
276              Same as tp({Module, Function, '_'}, MatchSpec)
277
278       tp(Module, Function, Arity, MatchSpec)
279
280              Same as tp({Module, Function, Arity}, MatchSpec)
281
282       tp({Module,  Function,  Arity}, MatchSpec) -> {ok, MatchDesc} | {error,
283       term()}
284
285              Types:
286
287                 Module = atom() | '_'
288                 Function = atom() | '_'
289                 Arity = integer() |'_'
290                 MatchSpec = integer() | Built-inAlias | [] | match_spec()
291                 Built-inAlias = x | c | cx
292                 MatchDesc = [MatchInfo]
293                 MatchInfo = {saved, integer()} | MatchNum
294                 MatchNum = {matched, node(), integer()} |  {matched,  node(),
295                 0, RPCError}
296
297              This  function enables call trace for one or more functions. All
298              exported functions matching the {Module, Function, Arity}  argu‐
299              ment  will be concerned, but the match_spec() may further narrow
300              down the set of function calls generating trace messages.
301
302              For a description of the match_spec() syntax, please turn to the
303              User's  guide  part  of the online documentation for the runtime
304              system (erts). The chapter Match Specifications  in  Erlang  ex‐
305              plains the general match specification "language". The most com‐
306              mon generic match specifications used can be found as Built-inA‐
307              lias', see ltp/0 below for details.
308
309              The  Module,  Function  and/or  Arity  parts of the tuple may be
310              specified as the atom '_' which is a  "wild-card"  matching  all
311              modules/functions/arities.  Note,  if the Module is specified as
312              '_', the Function and Arity parts have to be  specified  as  '_'
313              too. The same holds for the Functions relation to the Arity.
314
315              All  nodes  added  with n/1 or tracer/3 will be affected by this
316              call, and if Module is not '_' the module will be loaded on  all
317              nodes.
318
319              The  function  returns  either  an  error  tuple or a tuple {ok,
320              List}. The List consists of specifications of how many functions
321              that  matched,  in  the  same way as the processes and ports are
322              presented in the return value of p/2.
323
324              There may be a tuple {saved, N} in  the  return  value,  if  the
325              MatchSpec  is  other  than []. The integer N may then be used in
326              subsequent calls to this function and will stand as  an  "alias"
327              for  the  given  expression. There are also a couple of built-in
328              aliases for common expressions, see ltp/0 below for details.
329
330              If an error is returned, it can be due to errors in  compilation
331              of  the match specification. Such errors are presented as a list
332              of tuples {error, string()} where the string is a textual expla‐
333              nation of the compilation error. An example:
334
335              (x@y)4> dbg:tp({dbg,ltp,0},[{[],[],[{message, two, arguments}, {noexist}]}]).
336              {error,
337               [{error,"Special form 'message' called with wrong number of
338                        arguments in {message,two,arguments}."},
339                {error,"Function noexist/1 does_not_exist."}]}
340
341       tpl(Module,MatchSpec)
342
343              Same as tpl({Module, '_', '_'}, MatchSpec)
344
345       tpl(Module,Function,MatchSpec)
346
347              Same as tpl({Module, Function, '_'}, MatchSpec)
348
349       tpl(Module, Function, Arity, MatchSpec)
350
351              Same as tpl({Module, Function, Arity}, MatchSpec)
352
353       tpl({Module,  Function, Arity}, MatchSpec) -> {ok, MatchDesc} | {error,
354       term()}
355
356              This function works as tp/2, but enables tracing for local calls
357              (and  local  functions)  as  well as for global calls (and func‐
358              tions).
359
360       tpe(Event, MatchSpec) -> {ok, MatchDesc} | {error, term()}
361
362              Types:
363
364                 Event = send | 'receive'
365                 MatchSpec = integer() | Built-inAlias | [] | match_spec()
366                 Built-inAlias = x | c | cx
367                 MatchDesc = [MatchInfo]
368                 MatchInfo = {saved, integer()} | MatchNum
369                 MatchNum = {matched, node(), 1} | {matched, node(), 0, RPCEr‐
370                 ror}
371
372              This  function associates a match specification with trace event
373              send or 'receive'. By default all executed  send  and  'receive'
374              events  are  traced if enabled for a process. A match specifica‐
375              tion can be used to filter traced events based  on  sender,  re‐
376              ceiver and/or message content.
377
378              For a description of the match_spec() syntax, please turn to the
379              User's guide part of the online documentation  for  the  runtime
380              system  (erts).  The  chapter Match Specifications in Erlang ex‐
381              plains the general match specification "language".
382
383              For send, the matching is done on the list [Receiver, Msg].  Re‐
384              ceiver  is  the process or port identity of the receiver and Msg
385              is the message term. The pid of the sending process can  be  ac‐
386              cessed with the guard function self/0.
387
388              For  'receive',  the matching is done on the list [Node, Sender,
389              Msg]. Node is the node name of the sender. Sender is the process
390              or  port  identity  of  the sender, or the atom undefined if the
391              sender is not known (which may be the case for remote  senders).
392              Msg is the message term. The pid of the receiving process can be
393              accessed with the guard function self/0.
394
395              All nodes added with n/1 or tracer/3 will be  affected  by  this
396              call.
397
398              The  return value is the same as for tp/2. The number of matched
399              events are never larger than 1 as tpe/2 does not accept any form
400              of wildcards for argument Event.
401
402       ctp()
403
404              Same as ctp({'_', '_', '_'})
405
406       ctp(Module)
407
408              Same as ctp({Module, '_', '_'})
409
410       ctp(Module, Function)
411
412              Same as ctp({Module, Function, '_'})
413
414       ctp(Module, Function, Arity)
415
416              Same as ctp({Module, Function, Arity})
417
418       ctp({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
419
420              Types:
421
422                 Module = atom() | '_'
423                 Function = atom() | '_'
424                 Arity = integer() | '_'
425                 MatchDesc = [MatchNum]
426                 MatchNum  =  {matched, node(), integer()} | {matched, node(),
427                 0, RPCError}
428
429              This function disables call tracing on the specified  functions.
430              The  semantics  of  the  parameter is the same as for the corre‐
431              sponding function specification in tp/2 or tpl/2. Both local and
432              global call trace is disabled.
433
434              The  return  value reflects how many functions that matched, and
435              is constructed as described in tp/2. No tuple {saved, N} is how‐
436              ever ever returned (for obvious reasons).
437
438       ctpl()
439
440              Same as ctpl({'_', '_', '_'})
441
442       ctpl(Module)
443
444              Same as ctpl({Module, '_', '_'})
445
446       ctpl(Module, Function)
447
448              Same as ctpl({Module, Function, '_'})
449
450       ctpl(Module, Function, Arity)
451
452              Same as ctpl({Module, Function, Arity})
453
454       ctpl({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
455
456              This  function  works as ctp/1, but only disables tracing set up
457              with tpl/2 (not with tp/2).
458
459       ctpg()
460
461              Same as ctpg({'_', '_', '_'})
462
463       ctpg(Module)
464
465              Same as ctpg({Module, '_', '_'})
466
467       ctpg(Module, Function)
468
469              Same as ctpg({Module, Function, '_'})
470
471       ctpg(Module, Function, Arity)
472
473              Same as ctpg({Module, Function, Arity})
474
475       ctpg({Module, Function, Arity}) -> {ok, MatchDesc} | {error, term()}
476
477              This function works as ctp/1, but only disables tracing  set  up
478              with tp/2 (not with tpl/2).
479
480       ctpe(Event) -> {ok, MatchDesc} | {error, term()}
481
482              Types:
483
484                 Event = send | 'receive'
485                 MatchDesc = [MatchNum]
486                 MatchNum = {matched, node(), 1} | {matched, node(), 0, RPCEr‐
487                 ror}
488
489              This function clears  match  specifications  for  the  specified
490              trace  event (send or 'receive'). It will revert back to the de‐
491              fault behavior of tracing all triggered events.
492
493              The return value follow the same style as for ctp/1.
494
495       ltp() -> ok
496
497              Use this function to recall all match specifications  previously
498              used  in  the  session  (i.  e. previously saved during calls to
499              tp/2, and built-in match specifications. This is very useful, as
500              a  complicated  match_spec  can  be quite awkward to write. Note
501              that the match specifications are lost if stop/0 is called.
502
503              Match specifications used can be saved in a  file  (if  a  read-
504              write  file  system  is present) for use in later debugging ses‐
505              sions, see wtp/1 and rtp/1
506
507              There  are  three  built-in  trace  patterns:   exception_trace,
508              caller_trace  and caller_exception_trace (or x, c and cx respec‐
509              tively). Exception trace sets a trace which will  show  function
510              names,  parameters,  return  values  and  exceptions thrown from
511              functions. Caller traces display function names, parameters  and
512              information  about  which function called it. An example using a
513              built-in alias:
514
515              (x@y)4> dbg:tp(lists,sort,cx).
516              {ok,[{matched,nonode@nohost,2},{saved,cx}]}
517              (x@y)4> lists:sort([2,1]).
518              (<0.32.0>) call lists:sort([2,1]) ({erl_eval,do_apply,5})
519              (<0.32.0>) returned from lists:sort/1 -> [1,2]
520              [1,2]
521
522       dtp() -> ok
523
524              Use this function to "forget"  all  match  specifications  saved
525              during  calls  to tp/2. This is useful when one wants to restore
526              other match specifications from a file with rtp/1. Use dtp/1  to
527              delete specific saved match specifications.
528
529       dtp(N) -> ok
530
531              Types:
532
533                 N = integer()
534
535              Use  this  function  to  "forget" a specific match specification
536              saved during calls to tp/2.
537
538       wtp(Name) -> ok | {error, IOError}
539
540              Types:
541
542                 Name = string()
543                 IOError = term()
544
545              This function will save all match  specifications  saved  during
546              the session (during calls to tp/2) and built-in match specifica‐
547              tions in a text file with the name designated by Name. The  for‐
548              mat  of  the file is textual, why it can be edited with an ordi‐
549              nary text editor, and then restored with rtp/1.
550
551              Each match spec in the file ends with a full stop  (.)  and  new
552              (syntactically correct) match specifications can be added to the
553              file manually.
554
555              The function returns ok or an error tuple where the second  ele‐
556              ment contains the I/O error that made the writing impossible.
557
558       rtp(Name) -> ok | {error, Error}
559
560              Types:
561
562                 Name = string()
563                 Error = term()
564
565              This  function reads match specifications from a file (possibly)
566              generated by the wtp/1 function. It checks  the  syntax  of  all
567              match specifications and verifies that they are correct. The er‐
568              ror handling principle is "all or nothing", i. e. if some of the
569              match  specifications  are wrong, none of the specifications are
570              added to the list of saved match specifications for the  running
571              system.
572
573              The match specifications in the file are merged with the current
574              match specifications, so that no duplicates are  generated.  Use
575              ltp/0  to  see  what numbers were assigned to the specifications
576              from the file.
577
578              The function will return an error, either due  to  I/O  problems
579              (like a non existing or non readable file) or due to file format
580              problems. The errors from a bad format file are  in  a  more  or
581              less  textual  format,  which will give a hint to what's causing
582              the problem.
583
584       n(Nodename) -> {ok, Nodename} | {error, Reason}
585
586              Types:
587
588                 Nodename = atom()
589                 Reason = term()
590
591              The dbg server keeps a list of nodes  where  tracing  should  be
592              performed. Whenever a tp/2 call or a p/2 call is made, it is ex‐
593              ecuted for all nodes in this list including the local node  (ex‐
594              cept  for p/2 with a specific pid() or port() as first argument,
595              in which case the command is executed only on the node where the
596              designated process or port resides).
597
598              This function adds a remote node (Nodename) to the list of nodes
599              where tracing is performed. It starts a tracer  process  on  the
600              remote  node,  which  will send all trace messages to the tracer
601              process on the local node (via the Erlang distribution).  If  no
602              tracer  process  is  running on the local node, the error reason
603              no_local_tracer is returned. The tracer  process  on  the  local
604              node must be started with the tracer/0/2 function.
605
606              If  Nodename  is  the  local node, the error reason cant_add_lo‐
607              cal_node is returned.
608
609              If a trace port (see trace_port/2) is running on the local node,
610              remote  nodes  cannot be traced with a tracer process. The error
611              reason cant_trace_remote_pid_to_local_port is returned. A  trace
612              port can however be started on the remote node with the tracer/3
613              function.
614
615              The function will also return an error if the node  Nodename  is
616              not reachable.
617
618       cn(Nodename) -> ok
619
620              Types:
621
622                 Nodename = atom()
623
624              Clears a node from the list of traced nodes. Subsequent calls to
625              tp/2 and p/2 will not consider that node,  but  tracing  already
626              activated on the node will continue to be in effect.
627
628              Returns ok, cannot fail.
629
630       ln() -> ok
631
632              Shows the list of traced nodes on the console.
633
634       tracer() -> {ok, pid()} | {error, already_started}
635
636              This function starts a server on the local node that will be the
637              recipient of all trace messages. All  subsequent  calls  to  p/2
638              will result in messages sent to the newly started trace server.
639
640              A trace server started in this way will simply display the trace
641              messages in a formatted way in  the  Erlang  shell  (i.  e.  use
642              io:format). See tracer/2 for a description of how the trace mes‐
643              sage handler can be customized.
644
645              To start a similar tracer on a remote node, use n/1.
646
647       tracer(Type, Data) -> {ok, pid()} | {error, Error}
648
649              Types:
650
651                 Type = port | process | module
652                 Data = PortGenerator | HandlerSpec | ModuleSpec
653                 PortGenerator = fun() (no arguments)
654                 Error = term()
655                 HandlerSpec = {HandlerFun, InitialData}
656                 HandlerFun = fun() (two arguments)
657                 ModuleSpec = fun() (no arguments)  |  {TracerModule,  Tracer‐
658                 State}
659                 TracerModule = atom()
660                 InitialData = TracerState = term()
661
662              This  function starts a tracer server with additional parameters
663              on the local node. The first parameter, the Type,  indicates  if
664              trace   messages  should  be  handled  by  a  receiving  process
665              (process), by a tracer port (port) or by a tracer  module  (mod‐
666              ule).  For a description about tracer ports see trace_port/2 and
667              for a tracer modules see erl_tracer.
668
669              If Type is process, a message handler function can be  specified
670              (HandlerSpec).  The handler function, which should be a fun tak‐
671              ing two arguments, will be called for each trace  message,  with
672              the  first argument containing the message as it is and the sec‐
673              ond argument containing the return value from the  last  invoca‐
674              tion  of  the  fun. The initial value of the second parameter is
675              specified in the InitialData part of the HandlerSpec.  The  Han‐
676              dlerFun  may choose any appropriate action to take when invoked,
677              and can save a state for the next invocation by returning it.
678
679              If Type is port, then the second parameter should be a fun which
680              takes  no  arguments  and returns a newly opened trace port when
681              called.  Such  a  fun  is  preferably   generated   by   calling
682              trace_port/2.
683
684              if  Type is module, then the second parameter should be either a
685              tuple describing the erl_tracer module to be  used  for  tracing
686              and the state to be used for that tracer module or a fun return‐
687              ing the same tuple.
688
689              If an error is returned, it can either be due to a tracer server
690              already running ({error,already_started}) or due to the Handler‐
691              Fun throwing an exception.
692
693              To start a similar tracer on a remote node, use tracer/3.
694
695       tracer(Nodename, Type, Data) -> {ok, Nodename} | {error, Reason}
696
697              Types:
698
699                 Nodename = atom()
700
701              This function is equivalent to tracer/2, but acts on  the  given
702              node. A tracer is started on the node (Nodename) and the node is
703              added to the list of traced nodes.
704
705          Note:
706              This function is not equivalent  to  n/1.  While  n/1  starts  a
707              process  tracer  which  redirects  all  trace  information  to a
708              process tracer on the local node (i.e. the trace control  node),
709              tracer/3 starts a tracer of any type which is independent of the
710              tracer on the trace control node.
711
712
713              For details, see tracer/2.
714
715       trace_port(Type, Parameters) -> fun()
716
717              Types:
718
719                 Type = ip | file
720                 Parameters = Filename | WrapFilesSpec | IPPortSpec
721                 Filename = string() | [string()] | atom()
722                 WrapFilesSpec = {Filename, wrap, Suffix} |  {Filename,  wrap,
723                 Suffix,   WrapSize}  |  {Filename,  wrap,  Suffix,  WrapSize,
724                 WrapCnt}
725                 Suffix = string()
726                 WrapSize = integer() >= 0 | {time, WrapTime}
727                 WrapTime = integer() >= 1
728                 WrapCnt = integer() >= 1
729                 IpPortSpec = PortNumber | {PortNumber, QueSize}
730                 PortNumber = integer()
731                 QueSize = integer()
732
733              This function creates a trace port generating fun. The fun takes
734              no  arguments  and returns a newly opened trace port. The return
735              value from this function is suitable as a  second  parameter  to
736              tracer/2, i.e. dbg:tracer(port, dbg:trace_port(ip, 4711)).
737
738              A trace port is an Erlang port to a dynamically linked in driver
739              that handles trace messages directly, without  the  overhead  of
740              sending them as messages in the Erlang virtual machine.
741
742              Two trace drivers are currently implemented, the file and the ip
743              trace drivers. The file driver sends all trace messages into one
744              or  several  binary  files, from where they later can be fetched
745              and processed with the trace_client/2 function.  The  ip  driver
746              opens  a  TCP/IP  port  where it listens for connections. When a
747              client (preferably started by calling trace_client/2 on  another
748              Erlang  node)  connects, all trace messages are sent over the IP
749              network for further processing by the remote client.
750
751              Using a trace port significantly lowers the overhead imposed  by
752              using tracing.
753
754              The  file trace driver expects a filename or a wrap files speci‐
755              fication as parameter. A file is written with a high  degree  of
756              buffering, why all trace messages are not guaranteed to be saved
757              in the file in case of a system crash. That is the price to  pay
758              for low tracing overhead.
759
760              A  wrap files specification is used to limit the disk space con‐
761              sumed by the trace. The trace is written to a limited number  of
762              files  each  with a limited size. The actual filenames are File‐
763              name ++ SeqCnt ++ Suffix,  where  SeqCnt  counts  as  a  decimal
764              string  from  0  to WrapCnt and then around again from 0. When a
765              trace term written to the current  file  makes  it  longer  than
766              WrapSize,  that  file  is closed, if the number of files in this
767              wrap trace is as many as WrapCnt the oldest file is deleted then
768              a  new  file  is opened to become the current. Thus, when a wrap
769              trace has been stopped, there are at most  WrapCnt  trace  files
770              saved  with  a  size of at least WrapSize (but not much bigger),
771              except for the last file that might even be empty.  The  default
772              values are WrapSize = 128*1024 and WrapCnt = 8.
773
774              The  SeqCnt  values  in  the  filenames  are  all in the range 0
775              through WrapCnt with a gap in the circular sequence. The gap  is
776              needed to find the end of the trace.
777
778              If  the  WrapSize  is specified as {time, WrapTime}, the current
779              file is closed when it has been open  more  than  WrapTime  mil‐
780              liseconds, regardless of it being empty or not.
781
782              The  ip  trace driver has a queue of QueSize messages waiting to
783              be delivered. If the driver cannot deliver messages as  fast  as
784              they  are  produced  by the runtime system, a special message is
785              sent, which indicates how many messages that are  dropped.  That
786              message  will  arrive  at  the  handler  function  specified  in
787              trace_client/3 as the tuple {drop, N} where N is the  number  of
788              consecutive  messages  dropped. In case of heavy tracing, drop's
789              are likely to occur, and they surely occur if no client is read‐
790              ing the trace messages. The default value of QueSize is 200.
791
792       flush_trace_port()
793
794              Equivalent to flush_trace_port(node()).
795
796       flush_trace_port(Nodename) -> ok | {error, Reason}
797
798              Equivalent to trace_port_control(Nodename,flush).
799
800       trace_port_control(Operation)
801
802              Equivalent to trace_port_control(node(),Operation).
803
804       trace_port_control(Nodename,Operation)  ->  ok | {ok, Result} | {error,
805       Reason}
806
807              Types:
808
809                 Nodename = atom()
810
811              This function is used to do a control operation  on  the  active
812              trace port driver on the given node (Nodename). Which operations
813              are allowed as well as their return values depend on which trace
814              driver is used.
815
816              Returns  either ok or {ok, Result} if the operation was success‐
817              ful, or {error, Reason} if the current tracer is a process or if
818              it is a port not supporting the operation.
819
820              The allowed values for Operation are:
821
822                flush:
823                  This  function is used to flush the internal buffers held by
824                  a trace port driver. Currently only the  file  trace  driver
825                  supports this operation. Returns ok.
826
827                get_listen_port:
828                  Returns {ok, IpPort} where IpPort is the IP port number used
829                  by the driver listen socket. Only the ip trace  driver  sup‐
830                  ports this operation.
831
832       trace_client(Type, Parameters) -> pid()
833
834              Types:
835
836                 Type = ip | file | follow_file
837                 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
838                 Filename = string() | [string()] | atom()
839                 WrapFilesSpec = see trace_port/2
840                 Suffix = string()
841                 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
842                 PortNumber = integer()
843                 Hostname = string()
844
845              This  function  starts a trace client that reads the output cre‐
846              ated by a trace port driver and handles it in  mostly  the  same
847              way as a tracer process created by the tracer/0 function.
848
849              If  Type  is file, the client reads all trace messages stored in
850              the file named Filename or specified by WrapFilesSpec  (must  be
851              the  same as used when creating the trace, see trace_port/2) and
852              let's the default handler function format the  messages  on  the
853              console.  This is one way to interpret the data stored in a file
854              by the file trace port driver.
855
856              If Type is follow_file, the client behaves as in the file  case,
857              but  keeps  trying to read (and process) more data from the file
858              until stopped by stop_trace_client/1. WrapFilesSpec is  not  al‐
859              lowed as second argument for this Type.
860
861              If Type is ip, the client connects to the TCP/IP port PortNumber
862              on the host Hostname, from where it reads trace  messages  until
863              the  TCP/IP  connection  is closed. If no Hostname is specified,
864              the local host is assumed.
865
866              As an example, one can let trace messages be sent over the  net‐
867              work  to another Erlang node (preferably not distributed), where
868              the formatting occurs:
869
870              On the node stack there's  an  Erlang  node  ant@stack,  in  the
871              shell, type the following:
872
873              ant@stack> dbg:tracer(port, dbg:trace_port(ip,4711)).
874              <0.17.0>
875              ant@stack> dbg:p(self(), send).
876              {ok,1}
877
878              All  trace messages are now sent to the trace port driver, which
879              in turn listens for connections on the TCP/IP port 4711.  If  we
880              want  to see the messages on another node, preferably on another
881              host, we do like this:
882
883              -> dbg:trace_client(ip, {"stack", 4711}).
884              <0.42.0>
885
886              If we now send a message from the shell on the  node  ant@stack,
887              where all sends from the shell are traced:
888
889              ant@stack> self() ! hello.
890              hello
891
892              The  following  will  appear  at  the  console  on the node that
893              started the trace client:
894
895              (<0.23.0>) <0.23.0> ! hello
896              (<0.23.0>) <0.22.0> ! {shell_rep,<0.23.0>,{value,hello,[],[]}}
897
898              The last line is generated due to internal  message  passing  in
899              the Erlang shell. The process id's will vary.
900
901       trace_client(Type, Parameters, HandlerSpec) -> pid()
902
903              Types:
904
905                 Type = ip | file | follow_file
906                 Parameters = Filename | WrapFilesSpec | IPClientPortSpec
907                 Filename = string() | [string()] | atom()
908                 WrapFilesSpec = see trace_port/2
909                 Suffix = string()
910                 IpClientPortSpec = PortNumber | {Hostname, PortNumber}
911                 PortNumber = integer()
912                 Hostname = string()
913                 HandlerSpec = {HandlerFun, InitialData}
914                 HandlerFun = fun() (two arguments)
915                 InitialData = term()
916
917              This function works exactly as trace_client/2, but allows you to
918              write your own handler  function.  The  handler  function  works
919              mostly  as  the one described in tracer/2, but will also have to
920              be prepared to handle trace messages  of  the  form  {drop,  N},
921              where  N  is  the  number of dropped messages. This pseudo trace
922              message will only occur if the ip trace driver is used.
923
924              For trace type file, the pseudo trace message end_of_trace  will
925              appear  at  the end of the trace. The return value from the han‐
926              dler function is in this case ignored.
927
928       stop_trace_client(Pid) -> ok
929
930              Types:
931
932                 Pid = pid()
933
934              This function shuts down a previously started trace client.  The
935              Pid  argument is the process id returned from the trace_client/2
936              or trace_client/3 call.
937
938       get_tracer()
939
940              Equivalent to get_tracer(node()).
941
942       get_tracer(Nodename) -> {ok, Tracer}
943
944              Types:
945
946                 Nodename = atom()
947                 Tracer = port() | pid() | {module(), term()}
948
949              Returns the process, port or tracer module to  which  all  trace
950              messages are sent.
951
952       stop() -> ok
953
954              Stops  the  dbg  server  and clears all trace flags for all pro‐
955              cesses and all local trace  patterns  for  all  functions.  Also
956              shuts down all trace clients and closes all trace ports.
957
958              Note  that  no  global trace patterns are affected by this func‐
959              tion.
960
961       stop_clear() -> ok
962
963              Same as stop/0, but also clears all  trace  patterns  on  global
964              functions calls.
965

SIMPLE EXAMPLES - TRACING FROM THE SHELL

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

ADVANCED TOPICS - COMBINING WITH SEQ_TRACE

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

NOTE OF CAUTION

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