; etc/DEBUG copedits
[emacs.git] / etc / DEBUG
blob51a3736855fc0e12cabd475f5f0f60a944b58810
1 Debugging GNU Emacs
3 Copyright (C) 1985, 2000-2015 Free Software Foundation, Inc.
4 See the end of the file for license conditions.
7 [People who debug Emacs on Windows using Microsoft debuggers should
8 read the Windows-specific section near the end of this document.]
10 ** When you debug Emacs with GDB, you should start GDB in the directory
11 where the Emacs executable was made (the 'src' directory in the Emacs
12 source tree).  That directory has a .gdbinit file that defines various
13 "user-defined" commands for debugging Emacs.  (These commands are
14 described below under "Examining Lisp object values" and "Debugging
15 Emacs Redisplay problems".)
17 Some GDB versions by default do not automatically load .gdbinit files
18 in the directory where you invoke GDB.  With those versions of GDB,
19 you will see a warning when GDB starts, like this:
21   warning: File ".../src/.gdbinit" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
23 There are several ways to overcome that difficulty, they are all
24 described in the node "Auto-loading safe path" in the GDB user
25 manual.  If nothing else helps, type "source /path/to/.gdbinit RET" at
26 the GDB prompt, to unconditionally load the GDB init file.
28 ** When you are trying to analyze failed assertions or backtraces, it
29 is essential to compile Emacs with flags suitable for debugging.
30 With GCC 4.8 or later, you can invoke 'make' with CFLAGS="-Og -g3".
31 With older GCC or non-GCC compilers, you can use CFLAGS="-O0 -g3".
32 With GCC and higher optimization levels such as -O2, the
33 -fno-omit-frame-pointer and -fno-crossjumping options are often
34 essential.  The latter prevents GCC from using the same abort call for
35 all assertions in a given function, rendering the stack backtrace
36 useless for identifying the specific failed assertion.
37 Some versions of GCC support recent versions of the DWARF standard for
38 debugging info, but default to older versions; for example, they could
39 support -gdwarf-4 compiler option (for DWARF v4), but default to
40 version 2 of the DWARF standard.  For best results in debugging
41 abilities, find out the highest version of DWARF your GCC can support,
42 and use the corresponding -gdwarf-N switch instead of just -g (you
43 will still need -g3, as in "-gdwarf-4 -g3").
45 ** It is a good idea to run Emacs under GDB (or some other suitable
46 debugger) *all the time*.  Then, when Emacs crashes, you will be able
47 to debug the live process, not just a core dump.  (This is especially
48 important on systems which don't support core files, and instead print
49 just the registers and some stack addresses.)
51 ** If Emacs hangs, or seems to be stuck in some infinite loop, typing
52 "kill -TSTP PID", where PID is the Emacs process ID, will cause GDB to
53 kick in, provided that you run under GDB.
55 ** Getting control to the debugger
57 `Fsignal' is a very useful place to put a breakpoint in.
58 All Lisp errors go through there.
60 It is useful, when debugging, to have a guaranteed way to return to
61 the debugger at any time.  When using X, this is easy: type C-z at the
62 window where Emacs is running under GDB, and it will stop Emacs just
63 as it would stop any ordinary program.  When Emacs is running in a
64 terminal, things are not so easy.
66 The src/.gdbinit file in the Emacs distribution arranges for SIGINT
67 (C-g in Emacs) to be passed to Emacs and not give control back to GDB.
68 On modern POSIX systems, you can override that with this command:
70    handle SIGINT stop nopass
72 After this `handle' command, SIGINT will return control to GDB.  If
73 you want the C-g to cause a QUIT within Emacs as well, omit the `nopass'.
75 A technique that can work when `handle SIGINT' does not is to store
76 the code for some character into the variable stop_character.  Thus,
78     set stop_character = 29
80 makes Control-] (decimal code 29) the stop character.
81 Typing Control-] will cause immediate stop.  You cannot
82 use the set command until the inferior process has been started.
83 Put a breakpoint early in `main', or suspend the Emacs,
84 to get an opportunity to do the set command.
86 Another technique for get control to the debugger is to put a
87 breakpoint in some rarely used function.  One such convenient function
88 is Fredraw_display, which you can invoke at will interactively with
89 "M-x redraw-display RET".
91 When Emacs is running in a terminal, it is sometimes useful to use a separate
92 terminal for the debug session.  This can be done by starting Emacs as usual,
93 then attaching to it from gdb with the `attach' command which is explained in
94 the node "Attach" of the GDB manual.
96 On MS-Windows, you can start Emacs in its own separate terminal by
97 setting the new-console option before running Emacs under GDB:
99   (gdb) set new-console 1
100   (gdb) run
102 ** Examining Lisp object values.
104 When you have a live process to debug, and it has not encountered a
105 fatal error, you can use the GDB command `pr'.  First print the value
106 in the ordinary way, with the `p' command.  Then type `pr' with no
107 arguments.  This calls a subroutine which uses the Lisp printer.
109 You can also use `pp value' to print the emacs value directly.
111 To see the current value of a Lisp Variable, use `pv variable'.
113 Note: It is not a good idea to try `pr', `pp', or `pv' if you know that Emacs
114 is in deep trouble: its stack smashed (e.g., if it encountered SIGSEGV
115 due to stack overflow), or crucial data structures, such as `obarray',
116 corrupted, etc.  In such cases, the Emacs subroutine called by `pr'
117 might make more damage, like overwrite some data that is important for
118 debugging the original problem.
120 Also, on some systems it is impossible to use `pr' if you stopped
121 Emacs while it was inside `select'.  This is in fact what happens if
122 you stop Emacs while it is waiting.  In such a situation, don't try to
123 use `pr'.  Instead, use `s' to step out of the system call.  Then
124 Emacs will be between instructions and capable of handling `pr'.
126 If you can't use `pr' command, for whatever reason, you can use the
127 `xpr' command to print out the data type and value of the last data
128 value, For example:
130     p it->object
131     xpr
133 You may also analyze data values using lower-level commands.  Use the
134 `xtype' command to print out the data type of the last data value.
135 Once you know the data type, use the command that corresponds to that
136 type.  Here are these commands:
138     xint xptr xwindow xmarker xoverlay xmiscfree xintfwd xboolfwd xobjfwd
139     xbufobjfwd xkbobjfwd xbuflocal xbuffer xsymbol xstring xvector xframe
140     xwinconfig xcompiled xcons xcar xcdr xsubr xprocess xfloat xscrollbar
141     xchartable xsubchartable xboolvector xhashtable xlist xcoding
142     xcharset xfontset xfont xbytecode
144 Each one of them applies to a certain type or class of types.
145 (Some of these types are not visible in Lisp, because they exist only
146 internally.)
148 Each x... command prints some information about the value, and
149 produces a GDB value (subsequently available in $) through which you
150 can get at the rest of the contents.
152 In general, most of the rest of the contents will be additional Lisp
153 objects which you can examine in turn with the x... commands.
155 Even with a live process, these x...  commands are useful for
156 examining the fields in a buffer, window, process, frame or marker.
157 Here's an example using concepts explained in the node "Value History"
158 of the GDB manual to print values associated with the variable
159 called frame.  First, use these commands:
161   cd src
162   gdb emacs
163   b set_frame_buffer_list
164   r -q
166 Then Emacs hits the breakpoint:
168   (gdb) p frame
169   $1 = 139854428
170   (gdb) xpr
171   Lisp_Vectorlike
172   PVEC_FRAME
173   $2 = (struct frame *) 0x8560258
174   "emacs@localhost"
175   (gdb) p *$
176   $3 = {
177     size = 1073742931,
178     next = 0x85dfe58,
179     name = 140615219,
180     [...]
181   }
183 Now we can use `pr' to print the frame parameters:
185   (gdb) pp $->param_alist
186   ((background-mode . light) (display-type . color) [...])
188 The Emacs C code heavily uses macros defined in lisp.h.  So suppose
189 we want the address of the l-value expression near the bottom of
190 `add_command_key' from keyboard.c:
192   XVECTOR (this_command_keys)->contents[this_command_key_count++] = key;
194 XVECTOR is a macro, so GDB only knows about it if Emacs has been compiled with
195 preprocessor macro information.  GCC provides this if you specify the options
196 `-gdwarf-N' (where N is 2 or higher) and `-g3'.  In this case, GDB can
197 evaluate expressions like "p XVECTOR (this_command_keys)".
199 When this information isn't available, you can use the xvector command in GDB
200 to get the same result.  Here is how:
202   (gdb) p this_command_keys
203   $1 = 1078005760
204   (gdb) xvector
205   $2 = (struct Lisp_Vector *) 0x411000
206   0
207   (gdb) p $->contents[this_command_key_count]
208   $3 = 1077872640
209   (gdb) p &$
210   $4 = (int *) 0x411008
212 Here's a related example of macros and the GDB `define' command.
213 There are many Lisp vectors such as `recent_keys', which contains the
214 last 300 keystrokes.  We can print this Lisp vector
216   p recent_keys
217   pr
219 But this may be inconvenient, since `recent_keys' is much more verbose
220 than `C-h l'.  We might want to print only the last 10 elements of
221 this vector.  `recent_keys' is updated in keyboard.c by the command
223   XVECTOR (recent_keys)->contents[recent_keys_index] = c;
225 So we define a GDB command `xvector-elts', so the last 10 keystrokes
226 are printed by
228   xvector-elts recent_keys recent_keys_index 10
230 where you can define xvector-elts as follows:
232   define xvector-elts
233   set $i = 0
234   p $arg0
235   xvector
236   set $foo = $
237   while $i < $arg2
238   p $foo->contents[$arg1-($i++)]
239   pr
240   end
241   document xvector-elts
242   Prints a range of elements of a Lisp vector.
243   xvector-elts  v n i
244   prints `i' elements of the vector `v' ending at the index `n'.
245   end
247 ** Getting Lisp-level backtrace information within GDB
249 The most convenient way is to use the `xbacktrace' command.  This
250 shows the names of the Lisp functions that are currently active.
252 If that doesn't work (e.g., because the `backtrace_list' structure is
253 corrupted), type "bt" at the GDB prompt, to produce the C-level
254 backtrace, and look for stack frames that call Ffuncall.  Select them
255 one by one in GDB, by typing "up N", where N is the appropriate number
256 of frames to go up, and in each frame that calls Ffuncall type this:
258    p *args
259    pr
261 This will print the name of the Lisp function called by that level
262 of function calling.
264 By printing the remaining elements of args, you can see the argument
265 values.  Here's how to print the first argument:
267    p args[1]
268    pr
270 If you do not have a live process, you can use xtype and the other
271 x...  commands such as xsymbol to get such information, albeit less
272 conveniently.  For example:
274    p *args
275    xtype
277 and, assuming that "xtype" says that args[0] is a symbol:
279    xsymbol
281 ** Debugging Emacs redisplay problems
283 If you configured Emacs with --enable-checking='glyphs', you can use redisplay
284 tracing facilities from a running Emacs session.
286 The command "M-x trace-redisplay RET" will produce a trace of what redisplay
287 does on the standard error stream.  This is very useful for understanding the
288 code paths taken by the display engine under various conditions, especially if
289 some redisplay optimizations produce wrong results.  (You know that redisplay
290 optimizations might be involved if "M-x redraw-display RET", or even just
291 typing "M-x", causes Emacs to correct the bad display.)  Since the cursor
292 blinking feature triggers periodic redisplay cycles, we recommend disabling
293 `blink-cursor-mode' before invoking `trace-redisplay', so that you have less
294 clutter in the trace.  You can also have up to 30 last trace messages dumped to
295 standard error by invoking the `dump-redisplay-history' command.
297 To find the code paths which were taken by the display engine, search xdisp.c
298 for the trace messages you see.
300 The command `dump-glyph-matrix' is useful for producing on standard error
301 stream a full dump of the selected window's glyph matrix.  See the function's
302 doc string for more details.  If you are debugging redisplay issues in
303 text-mode frames, you may find the command `dump-frame-glyph-matrix' useful.
305 Other commands useful for debugging redisplay are `dump-glyph-row' and
306 `dump-tool-bar-row'.
308 If you run Emacs under GDB, you can print the contents of any glyph matrix by
309 just calling that function with the matrix as its argument.  For example, the
310 following command will print the contents of the current matrix of the window
311 whose pointer is in `w':
313   (gdb) p dump_glyph_matrix (w->current_matrix, 2)
315 (The second argument 2 tells dump_glyph_matrix to print the glyphs in
316 a long form.)
318 The Emacs display code includes special debugging code, but it is normally
319 disabled.  Configuring Emacs with --enable-checking='yes,glyphs' enables it.
321 Building Emacs like that activates many assertions which scrutinize
322 display code operation more than Emacs does normally.  (To see the
323 code which tests these assertions, look for calls to the `eassert'
324 macros.)  Any assertion that is reported to fail should be investigated.
326 When you debug display problems running emacs under X, you can use
327 the `ff' command to flush all pending display updates to the screen.
329 The src/.gdbinit file defines many useful commands for dumping redisplay
330 related data structures in a terse and user-friendly format:
332  `ppt' prints value of PT, narrowing, and gap in current buffer.
333  `pit' dumps the current display iterator `it'.
334  `pwin' dumps the current window 'win'.
335  `prow' dumps the current glyph_row `row'.
336  `pg' dumps the current glyph `glyph'.
337  `pgi' dumps the next glyph.
338  `pgrow' dumps all glyphs in current glyph_row `row'.
339  `pcursor' dumps current output_cursor.
341 The above commands also exist in a version with an `x' suffix which takes an
342 object of the relevant type as argument.  For example, `pgrowx' dumps all
343 glyphs in its argument, which must be of type `struct glyph_row'.
345 Since redisplay is performed by Emacs very frequently, you need to place your
346 breakpoints cleverly to avoid hitting them all the time, when the issue you are
347 debugging did not (yet) happen.  Here are some useful techniques for that:
349  . Put a breakpoint at `Fredraw_display' before running Emacs.  Then do
350    whatever is required to reproduce the bad display, and invoke "M-x
351    redraw-display".  The debugger will kick in, and you can set or enable
352    breakpoints in strategic places, knowing that the bad display will be
353    redrawn from scratch.
355  . For debugging incorrect cursor position, a good place to put a breakpoint is
356    in `set_cursor_from_row'.  The first time this function is called as part of
357    `redraw-display', Emacs is redrawing the minibuffer window, which is usually
358    not what you want; type "continue" to get to the call you want.  In general,
359    always make sure `set_cursor_from_row' is called for the right window and
360    buffer by examining the value of w->contents: it should be the buffer whose
361    display you are debugging.
363  . `set_cursor_from_row' is also a good place to look at the contents of a
364    screen line (a.k.a. "glyph row"), by means of the `pgrow' GDB command.  Of
365    course, you need first to make sure the cursor is on the screen line which
366    you want to investigate.  If you have set a breakpoint in `Fredraw_display',
367    as advised above, move cursor to that line before invoking `redraw-display'.
369  . If the problem happens only at some specific buffer position or for some
370    specific rarely-used character, you can make your breakpoints conditional on
371    those values.  The display engine maintains the buffer and string position
372    it is processing in the it->current member; for example, the buffer
373    character position is in it->current.pos.charpos.  Most redisplay functions
374    accept a pointer to a 'struct it' object as their argument, so you can make
375    conditional breakpoints in those functions, like this:
377     (gdb) break x_produce_glyphs if it->current.pos.charpos == 1234
379    For conditioning on the character being displayed, use it->c or
380    it->char_to_display.
382  . You can also make the breakpoints conditional on what object is being used
383    for producing glyphs for display.  The it->method member has the value
384    GET_FROM_BUFFER for displaying buffer contents, GET_FROM_STRING for
385    displaying a Lisp string (e.g., a `display' property or an overlay string),
386    GET_FROM_IMAGE for displaying an image, etc.  See `enum it_method' in
387    dispextern.h for the full list of values.
389 ** Following longjmp call.
391 Recent versions of glibc (2.4+?) encrypt stored values for setjmp/longjmp which
392 prevents GDB from being able to follow a longjmp call using `next'.  To
393 disable this protection you need to set the environment variable
394 LD_POINTER_GUARD to 0.
396 ** Using GDB in Emacs
398 Debugging with GDB in Emacs offers some advantages over the command line (See
399 the GDB Graphical Interface node of the Emacs manual).  There are also some
400 features available just for debugging Emacs:
402 1) The command gud-pp is available on the tool bar (the `pp' icon) and
403    allows the user to print the s-expression of the variable at point,
404    in the GUD buffer.
406 2) Pressing `p' on a component of a watch expression that is a lisp object
407    in the speedbar prints its s-expression in the GUD buffer.
409 3) The STOP button on the tool bar is adjusted so that it sends SIGTSTP
410    instead of the usual SIGINT.
412 4) The command gud-pv has the global binding 'C-x C-a C-v' and prints the
413    value of the lisp variable at point.
415 ** Debugging what happens while preloading and dumping Emacs
417 Debugging `temacs' is useful when you want to establish whether a
418 problem happens in an undumped Emacs.  To run `temacs' under a
419 debugger, type "gdb temacs", then start it with `r -batch -l loadup'.
421 If you need to debug what happens during dumping, start it with `r -batch -l
422 loadup dump' instead.  For debugging the bootstrap dumping, use "loadup
423 bootstrap" instead of "loadup dump".
425 If temacs actually succeeds when running under GDB in this way, do not
426 try to run the dumped Emacs, because it was dumped with the GDB
427 breakpoints in it.
429 ** If you encounter X protocol errors
431 The X server normally reports protocol errors asynchronously,
432 so you find out about them long after the primitive which caused
433 the error has returned.
435 To get clear information about the cause of an error, try evaluating
436 (x-synchronize t).  That puts Emacs into synchronous mode, where each
437 Xlib call checks for errors before it returns.  This mode is much
438 slower, but when you get an error, you will see exactly which call
439 really caused the error.
441 You can start Emacs in a synchronous mode by invoking it with the -xrm
442 option, like this:
444     emacs -xrm "emacs.synchronous: true"
446 Setting a breakpoint in the function `x_error_quitter' and looking at
447 the backtrace when Emacs stops inside that function will show what
448 code causes the X protocol errors.
450 Some bugs related to the X protocol disappear when Emacs runs in a
451 synchronous mode.  To track down those bugs, we suggest the following
452 procedure:
454   - Run Emacs under a debugger and put a breakpoint inside the
455     primitive function which, when called from Lisp, triggers the X
456     protocol errors.  For example, if the errors happen when you
457     delete a frame, put a breakpoint inside `Fdelete_frame'.
459   - When the breakpoint breaks, step through the code, looking for
460     calls to X functions (the ones whose names begin with "X" or
461     "Xt" or "Xm").
463   - Insert calls to `XSync' before and after each call to the X
464     functions, like this:
466        XSync (f->output_data.x->display_info->display, 0);
468     where `f' is the pointer to the `struct frame' of the selected
469     frame, normally available via XFRAME (selected_frame).  (Most
470     functions which call X already have some variable that holds the
471     pointer to the frame, perhaps called `f' or `sf', so you shouldn't
472     need to compute it.)
474     If your debugger can call functions in the program being debugged,
475     you should be able to issue the calls to `XSync' without recompiling
476     Emacs.  For example, with GDB, just type:
478        call XSync (f->output_data.x->display_info->display, 0)
480     before and immediately after the suspect X calls.  If your
481     debugger does not support this, you will need to add these pairs
482     of calls in the source and rebuild Emacs.
484     Either way, systematically step through the code and issue these
485     calls until you find the first X function called by Emacs after
486     which a call to `XSync' winds up in the function
487     `x_error_quitter'.  The first X function call for which this
488     happens is the one that generated the X protocol error.
490   - You should now look around this offending X call and try to figure
491     out what is wrong with it.
493 ** If Emacs causes errors or memory leaks in your X server
495 You can trace the traffic between Emacs and your X server with a tool
496 like xmon, available at ftp://ftp.x.org/contrib/devel_tools/.
498 Xmon can be used to see exactly what Emacs sends when X protocol errors
499 happen.  If Emacs causes the X server memory usage to increase you can
500 use xmon to see what items Emacs creates in the server (windows,
501 graphical contexts, pixmaps) and what items Emacs delete.  If there
502 are consistently more creations than deletions, the type of item
503 and the activity you do when the items get created can give a hint where
504 to start debugging.
506 ** If the symptom of the bug is that Emacs fails to respond
508 Don't assume Emacs is `hung'--it may instead be in an infinite loop.
509 To find out which, make the problem happen under GDB and stop Emacs
510 once it is not responding.  (If Emacs is using X Windows directly, you
511 can stop Emacs by typing C-z at the GDB job.  On MS-Windows, run Emacs
512 as usual, and then attach GDB to it -- that will usually interrupt
513 whatever Emacs is doing and let you perform the steps described
514 below.)
516 Then try stepping with `step'.  If Emacs is hung, the `step' command
517 won't return.  If it is looping, `step' will return.
519 If this shows Emacs is hung in a system call, stop it again and
520 examine the arguments of the call.  If you report the bug, it is very
521 important to state exactly where in the source the system call is, and
522 what the arguments are.
524 If Emacs is in an infinite loop, try to determine where the loop
525 starts and ends.  The easiest way to do this is to use the GDB command
526 `finish'.  Each time you use it, Emacs resumes execution until it
527 exits one stack frame.  Keep typing `finish' until it doesn't
528 return--that means the infinite loop is in the stack frame which you
529 just tried to finish.
531 Stop Emacs again, and use `finish' repeatedly again until you get back
532 to that frame.  Then use `next' to step through that frame.  By
533 stepping, you will see where the loop starts and ends.  Also, examine
534 the data being used in the loop and try to determine why the loop does
535 not exit when it should.
537 On GNU and Unix systems, you can also trying sending Emacs SIGUSR2,
538 which, if `debug-on-event' has its default value, will cause Emacs to
539 attempt to break it out of its current loop and into the Lisp
540 debugger.  This feature is useful when a C-level debugger is not
541 conveniently available.
543 ** If certain operations in Emacs are slower than they used to be, here
544 is some advice for how to find out why.
546 Stop Emacs repeatedly during the slow operation, and make a backtrace
547 each time.  Compare the backtraces looking for a pattern--a specific
548 function that shows up more often than you'd expect.
550 If you don't see a pattern in the C backtraces, get some Lisp
551 backtrace information by typing "xbacktrace" or by looking at Ffuncall
552 frames (see above), and again look for a pattern.
554 When using X, you can stop Emacs at any time by typing C-z at GDB.
555 When not using X, you can do this with C-g.  On non-Unix platforms,
556 such as MS-DOS, you might need to press C-BREAK instead.
558 ** If GDB does not run and your debuggers can't load Emacs.
560 On some systems, no debugger can load Emacs with a symbol table,
561 perhaps because they all have fixed limits on the number of symbols
562 and Emacs exceeds the limits.  Here is a method that can be used
563 in such an extremity.  Do
565     nm -n temacs > nmout
566     strip temacs
567     adb temacs
568     0xd:i
569     0xe:i
570     14:i
571     17:i
572     :r -l loadup   (or whatever)
574 It is necessary to refer to the file `nmout' to convert
575 numeric addresses into symbols and vice versa.
577 It is useful to be running under a window system.
578 Then, if Emacs becomes hopelessly wedged, you can create another
579 window to do kill -9 in.  kill -ILL is often useful too, since that
580 may make Emacs dump core or return to adb.
582 ** Debugging incorrect screen updating on a text terminal.
584 To debug Emacs problems that update the screen wrong, it is useful
585 to have a record of what input you typed and what Emacs sent to the
586 screen.  To make these records, do
588 (open-dribble-file "~/.dribble")
589 (open-termscript "~/.termscript")
591 The dribble file contains all characters read by Emacs from the
592 terminal, and the termscript file contains all characters it sent to
593 the terminal.  The use of the directory `~/' prevents interference
594 with any other user.
596 If you have irreproducible display problems, put those two expressions
597 in your ~/.emacs file.  When the problem happens, exit the Emacs that
598 you were running, kill it, and rename the two files.  Then you can start
599 another Emacs without clobbering those files, and use it to examine them.
601 An easy way to see if too much text is being redrawn on a terminal is to
602 evaluate `(setq inverse-video t)' before you try the operation you think
603 will cause too much redrawing.  This doesn't refresh the screen, so only
604 newly drawn text is in inverse video.
606 ** Debugging LessTif
608 If you encounter bugs whereby Emacs built with LessTif grabs all mouse
609 and keyboard events, or LessTif menus behave weirdly, it might be
610 helpful to set the `DEBUGSOURCES' and `DEBUG_FILE' environment
611 variables, so that one can see what LessTif was doing at this point.
612 For instance
614   export DEBUGSOURCES="RowColumn.c:MenuShell.c:MenuUtil.c"
615   export DEBUG_FILE=/usr/tmp/LESSTIF_TRACE
616   emacs &
618 causes LessTif to print traces from the three named source files to a
619 file in `/usr/tmp' (that file can get pretty large).  The above should
620 be typed at the shell prompt before invoking Emacs, as shown by the
621 last line above.
623 Running GDB from another terminal could also help with such problems.
624 You can arrange for GDB to run on one machine, with the Emacs display
625 appearing on another.  Then, when the bug happens, you can go back to
626 the machine where you started GDB and use the debugger from there.
628 ** Debugging problems which happen in GC
630 The array `last_marked' (defined on alloc.c) can be used to display up
631 to 500 last objects marked by the garbage collection process.
632 Whenever the garbage collector marks a Lisp object, it records the
633 pointer to that object in the `last_marked' array, which is maintained
634 as a circular buffer.  The variable `last_marked_index' holds the
635 index into the `last_marked' array one place beyond where the pointer
636 to the very last marked object is stored.
638 The single most important goal in debugging GC problems is to find the
639 Lisp data structure that got corrupted.  This is not easy since GC
640 changes the tag bits and relocates strings which make it hard to look
641 at Lisp objects with commands such as `pr'.  It is sometimes necessary
642 to convert Lisp_Object variables into pointers to C struct's manually.
644 Use the `last_marked' array and the source to reconstruct the sequence
645 that objects were marked.  In general, you need to correlate the
646 values recorded in the `last_marked' array with the corresponding
647 stack frames in the backtrace, beginning with the innermost frame.
648 Some subroutines of `mark_object' are invoked recursively, others loop
649 over portions of the data structure and mark them as they go.  By
650 looking at the code of those routines and comparing the frames in the
651 backtrace with the values in `last_marked', you will be able to find
652 connections between the values in `last_marked'.  E.g., when GC finds
653 a cons cell, it recursively marks its car and its cdr.  Similar things
654 happen with properties of symbols, elements of vectors, etc.  Use
655 these connections to reconstruct the data structure that was being
656 marked, paying special attention to the strings and names of symbols
657 that you encounter: these strings and symbol names can be used to grep
658 the sources to find out what high-level symbols and global variables
659 are involved in the crash.
661 Once you discover the corrupted Lisp object or data structure, grep
662 the sources for its uses and try to figure out what could cause the
663 corruption.  If looking at the sources doesn't help, you could try
664 setting a watchpoint on the corrupted data, and see what code modifies
665 it in some invalid way.  (Obviously, this technique is only useful for
666 data that is modified only very rarely.)
668 It is also useful to look at the corrupted object or data structure in
669 a fresh Emacs session and compare its contents with a session that you
670 are debugging.
672 ** Debugging problems with non-ASCII characters
674 If you experience problems which seem to be related to non-ASCII
675 characters, such as \201 characters appearing in the buffer or in your
676 files, set the variable byte-debug-flag to t.  This causes Emacs to do
677 some extra checks, such as look for broken relations between byte and
678 character positions in buffers and strings; the resulting diagnostics
679 might pinpoint the cause of the problem.
681 ** Debugging the TTY (non-windowed) version
683 The most convenient method of debugging the character-terminal display
684 is to do that on a window system such as X.  Begin by starting an
685 xterm window, then type these commands inside that window:
687   $ tty
688   $ echo $TERM
690 Let's say these commands print "/dev/ttyp4" and "xterm", respectively.
692 Now start Emacs (the normal, windowed-display session, i.e. without
693 the `-nw' option), and invoke "M-x gdb RET emacs RET" from there.  Now
694 type these commands at GDB's prompt:
696   (gdb) set args -nw -t /dev/ttyp4
697   (gdb) set environment TERM xterm
698   (gdb) run
700 The debugged Emacs should now start in no-window mode with its display
701 directed to the xterm window you opened above.
703 Similar arrangement is possible on a character terminal by using the
704 `screen' package.
706 On MS-Windows, you can start Emacs in its own separate terminal by
707 setting the new-console option before running Emacs under GDB:
709   (gdb) set new-console 1
710   (gdb) run
712 ** Running Emacs built with malloc debugging packages
714 If Emacs exhibits bugs that seem to be related to use of memory
715 allocated off the heap, it might be useful to link Emacs with a
716 special debugging library, such as Electric Fence (a.k.a. efence) or
717 GNU Checker, which helps find such problems.
719 Emacs compiled with such packages might not run without some hacking,
720 because Emacs replaces the system's memory allocation functions with
721 its own versions, and because the dumping process might be
722 incompatible with the way these packages use to track allocated
723 memory.  Here are some of the changes you might find necessary:
725   - Edit configure, to set system_malloc and CANNOT_DUMP to "yes".
727   - Configure with a different --prefix= option.  If you use GCC,
728     version 2.7.2 is preferred, as some malloc debugging packages
729     work a lot better with it than with 2.95 or later versions.
731   - Type "make" then "make -k install".
733   - If required, invoke the package-specific command to prepare
734     src/temacs for execution.
736   - cd ..; src/temacs
738 (Note that this runs `temacs' instead of the usual `emacs' executable.
739 This avoids problems with dumping Emacs mentioned above.)
741 Some malloc debugging libraries might print lots of false alarms for
742 bitfields used by Emacs in some data structures.  If you want to get
743 rid of the false alarms, you will have to hack the definitions of
744 these data structures on the respective headers to remove the `:N'
745 bitfield definitions (which will cause each such field to use a full
746 int).
748 ** How to recover buffer contents from an Emacs core dump file
750 The file etc/emacs-buffer.gdb defines a set of GDB commands for
751 recovering the contents of Emacs buffers from a core dump file.  You
752 might also find those commands useful for displaying the list of
753 buffers in human-readable format from within the debugger.
755 ** Some suggestions for debugging on MS Windows:
757    (written by Marc Fleischeuers, Geoff Voelker and Andrew Innes)
759 To debug Emacs with Microsoft Visual C++, you either start emacs from
760 the debugger or attach the debugger to a running emacs process.
762 To start emacs from the debugger, you can use the file bin/debug.bat.
763 The Microsoft Developer studio will start and under Project, Settings,
764 Debug, General you can set the command-line arguments and Emacs's
765 startup directory.  Set breakpoints (Edit, Breakpoints) at Fsignal and
766 other functions that you want to examine.  Run the program (Build,
767 Start debug).  Emacs will start and the debugger will take control as
768 soon as a breakpoint is hit.
770 You can also attach the debugger to an already running Emacs process.
771 To do this, start up the Microsoft Developer studio and select Build,
772 Start debug, Attach to process.  Choose the Emacs process from the
773 list.  Send a break to the running process (Debug, Break) and you will
774 find that execution is halted somewhere in user32.dll.  Open the stack
775 trace window and go up the stack to w32_msg_pump.  Now you can set
776 breakpoints in Emacs (Edit, Breakpoints).  Continue the running Emacs
777 process (Debug, Step out) and control will return to Emacs, until a
778 breakpoint is hit.
780 To examine the contents of a Lisp variable, you can use the function
781 'debug_print'.  Right-click on a variable, select QuickWatch (it has
782 an eyeglass symbol on its button in the toolbar), and in the text
783 field at the top of the window, place 'debug_print(' and ')' around
784 the expression.  Press 'Recalculate' and the output is sent to stderr,
785 and to the debugger via the OutputDebugString routine.  The output
786 sent to stderr should be displayed in the console window that was
787 opened when the emacs.exe executable was started.  The output sent to
788 the debugger should be displayed in the 'Debug' pane in the Output
789 window.  If Emacs was started from the debugger, a console window was
790 opened at Emacs' startup; this console window also shows the output of
791 'debug_print'.
793 For example, start and run Emacs in the debugger until it is waiting
794 for user input.  Then click on the `Break' button in the debugger to
795 halt execution.  Emacs should halt in `ZwUserGetMessage' waiting for
796 an input event.  Use the `Call Stack' window to select the procedure
797 `w32_msp_pump' up the call stack (see below for why you have to do
798 this).  Open the QuickWatch window and enter
799 "debug_print(Vexec_path)".  Evaluating this expression will then print
800 out the contents of the Lisp variable `exec-path'.
802 If QuickWatch reports that the symbol is unknown, then check the call
803 stack in the `Call Stack' window.  If the selected frame in the call
804 stack is not an Emacs procedure, then the debugger won't recognize
805 Emacs symbols.  Instead, select a frame that is inside an Emacs
806 procedure and try using `debug_print' again.
808 If QuickWatch invokes debug_print but nothing happens, then check the
809 thread that is selected in the debugger.  If the selected thread is
810 not the last thread to run (the "current" thread), then it cannot be
811 used to execute debug_print.  Use the Debug menu to select the current
812 thread and try using debug_print again.  Note that the debugger halts
813 execution (e.g., due to a breakpoint) in the context of the current
814 thread, so this should only be a problem if you've explicitly switched
815 threads.
817 It is also possible to keep appropriately masked and typecast Lisp
818 symbols in the Watch window, this is more convenient when steeping
819 though the code.  For instance, on entering apply_lambda, you can
820 watch (struct Lisp_Symbol *) (0xfffffff & args[0]).
822 Optimizations often confuse the MS debugger.  For example, the
823 debugger will sometimes report wrong line numbers, e.g., when it
824 prints the backtrace for a crash.  It is usually best to look at the
825 disassembly to determine exactly what code is being run--the
826 disassembly will probably show several source lines followed by a
827 block of assembler for those lines.  The actual point where Emacs
828 crashes will be one of those source lines, but not necessarily the one
829 that the debugger reports.
831 Another problematic area with the MS debugger is with variables that
832 are stored in registers: it will sometimes display wrong values for
833 those variables.  Usually you will not be able to see any value for a
834 register variable, but if it is only being stored in a register
835 temporarily, you will see an old value for it.  Again, you need to
836 look at the disassembly to determine which registers are being used,
837 and look at those registers directly, to see the actual current values
838 of these variables.
841 This file is part of GNU Emacs.
843 GNU Emacs is free software: you can redistribute it and/or modify
844 it under the terms of the GNU General Public License as published by
845 the Free Software Foundation, either version 3 of the License, or
846 (at your option) any later version.
848 GNU Emacs is distributed in the hope that it will be useful,
849 but WITHOUT ANY WARRANTY; without even the implied warranty of
850 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
851 GNU General Public License for more details.
853 You should have received a copy of the GNU General Public License
854 along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
857 Local variables:
858 mode: outline
859 paragraph-separate: "[  \f]*$"
860 end: