gdb-mi.el 155 KB
Newer Older
1 2
;;; gdb-mi.el --- User Interface for running GDB

3
;; Copyright (C) 2007-2011  Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

;; Author: Nick Roberts <nickrob@gnu.org>
;; Maintainer: FSF
;; Keywords: unix, tools

;; This file is part of GNU Emacs.

;; Homepage: http://www.emacswiki.org/emacs/GDB-MI

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.

;;; Credits:

;; This file was written by by Nick Roberts following the general design
;; used in gdb-ui.el for Emacs 22.1 - 23.1.  It is currently being developed
;; by Dmitry Dzhus <dima@sphinx.net.ru> as part of the Google Summer
;; of Code 2009 Project "Emacs GDB/MI migration".

;;; Commentary:

;; This mode acts as a graphical user interface to GDB.  You can interact with
;; GDB through the GUD buffer in the usual way, but there are also further
;; buffers which control the execution and describe the state of your program.
;; It separates the input/output of your program from that of GDB and displays
;; expressions and their current values in their own buffers.  It also uses
;; features of Emacs 21 such as the fringe/display margin for breakpoints, and
;; the toolbar (see the GDB Graphical Interface section in the Emacs info
;; manual).

;; M-x gdb will start the debugger.

;; This file uses GDB/MI as the primary interface to GDB.  It is still under
;; development and is part of a process to migrate Emacs from annotations (as
;; used in gdb-ui.el) to GDB/MI.  It runs gdb with GDB/MI (-interp=mi) and
;; access CLI using "-interpreter-exec console cli-command".  This code works
;; without gdb-ui.el and uses MI tokens instead of queues. Eventually MI
;; should be asynchronous.

;; This mode will PARTLY WORK WITH RECENT GDB RELEASES (status in modeline
;; doesn't update properly when execution commands are issued from GUD buffer)
;; and WORKS BEST when GDB runs asynchronously: maint set linux-async on.
;;
;; You need development version of GDB 7.0 for the thread buffer to work.

;; This file replaces gdb-ui.el and is for development with GDB.  Use the
;; release branch of Emacs 22 for the latest version of gdb-ui.el.

;; Windows Platforms:

;; If you are using Emacs and GDB on Windows you will need to flush the buffer
;; explicitly in your program if you want timely display of I/O in Emacs.
;; Alternatively you can make the output stream unbuffered, for example, by
;; using a macro:

;;           #ifdef UNBUFFERED
;;	     setvbuf (stdout, (char *) NULL, _IONBF, 0);
;;	     #endif

;; and compiling with -DUNBUFFERED while debugging.

;; If you are using Cygwin GDB and find that the source is not being displayed
;; in Emacs when you step through it, possible solutions are to:

;;   1) Use Cygwin X Windows and Cygwin Emacs.
;;        (Since 22.1 Emacs builds under Cygwin.)
;;   2) Use MinGW GDB instead.
;;   3) Use cygwin-mount.el

;;; Mac OSX:

;; GDB in Emacs on Mac OSX works best with FSF GDB as Apple have made
;; some changes to the version that they include as part of Mac OSX.
;; This requires GDB version 7.0 or later (estimated release date Aug 2009)
;; as earlier versions don not compile on Mac OSX.

;;; Known Bugs:

;; 1) Stack buffer doesn't parse MI output if you stop in a routine without
;;    line information, e.g., a routine in libc (just a TODO item).

;; TODO:
;; 2) Watch windows to work with threads.
;; 3) Use treebuffer.el instead of the speedbar for watch-expressions?
;; 4) Mark breakpoint locations on scroll-bar of source buffer?

;;; Code:

(require 'gud)
(require 'json)
(require 'bindat)
(eval-when-compile (require 'cl))

107 108
(declare-function speedbar-change-initial-expansion-list
                  "speedbar" (new-default))
109 110 111 112 113 114
(declare-function speedbar-timer-fn "speedbar" ())
(declare-function speedbar-line-text "speedbar" (&optional p))
(declare-function speedbar-change-expand-button-char "speedbar" (char))
(declare-function speedbar-delete-subblock "speedbar" (indent))
(declare-function speedbar-center-buffer-smartly "speedbar" ())

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
(defvar tool-bar-map)
(defvar speedbar-initial-expansion-list-name)
(defvar speedbar-frame)

(defvar	gdb-memory-address "main")
(defvar	gdb-memory-last-address nil
  "Last successfully accessed memory address.")
(defvar	gdb-memory-next-page nil
  "Address of next memory page for program memory buffer.")
(defvar	gdb-memory-prev-page nil
  "Address of previous memory page for program memory buffer.")

(defvar gdb-thread-number nil
  "Main current thread.

Invalidation triggers use this variable to query GDB for
information on the specified thread by wrapping GDB/MI commands
in `gdb-current-context-command'.

This variable may be updated implicitly by GDB via `gdb-stopped'
or explicitly by `gdb-select-thread'.

Only `gdb-setq-thread-number' should be used to change this
value.")

(defvar gdb-frame-number nil
  "Selected frame level for main current thread.

Updated according to the following rules:

When a thread is selected or current thread stops, set to \"0\".

When current thread goes running (and possibly exits eventually),
set to nil.

May be manually changed by user with `gdb-select-frame'.")

(defvar gdb-frame-address nil "Identity of frame for watch expression.")

;; Used to show overlay arrow in source buffer. All set in
;; gdb-get-main-selected-frame. Disassembly buffer should not use
;; these but rely on buffer-local thread information instead.
(defvar gdb-selected-frame nil
  "Name of selected function for main current thread.")
(defvar gdb-selected-file nil
  "Name of selected file for main current thread.")
(defvar gdb-selected-line nil
  "Number of selected line for main current thread.")

(defvar gdb-threads-list nil
  "Associative list of threads provided by \"-thread-info\" MI command.

Keys are thread numbers (in strings) and values are structures as
returned from -thread-info by `gdb-json-partial-output'. Updated in
`gdb-thread-list-handler-custom'.")

(defvar gdb-running-threads-count nil
  "Number of currently running threads.

Juanma Barranquero's avatar
Juanma Barranquero committed
174
If nil, no information is available.
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

Updated in `gdb-thread-list-handler-custom'.")

(defvar gdb-stopped-threads-count nil
  "Number of currently stopped threads.

See also `gdb-running-threads-count'.")

(defvar gdb-breakpoints-list nil
  "Associative list of breakpoints provided by \"-break-list\" MI command.

Keys are breakpoint numbers (in string) and values are structures
as returned from \"-break-list\" by `gdb-json-partial-output'
\(\"body\" field is used). Updated in
`gdb-breakpoints-list-handler-custom'.")

(defvar gdb-current-language nil)
(defvar gdb-var-list nil
  "List of variables in watch window.
194 195
Each element has the form
  (VARNUM EXPRESSION NUMCHILD TYPE VALUE STATUS HAS_MORE FP)
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
where STATUS is nil (`unchanged'), `changed' or `out-of-scope', FP the frame
address for root variables.")
(defvar gdb-main-file nil "Source file from which program execution begins.")

;; Overlay arrow markers
(defvar gdb-stack-position nil)
(defvar gdb-thread-position nil)
(defvar gdb-disassembly-position nil)

(defvar gdb-location-alist nil
  "Alist of breakpoint numbers and full filenames.  Only used for files that
Emacs can't find.")
(defvar gdb-active-process nil
  "GUD tooltips display variable values when t, and macro definitions otherwise.")
(defvar gdb-error "Non-nil when GDB is reporting an error.")
(defvar gdb-macro-info nil
  "Non-nil if GDB knows that the inferior includes preprocessor macro info.")
(defvar gdb-register-names nil "List of register names.")
(defvar gdb-changed-registers nil
  "List of changed register numbers (strings).")
(defvar gdb-buffer-fringe-width nil)
(defvar gdb-last-command nil)
(defvar gdb-prompt-name nil)
(defvar gdb-token-number 0)
(defvar gdb-handler-alist '())
(defvar gdb-handler-number nil)
(defvar gdb-source-file-list nil
  "List of source files for the current executable.")
(defvar gdb-first-done-or-error t)
(defvar gdb-source-window nil)
(defvar gdb-inferior-status nil)
(defvar gdb-continuation nil)
(defvar gdb-version nil)
(defvar gdb-filter-output nil
  "Message to be shown in GUD console.

This variable is updated in `gdb-done-or-error' and returned by
`gud-gdbmi-marker-filter'.")

(defvar gdb-non-stop nil
  "Indicates whether current GDB session is using non-stop mode.

It is initialized to `gdb-non-stop-setting' at the beginning of
every GDB session.")

(defvar gdb-buffer-type nil
  "One of the symbols bound in `gdb-buffer-rules'.")
(make-variable-buffer-local 'gdb-buffer-type)

(defvar gdb-output-sink 'nil
  "The disposition of the output of the current gdb command.
Possible values are these symbols:

    `user' -- gdb output should be copied to the GUD buffer
              for the user to see.

    `emacs' -- output should be collected in the partial-output-buffer
	       for subsequent processing by a command.  This is the
	       disposition of output generated by commands that
	       gdb mode sends to gdb on its own behalf.")

;; Pending triggers prevent congestion: Emacs won't send two similar
;; consecutive requests.

(defvar gdb-pending-triggers '()
  "A list of trigger functions which have not yet been handled.

Elements are either function names or pairs (buffer . function)")

(defmacro gdb-add-pending (item)
  `(push ,item gdb-pending-triggers))
(defmacro gdb-pending-p (item)
  `(member ,item gdb-pending-triggers))
(defmacro gdb-delete-pending (item)
  `(setq gdb-pending-triggers
         (delete ,item gdb-pending-triggers)))

(defmacro gdb-wait-for-pending (&rest body)
  "Wait until `gdb-pending-triggers' is empty and evaluate FORM.

This function checks `gdb-pending-triggers' value every
`gdb-wait-for-pending' seconds."
  (run-with-timer
   0.5 nil
   `(lambda ()
      (if (not gdb-pending-triggers)
          (progn ,@body)
        (gdb-wait-for-pending ,@body)))))

;; Publish-subscribe

(defmacro gdb-add-subscriber (publisher subscriber)
  "Register new PUBLISHER's SUBSCRIBER.

SUBSCRIBER must be a pair, where cdr is a function of one
argument (see `gdb-emit-signal')."
  `(add-to-list ',publisher ,subscriber t))

(defmacro gdb-delete-subscriber (publisher subscriber)
  "Unregister SUBSCRIBER from PUBLISHER."
  `(setq ,publisher (delete ,subscriber
                            ,publisher)))

(defun gdb-get-subscribers (publisher)
  publisher)

(defun gdb-emit-signal (publisher &optional signal)
  "Call cdr for each subscriber of PUBLISHER with SIGNAL as argument."
  (dolist (subscriber (gdb-get-subscribers publisher))
    (funcall (cdr subscriber) signal)))

(defvar gdb-buf-publisher '()
  "Used to invalidate GDB buffers by emitting a signal in
`gdb-update'.

Must be a list of pairs with cars being buffers and cdr's being
valid signal handlers.")

(defgroup gdb nil
  "GDB graphical interface"
  :group 'tools
  :link '(info-link "(emacs)GDB Graphical Interface")
  :version "23.2")

(defgroup gdb-non-stop nil
  "GDB non-stop debugging settings"
  :group 'gdb
  :version "23.2")

(defgroup gdb-buffers nil
  "GDB buffers"
  :group 'gdb
  :version "23.2")

(defcustom gdb-debug-log-max 128
  "Maximum size of `gdb-debug-log'.  If nil, size is unlimited."
  :group 'gdb
  :type '(choice (integer :tag "Number of elements")
334
          (const   :tag "Unlimited" nil))
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  :version "22.1")

(defcustom gdb-non-stop-setting t
  "When in non-stop mode, stopped threads can be examined while
other threads continue to execute.

GDB session needs to be restarted for this setting to take
effect."
  :type 'boolean
  :group 'gdb-non-stop
  :version "23.2")

;; TODO Some commands can't be called with --all (give a notice about
;; it in setting doc)
(defcustom gdb-gud-control-all-threads t
  "When enabled, GUD execution commands affect all threads when
in non-stop mode. Otherwise, only current thread is affected."
  :type 'boolean
  :group 'gdb-non-stop
  :version "23.2")

(defcustom gdb-switch-reasons t
  "List of stop reasons which cause Emacs to switch to the thread
which caused the stop. When t, switch to stopped thread no matter
what the reason was. When nil, never switch to stopped thread
automatically.

This setting is used in non-stop mode only. In all-stop mode,
Emacs always switches to the thread which caused the stop."
  ;; exited, exited-normally and exited-signalled are not
  ;; thread-specific stop reasons and therefore are not included in
  ;; this list
  :type '(choice
          (const :tag "All reasons" t)
          (set :tag "Selection of reasons..."
               (const :tag "A breakpoint was reached." "breakpoint-hit")
               (const :tag "A watchpoint was triggered." "watchpoint-trigger")
372 373 374 375
               (const :tag "A read watchpoint was triggered."
                      "read-watchpoint-trigger")
               (const :tag "An access watchpoint was triggered."
                      "access-watchpoint-trigger")
376 377
               (const :tag "Function finished execution." "function-finished")
               (const :tag "Location reached." "location-reached")
378 379 380 381 382 383
               (const :tag "Watchpoint has gone out of scope"
                      "watchpoint-scope")
               (const :tag "End of stepping range reached."
                      "end-stepping-range")
               (const :tag "Signal received (like interruption)."
                      "signal-received"))
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
          (const :tag "None" nil))
  :group 'gdb-non-stop
  :version "23.2"
  :link '(info-link "(gdb)GDB/MI Async Records"))

(defcustom gdb-stopped-hooks nil
  "This variable holds a list of functions to be called whenever
GDB stops.

Each function takes one argument, a parsed MI response, which
contains fields of corresponding MI *stopped async record:

    ((stopped-threads . \"all\")
     (thread-id . \"1\")
     (frame (line . \"38\")
            (fullname . \"/home/sphinx/projects/gsoc/server.c\")
            (file . \"server.c\")
            (args ((value . \"0x804b038\")
                   (name . \"arg\")))
            (func . \"hello\")
            (addr . \"0x0804869e\"))
     (reason . \"end-stepping-range\"))

Note that \"reason\" is only present in non-stop debugging mode.

`bindat-get-field' may be used to access the fields of response.

Each function is called after the new current thread was selected
and GDB buffers were updated in `gdb-stopped'."
  :type '(repeat function)
  :group 'gdb
  :version "23.2"
  :link '(info-link "(gdb)GDB/MI Async Records"))

(defcustom gdb-switch-when-another-stopped t
  "When nil, Emacs won't switch to stopped thread if some other
stopped thread is already selected."
  :type 'boolean
  :group 'gdb-non-stop
  :version "23.2")

(defcustom gdb-stack-buffer-locations t
  "Show file information or library names in stack buffers."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-stack-buffer-addresses nil
  "Show frame addresses in stack buffers."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-thread-buffer-verbose-names t
  "Show long thread names in threads buffer."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-thread-buffer-arguments t
  "Show function arguments in threads buffer."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-thread-buffer-locations t
  "Show file information or library names in threads buffer."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-thread-buffer-addresses nil
  "Show addresses for thread frames in threads buffer."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defcustom gdb-show-threads-by-default nil
  "Show threads list buffer instead of breakpoints list by
default."
  :type 'boolean
  :group 'gdb-buffers
  :version "23.2")

(defvar gdb-debug-log nil
  "List of commands sent to and replies received from GDB.
Most recent commands are listed first.  This list stores only the last
`gdb-debug-log-max' values.  This variable is used to debug GDB-MI.")

;;;###autoload
(defcustom gdb-enable-debug nil
  "Non-nil means record the process input and output in `gdb-debug-log'."
  :type 'boolean
  :group 'gdb
  :version "22.1")

(defcustom gdb-cpp-define-alist-program "gcc -E -dM -"
  "Shell command for generating a list of defined macros in a source file.
This list is used to display the #define directive associated
with an identifier as a tooltip.  It works in a debug session with
GDB, when `gud-tooltip-mode' is t.

Set `gdb-cpp-define-alist-flags' for any include paths or
predefined macros."
  :type 'string
  :group 'gdb
  :version "22.1")

(defcustom gdb-cpp-define-alist-flags ""
  "Preprocessor flags for `gdb-cpp-define-alist-program'."
  :type 'string
  :group 'gdb
  :version "22.1")

498 499
(defcustom gdb-create-source-file-list t
  "Non-nil means create a list of files from which the executable was built.
500 501 502 503 504 505
 Set this to nil if the GUD buffer displays \"initializing...\" in the mode
 line for a long time when starting, possibly because your executable was
 built from a large number of files.  This allows quicker initialization
 but means that these files are not automatically enabled for debugging,
 e.g., you won't be able to click in the fringe to set a breakpoint until
 execution has already stopped there."
506 507 508
  :type 'boolean
  :group 'gdb
  :version "23.1")
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

(defcustom gdb-show-main nil
  "Non-nil means display source file containing the main routine at startup.
Also display the main routine in the disassembly buffer if present."
  :type 'boolean
  :group 'gdb
  :version "22.1")

(defun gdb-force-mode-line-update (status)
  (let ((buffer gud-comint-buffer))
    (if (and buffer (buffer-name buffer))
	(with-current-buffer buffer
	  (setq mode-line-process
		(format ":%s [%s]"
			(process-status (get-buffer-process buffer)) status))
	  ;; Force mode line redisplay soon.
	  (force-mode-line-update)))))

(defun gdb-enable-debug (arg)
  "Toggle logging of transaction between Emacs and Gdb.
The log is stored in `gdb-debug-log' as an alist with elements
whose cons is send, send-item or recv and whose cdr is the string
being transferred.  This list may grow up to a size of
`gdb-debug-log-max' after which the oldest element (at the end of
the list) is deleted every time a new one is added (at the front)."
  (interactive "P")
  (setq gdb-enable-debug
	(if (null arg)
	    (not gdb-enable-debug)
	  (> (prefix-numeric-value arg) 0)))
  (message (format "Logging of transaction %sabled"
		   (if gdb-enable-debug "en" "dis"))))

;; These two are used for menu and toolbar
(defun gdb-control-all-threads ()
  "Switch to non-stop/A mode."
  (interactive)
  (setq gdb-gud-control-all-threads t)
  ;; Actually forcing the tool-bar to update.
  (force-mode-line-update)
  (message "Now in non-stop/A mode."))

(defun gdb-control-current-thread ()
  "Switch to non-stop/T mode."
  (interactive)
  (setq gdb-gud-control-all-threads nil)
  ;; Actually forcing the tool-bar to update.
  (force-mode-line-update)
  (message "Now in non-stop/T mode."))

(defun gdb-find-watch-expression ()
  (let* ((var (nth (- (line-number-at-pos (point)) 2) gdb-var-list))
561
	 (varnum (car var)) expr)
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    (string-match "\\(var[0-9]+\\)\\.\\(.*\\)" varnum)
    (let ((var1 (assoc (match-string 1 varnum) gdb-var-list)) var2 varnumlet
	  (component-list (split-string (match-string 2 varnum) "\\." t)))
      (setq expr (nth 1 var1))
      (setq varnumlet (car var1))
      (dolist (component component-list)
	(setq var2 (assoc varnumlet gdb-var-list))
	(setq expr (concat expr
			   (if (string-match ".*\\[[0-9]+\\]$" (nth 3 var2))
			       (concat "[" component "]")
			     (concat "." component))))
	(setq varnumlet (concat varnumlet "." component)))
      expr)))

;; noall is used for commands which don't take --all, but only
;; --thread.
(defun gdb-gud-context-command (command &optional noall)
  "When `gdb-non-stop' is t, add --thread option to COMMAND if
`gdb-gud-control-all-threads' is nil and --all option otherwise.
If NOALL is t, always add --thread option no matter what
`gdb-gud-control-all-threads' value is.

When `gdb-non-stop' is nil, return COMMAND unchanged."
  (if gdb-non-stop
      (if (and gdb-gud-control-all-threads
               (not noall)
	       (string-equal gdb-version "7.0+"))
          (concat command " --all ")
        (gdb-current-context-command command))
    command))

(defmacro gdb-gud-context-call (cmd1 &optional cmd2 noall noarg)
  "`gud-call' wrapper which adds --thread/--all options between
CMD1 and CMD2. NOALL is the same as in `gdb-gud-context-command'.

NOARG must be t when this macro is used outside `gud-def'"
  `(gud-call
    (concat (gdb-gud-context-command ,cmd1 ,noall) " " ,cmd2)
    ,(when (not noarg) 'arg)))

;;;###autoload
(defun gdb (command-line)
  "Run gdb on program FILE in buffer *gud-FILE*.
The directory containing FILE becomes the initial working directory
and source-file directory for your debugger.

608 609 610 611
COMMAND-LINE is the shell command for starting the gdb session.
It should be a string consisting of the name of the gdb
executable followed by command-line options.  The command-line
options should include \"-i=mi\" to use gdb's MI text interface.
612
Note that the old \"--annotate\" option is no longer supported.
613

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
If `gdb-many-windows' is nil (the default value) then gdb just
pops up the GUD buffer unless `gdb-show-main' is t.  In this case
it starts with two windows: one displaying the GUD buffer and the
other with the source file with the main routine of the inferior.

If `gdb-many-windows' is t, regardless of the value of
`gdb-show-main', the layout below will appear.  Keybindings are
shown in some of the buffers.

Watch expressions appear in the speedbar/slowbar.

The following commands help control operation :

`gdb-many-windows'    - Toggle the number of windows gdb uses.
`gdb-restore-windows' - To restore the window layout.

See Info node `(emacs)GDB Graphical Interface' for a more
detailed description of this mode.


+----------------------------------------------------------------------+
|                               GDB Toolbar                            |
+-----------------------------------+----------------------------------+
| GUD buffer (I/O of GDB)           | Locals buffer                    |
|                                   |                                  |
|                                   |                                  |
|                                   |                                  |
+-----------------------------------+----------------------------------+
| Source buffer                     | I/O buffer (of debugged program) |
|                                   | (comint-mode)                    |
|                                   |                                  |
|                                   |                                  |
|                                   |                                  |
|                                   |                                  |
|                                   |                                  |
|                                   |                                  |
+-----------------------------------+----------------------------------+
| Stack buffer                      | Breakpoints buffer               |
| RET      gdb-select-frame         | SPC    gdb-toggle-breakpoint     |
|                                   | RET    gdb-goto-breakpoint       |
|                                   | D      gdb-delete-breakpoint     |
+-----------------------------------+----------------------------------+"
  ;;
  (interactive (list (gud-query-cmdline 'gdb)))

  (when (and gud-comint-buffer
660 661 662 663 664 665
             (buffer-name gud-comint-buffer)
             (get-buffer-process gud-comint-buffer)
             (with-current-buffer gud-comint-buffer (eq gud-minor-mode 'gdba)))
    (gdb-restore-windows)
    (error
     "Multiple debugging requires restarting in text command mode"))
666 667 668 669
  ;;
  (gud-common-init command-line nil 'gud-gdbmi-marker-filter)
  (set (make-local-variable 'gud-minor-mode) 'gdbmi)
  (setq comint-input-sender 'gdb-send)
670
  (when (ring-empty-p comint-input-ring) ; cf shell-mode
671
    (let ((hfile (expand-file-name (or (getenv "GDBHISTFILE")
Glenn Morris's avatar
Glenn Morris committed
672 673 674 675 676 677 678
				       (if (eq system-type 'ms-dos)
					   "_gdb_history"
					 ".gdb_history"))))
	  ;; gdb defaults to 256, but we'll default to comint-input-ring-size.
	  (hsize (getenv "HISTSIZE")))
      (dolist (file (append '("~/.gdbinit")
			    (unless (string-equal (expand-file-name ".")
679
                                                  (expand-file-name "~"))
Glenn Morris's avatar
Glenn Morris committed
680 681 682 683 684 685 686 687 688 689 690 691 692 693
			      '(".gdbinit"))))
	(if (file-readable-p (setq file (expand-file-name file)))
	    (with-temp-buffer
	      (insert-file-contents file)
	      ;; TODO? check for "set history save\\(  *on\\)?" and do
	      ;; not use history otherwise?
	      (while (re-search-forward
		      "^ *set history \\(filename\\|size\\)  *\\(.*\\)" nil t)
		(cond ((string-equal (match-string 1) "filename")
		       (setq hfile (expand-file-name
				    (match-string 2)
				    (file-name-directory file))))
		      ((string-equal (match-string 1) "size")
		       (setq hsize (match-string 2))))))))
Glenn Morris's avatar
Glenn Morris committed
694
      (and (stringp hsize)
Glenn Morris's avatar
Glenn Morris committed
695
	   (integerp (setq hsize (string-to-number hsize)))
Glenn Morris's avatar
Glenn Morris committed
696 697
	   (> hsize 0)
	   (set (make-local-variable 'comint-input-ring-size) hsize))
Glenn Morris's avatar
Glenn Morris committed
698 699 700
      (if (stringp hfile)
	  (set (make-local-variable 'comint-input-ring-file-name) hfile))
      (comint-read-input-ring t)))
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  (gud-def gud-tbreak "tbreak %f:%l" "\C-t"
	   "Set temporary breakpoint at current line.")
  (gud-def gud-jump
	   (progn (gud-call "tbreak %f:%l") (gud-call "jump %f:%l"))
	   "\C-j" "Set execution address to current line.")

  (gud-def gud-up     "up %p"     "<" "Up N stack frames (numeric arg).")
  (gud-def gud-down   "down %p"   ">" "Down N stack frames (numeric arg).")
  (gud-def gud-print  "print %e"  "\C-p" "Evaluate C expression at point.")
  (gud-def gud-pstar  "print* %e" nil
	   "Evaluate C dereferenced pointer expression at point.")

  (gud-def gud-step   (gdb-gud-context-call "-exec-step" "%p" t)
           "\C-s"
	   "Step one source line with display.")
  (gud-def gud-stepi  (gdb-gud-context-call "-exec-step-instruction" "%p" t)
           "\C-i"
	   "Step one instruction with display.")
  (gud-def gud-next   (gdb-gud-context-call "-exec-next" "%p" t)
           "\C-n"
	   "Step one line (skip functions).")
  (gud-def gud-nexti  (gdb-gud-context-call "-exec-next-instruction" "%p" t)
           nil
	   "Step one instruction (skip functions).")
  (gud-def gud-cont   (gdb-gud-context-call "-exec-continue")
           "\C-r"
	   "Continue with display.")
  (gud-def gud-finish (gdb-gud-context-call "-exec-finish" nil t)
           "\C-f"
	   "Finish executing current function.")
  (gud-def gud-run    "-exec-run"
           nil
           "Run the program.")

  (gud-def gud-break (if (not (string-match "Disassembly" mode-name))
			 (gud-call "break %f:%l" arg)
		       (save-excursion
			 (beginning-of-line)
			 (forward-char 2)
			 (gud-call "break *%a" arg)))
	   "\C-b" "Set breakpoint at current line or address.")

  (gud-def gud-remove (if (not (string-match "Disassembly" mode-name))
			  (gud-call "clear %f:%l" arg)
			(save-excursion
			  (beginning-of-line)
			  (forward-char 2)
			  (gud-call "clear *%a" arg)))
	   "\C-d" "Remove breakpoint at current line or address.")

  ;; -exec-until doesn't support --all yet
  (gud-def gud-until  (if (not (string-match "Disassembly" mode-name))
			  (gud-call "-exec-until %f:%l" arg)
			(save-excursion
			  (beginning-of-line)
			  (forward-char 2)
			  (gud-call "-exec-until *%a" arg)))
	   "\C-u" "Continue to current line or address.")
  ;; TODO Why arg here?
  (gud-def
   gud-go (gud-call (if gdb-active-process
                        (gdb-gud-context-command "-exec-continue")
                      "-exec-run") arg)
   nil "Start or continue execution.")

  ;; For debugging Emacs only.
  (gud-def gud-pp
	   (gud-call
	    (concat
	     "pp1 " (if (eq (buffer-local-value
			     'major-mode (window-buffer)) 'speedbar-mode)
			(gdb-find-watch-expression) "%e")) arg)
	   nil   "Print the Emacs s-expression.")

  (define-key gud-minor-mode-map [left-margin mouse-1]
    'gdb-mouse-set-clear-breakpoint)
  (define-key gud-minor-mode-map [left-fringe mouse-1]
    'gdb-mouse-set-clear-breakpoint)
779
  (define-key gud-minor-mode-map [left-margin C-mouse-1]
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
    'gdb-mouse-toggle-breakpoint-margin)
  (define-key gud-minor-mode-map [left-fringe C-mouse-1]
    'gdb-mouse-toggle-breakpoint-fringe)

  (define-key gud-minor-mode-map [left-margin drag-mouse-1]
    'gdb-mouse-until)
  (define-key gud-minor-mode-map [left-fringe drag-mouse-1]
    'gdb-mouse-until)
  (define-key gud-minor-mode-map [left-margin mouse-3]
    'gdb-mouse-until)
  (define-key gud-minor-mode-map [left-fringe mouse-3]
    'gdb-mouse-until)

  (define-key gud-minor-mode-map [left-margin C-drag-mouse-1]
    'gdb-mouse-jump)
  (define-key gud-minor-mode-map [left-fringe C-drag-mouse-1]
    'gdb-mouse-jump)
  (define-key gud-minor-mode-map [left-fringe C-mouse-3]
    'gdb-mouse-jump)
  (define-key gud-minor-mode-map [left-margin C-mouse-3]
    'gdb-mouse-jump)

802 803 804 805
  (add-hook 'completion-at-point-functions #'gud-gdb-completion-at-point
            nil 'local)
  (local-set-key "\C-i" 'completion-at-point)

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
  (setq gdb-first-prompt t)
  (setq gud-running nil)

  (gdb-update)

  (run-hooks 'gdb-mode-hook))

(defun gdb-init-1 ()
  ;; (re-)initialise
  (setq gdb-selected-frame nil
	gdb-frame-number nil
        gdb-thread-number nil
	gdb-var-list nil
	gdb-pending-triggers nil
	gdb-output-sink 'user
	gdb-location-alist nil
	gdb-source-file-list nil
	gdb-last-command nil
	gdb-token-number 0
	gdb-handler-alist '()
	gdb-handler-number nil
	gdb-prompt-name nil
	gdb-first-done-or-error t
	gdb-buffer-fringe-width (car (window-fringes))
	gdb-debug-log nil
	gdb-source-window nil
	gdb-inferior-status nil
	gdb-continuation nil
        gdb-buf-publisher '()
        gdb-threads-list '()
        gdb-breakpoints-list '()
        gdb-register-names '()
        gdb-non-stop gdb-non-stop-setting)
  ;;
  (setq gdb-buffer-type 'gdbmi)
  ;;
  (gdb-force-mode-line-update
   (propertize "initializing..." 'face font-lock-variable-name-face))

  (gdb-get-buffer-create 'gdb-inferior-io)
  (gdb-clear-inferior-io)
  (set-process-filter (get-process "gdb-inferior") 'gdb-inferior-filter)
  (gdb-input
   ;; Needs GDB 6.4 onwards
   (list (concat "-inferior-tty-set "
851 852 853 854
		 (or
		  ;; The process can run on a remote host.
		  (process-get (get-process "gdb-inferior") 'remote-tty)
		  (process-tty-name (get-process "gdb-inferior"))))
855 856 857 858 859 860 861 862 863 864
	 'ignore))
  (if (eq window-system 'w32)
      (gdb-input (list "-gdb-set new-console off" 'ignore)))
  (gdb-input (list "-gdb-set height 0" 'ignore))

  (when gdb-non-stop
    (gdb-input (list "-gdb-set non-stop 1" 'gdb-non-stop-handler)))

  ;; find source file and compilation directory here
  (gdb-input
865
                                        ; Needs GDB 6.2 onwards.
866 867 868
   (list "-file-list-exec-source-files" 'gdb-get-source-file-list))
  (if gdb-create-source-file-list
      (gdb-input
869
                                        ; Needs GDB 6.0 onwards.
870 871 872 873 874 875 876 877
       (list "-file-list-exec-source-file" 'gdb-get-source-file)))
  (gdb-input
   (list "-gdb-show prompt" 'gdb-get-prompt)))

(defun gdb-non-stop-handler ()
  (goto-char (point-min))
  (if (re-search-forward "No symbol" nil t)
      (progn
878 879
	(message
         "This version of GDB doesn't support non-stop mode.  Turning it off.")
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
	(setq gdb-non-stop nil)
	(setq gdb-version "pre-7.0"))
    (setq gdb-version "7.0+")
    (gdb-input (list "-gdb-set target-async 1" 'ignore))
    (gdb-input (list "-enable-pretty-printing" 'ignore))))

(defvar gdb-define-alist nil "Alist of #define directives for GUD tooltips.")

(defun gdb-create-define-alist ()
  "Create an alist of #define directives for GUD tooltips."
  (let* ((file (buffer-file-name))
	 (output
	  (with-output-to-string
	    (with-current-buffer standard-output
 	      (and file
		   (file-exists-p file)
 		   ;; call-process doesn't work with remote file names.
		   (not (file-remote-p default-directory))
 		   (call-process shell-file-name file
				 (list t nil) nil "-c"
				 (concat gdb-cpp-define-alist-program " "
					 gdb-cpp-define-alist-flags))))))
902 903
         (define-list (split-string output "\n" t))
         (name))
904 905 906 907 908 909 910 911 912
    (setq gdb-define-alist nil)
    (dolist (define define-list)
      (setq name (nth 1 (split-string define "[( ]")))
      (push (cons name define) gdb-define-alist))))

(declare-function tooltip-show "tooltip" (text &optional use-echo-area))
(defvar tooltip-use-echo-area)

(defun gdb-tooltip-print (expr)
913 914 915 916 917 918 919
  (with-current-buffer (gdb-get-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (if (re-search-forward ".*value=\\(\".*\"\\)" nil t)
        (tooltip-show
         (concat expr " = " (read (match-string 1)))
         (or gud-tooltip-echo-area tooltip-use-echo-area
             (not (display-graphic-p)))))))
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

;; If expr is a macro for a function don't print because of possible dangerous
;; side-effects. Also printing a function within a tooltip generates an
;; unexpected starting annotation (phase error).
(defun gdb-tooltip-print-1 (expr)
  (with-current-buffer (gdb-get-buffer 'gdb-partial-output-buffer)
    (goto-char (point-min))
    (if (search-forward "expands to: " nil t)
	(unless (looking-at "\\S-+.*(.*).*")
	  (gdb-input
	   (list  (concat "-data-evaluate-expression " expr)
		  `(lambda () (gdb-tooltip-print ,expr))))))))

(defun gdb-init-buffer ()
  (set (make-local-variable 'gud-minor-mode) 'gdbmi)
  (set (make-local-variable 'tool-bar-map) gud-tool-bar-map)
  (when gud-tooltip-mode
    (make-local-variable 'gdb-define-alist)
    (gdb-create-define-alist)
    (add-hook 'after-save-hook 'gdb-create-define-alist nil t)))

(defmacro gdb-if-arrow (arrow-position &rest body)
  `(if ,arrow-position
943 944 945 946 947 948 949
       (let ((buffer (marker-buffer ,arrow-position)) (line))
         (if (equal buffer (window-buffer (posn-window end)))
             (with-current-buffer buffer
               (when (or (equal start end)
                         (equal (posn-point start)
                                (marker-position ,arrow-position)))
                 ,@body))))))
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

(defun gdb-mouse-until (event)
  "Continue running until a source line past the current line.
The destination source line can be selected either by clicking
with mouse-3 on the fringe/margin or dragging the arrow
with mouse-1 (default bindings)."
  (interactive "e")
  (let ((start (event-start event))
	(end (event-end event)))
    (gdb-if-arrow gud-overlay-arrow-position
		  (setq line (line-number-at-pos (posn-point end)))
		  (gud-call (concat "until " (number-to-string line))))
    (gdb-if-arrow gdb-disassembly-position
		  (save-excursion
		    (goto-char (point-min))
		    (forward-line (1- (line-number-at-pos (posn-point end))))
		    (forward-char 2)
		    (gud-call (concat "until *%a"))))))

(defun gdb-mouse-jump (event)
  "Set execution address/line.
The destination source line can be selected either by clicking with C-mouse-3
on the fringe/margin or dragging the arrow with C-mouse-1 (default bindings).
Unlike `gdb-mouse-until' the destination address can be before the current
line, and no execution takes place."
  (interactive "e")
  (let ((start (event-start event))
	(end (event-end event)))
    (gdb-if-arrow gud-overlay-arrow-position
		  (setq line (line-number-at-pos (posn-point end)))
		  (progn
		    (gud-call (concat "tbreak " (number-to-string line)))
		    (gud-call (concat "jump " (number-to-string line)))))
    (gdb-if-arrow gdb-disassembly-position
		  (save-excursion
		    (goto-char (point-min))
		    (forward-line (1- (line-number-at-pos (posn-point end))))
		    (forward-char 2)
		    (progn
		      (gud-call (concat "tbreak *%a"))
		      (gud-call (concat "jump *%a")))))))

(defcustom gdb-show-changed-values t
  "If non-nil change the face of out of scope variables and changed values.
Out of scope variables are suppressed with `shadow' face.
Changed values are highlighted with the face `font-lock-warning-face'."
  :type 'boolean
  :group 'gdb
  :version "22.1")

(defcustom gdb-max-children 40
  "Maximum number of children before expansion requires confirmation."
  :type 'integer
  :group 'gdb
  :version "22.1")

(defcustom gdb-delete-out-of-scope t
  "If non-nil delete watch expressions automatically when they go out of scope."
  :type 'boolean
  :group 'gdb
  :version "22.2")

(defcustom gdb-speedbar-auto-raise nil
  "If non-nil raise speedbar every time display of watch expressions is\
 updated."
  :type 'boolean
  :group 'gdb
  :version "22.1")

(defcustom gdb-use-colon-colon-notation nil
  "If non-nil use FUN::VAR format to display variables in the speedbar."
  :type 'boolean
  :group 'gdb
  :version "22.1")

(defun gdb-speedbar-auto-raise (arg)
  "Toggle automatic raising of the speedbar for watch expressions.
With prefix argument ARG, automatically raise speedbar if ARG is
positive, otherwise don't automatically raise it."
  (interactive "P")
  (setq gdb-speedbar-auto-raise
	(if (null arg)
	    (not gdb-speedbar-auto-raise)
	  (> (prefix-numeric-value arg) 0)))
  (message (format "Auto raising %sabled"
		   (if gdb-speedbar-auto-raise "en" "dis"))))

(define-key gud-minor-mode-map "\C-c\C-w" 'gud-watch)
(define-key global-map (concat gud-key-prefix "\C-w") 'gud-watch)

(declare-function tooltip-identifier-from-point "tooltip" (point))

(defun gud-watch (&optional arg event)
  "Watch expression at point.
With arg, enter name of variable to be watched in the minibuffer."
  (interactive (list current-prefix-arg last-input-event))
  (let ((minor-mode (buffer-local-value 'gud-minor-mode gud-comint-buffer)))
    (if (eq minor-mode 'gdbmi)
	(progn
	  (if event (posn-set-point (event-end event)))
	  (require 'tooltip)
	  (save-selected-window
	    (let ((expr
		   (if arg
		       (completing-read "Name of variable: "
					'gud-gdb-complete-command)
		     (if (and transient-mark-mode mark-active)
			 (buffer-substring (region-beginning) (region-end))
1058
		       (concat (if (derived-mode-p 'gdb-registers-mode) "$")
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
			       (tooltip-identifier-from-point (point)))))))
	      (set-text-properties 0 (length expr) nil expr)
	      (gdb-input
	       (list (concat"-var-create - * "  expr "")
		     `(lambda () (gdb-var-create-handler ,expr)))))))
      (message "gud-watch is a no-op in this mode."))))

(defun gdb-var-create-handler (expr)
  (let* ((result (gdb-json-partial-output)))
    (if (not (bindat-get-field result 'msg))
        (let ((var
	       (list (bindat-get-field result 'name)
		     (if (and (string-equal gdb-current-language "c")
			      gdb-use-colon-colon-notation gdb-selected-frame)
			 (setq expr (concat gdb-selected-frame "::" expr))
		       expr)
		     (bindat-get-field result 'numchild)
		     (bindat-get-field result 'type)
		     (bindat-get-field result 'value)
		     nil
		     (bindat-get-field result 'has_more)
1080
                     gdb-frame-address)))
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
	  (push var gdb-var-list)
	  (speedbar 1)
	  (unless (string-equal
		   speedbar-initial-expansion-list-name "GUD")
	    (speedbar-change-initial-expansion-list "GUD")))
      (message-box "No symbol \"%s\" in current context." expr))))

(defun gdb-speedbar-update ()
  (when (and (boundp 'speedbar-frame) (frame-live-p speedbar-frame)
	     (not (gdb-pending-p 'gdb-speedbar-timer)))
    ;; Dummy command to update speedbar even when idle.
    (gdb-input (list "-environment-pwd" 'gdb-speedbar-timer-fn))
    ;; Keep gdb-pending-triggers non-nil till end.
    (gdb-add-pending 'gdb-speedbar-timer)))

(defun gdb-speedbar-timer-fn ()
  (if gdb-speedbar-auto-raise
      (raise-frame speedbar-frame))
  (gdb-delete-pending 'gdb-speedbar-timer)
  (speedbar-timer-fn))

(defun gdb-var-evaluate-expression-handler (varnum changed)
  (goto-char (point-min))
  (re-search-forward ".*value=\\(\".*\"\\)" nil t)
  (let ((var (assoc varnum gdb-var-list)))
    (when var
      (if changed (setcar (nthcdr 5 var) 'changed))
      (setcar (nthcdr 4 var) (read (match-string 1)))))
  (gdb-speedbar-update))

1111
                                        ; Uses "-var-list-children --all-values".  Needs GDB 6.1 onwards.
1112 1113 1114 1115 1116
(defun gdb-var-list-children (varnum)
  (gdb-input
   (list (concat "-var-update " varnum) 'ignore))
  (gdb-input
   (list (concat "-var-list-children --all-values "
1117 1118
                 varnum)
         `(lambda () (gdb-var-list-children-handler ,varnum)))))
1119 1120 1121 1122 1123

(defun gdb-var-list-children-handler (varnum)
  (let* ((var-list nil)
	 (output (bindat-get-field (gdb-json-partial-output "child")))
	 (children (bindat-get-field output 'children)))
1124
    (catch 'child-already-watched
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
      (dolist (var gdb-var-list)
	(if (string-equal varnum (car var))
	    (progn
	      ;; With dynamic varobjs numchild may have increased.
	      (setcar (nthcdr 2 var) (bindat-get-field output 'numchild))
	      (push var var-list)
	      (dolist (child children)
		(let ((varchild (list (bindat-get-field child 'name)
				      (bindat-get-field child 'exp)
				      (bindat-get-field child 'numchild)
				      (bindat-get-field child 'type)
				      (bindat-get-field child 'value)
				      nil
				      (bindat-get-field child 'has_more))))
		  (if (assoc (car varchild) gdb-var-list)
		      (throw 'child-already-watched nil))
		  (push varchild var-list))))
	  (push var var-list)))
      (setq gdb-var-list (nreverse var-list))))
  (gdb-speedbar-update))

(defun gdb-var-set-format (format)
  "Set the output format for a variable displayed in the speedbar."
  (let* ((var (nth (- (count-lines (point-min) (point)) 2) gdb-var-list))
	 (varnum (car var)))
    (gdb-input
     (list (concat "-var-set-format " varnum " " format) 'ignore))
    (gdb-var-update)))

(defun gdb-var-delete-1 (var varnum)
  (gdb-input
   (list (concat "-var-delete " varnum) 'ignore))
  (setq gdb-var-list (delq var gdb-var-list))
  (dolist (varchild gdb-var-list)
    (if (string-match (concat (car var) "\\.") (car varchild))
	(setq gdb-var-list (delq varchild gdb-var-list)))))

(defun gdb-var-delete ()
  "Delete watch expression at point from the speedbar."
  (interactive)
  (let ((text (speedbar-line-text)))
    (string-match "\\(\\S-+\\)" text)
1167 1168 1169 1170 1171
    (let* ((var (nth (- (count-lines (point-min) (point)) 2) gdb-var-list))
           (varnum (car var)))
      (if (string-match "\\." (car var))
          (message-box "Can only delete a root expression")
        (gdb-var-delete-1 var varnum)))))
1172 1173 1174 1175 1176 1177

(defun gdb-var-delete-children (varnum)
  "Delete children of variable object at point from the speedbar."
  (gdb-input
   (list (concat "-var-delete -c " varnum) 'ignore)))

1178
(defun gdb-edit-value (_text _token _indent)
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
  "Assign a value to a variable displayed in the speedbar."
  (let* ((var (nth (- (count-lines (point-min) (point)) 2) gdb-var-list))
	 (varnum (car var)) (value))
    (setq value (read-string "New value: "))
    (gdb-input
     (list (concat "-var-assign " varnum " " value)
	   `(lambda () (gdb-edit-value-handler ,value))))))

(defconst gdb-error-regexp "\\^error,msg=\\(\".+\"\\)")

(defun gdb-edit-value-handler (value)
  (goto-char (point-min))
  (if (re-search-forward gdb-error-regexp nil t)
      (message-box "Invalid number or expression (%s)" value)))

1194
                                        ; Uses "-var-update --all-values".  Needs GDB 6.4 onwards.
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
(defun gdb-var-update ()
  (if (not (gdb-pending-p 'gdb-var-update))
      (gdb-input
       (list "-var-update --all-values *" 'gdb-var-update-handler)))
  (gdb-add-pending 'gdb-var-update))

(defun gdb-var-update-handler ()
  (let ((changelist (bindat-get-field (gdb-json-partial-output) 'changelist)))
    (dolist (var gdb-var-list)
      (setcar (nthcdr 5 var) nil))
    (let ((temp-var-list gdb-var-list))
      (dolist (change changelist)
	(let* ((varnum (bindat-get-field change 'name))
	       (var (assoc varnum gdb-var-list))
	       (new-num (bindat-get-field change 'new_num_children)))
	  (when var
	    (let ((scope (bindat-get-field change 'in_scope))
		  (has-more (bindat-get-field change 'has_more)))
	      (cond ((string-equal scope "false")
		     (if gdb-delete-out-of-scope
			 (gdb-var-delete-1 var varnum)
		       (setcar (nthcdr 5 var) 'out-of-scope)))
		    ((string-equal scope "true")
		     (setcar (nthcdr 6 var) has-more)
		     (when (and (or (not has-more)
				    (string-equal has-more "0"))
				(not new-num)
				(string-equal (nth 2 var) "0"))
		       (setcar (nthcdr 4 var)
			       (bindat-get-field change 'value))
		       (setcar (nthcdr 5 var) 'changed)))
		    ((string-equal scope "invalid")
		     (gdb-var-delete-1 var varnum)))))
	  (let ((var-list nil) var1
		(children (bindat-get-field change 'new_children)))
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	    (when new-num
              (setq var1 (pop temp-var-list))
              (while var1
                (if (string-equal varnum (car var1))
                    (let ((new (string-to-number new-num))
                          (previous (string-to-number (nth 2 var1))))
                      (setcar (nthcdr 2 var1) new-num)
                      (push var1 var-list)
                      (cond
                       ((> new previous)
                        ;; Add new children to list.
                        (dotimes (dummy previous)
                          (push (pop temp-var-list) var-list))
                        (dolist (child children)
                          (let ((varchild
                                 (list (bindat-get-field child 'name)
                                       (bindat-get-field child 'exp)
                                       (bindat-get-field child 'numchild)
                                       (bindat-get-field child 'type)
                                       (bindat-get-field child 'value)
                                       'changed
                                       (bindat-get-field child 'has_more))))
                            (push varchild var-list))))
                       ;; Remove deleted children from list.
                       ((< new previous)
                        (dotimes (dummy new)
                          (push (pop temp-var-list) var-list))
                        (dotimes (dummy (- previous new))
                          (pop temp-var-list)))))
                  (push var1 var-list))
                (setq var1 (pop temp-var-list)))
              (setq gdb-var-list (nreverse var-list))))))))
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
  (setq gdb-pending-triggers
	(delq 'gdb-var-update gdb-pending-triggers))
  (gdb-speedbar-update))

(defun gdb-speedbar-expand-node (text token indent)
  "Expand the node the user clicked on.
TEXT is the text of the button we clicked on, a + or - item.
TOKEN is data related to this node.
INDENT is the current indentation depth."
  (cond ((string-match "+" text)        ;expand this node
	 (let* ((var (assoc token gdb-var-list))
		(expr (nth 1 var)) (children (nth 2 var)))
	   (if (or (<= (string-to-number children) gdb-max-children)
		   (y-or-n-p
		    (format "%s has %s children. Continue? " expr children)))
	       (gdb-var-list-children token))))
	((string-match "-" text)	;contract this node
	 (dolist (var gdb-var-list)
	   (if (string-match (concat token "\\.") (car var))
	       (setq gdb-var-list (delq var gdb-var-list))))
	 (gdb-var-delete-children token)
	 (speedbar-change-expand-button-char ?+)
	 (speedbar-delete-subblock indent))
	(t (error "Ooops...  not sure what to do")))
  (speedbar-center-buffer-smartly))

(defun gdb-get-target-string ()
  (with-current-buffer gud-comint-buffer
    gud-target-name))


;;
;; gdb buffers.
;;
;; Each buffer has a TYPE -- a symbol that identifies the function
;; of that particular buffer.
;;
;; The usual gdb interaction buffer is given the type `gdbmi' and
;; is constructed specially.
;;
;; Others are constructed by gdb-get-buffer-create and
;; named according to the rules set forth in the gdb-buffer-rules

(defvar gdb-buffer-rules '())

(defun gdb-rules-name-maker (rules-entry)
  (cadr rules-entry))
(defun gdb-rules-buffer-mode (rules-entry)
  (nth 2 rules-entry))
(defun gdb-rules-update-trigger (rules-entry)
  (nth 3 rules-entry))

(defun gdb-update-buffer-name ()
  "Rename current buffer according to name-maker associated with
it in `gdb-buffer-rules'."
  (let ((f (gdb-rules-name-maker (assoc gdb-buffer-type
                                        gdb-buffer-rules))))
    (when f (rename-buffer (funcall f)))))

(defun gdb-current-buffer-rules ()
  "Get `gdb-buffer-rules' entry for current buffer type."
  (assoc gdb-buffer-type gdb-buffer-rules))

(defun gdb-current-buffer-thread ()
  "Get thread object of current buffer from `gdb-threads-list'.

When current buffer is not bound to any thread, return main
thread."
  (cdr (assoc gdb-thread-number gdb-threads-list)))

(defun gdb-current-buffer-frame ()
  "Get current stack frame object for thread of current buffer."
  (bindat-get-field (gdb-current-buffer-thread) 'frame))

(defun gdb-buffer-type (buffer)
  "Get value of `gdb-buffer-type' for BUFFER."
  (with-current-buffer buffer
    gdb-buffer-type))

(defun gdb-buffer-shows-main-thread-p ()
  "Return t if current GDB buffer shows main selected thread and
is not bound to it."
  (current-buffer)
  (not (local-variable-p 'gdb-thread-number)))

(defun gdb-get-buffer (buffer-type &optional thread)
  "Get a specific GDB buffer.

In that buffer, `gdb-buffer-type' must be equal to BUFFER-TYPE
and `gdb-thread-number' (if provided) must be equal to THREAD."
  (catch 'found
    (dolist (buffer (buffer-list) nil)
      (with-current-buffer buffer
        (when (and (eq gdb-buffer-type buffer-type)
                   (or (not thread)
                       (equal gdb-thread-number thread)))
          (throw 'found buffer))))))

(defun gdb-get-buffer-create (buffer-type &optional thread)
  "Create a new GDB buffer of the type specified by BUFFER-TYPE.
The buffer-type should be one of the cars in `gdb-buffer-rules'.

If THREAD is non-nil, it is assigned to `gdb-thread-number'
buffer-local variable of the new buffer.

Buffer mode and name are selected according to buffer type.

If buffer has trigger associated with it in `gdb-buffer-rules',
this trigger is subscribed to `gdb-buf-publisher' and called with
'update argument."
  (or (gdb-get-buffer buffer-type thread)
      (let ((rules (assoc buffer-type gdb-buffer-rules))
            (new (generate-new-buffer "limbo")))
	(with-current-buffer new
	  (let ((mode (gdb-rules-buffer-mode rules))
                (trigger (gdb-rules-update-trigger rules)))
	    (when mode (funcall mode))
	    (setq gdb-buffer-type buffer-type)
            (when thread
              (set (make-local-variable 'gdb-thread-number) thread))
	    (set (make-local-variable 'gud-minor-mode)
		 (buffer-local-value 'gud-minor-mode gud-comint-buffer))
	    (set (make-local-variable 'tool-bar-map) gud-tool-bar-map)
            (rename-buffer (funcall (gdb-rules-name-maker rules)))
	    (when trigger
              (gdb-add-subscriber gdb-buf-publisher
                                  (cons (current-buffer)
1389 1390
                                        (gdb-bind-function-to-buffer
                                         trigger (current-buffer))))
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
              (funcall trigger 'start))
            (current-buffer))))))

(defun gdb-bind-function-to-buffer (expr buffer)
  "Return a function which will evaluate EXPR in BUFFER."
  `(lambda (&rest args)
     (with-current-buffer ,buffer
       (apply ',expr args))))

;; Used to define all gdb-frame-*-buffer functions except
;; `gdb-frame-io-buffer'
(defmacro def-gdb-frame-for-buffer (name buffer &optional doc)
  "Define a function NAME which shows gdb BUFFER in a separate frame.

DOC is an optional documentation string."
  `(defun ,name (&optional thread)
     ,(when doc doc)
     (interactive)
     (let ((special-display-regexps (append special-display-regexps '(".*")))
           (special-display-frame-alist gdb-frame-parameters))
       (display-buffer (gdb-get-buffer-create ,buffer thread)))))

(defmacro def-gdb-display-buffer (name buffer &optional doc)
  "Define a function NAME which shows gdb BUFFER.

DOC is an optional documentation string."
  `(defun ,name (&optional thread)
     ,(when doc doc)
     (interactive)
     (gdb-display-buffer
      (gdb-get-buffer-create ,buffer thread) t)))

;; Used to display windows with thread-bound buffers
(defmacro def-gdb-preempt-display-buffer (name buffer &optional doc
					       split-horizontal)
  `(defun ,name (&optional thread)
     ,(when doc doc)
     (message thread)
     (gdb-preempt-existing-or-display-buffer
      (gdb-get-buffer-create ,buffer thread)
      ,split-horizontal)))

;; This assoc maps buffer type symbols to rules.  Each rule is a list of
;; at least one and possible more functions.  The functions have these
;; roles in defining a buffer type:
;;
;;     NAME - Return a name for this  buffer type.
;;
;; The remaining function(s) are optional:
;;
;;     MODE - called in a new buffer with no arguments, should establish
;;	      the proper mode for the buffer.
;;

(defun gdb-set-buffer-rules (buffer-type &rest rules)
  (let ((binding (assoc buffer-type gdb-buffer-rules)))
    (if binding
	(setcdr binding rules)
      (push (cons buffer-type rules)
	    gdb-buffer-rules))))

(defun gdb-parent-mode ()
  "Generic mode to derive all other GDB buffer modes from."
  (kill-all-local-variables)
  (setq buffer-read-only t)
  (buffer-disable-undo)
  ;; Delete buffer from gdb-buf-publisher when it's killed
  ;; (if it has an associated update trigger)
  (add-hook
   'kill-buffer-hook
   (function
    (lambda ()
      (let ((trigger (gdb-rules-update-trigger
                      (gdb-current-buffer-rules))))
        (when trigger
          (gdb-delete-subscriber
           gdb-buf-publisher
           ;; This should match gdb-add-subscriber done in
           ;; gdb-get-buffer-create
           (cons (current-buffer)
                 (gdb-bind-function-to-buffer trigger (current-buffer))))))))
   nil t))

;; Partial-output buffer : This accumulates output from a command executed on
;; behalf of emacs (rather than the user).
;;
(gdb-set-buffer-rules 'gdb-partial-output-buffer
		      'gdb-partial-output-name)

(defun gdb-partial-output-name ()
  (concat " *partial-output-"
	  (gdb-get-target-string)
	  "*"))


(gdb-set-buffer-rules 'gdb-inferior-io
		      'gdb-inferior-io-name
		      'gdb-inferior-io-mode)

(defun gdb-inferior-io-name ()
  (concat "*input/output of "
	  (gdb-get-target-string)
	  "*"))

(defun gdb-display-io-buffer ()
  "Display IO of debugged program in a separate window."
  (interactive)
  (gdb-display-buffer
   (gdb-get-buffer-create 'gdb-inferior-io) t))

(defconst gdb-frame-parameters
  '((height . 14) (width . 80)
    (unsplittable . t)
    (tool-bar-lines . nil)
    (menu-bar-lines . nil)
    (minibuffer . nil)))

(defun gdb-frame-io-buffer ()
  "Display IO of debugged program in a new frame."
  (interactive)
  (let ((special-display-regexps (append special-display-regexps '(".*")))
	(special-display-frame-alist gdb-frame-parameters))
    (display-buffer (gdb-get-buffer-create 'gdb-inferior-io))))

(defvar gdb-inferior-io-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\C-c\C-c" 'gdb-io-interrupt)
    (define-key map "\C-c\C-z" 'gdb-io-stop)
    (define-key map "\C-c\C-\\" 'gdb-io-quit)
    (define-key map "\C-c\C-d" 'gdb-io-eof)
    (define-key map "\C-d" 'gdb-io-eof)
    map))

;; We want to use comint because it has various nifty and familiar features.
(define-derived-mode gdb-inferior-io-mode comint-mode "Inferior I/O"
1526
  "Major mode for gdb inferior-io."
1527
  :syntax-table nil :abbrev-table nil
1528
  (make-comint-in-buffer "gdb-inferior" (current-buffer) nil))
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803

(defun gdb-inferior-filter (proc string)
  (unless (string-equal string "")
    (gdb-display-buffer (gdb-get-buffer-create 'gdb-inferior-io) t))
  (with-current-buffer (gdb-get-buffer-create 'gdb-inferior-io)
    (comint-output-filter proc string)))

(defun gdb-io-interrupt ()
  "Interrupt the program being debugged."
  (interactive)
  (interrupt-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-io-quit ()
  "Send quit signal to the program being debugged."
  (interactive)
  (quit-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-io-stop ()
  "Stop the program being debugged."
  (interactive)
  (stop-process
   (get-buffer-process gud-comint-buffer) comint-ptyp))

(defun gdb-io-eof ()
  "Send end-of-file to the program being debugged."
  (interactive)
  (process-send-eof
   (get-buffer-process gud-comint-buffer)))

(defun gdb-clear-inferior-io ()
  (with-current-buffer (gdb-get-buffer-create 'gdb-inferior-io)
    (erase-buffer)))


(defconst breakpoint-xpm-data
  "/* XPM */
static char *magick[] = {
/* columns rows colors chars-per-pixel */
\"10 10 2 1\",
\"  c red\",
\"+ c None\",
/* pixels */
\"+++    +++\",
\"++      ++\",
\"+        +\",
\"          \",
\"          \",
\"          \",
\"          \",
\"+        +\",
\"++      ++\",
\"+++    +++\",
};"
  "XPM data used for breakpoint icon.")

(defconst breakpoint-enabled-pbm-data
  "P1
10 10\",
0 0 0 0 1 1 1 1 0 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 1 1 0 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 0 1 1 1 1 1 1 1 1 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 0 1 1 1 1 0 0 0 0"
  "PBM data used for enabled breakpoint icon.")

(defconst breakpoint-disabled-pbm-data
  "P1
10 10\",
0 0 1 0 1 0 1 0 0 0
0 1 0 1 0 1 0 1 0 0
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
0 0 1 0 1 0 1 0 1 0
0 0 0 1 0 1 0 1 0 0"
  "PBM data used for disabled breakpoint icon.")

(defvar breakpoint-enabled-icon nil
  "Icon for enabled breakpoint in display margin.")

(defvar breakpoint-disabled-icon nil
  "Icon for disabled breakpoint in display margin.")

(declare-function define-fringe-bitmap "fringe.c"
		  (bitmap bits &optional height width align))

(and (display-images-p)
     ;; Bitmap for breakpoint in fringe
     (define-fringe-bitmap 'breakpoint
       "\x3c\x7e\xff\xff\xff\xff\x7e\x3c")
     ;; Bitmap for gud-overlay-arrow in fringe
     (define-fringe-bitmap 'hollow-right-triangle
       "\xe0\x90\x88\x84\x84\x88\x90\xe0"))

(defface breakpoint-enabled
  '((t
     :foreground "red1"
     :weight bold))
  "Face for enabled breakpoint icon in fringe."
  :group 'gdb)

(defface breakpoint-disabled
  '((((class color) (min-colors 88)) :foreground "grey70")
    ;; Ensure that on low-color displays that we end up something visible.
    (((class color) (min-colors 8) (background light))
     :foreground "black")
    (((class color) (min-colors 8) (background dark))
     :foreground "white")
    (((type tty) (class mono))
     :inverse-video t)
    (t :background "gray"))
  "Face for disabled breakpoint icon in fringe."
  :group 'gdb)


(defun gdb-send (proc string)
  "A comint send filter for gdb."
  (with-current-buffer gud-comint-buffer
    (let ((inhibit-read-only t))
      (remove-text-properties (point-min) (point-max) '(face))))
  ;; mimic <RET> key to repeat previous command in GDB
  (if (not (string= "" string))
      (setq gdb-last-command string)
    (if gdb-last-command (setq string gdb-last-command)))
  (if gdb-enable-debug
      (push (cons 'mi-send (concat string "\n")) gdb-debug-log))
  (if (string-match "^-" string)
      ;; MI command
      (progn
	(setq gdb-first-done-or-error t)
	(process-send-string proc (concat string "\n")))
    ;; CLI command
    (if (string-match "\\\\$" string)
	(setq gdb-continuation (concat gdb-continuation string "\n"))
      (setq gdb-first-done-or-error t)
      (process-send-string proc (concat "-interpreter-exec console \""
					gdb-continuation string "\"\n"))
      (setq gdb-continuation nil))))

(defun gdb-input (item)
  (if gdb-enable-debug (push (cons 'send-item item) gdb-debug-log))
  (setq gdb-token-number (1+ gdb-token-number))
  (setcar item (concat (number-to-string gdb-token-number) (car item)))
  (push (cons gdb-token-number (car (cdr item))) gdb-handler-alist)
  (process-send-string (get-buffer-process gud-comint-buffer)
		       (concat (car item) "\n")))

;; NOFRAME is used for gud execution control commands
(defun gdb-current-context-command (command)
  "Add --thread to gdb COMMAND when needed."
  (if (and gdb-thread-number
	   (string-equal gdb-version "7.0+"))
      (concat command " --thread " gdb-thread-number)
    command))

(defun gdb-current-context-buffer-name (name)
  "Add thread information and asterisks to string NAME.

If `gdb-thread-number' is nil, just wrap NAME in asterisks."
  (concat "*" name
          (if (local-variable-p 'gdb-thread-number)
              (format " (bound to thread %s)" gdb-thread-number)
            "")
          "*"))

(defun gdb-current-context-mode-name (mode)
  "Add thread information to MODE which is to be used as
`mode-name'."
  (concat mode
          (if gdb-thread-number
              (format " [thread %s]" gdb-thread-number)
            "")))


(defcustom gud-gdb-command-name "gdb -i=mi"
  "Default command to execute an executable under the GDB debugger."
  :type 'string
  :group 'gdb)

(defun gdb-resync()
  (setq gud-running nil)
  (setq gdb-output-sink 'user)
  (setq gdb-pending-triggers nil))

(defun gdb-update ()
  "Update buffers showing status of debug session."
  (when gdb-first-prompt
    (gdb-force-mode-line-update
     (propertize "initializing..." 'face font-lock-variable-name-face))
    (gdb-init-1)
    (setq gdb-first-prompt nil))

  (gdb-get-main-selected-frame)
  ;; We may need to update gdb-threads-list so we can use
  (gdb-get-buffer-create 'gdb-threads-buffer)
  ;; gdb-break-list is maintained in breakpoints handler
  (gdb-get-buffer-create 'gdb-breakpoints-buffer)

  (gdb-emit-signal gdb-buf-publisher 'update)

  (gdb-get-changed-registers)

  (when (and (boundp 'speedbar-frame) (frame-live-p speedbar-frame))
    (dolist (var gdb-var-list)
      (setcar (nthcdr 5 var) nil))
    (gdb-var-update)))

;; gdb-setq-thread-number and gdb-update-gud-running are decoupled
;; because we may need to update current gud-running value without
;; changing current thread (see gdb-running)
(defun gdb-setq-thread-number (number)
  "Only this function must be used to change `gdb-thread-number'
value to NUMBER, because `gud-running' and `gdb-frame-number'
need to be updated appropriately when current thread changes."
  ;; GDB 6.8 and earlier always output thread-id="0" when stopping.
  (unless (string-equal number "0") (setq gdb-thread-number number))
  (setq gdb-frame-number "0")
  (gdb-update-gud-running))

(defun gdb-update-gud-running ()
  "Set `gud-running' according to the state of current thread.

`gdb-frame-number' is set to 0 if current thread is now stopped.

Note that when `gdb-gud-control-all-threads' is t, `gud-running'
cannot be reliably used to determine whether or not execution
control buttons should be shown in menu or toolbar. Use
`gdb-running-threads-count' and `gdb-stopped-threads-count'
instead.

For all-stop mode, thread information is unavailable while target
is running."
  (let ((old-value gud-running))
    (setq gud-running
          (string= (bindat-get-field (gdb-current-buffer-thread) 'state)
                   "running"))
    ;; Set frame number to "0" when _current_ threads stops
    (when (and (gdb-current-buffer-thread)
               (not (eq gud-running old-value)))
      (setq gdb-frame-number "0"))))

(defun gdb-show-run-p ()
  "Return t if \"Run/continue\" should be shown on the toolbar."
  (or (not gdb-active-process)
      (and (or
            (not gdb-gud-control-all-threads)
            (not gdb-non-stop))
           (not gud-running))
      (and gdb-gud-control-all-threads
           (> gdb-stopped-threads-count 0))))

(defun gdb-show-stop-p ()
  "Return t if \"Stop\" should be shown on the toolbar."
  (or (and (or
            (not gdb-gud-control-all-threads)
            (not gdb-non-stop))
           gud-running)
      (and gdb-gud-control-all-threads
           (> gdb-running-threads-count 0))))

;; GUD displays the selected GDB frame.  This might might not be the current
;; GDB frame (after up, down etc).  If no GDB frame is visible but the last
;; visited breakpoint is, use that window.
(defun gdb-display-source-buffer (buffer)
  (let* ((last-window (if gud-last-last-frame
1804 1805
                          (get-buffer-window
                           (gud-find-file (car gud-last-last-frame)))))
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
	 (source-window (or last-window
			    (if (and gdb-source-window
				     (window-live-p gdb-source-window))
				gdb-source-window))))
    (when source-window
      (setq gdb-source-window source-window)
      (set-window-buffer source-window buffer))
    source-window))

(defun gdb-car< (a b)
  (< (car a) (car b)))

(defvar gdbmi-record-list
  '((gdb-gdb . "(gdb) \n")
    (gdb-done . "\\([0-9]*\\)\\^done,?\\(.*?\\)\n")
    (gdb-starting . "\\([0-9]*\\)\\^running\n")
    (gdb-error . "\\([0-9]*\\)\\^error,\\(.*?\\)\n")
    (gdb-console . "~\\(\".*?\"\\)\n")
    (gdb-internals . "&\\(\".*?\"\\)\n")
    (gdb-stopped . "\\*stopped,?\\(.*?\\)\n")
    (gdb-running . "\\*running,\\(.*?\n\\)")
    (gdb-thread-created . "=thread-created,\\(.*?\n\\)")
    (gdb-thread-selected . "=thread-selected,\\(.*?\\)\n")
    (gdb-thread-exited . "=thread-exited,\\(.*?\n\\)")
    (gdb-ignored-notification . "=[-[:alpha:]]+,?\\(.*?\\)\n")
    (gdb-shell . "\\(\\(?:^.+\n\\)+\\)")))

(defun gud-gdbmi-marker-filter (string)
  "Filter GDB/MI output."

  ;; Record transactions if logging is enabled.
  (when gdb-enable-debug
    (push (cons 'recv string) gdb-debug-log)
    (if (and gdb-debug-log-max
	     (> (length gdb-debug-log) gdb-debug-log-max))
	(setcdr (nthcdr (1- gdb-debug-log-max) gdb-debug-log) nil)))

  ;; Recall the left over gud-marker-acc from last time
  (setq gud-marker-acc (concat gud-marker-acc string))

  ;; Start accumulating output for the GUD buffer
  (setq gdb-filter-output "")
1848
  (let (output-record-list)
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877

    ;; Process all the complete markers in this chunk.
    (dolist (gdbmi-record gdbmi-record-list)
      (while (string-match (cdr gdbmi-record) gud-marker-acc)
	(push (list (match-beginning 0)
		    (car gdbmi-record)
		    (match-string 1 gud-marker-acc)
		    (match-string 2 gud-marker-acc)
		    (match-end 0))
	      output-record-list)
	(setq gud-marker-acc
	      (concat (substring gud-marker-acc 0 (match-beginning 0))
		      ;; Pad with spaces to preserve position.
		      (make-string (length (match-string 0 gud-marker-acc)) 32)
		      (substring gud-marker-acc (match-end 0))))))

    (setq output-record-list (sort output-record-list 'gdb-car<))

    (dolist (output-record output-record-list)
      (let ((record-type (cadr output-record))
	    (arg1 (nth 2 output-record))
	    (arg2 (nth 3 output-record)))
	(if (eq record-type 'gdb-error)
	    (gdb-done-or-error arg2 arg1 'error)
	  (if (eq record-type 'gdb-done)
	      (gdb-done-or-error arg2 arg1 'done)
	    ;; Suppress "No registers." since GDB 6.8 and earlier duplicates MI
	    ;; error message on internal stream.  Don't print to GUD buffer.
	    (unless (and (eq record-type 'gdb-internals)
1878
                         (string-equal (read arg1) "No registers.\n"))
1879 1880 1881 1882 1883 1884 1885 1886 1887
	      (funcall record-type arg1))))))

    (setq gdb-output-sink 'user)
    ;; Remove padding.
    (string-match "^ *" gud-marker-acc)
    (setq gud-marker-acc (substring gud-marker-acc (match-end 0)))

    gdb-filter-output))

1888
(defun gdb-gdb (_output-field))
1889 1890 1891 1892 1893 1894

(defun gdb-shell (output-field)
  (let ((gdb-output-sink gdb-output-sink))
    (setq gdb-filter-output
          (concat output-field gdb-filter-output))))

1895
(defun gdb-ignored-notification (_output-field))
1896 1897

;; gdb-invalidate-threads is defined to accept 'update-threads signal
1898
(defun gdb-thread-created (_output-field))
1899 1900 1901
(defun gdb-thread-exited (output-field)
  "Handle =thread-exited async record: unset `gdb-thread-number'
 if current thread exited and update threads list."
1902 1903 1904 1905 1906 1907 1908 1909 1910