Skip to contentSkip to conversation

Add gdb python scripts as kernel debugging helpers

PATCH Superseded Jan Kiszka 4 participants 28 messages Jan 21, 2013 – Jan 24, 2013

Subsystems (3)

v4 of 13 Superseded Latest is v13 →

lore
Share & tools
lore

Jan Kiszka

author maintainer
#0 lore raw

v4 cover Add gdb python scripts as kernel debugging helpers

Version 4 of this series is a rebase over latest 3.8-rc4+. Moreover, I updated the mechanism that implements automatic symbol loading for new modules. It was affected by the refactorings around finit_module.

While waiting for feedback who could imagine picking this up for merge, I wrote a tiny tutorial, see below.

Here is the original series intro again:

This adds the infrastructure and first tools that make kernel debugging through gdb more comfortable. Since 7.0, gdb supports python scripting. And this opens the doors to automate steps like the tedious loading of module symbols at the right address, resolving per-cpu variables or even retrieving the current kernel log without resuming an stopped target.

Many of the helpers naturally depend on the layout of structures or internal mechanics of the kernel. So the best place to maintain such things, keeping them consistent with the corresponding kernel is, well, the kernel itself.

While these scripts have been originally developed for debugging via QEMU/KVM, I've now also added the required bits for KGDB. Works fine, but as QEMU/KVM tends to outperform KGDB it remains the recommendation
- when available.

There are two architecture dependencies so far, one regarding per-cpu, the other regarding thread_info calculation. None of them I was able to test on a target, so I'm counting on review/testing by the corresponding communities.

This series should be considered the foundation of much more kernel state exploration helpers, e.g. around tasks, timers, locks, sockets - I guess people will have even more ideas.

And this is a tutorial for the gdb extension using QEMU/KVM as target platform:

o Set up a virtual Linux machine for KVM (see www.linux-kvm.org and www.qemu.org for more details)

o Build the kernel with this series applied, enabling CONFIG_DEBUG_INFO (but leave CONFIG_DEBUG_INFO_REDUCED off)

o Install that kernel on the guest

o Enable the gdb stub of QEMU/KVM, either
- at VM startup time by appending "-s" to the QEMU command line
or
- during runtime by issuing "gdbserver" from the QEMU monitor console

o cd /path/to/linux-build

o Start gdb: gdb vmlinux

o Attach to the booted guest:

    (gdb) target remote :1234

o Load module (and main kernel) symbols:

    (gdb) lx-symbols
    loading vmlinux
    scanning for modules in /home/user/linux/build
    loading @0xffffffffa0020000: /home/user/linux/build/net/netfilter/xt_tcpudp.ko
    loading @0xffffffffa0016000: /home/user/linux/build/net/netfilter/xt_pkttype.ko
    loading @0xffffffffa0002000: /home/user/linux/build/net/netfilter/xt_limit.ko
    loading @0xffffffffa00ca000: /home/user/linux/build/net/packet/af_packet.ko
    loading @0xffffffffa003c000: /home/user/linux/build/fs/fuse/fuse.ko
    ...
    loading @0xffffffffa0000000: /home/user/linux/build/drivers/ata/ata_generic.ko

o Set a breakpoint on some not yet loaded module function, e.g.:
(gdb) b btrfs_init_sysfs
Function "btrfs_init_sysfs" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y Breakpoint 1 (btrfs_init_sysfs) pending.

o Continue the target

o Load the module on the target and watch what happens:

    loading @0xffffffffa0034000: /home/user/linux/build/lib/libcrc32c.ko
    loading @0xffffffffa0050000: /home/user/linux/build/lib/lzo/lzo_compress.ko
    loading @0xffffffffa006e000: /home/user/linux/build/lib/zlib_deflate/zlib_deflate.ko
    loading @0xffffffffa01b1000: /home/user/linux/build/fs/btrfs/btrfs.ko

    Breakpoint 1, btrfs_init_sysfs () at /home/user/linux/fs/btrfs/sysfs.c:36
    36              btrfs_kset = kset_create_and_add("btrfs", NULL, fs_kobj);

o Let's examine the current task a bit:

    (gdb) p ().pid
     = 4998
    (gdb) p ().comm
     = "modprobe\000\000\000\000\000\000\000"

o Dump the log buffer of target kernel:

    (gdb) lx-dmesg
    [     0.000000] Initializing cgroup subsys cpuset
    [     0.000000] Initializing cgroup subsys cpu
    [     0.000000] Linux version 3.8.0-rc4-dbg+ (...
    [     0.000000] Command line: root=/dev/sda2 resume=/dev/sda1 vga=0x314
    [     0.000000] e820: BIOS-provided physical RAM map:
    [     0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable
    [     0.000000] BIOS-e820: [mem 0x000000000009fc00-0x000000000009ffff] reserved
    ....

o Make use of the per-cpu helper for the current or a specified CPU:

    (gdb) p ("runqueues").nr_running
     = 1
    (gdb) p ("runqueues", 2).nr_running
     = 0

o And now we are digging deep into hrtimers using the container_of helper:

    (gdb) set  = ("hrtimer_bases").clock_base[0].active.next
    (gdb) p *(, "struct hrtimer", "node")
     = {
      node = {
        node = {
          __rb_parent_color = 18446612133355256072,
          rb_right = 0x0 <irq_stack_union>,
          rb_left = 0x0 <irq_stack_union>
        },
        expires = {
          tv64 = 1835268000000
        }
      },
      _softexpires = {
        tv64 = 1835268000000
      },
      function = 0xffffffff81078232 <tick_sched_timer>,
      base = 0xffff88003fd0d6f0,
      state = 1,
      start_pid = 0,
      start_site = 0xffffffff81055c1f <hrtimer_start_range_ns+20>,
      start_comm = "swapper/2\000\000\000\000\000\000"
    }

Hope this provided some ideas and inspirations on how the commands and helper functions can support kernel development.

Enjoy,
Jan

PS: Also available via git://git.kiszka.org/linux.git queues/gdb-scripts

CC "David S. Miller" <[email protected]>
CC Fenghua Yu <[email protected]>
CC Kay Sievers <[email protected]>
CC Michal Marek <[email protected]>
CC Tony Luck <[email protected]>

Jan Kiszka (13):
scripts/gdb: Add infrastructure
scripts/gdb: Add container_of helper and convenience function scripts/gdb: Add lx-symbols command
scripts/gdb: Add get_target_endianness helper
scripts/gdb: Add read_u16/32/64 helpers
scripts/gdb: Add lx-dmesg command
scripts/gdb: Add task iteration helper
scripts/gdb: Add helper and convenience function to look up tasks scripts/gdb: Add is_target_arch helper
scripts/gdb: Add internal helper and convenience function to retrieve
thread_info
scripts/gdb: Add get_gdbserver_type helper
scripts/gdb: Add internal helper and convenience function for per-cpu
lookup
scripts/gdb: Add lx_current convenience function

 Makefile                   |    5 +-
 scripts/Makefile           |    3 +-
 scripts/gdb/Makefile       |    9 +++
 scripts/gdb/dmesg.py       |   63 ++++++++++++++++++
 scripts/gdb/percpu.py      |   76 ++++++++++++++++++++++
 scripts/gdb/symbols.py     |  153 ++++++++++++++++++++++++++++++++++++++++++++
 scripts/gdb/task.py        |  108 +++++++++++++++++++++++++++++++
 scripts/gdb/utils.py       |  137 +++++++++++++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |   28 ++++++++
 9 files changed, 580 insertions(+), 2 deletions(-)
 create mode 100644 scripts/gdb/Makefile
 create mode 100644 scripts/gdb/dmesg.py
 create mode 100644 scripts/gdb/percpu.py
 create mode 100644 scripts/gdb/symbols.py
 create mode 100644 scripts/gdb/task.py
 create mode 100644 scripts/gdb/utils.py
 create mode 100644 scripts/gdb/vmlinux-gdb.py
Signature · 1 line
1.7.3.4
author maintainer
#1 lore raw

PATCH v4 1/13 scripts/gdb: Add infrastructure

This provides the basic infrastructure to load kernel-specific python helper scripts when debugging the kernel in gdb.

The loading mechanism is based on gdb loading for <objfile>-gdb.py when opening <objfile>. Therefore, this places a corresponding link to the main helper script into the output directory that contains vmlinux.

The main scripts will pull in submodules containing Linux specific gdb commands and functions. To avoid polluting the source directory with compiled python modules, we link to them from the object directory.

Due to gdb.parse_and_eval, we depend on gdb >= 7.1. We need to pre-process the version string returned by gdb as some distros tend to prefix it with their name.

This feature depends on CONFIG_DEBUG_INFO.

---
 Makefile                   |    5 ++++-
 scripts/Makefile           |    3 ++-
 scripts/gdb/Makefile       |    9 +++++++++
 scripts/gdb/utils.py       |   17 +++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |   22 ++++++++++++++++++++++
 5 files changed, 54 insertions(+), 2 deletions(-)
 create mode 100644 scripts/gdb/Makefile
 create mode 100644 scripts/gdb/utils.py
 create mode 100644 scripts/gdb/vmlinux-gdb.py
Makefile +4 -1
index 253a455..fb18794 100644
@@ -774,6 +774,9 @@ endif
 ifdef CONFIG_BUILD_DOCSRC
 	$(Q)$(MAKE) $(build)=Documentation
 endif
+ifdef CONFIG_DEBUG_INFO
+	$(Q)ln -fsn $(srctree)/scripts/gdb/vmlinux-gdb.py
+endif
 	+$(call if_changed,link-vmlinux)
 
 # The actual objects are generated when descending, 
@@ -1019,7 +1022,7 @@ MRPROPER_FILES += .config .config.old .version .old_version $(version_h) \
 		  Module.symvers tags TAGS cscope* GPATH GTAGS GRTAGS GSYMS \
 		  signing_key.priv signing_key.x509 x509.genkey		\
 		  extra_certificates signing_key.x509.keyid		\
-		  signing_key.x509.signer
+		  signing_key.x509.signer vmlinux-gdb.py
 
 # clean - Delete most, but leave enough to build external modules
 #
scripts/Makefile +2 -1
index 01e7adb..3204b91 100644
@@ -37,6 +37,7 @@ subdir-$(CONFIG_MODVERSIONS) += genksyms
 subdir-y                     += mod
 subdir-$(CONFIG_SECURITY_SELINUX) += selinux
 subdir-$(CONFIG_DTC)         += dtc
+subdir-$(CONFIG_DEBUG_INFO)  += gdb
 
 # Let clean descend into subdirs
-subdir-	+= basic kconfig package selinux
+subdir-	+= basic kconfig package selinux gdb
scripts/gdb/Makefile new file +9 -0
new file mode 100644
index 0000000..34ccd06
@@ -0,0 +1,9 @@
+always := gdb-scripts
+
+$(obj)/gdb-scripts:
+ifneq ($(KBUILD_SRC),)
+	$(Q)ln -fsn $(srctree)/$(obj)/*.py $(objtree)/$(obj)
+endif
+	@:
+
+clean-files := *.pyc $(if $(KBUILD_SRC),*.py)
scripts/gdb/utils.py new file +17 -0
new file mode 100644
index 0000000..65a2e91
@@ -0,0 +1,17 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  common utilities
+#
+# Copyright (c) Siemens AG, 2011, 2012
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import gdb
+import re
+
+gdb_version = re.sub("^[^0-9]*", "", gdb.VERSION)
scripts/gdb/vmlinux-gdb.py new file +22 -0
new file mode 100644
index 0000000..bcb45cc
@@ -0,0 +1,22 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  loader module
+#
+# Copyright (c) Siemens AG, 2012
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import os
+
+sys.path = [ os.path.dirname(__file__) + "/scripts/gdb" ] + sys.path
+
+from utils import gdb_version
+
+if gdb_version < "7.1":
+	print "NOTE: gdb 7.1 or later required for Linux helper scripts " \
+	      "to work."
Signature · 1 line
1.7.3.4
#2 lore raw

Re: [PATCH v4 01/13] scripts/gdb: Add infrastructure

Quoted 36 lines · Jan Kiszka

This provides the basic infrastructure to load kernel-specific python helper scripts when debugging the kernel in gdb.

The loading mechanism is based on gdb loading for <objfile>-gdb.py when opening <objfile>. Therefore, this places a corresponding link to the main helper script into the output directory that contains vmlinux.

The main scripts will pull in submodules containing Linux specific gdb commands and functions. To avoid polluting the source directory with compiled python modules, we link to them from the object directory.

Due to gdb.parse_and_eval, we depend on gdb >= 7.1. We need to pre-process the version string returned by gdb as some distros tend to prefix it with their name.

This feature depends on CONFIG_DEBUG_INFO.

---
 Makefile                   |    5 ++++-
 scripts/Makefile           |    3 ++-
 scripts/gdb/Makefile       |    9 +++++++++
 scripts/gdb/utils.py       |   17 +++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |   22 ++++++++++++++++++++++
 5 files changed, 54 insertions(+), 2 deletions(-)
 create mode 100644 scripts/gdb/Makefile
 create mode 100644 scripts/gdb/utils.py
 create mode 100644 scripts/gdb/vmlinux-gdb.py
Makefile +0 -0
index 253a455..fb18794 100644

Makefile endif · line 779

Quoted 6 lines
Makefile +3 -0
@@ -774,6 +774,9 @@ endif
 ifdef CONFIG_BUILD_DOCSRC
 	$(Q)$(MAKE) $(build)=Documentation
 endif
+ifdef CONFIG_DEBUG_INFO
+	$(Q)ln -fsn $(srctree)/scripts/gdb/vmlinux-gdb.py
+endif

I'm wondering whether it won't be a better idea to make this symlink creation in the toplevel directory only when a user requires it.. I.e., not simply when CONFIG_DEBUG_INFO is enabled (it could be enabled for a lot and different reasons) but only when user wants to really debug the kernel with gdb.

Then, having a specific make target could arrange for all the setup like the symlink, gdb version checking, etc, maybe something like this:

$ make gdb

and all is prepared (or errored out with a sensible message).

Hmm....

Signature · 5 lines
Regards/Gruss,
    Boris.

Sent from a fat crate under my desk. Formatting is fine.
--
author maintainer
#3 lore raw

Re: [PATCH v4 01/13] scripts/gdb: Add infrastructure

Quoted 50 lines · Borislav Petkov
Quoted 36 lines · Jan Kiszka

This provides the basic infrastructure to load kernel-specific python helper scripts when debugging the kernel in gdb.

The loading mechanism is based on gdb loading for <objfile>-gdb.py when opening <objfile>. Therefore, this places a corresponding link to the main helper script into the output directory that contains vmlinux.

The main scripts will pull in submodules containing Linux specific gdb commands and functions. To avoid polluting the source directory with compiled python modules, we link to them from the object directory.

Due to gdb.parse_and_eval, we depend on gdb >= 7.1. We need to pre-process the version string returned by gdb as some distros tend to prefix it with their name.

This feature depends on CONFIG_DEBUG_INFO.

---
 Makefile                   |    5 ++++-
 scripts/Makefile           |    3 ++-
 scripts/gdb/Makefile       |    9 +++++++++
 scripts/gdb/utils.py       |   17 +++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |   22 ++++++++++++++++++++++
 5 files changed, 54 insertions(+), 2 deletions(-)
 create mode 100644 scripts/gdb/Makefile
 create mode 100644 scripts/gdb/utils.py
 create mode 100644 scripts/gdb/vmlinux-gdb.py
Makefile +0 -0
index 253a455..fb18794 100644

Makefile endif · line 779

Quoted 6 lines
Makefile +3 -0
@@ -774,6 +774,9 @@ endif
 ifdef CONFIG_BUILD_DOCSRC
 	$(Q)$(MAKE) $(build)=Documentation
 endif
+ifdef CONFIG_DEBUG_INFO
+	$(Q)ln -fsn $(srctree)/scripts/gdb/vmlinux-gdb.py
+endif

I'm wondering whether it won't be a better idea to make this symlink creation in the toplevel directory only when a user requires it.. I.e., not simply when CONFIG_DEBUG_INFO is enabled (it could be enabled for a lot and different reasons) but only when user wants to really debug the kernel with gdb.

Quoted 8 lines

Then, having a specific make target could arrange for all the setup like the symlink, gdb version checking, etc, maybe something like this:

$ make gdb

and all is prepared (or errored out with a sensible message).

Hmm....

I wonder why we should do this, remove the convenience of the automatic script setup, but I'm open for arguments.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RTC ITP SDP-DE
Corporate Competence Center Embedded Linux
#4 lore raw

Re: [PATCH v4 01/13] scripts/gdb: Add infrastructure

Quoted 2 lines · Jan Kiszka

I wonder why we should do this, remove the convenience of the automatic script setup, but I'm open for arguments.

Only one: you get the symlink

vmlinux-gdb.py -> /..../scripts/gdb/vmlinux-gdb.py

created automatically when CONFIG_DEBUG_INFO is enabled and people who enable CONFIG_DEBUG_INFO for other reasons and don't want to use gdb to debug the kernel don't need it but will get it anyway.

Signature · 5 lines
Regards/Gruss,
    Boris.

Sent from a fat crate under my desk. Formatting is fine.
--
author maintainer
#5 lore raw

Re: [PATCH v4 01/13] scripts/gdb: Add infrastructure

Quoted 11 lines · Borislav Petkov
Quoted 2 lines · Jan Kiszka

I wonder why we should do this, remove the convenience of the automatic script setup, but I'm open for arguments.

Only one: you get the symlink

vmlinux-gdb.py -> /..../scripts/gdb/vmlinux-gdb.py

created automatically when CONFIG_DEBUG_INFO is enabled and people who enable CONFIG_DEBUG_INFO for other reasons and don't want to use gdb to debug the kernel don't need it but will get it anyway.

A lot of stuff is generated in the output directories during the kernel build, so I wonder if this one really matters.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RTC ITP SDP-DE
Corporate Competence Center Embedded Linux
author maintainer
#6 lore raw

PATCH v4 2/13 scripts/gdb: Add container_of helper and convenience function

In reply to Jan Kiszka

Provide an internal helper with container_of semantics. As type lookups are very slow in gdb-python and we need a type "long" for this, cache the reference to this type object. Then export the helper also as a convenience function form use at the gdb command line.

---
 scripts/gdb/utils.py       |   41 +++++++++++++++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |    2 ++
 2 files changed, 43 insertions(+), 0 deletions(-)
scripts/gdb/utils.py +41 -0
index 65a2e91..2f6eafb 100644
@@ -15,3 +15,44 @@ import gdb
 import re
 
 gdb_version = re.sub("^[^0-9]*", "", gdb.VERSION)
+
+long_type = None
+
+def get_type(type_name):
+	t = gdb.lookup_type(type_name)
+	if t == None:
+		raise gdb.GdbError("cannot resolve type '%s'" % type_name)
+	return t
+
+def get_long_type():
+	global long_type
+	if long_type == None:
+		long_type = get_type("long")
+	return long_type
+
+
+def offset_of(typeobj, field):
+	element = gdb.Value(0).cast(typeobj)
+	return int(str(element[field].address).split()[0], 16)
+
+def container_of(ptr, typeobj, member):
+	return (ptr.cast(get_long_type()) -
+		offset_of(typeobj, member)).cast(typeobj)
+
+
+class ContainerOf(gdb.Function):
+	__doc__ = "Return pointer to containing data structure.\n" \
+		  "\n" \
+		  "$container_of(PTR, \"TYPE\", \"ELEMENT\"): Given PTR, return a pointer to the\n" \
+		  "data structure of the type TYPE in which PTR is the address of ELEMENT.\n" \
+		  "Note that TYPE and ELEMENT have to be quoted as strings."
+
+	def __init__(self):
+		super(ContainerOf, self).__init__("container_of")
+
+	def invoke(self, ptr, typename, elementname):
+		return container_of(ptr,
+				    gdb.lookup_type(typename.string()).pointer(),
+				    elementname.string())
+
+ContainerOf()
scripts/gdb/vmlinux-gdb.py +2 -0
index bcb45cc..8ef76c9 100644
@@ -20,3 +20,5 @@ from utils import gdb_version
 if gdb_version < "7.1":
 	print "NOTE: gdb 7.1 or later required for Linux helper scripts " \
 	      "to work."
+else:
+	import utils
Signature · 1 line
1.7.3.4
author maintainer
#7 lore raw

PATCH v4 3/13 scripts/gdb: Add lx-symbols command

In reply to Jan Kiszka

This is probably the most useful helper when debugging kernel modules:
lx-symbols will first reload vmlinux. Then it searches recursively for *.ko files in the specified paths and the current directory. Finally it walks the kernel's module list, issuing the necessary add-symbol-file command for each loaded module so that gdb know which module symbol correspond to which address.

In addition, the command installs a silent breakpoint in the load_module function at the point where the module was loaded but not yet initialized. The breakpoint handler will try to load symbols from the module files found during lx-symbols execution. This way, breakpoints can be set to module initialization functions, and there is usually no need to explicitly call lx-symbols after (re-)loading a module.

---
 scripts/gdb/symbols.py     |  153 ++++++++++++++++++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |    1 +
 2 files changed, 154 insertions(+), 0 deletions(-)
 create mode 100644 scripts/gdb/symbols.py
scripts/gdb/symbols.py new file +153 -0
new file mode 100644
index 0000000..c50d5e1
@@ -0,0 +1,153 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  load kernel and module symbols
+#
+# Copyright (c) Siemens AG, 2011-2013
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import gdb
+import os
+import re
+import string
+
+from utils import *
+
+class LinuxSymbols(gdb.Command):
+	__doc__ = "(Re-)load symbols of Linux kernel and currently loaded modules.\n" \
+		  "\n" \
+		  "The kernel (vmlinux) is taken from the current working directly. Modules (.ko)\n" \
+		  "are scanned recursively, starting in the same directory. Optionally, the module\n" \
+		  "search path can be extended by a space separated list of paths passed to the\n" \
+		  "lx-symbols command."
+
+	module_files = []
+	breakpoint = None
+
+	def __init__(self):
+		super(LinuxSymbols, self).__init__("lx-symbols",
+						   gdb.COMMAND_FILES,
+						   gdb.COMPLETE_FILENAME)
+
+	def _load_module_symbols(self, module):
+		module_name = module['name'].string()
+		module_addr = str(module['module_core']).split()[0]
+		module_pattern = ".*/" + \
+			string.replace(module_name, "_", r"[_\-]") + r"\.ko$"
+		module_path = ""
+		for name in self.module_files:
+			if re.match(module_pattern, name):
+				module_path = name
+				break
+
+		if module_path:
+			print "loading @" + module_addr + ": " + module_path
+			if gdb.VERSION >= "7.2":
+				gdb.execute("add-symbol-file " + \
+					    module_path + " " + module_addr,
+					    to_string = True)
+			else:
+				gdb.execute("add-symbol-file " + \
+					    module_path + " " + module_addr)
+		else:
+			print "no module object found for '" + \
+			      module_name + "'"
+
+	if gdb_version >= "7.3":
+		class _LoadModuleBreakpoint(gdb.Breakpoint):
+			def __init__(self, spec, gdb_command):
+				super(LinuxSymbols._LoadModuleBreakpoint,
+				      self).__init__(spec, internal = True)
+				self.silent = True
+				self.gdb_command = gdb_command
+
+			def stop(self):
+				module = gdb.parse_and_eval("mod")
+				self.gdb_command._load_module_symbols(module)
+				return False
+
+		def _find_breakpoint_location(self):
+			breakpoint_match = "^[0-9]*[\t]*err = parse_args\(.*"
+
+			src = gdb.execute("list kernel/module.c:load_module",
+					  to_string = True)
+			done = False
+			lineno = None
+			while not done:
+				src = gdb.execute("list", to_string = True)
+				for line in src.splitlines():
+					if re.match(breakpoint_match, line):
+						done = True
+						lineno = line.split()[0]
+						break
+					elif re.match("^[0-9]*\t}$", line):
+						done = True
+						break
+			return lineno
+
+	def _load_all_module_symbols(self, arg):
+		modules = gdb.parse_and_eval("modules")
+		entry = modules['next']
+		if entry == modules.address:
+			print "no modules found"
+			return
+
+		self.module_files = []
+		paths = arg.split()
+		paths.append(os.getcwd())
+		for path in paths:
+			print "scanning for modules in " + path
+			for root, dirs, files in os.walk(path):
+				for name in files:
+					if re.match(r".*\.ko$", name):
+						self.module_files.append(
+							root + "/" + name)
+
+		module_type = gdb.lookup_type("struct module").pointer()
+
+		while entry != modules.address:
+			module = container_of(entry, module_type, "list")
+			self._load_module_symbols(module)
+			entry = entry['next']
+
+	def invoke(self, arg, from_tty):
+		print "loading vmlinux"
+
+		saved_states = []
+		if (gdb.breakpoints() != None):
+			for breakpoint in gdb.breakpoints():
+				saved_states.append({
+					'breakpoint': breakpoint,
+					'enabled': breakpoint.enabled })
+
+		# drop all current symbols and reload vmlinux
+		gdb.execute("symbol-file", to_string = True)
+		gdb.execute("symbol-file vmlinux")
+
+		self._load_all_module_symbols(arg)
+
+		for saved_state in saved_states:
+			saved_state['breakpoint'].enabled = \
+				saved_state['enabled']
+
+		if gdb_version < "7.3":
+			print "Note: symbol update on module loading not " \
+			      "supported with this gdb version"
+		else:
+			if self.breakpoint != None:
+				self.breakpoint.delete()
+				self.breakpoint = None
+			lineno = self._find_breakpoint_location()
+			if lineno != None:
+				self.breakpoint = self._LoadModuleBreakpoint(
+					lineno, self)
+			else:
+				print "unable to detect breakpoint location " \
+				      "of load module completion"
+
+LinuxSymbols()
scripts/gdb/vmlinux-gdb.py +1 -0
index 8ef76c9..3553b7d 100644
@@ -22,3 +22,4 @@ if gdb_version < "7.1":
 	      "to work."
 else:
 	import utils
+	import symbols
Signature · 1 line
1.7.3.4
#8 lore raw

Re: [PATCH v4 03/13] scripts/gdb: Add lx-symbols command

Quoted 6 lines · Jan Kiszka

This is probably the most useful helper when debugging kernel modules:
lx-symbols will first reload vmlinux. Then it searches recursively for *.ko files in the specified paths and the current directory. Finally it walks the kernel's module list, issuing the necessary add-symbol-file command for each loaded module so that gdb know which module symbol correspond to which address.

Yes sounds very useful. I usually have to build everything statically for gdb debugging. Would definitely use it if it was in the standard tree.

-Andi

author maintainer
#9 lore raw

PATCH v4 4/13 scripts/gdb: Add get_target_endianness helper

In reply to Jan Kiszka

Parse the target endianness from the output of "show endian" and cache the result to return it via the new helper get_target_endiannes. We will need it for reading integers from buffers that contain target memory.

---
 scripts/gdb/utils.py |   17 +++++++++++++++++
 1 files changed, 17 insertions(+), 0 deletions(-)
scripts/gdb/utils.py +17 -0
index 2f6eafb..44daa29c 100644
@@ -56,3 +56,20 @@ class ContainerOf(gdb.Function):
 				    elementname.string())
 
 ContainerOf()
+
+
+BIG_ENDIAN = 0
+LITTLE_ENDIAN = 1
+target_endianness = None
+
+def get_target_endianness():
+	global target_endianness
+	if target_endianness == None:
+		endian = gdb.execute("show endian", False, True)
+		if endian.find("little endian") >= 0:
+			target_endianness = LITTLE_ENDIAN
+		elif endian.find("big endian") >= 0:
+			target_endianness = BIG_ENDIAN
+		else:
+			raise gdb.GdgError("unknown endianness '%s'" % endian)
+	return target_endianness
Signature · 1 line
1.7.3.4
author maintainer
#10 lore raw

PATCH v4 5/13 scripts/gdb: Add read_u16/32/64 helpers

In reply to Jan Kiszka

Add helpers for reading integers from target memory buffers. Required when caching the memory access is more efficient than reading individual values via gdb.

---
 scripts/gdb/utils.py |   18 ++++++++++++++++++
 1 files changed, 18 insertions(+), 0 deletions(-)
scripts/gdb/utils.py +18 -0
index 44daa29c..8d54241 100644
@@ -73,3 +73,21 @@ def get_target_endianness():
 		else:
 			raise gdb.GdgError("unknown endianness '%s'" % endian)
 	return target_endianness
+
+def read_u16(buffer):
+	if get_target_endianness() == LITTLE_ENDIAN:
+		return ord(buffer[0]) + (ord(buffer[1]) << 8)
+	else:
+		return ord(buffer[1]) + (ord(buffer[0]) << 8)
+
+def read_u32(buffer):
+	if get_target_endianness() == LITTLE_ENDIAN:
+		return read_u16(buffer[0:2]) + (read_u16(buffer[2:4]) << 16)
+	else:
+		return read_u16(buffer[2:4]) + (read_u16(buffer[0:2]) << 16)
+
+def read_u64(buffer):
+	if get_target_endianness() == LITTLE_ENDIAN:
+		return read_u32(buffer[0:4]) + (read_u32(buffer[4:8]) << 32)
+	else:
+		return read_u32(buffer[4:8]) + (read_u32(buffer[0:4]) << 32)
Signature · 1 line
1.7.3.4
author maintainer
#11 lore raw

PATCH v4 6/13 scripts/gdb: Add lx-dmesg command

In reply to Jan Kiszka

This pokes into the log buffer of the debugged kernel, dumping it to the gdb console. Helping in case the target should or can no longer execute dmesg itself.

---
 scripts/gdb/dmesg.py       |   63 ++++++++++++++++++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |    1 +
 2 files changed, 64 insertions(+), 0 deletions(-)
 create mode 100644 scripts/gdb/dmesg.py
scripts/gdb/dmesg.py new file +63 -0
new file mode 100644
index 0000000..1bc3368
@@ -0,0 +1,63 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  kernel log buffer dump
+#
+# Copyright (c) Siemens AG, 2011, 2012
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import gdb
+import string
+
+from utils import *
+
+class LinuxDmesg(gdb.Command):
+	__doc__ = "Print Linux kernel log buffer."
+
+	def __init__(self):
+		super(LinuxDmesg, self).__init__("lx-dmesg", gdb.COMMAND_DATA)
+
+	def invoke(self, arg, from_tty):
+		log_buf_addr = \
+			int(str(gdb.parse_and_eval("log_buf")).split()[0], 16)
+		log_first_idx = int(gdb.parse_and_eval("log_first_idx"))
+		log_next_idx = int(gdb.parse_and_eval("log_next_idx"))
+		log_buf_len = int(gdb.parse_and_eval("log_buf_len"))
+
+		inf = gdb.inferiors()[0]
+		start = log_buf_addr + log_first_idx
+		if log_first_idx < log_next_idx:
+			log_buf_2nd_half = -1
+			length = log_next_idx - log_first_idx
+			log_buf = inf.read_memory(start, length)
+		else:
+			log_buf_2nd_half = log_buf_len - log_first_idx
+			log_buf = inf.read_memory(start, log_buf_2nd_half) + \
+				  inf.read_memory(log_buf_addr, log_next_idx)
+
+		pos = 0
+		while pos < log_buf.__len__():
+			length = read_u16(log_buf[pos + 8 : pos + 10])
+			if length == 0:
+				if log_buf_2nd_half == -1:
+					print "Corrupted log buffer!"
+					break
+				pos = log_buf_2nd_half
+				continue
+
+			text_len = read_u16(log_buf[pos + 10 : pos + 12])
+			time_stamp = read_u64(log_buf[pos : pos + 8])
+
+			for line in log_buf[pos + 16 :
+					    pos + 16 + text_len].splitlines():
+				print "[%13.6f] " % \
+				      (time_stamp / 1000000000.0) + line
+
+			pos += length
+
+LinuxDmesg()
scripts/gdb/vmlinux-gdb.py +1 -0
index 3553b7d..47f296d 100644
@@ -23,3 +23,4 @@ if gdb_version < "7.1":
 else:
 	import utils
 	import symbols
+	import dmesg
Signature · 1 line
1.7.3.4
#12 lore raw

Re: [PATCH v4 06/13] scripts/gdb: Add lx-dmesg command

Quoted 3 lines · Jan Kiszka

This pokes into the log buffer of the debugged kernel, dumping it to the gdb console. Helping in case the target should or can no longer execute dmesg itself.

Very useful, as this got very painful when the log buffer was changed a few releases ago.

-Andi

author maintainer
#13 lore raw

PATCH v4 7/13 scripts/gdb: Add task iteration helper

In reply to Jan Kiszka

The internal helper for_each_task iterates over all tasks of the target, calling the provided function on each. For performance reasons, we cache a reference to the gdb type object of a task.

---
 scripts/gdb/task.py |   40 ++++++++++++++++++++++++++++++++++++++++
 1 files changed, 40 insertions(+), 0 deletions(-)
 create mode 100644 scripts/gdb/task.py
scripts/gdb/task.py new file +40 -0
new file mode 100644
index 0000000..ff05aa5
@@ -0,0 +1,40 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  task & thread tools
+#
+# Copyright (c) Siemens AG, 2011, 2012
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import gdb
+
+from utils import *
+
+task_ptr_type = None
+
+def get_task_ptr_type():
+	global task_ptr_type
+	if task_ptr_type == None:
+		task_ptr_type = get_type("struct task_struct").pointer()
+	return task_ptr_type
+
+def for_each_task(func, arg = None):
+	init_task = gdb.parse_and_eval("init_task")
+	g = init_task.address
+	while True:
+		g =  container_of(g['tasks']['next'], get_task_ptr_type(),
+				  "tasks")
+		if g == init_task.address:
+			break;
+		t = g
+		while True:
+			func(t, arg)
+			t = container_of(t['thread_group']['next'],
+					 get_task_ptr_type(), "thread_group")
+			if t == g:
+				break
Signature · 1 line
1.7.3.4
author maintainer
#14 lore raw

PATCH v4 8/13 scripts/gdb: Add helper and convenience function to look up tasks

In reply to Jan Kiszka

Add the helper task_by_pid that can look up a task by its PID. Also export it as a convenience function.

---
 scripts/gdb/task.py        |   29 +++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |    1 +
 2 files changed, 30 insertions(+), 0 deletions(-)
scripts/gdb/task.py +29 -0
index ff05aa5..93e6c0c 100644
@@ -38,3 +38,32 @@ def for_each_task(func, arg = None):
 					 get_task_ptr_type(), "thread_group")
 			if t == g:
 				break
+
+def get_task_by_pid(pid):
+	def match_pid(t, arg):
+		if int(t['pid']) == arg['pid']:
+			arg['task'] = t
+
+	arg = { 'pid': pid, 'task': None }
+	for_each_task(match_pid, arg)
+
+	return arg['task']
+
+
+class LxTaskByPidFunc(gdb.Function):
+	__doc__ = "Find Linux task by PID and return the task_struct variable.\n" \
+		  "\n" \
+		  "$lx_task_by_pid(PID): Given PID, iterate over all tasks of the target and\n" \
+		  "return that task_struct variable which PID matches.\n"
+
+	def __init__(self):
+		super(LxTaskByPidFunc, self).__init__("lx_task_by_pid")
+
+	def invoke(self, pid):
+		task = get_task_by_pid(pid)
+		if task:
+			return task.dereference()
+		else:
+			raise gdb.GdbError("No task of PID " + str(pid))
+
+LxTaskByPidFunc()
scripts/gdb/vmlinux-gdb.py +1 -0
index 47f296d..e78b353 100644
@@ -24,3 +24,4 @@ else:
 	import utils
 	import symbols
 	import dmesg
+	import task
Signature · 1 line
1.7.3.4
author maintainer
#15 lore raw

PATCH v4 9/13 scripts/gdb: Add is_target_arch helper

In reply to Jan Kiszka

This helper caches to result of "show architecture" and matches the provided arch (sub-)string against that output.

---
 scripts/gdb/utils.py |    9 +++++++++
 1 files changed, 9 insertions(+), 0 deletions(-)
scripts/gdb/utils.py +9 -0
index 8d54241..532d379 100644
@@ -91,3 +91,12 @@ def read_u64(buffer):
 		return read_u32(buffer[0:4]) + (read_u32(buffer[4:8]) << 32)
 	else:
 		return read_u32(buffer[4:8]) + (read_u32(buffer[0:4]) << 32)
+
+
+target_arch = None
+
+def is_target_arch(arch):
+	global target_arch
+	if target_arch == None:
+		target_arch = gdb.execute("show architecture", False, True)
+	return target_arch.find(arch) >= 0
Signature · 1 line
1.7.3.4
author maintainer
#16 lore raw

PATCH v4 10/13 scripts/gdb: Add internal helper and convenience function to retrieve thread_info

In reply to Jan Kiszka

Add the internal helper get_thread_info that calculated the thread_info from a given task variable. Also export this service as a convenience function.

Note: ia64 version is untested.

---
 scripts/gdb/task.py |   39 +++++++++++++++++++++++++++++++++++++++
 1 files changed, 39 insertions(+), 0 deletions(-)
scripts/gdb/task.py +39 -0
index 93e6c0c..0a45b3c 100644
@@ -67,3 +67,42 @@ class LxTaskByPidFunc(gdb.Function):
 			raise gdb.GdbError("No task of PID " + str(pid))
 
 LxTaskByPidFunc()
+
+
+thread_info_ptr_type = None
+
+def get_thread_info_ptr_type():
+	global thread_info_ptr_type
+	if thread_info_ptr_type = None:
+		thread_info_ptr_type = get_type('struct thread_info').pointer()
+	return thread_info_ptr_type
+
+ia64_task_size = None
+
+def get_thread_info(task):
+	if is_target_arch("ia64"):
+		global ia64_task_size
+		if ia64_task_size = None:
+			ia64_task_size = gdb.parse_and_eval(
+						"sizeof(struct task_struct)")
+		thread_info_addr = task.address + ia64_task_size
+		thread_info = thread_info_addr.cast(get_thread_info_ptr_type())
+	else:
+		thread_info = task['stack'].cast(get_thread_info_ptr_type())
+	return thread_info.dereference()
+
+
+class LxThreadInfoFunc (gdb.Function):
+	# Calculate Linux thread_info from task variable.
+	__doc__ = "Calculate Linux thread_info from task variable.\n" \
+		  "\n" \
+		  "$lx_thread_info(TASK): Given TASK, return the corresponding thread_info\n" \
+		  "variable.\n"
+
+	def __init__(self):
+		super(LxThreadInfoFunc, self).__init__("lx_thread_info")
+
+	def invoke(self, task):
+		return get_thread_info(task)
+
+LxThreadInfoFunc()
Signature · 1 line
1.7.3.4
author maintainer
#17 lore raw

PATCH v4 11/13 scripts/gdb: Add get_gdbserver_type helper

In reply to Jan Kiszka

This helper probes the type of the gdb server. Supported are QEMU and KGDB so far. Knowledge about the gdb server is required e.g. to retrieve the current CPU or current task.

---
 scripts/gdb/utils.py |   35 +++++++++++++++++++++++++++++++++++
 1 files changed, 35 insertions(+), 0 deletions(-)
scripts/gdb/utils.py +35 -0
index 532d379..a20f096 100644
@@ -100,3 +100,38 @@ def is_target_arch(arch):
 	if target_arch == None:
 		target_arch = gdb.execute("show architecture", False, True)
 	return target_arch.find(arch) >= 0
+
+
+GDBSERVER_QEMU = 0
+GDBSERVER_KGDB = 1
+gdbserver_type = None
+
+def get_gdbserver_type():
+	def exit_handler(event):
+		global gdbserver_type
+		gdbserver_type = None
+		gdb.events.exited.disconnect(exit_handler)
+
+	def probe_qemu():
+		try:
+			return gdb.execute("monitor info version", False,
+					   True) != ""
+		except:
+			return False
+
+	def probe_kgdb():
+		try:
+			thread_info = gdb.execute("info thread 2", False, True)
+			return thread_info.find("shadowCPU0") >= 0
+		except:
+			return False
+
+	global gdbserver_type
+	if gdbserver_type == None:
+		if probe_qemu():
+			gdbserver_type = GDBSERVER_QEMU
+		elif probe_kgdb():
+			gdbserver_type = GDBSERVER_KGDB
+		if gdbserver_type != None:
+			gdb.events.exited.connect(exit_handler)
+	return gdbserver_type
Signature · 1 line
1.7.3.4
author maintainer
#18 lore raw

PATCH v4 12/13 scripts/gdb: Add internal helper and convenience function for per-cpu lookup

In reply to Jan Kiszka

This function allows to obtain a per-cpu variable, either of the current or an explicitly specified CPU.

Note: sparc64 version is untested.

---
 scripts/gdb/percpu.py      |   61 ++++++++++++++++++++++++++++++++++++++++++++
 scripts/gdb/vmlinux-gdb.py |    1 +
 2 files changed, 62 insertions(+), 0 deletions(-)
 create mode 100644 scripts/gdb/percpu.py
scripts/gdb/percpu.py new file +61 -0
new file mode 100644
index 0000000..e2556919
@@ -0,0 +1,61 @@
+#
+# gdb helper commands and functions for Linux kernel debugging
+#
+#  per-cpu tools
+#
+# Copyright (c) Siemens AG, 2011, 2012
+#
+# Authors:
+#  Jan Kiszka <[email protected]>
+#
+# This work is licensed under the terms of the GNU GPL version 2.
+#
+
+import gdb
+
+from utils import *
+from task import *
+
+MAX_CPUS = 4096
+
+def get_current_cpu():
+	if get_gdbserver_type() = GDBSERVER_QEMU:
+		return gdb.selected_thread().num - 1
+	elif get_gdbserver_type() = GDBSERVER_KGDB:
+		tid = gdb.selected_thread().ptid[2]
+		if tid > (0x100000000 - MAX_CPUS - 2):
+			return 0x100000000 - tid - 2
+		else:
+			return get_thread_info(get_task_by_pid(tid))['cpu']
+	else:
+		raise gdb.GdbError("Sorry, obtaining the current CPU is "
+				   "not yet supported with this gdb server.")
+
+def per_cpu(var_name, cpu):
+	var = gdb.parse_and_eval("&" + var_name)
+	if cpu = -1:
+		cpu = get_current_cpu()
+	if is_target_arch("sparc:v9"):
+		offset = gdb.parse_and_eval("trap_block[" + str(cpu) +
+					    "].__per_cpu_base")
+	else:
+		offset = gdb.parse_and_eval("__per_cpu_offset[" + str(cpu) +
+					    "]")
+	pointer = var.cast(get_long_type()) + offset
+	return pointer.cast(var.type).dereference()
+
+
+class PerCpu(gdb.Function):
+	__doc__ = "Return per-cpu variable.\n" \
+		  "\n" \
+		  "$lx_per_cpu(\"VAR\"[, CPU]): Return the per-cpu variable called VAR for the\n" \
+		  "given CPU number. If CPU is omitted, the CPU of the current context is used.\n" \
+		  "Note that VAR has to be quoted as string."
+
+	def __init__(self):
+		super(PerCpu, self).__init__("lx_per_cpu")
+
+	def invoke(self, var_name, cpu = -1):
+		return per_cpu(var_name.string(), cpu)
+
+PerCpu()
scripts/gdb/vmlinux-gdb.py +1 -0
index e78b353..6606247 100644
@@ -25,3 +25,4 @@ else:
 	import symbols
 	import dmesg
 	import task
+	import percpu
Signature · 1 line
1.7.3.4
author maintainer
#19 lore raw

PATCH v4 13/13 scripts/gdb: Add lx_current convenience function

In reply to Jan Kiszka

This is a shorthand for *$lx_per_cpu("current_task"), i.e. a convenience function to retrieve the currently running task of the active context.

---
 scripts/gdb/percpu.py |   15 +++++++++++++++
 1 files changed, 15 insertions(+), 0 deletions(-)
scripts/gdb/percpu.py +15 -0
index e2556919..dbc84c0 100644
@@ -59,3 +59,18 @@ class PerCpu(gdb.Function):
 		return per_cpu(var_name.string(), cpu)
 
 PerCpu()
+
+
+class LxCurrentFunc(gdb.Function):
+	__doc__ = "Return current task.\n" \
+		  "\n" \
+		  "$lx_current([CPU]): Return the per-cpu task variable for the given CPU\n" \
+		  "number. If CPU is omitted, the CPU of the current context is used."
+
+	def __init__(self):
+		super(LxCurrentFunc, self).__init__("lx_current")
+
+	def invoke(self, cpu = -1):
+		return per_cpu("current_task", cpu).dereference()
+
+LxCurrentFunc()
Signature · 1 line
1.7.3.4
#20 lore raw
In reply to Jan Kiszka
Quoted 3 lines

And this is a tutorial for the gdb extension using QEMU/KVM as target platform:

Can you add the tutorial as a file in Documentation? Other than that everything looks good to me.

-Andi

author maintainer
#21 lore raw
Quoted 5 lines · Andi Kleen
Quoted 3 lines

And this is a tutorial for the gdb extension using QEMU/KVM as target platform:

Can you add the tutorial as a file in Documentation?

Sure, will do.

Quoted 1 line

Other than that everything looks good to me.

Thanks,
Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RTC ITP SDP-DE
Corporate Competence Center Embedded Linux
Acked-by on the v4 series
#22 lore raw
In reply to Jan Kiszka
Quoted 146 lines · On Mon, 21 Jan 2013 18:06:07 +0100 Jan Kiszka <[email protected]> wrote:

Version 4 of this series is a rebase over latest 3.8-rc4+. Moreover, I updated the mechanism that implements automatic symbol loading for new modules. It was affected by the refactorings around finit_module.

While waiting for feedback who could imagine picking this up for merge, I wrote a tiny tutorial, see below.

Here is the original series intro again:

This adds the infrastructure and first tools that make kernel debugging through gdb more comfortable. Since 7.0, gdb supports python scripting. And this opens the doors to automate steps like the tedious loading of module symbols at the right address, resolving per-cpu variables or even retrieving the current kernel log without resuming an stopped target.

Many of the helpers naturally depend on the layout of structures or internal mechanics of the kernel. So the best place to maintain such things, keeping them consistent with the corresponding kernel is, well, the kernel itself.

While these scripts have been originally developed for debugging via QEMU/KVM, I've now also added the required bits for KGDB. Works fine, but as QEMU/KVM tends to outperform KGDB it remains the recommendation
- when available.

There are two architecture dependencies so far, one regarding per-cpu, the other regarding thread_info calculation. None of them I was able to test on a target, so I'm counting on review/testing by the corresponding communities.

This series should be considered the foundation of much more kernel state exploration helpers, e.g. around tasks, timers, locks, sockets - I guess people will have even more ideas.

And this is a tutorial for the gdb extension using QEMU/KVM as target platform:

o Set up a virtual Linux machine for KVM (see www.linux-kvm.org and www.qemu.org for more details)

o Build the kernel with this series applied, enabling CONFIG_DEBUG_INFO (but leave CONFIG_DEBUG_INFO_REDUCED off)

o Install that kernel on the guest

o Enable the gdb stub of QEMU/KVM, either
- at VM startup time by appending "-s" to the QEMU command line
or
- during runtime by issuing "gdbserver" from the QEMU monitor console

o cd /path/to/linux-build

o Start gdb: gdb vmlinux

o Attach to the booted guest:

    (gdb) target remote :1234

o Load module (and main kernel) symbols:

    (gdb) lx-symbols
    loading vmlinux
    scanning for modules in /home/user/linux/build
    loading @0xffffffffa0020000: /home/user/linux/build/net/netfilter/xt_tcpudp.ko
    loading @0xffffffffa0016000: /home/user/linux/build/net/netfilter/xt_pkttype.ko
    loading @0xffffffffa0002000: /home/user/linux/build/net/netfilter/xt_limit.ko
    loading @0xffffffffa00ca000: /home/user/linux/build/net/packet/af_packet.ko
    loading @0xffffffffa003c000: /home/user/linux/build/fs/fuse/fuse.ko
    ...
    loading @0xffffffffa0000000: /home/user/linux/build/drivers/ata/ata_generic.ko

o Set a breakpoint on some not yet loaded module function, e.g.:
(gdb) b btrfs_init_sysfs
Function "btrfs_init_sysfs" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y Breakpoint 1 (btrfs_init_sysfs) pending.

o Continue the target

o Load the module on the target and watch what happens:

    loading @0xffffffffa0034000: /home/user/linux/build/lib/libcrc32c.ko
    loading @0xffffffffa0050000: /home/user/linux/build/lib/lzo/lzo_compress.ko
    loading @0xffffffffa006e000: /home/user/linux/build/lib/zlib_deflate/zlib_deflate.ko
    loading @0xffffffffa01b1000: /home/user/linux/build/fs/btrfs/btrfs.ko

    Breakpoint 1, btrfs_init_sysfs () at /home/user/linux/fs/btrfs/sysfs.c:36
    36              btrfs_kset = kset_create_and_add("btrfs", NULL, fs_kobj);

o Let's examine the current task a bit:

    (gdb) p ().pid
     = 4998
    (gdb) p ().comm
     = "modprobe\000\000\000\000\000\000\000"

o Dump the log buffer of target kernel:

    (gdb) lx-dmesg
    [     0.000000] Initializing cgroup subsys cpuset
    [     0.000000] Initializing cgroup subsys cpu
    [     0.000000] Linux version 3.8.0-rc4-dbg+ (...
    [     0.000000] Command line: root=/dev/sda2 resume=/dev/sda1 vga=0x314
    [     0.000000] e820: BIOS-provided physical RAM map:
    [     0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable
    [     0.000000] BIOS-e820: [mem 0x000000000009fc00-0x000000000009ffff] reserved
    ....

o Make use of the per-cpu helper for the current or a specified CPU:

    (gdb) p ("runqueues").nr_running
     = 1
    (gdb) p ("runqueues", 2).nr_running
     = 0

o And now we are digging deep into hrtimers using the container_of helper:

    (gdb) set  = ("hrtimer_bases").clock_base[0].active.next
    (gdb) p *(, "struct hrtimer", "node")
     = {
      node = {
        node = {
          __rb_parent_color = 18446612133355256072,
          rb_right = 0x0 <irq_stack_union>,
          rb_left = 0x0 <irq_stack_union>
        },
        expires = {
          tv64 = 1835268000000
        }
      },
      _softexpires = {
        tv64 = 1835268000000
      },
      function = 0xffffffff81078232 <tick_sched_timer>,
      base = 0xffff88003fd0d6f0,
      state = 1,
      start_pid = 0,
      start_site = 0xffffffff81055c1f <hrtimer_start_range_ns+20>,
      start_comm = "swapper/2\000\000\000\000\000\000"
    }

Hope this provided some ideas and inspirations on how the commands and helper functions can support kernel development.

Enjoy,
Jan

PS: Also available via git://git.kiszka.org/linux.git queues/gdb-scripts

Quoted 8 lines
CC "David S. Miller" <[email protected]>
CC Fenghua Yu <[email protected]>
CC Kay Sievers <[email protected]>
CC Michal Marek <[email protected]>
CC Tony Luck <[email protected]>

My less than useful from v3 still applies:

I'm not really an appropriate person to review, but I've mde heavy use of lx-symbols and lx-dmesg and am very happy.

Signature · 1 line
Ben Widawsky, Intel Open Source Technology Center
#23 lore raw
In reply to Jan Kiszka
Quoted 2 lines

o Install that kernel on the guest

If you use a static kernel you can also do

- copy the initrd out of the guest once

qemu... -bzImage kernel -initrd initrd

This saves the step of getting the kernel into the kernel. Doesn't work with modules unfortunately.

-Andi

author maintainer
#24 lore raw
Quoted 8 lines · Andi Kleen
Quoted 2 lines

o Install that kernel on the guest

If you use a static kernel you can also do

- copy the initrd out of the guest once

qemu... -bzImage kernel -initrd initrd

-kernel/append/initrd, of course.

Quoted 3 lines

This saves the step of getting the kernel into the kernel. Doesn't work with modules unfortunately.

True. An alternative can be nfsroot. Or root on virtfs.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RTC ITP SDP-DE
Corporate Competence Center Embedded Linux
#25 lore raw
In reply to Jan Kiszka

Ok, first of all, I gotta say, this is very cool stuff, thanks for doing this. I'm playing with your tutorial and I'm having some trouble, see below:

Quoted 2 lines · Jan Kiszka

o Let's examine the current task a bit:

    (gdb) p ().pid

when I do that, it says:

(gdb) p ().pid
A syntax error in expression, near `).pid'

Here's what I do:

$ gdb --data-directory $(pwd)/scripts/gdb/ ./vmlinux
GNU gdb (GDB) 7.4.1-debian
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /w/kernel/linux-2.6/vmlinux...done.
(gdb) target remote :1234
Remote debugging using :1234
[New Thread 2]
[Switching to Thread 2]
default_idle () at arch/x86/kernel/process.c:391
391             current_thread_info()->status |= TS_POLLING;
(gdb) p ().pid
A syntax error in expression, near `).pid'.
(gdb) show data-directory
GDB's data directory is "/w/kernel/linux-2.6/scripts/gdb/".
(gdb) lx-symbols
loading vmlinux
no modules found
(gdb) p ().pid
A syntax error in expression, near `).pid'.
(gdb)

So, I thought I should point it explicitly to the python scripts with --data-directory but it still doesn't fly. And gdb is 7.4.1 so it should be recent enough.

lx-dmesg works, for example:

(gdb) lx-dmesg

[     0.000000] Linux version 3.8.0-rc4+ (boris@pd) (gcc version 4.7.2 (Debian 4.7.2-5) ) #2 SMP PREEMPT Wed Jan 23 11:59:58 CET 2013
[     0.000000] Command line: vga=0 root=/dev/sda1 debug ignore_loglevel console=ttyS0,115200 console=tty0
[     0.000000] e820: BIOS-provided physical RAM map:
[     0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009f3ff] usable
[     0.000000] BIOS-e820: [mem 0x000000000009f400-0x000000000009ffff] reserved
[     0.000000] BIOS-e820: [mem 0x00000000000f0000-0x00000000000fffff] reserved
[     0.000000] BIOS-e820: [mem 0x0000000000100000-0x000000007fffdfff] usable

...

So what am I missing?

Thanks.

Signature · 5 lines
Regards/Gruss,
    Boris.

Sent from a fat crate under my desk. Formatting is fine.
--
author maintainer
#26 lore raw
Quoted 4 lines · Borislav Petkov

Ok, first of all, I gotta say, this is very cool stuff, thanks for doing this. I'm playing with your tutorial and I'm having some trouble, see below:

Quoted 8 lines
Quoted 2 lines · Jan Kiszka

o Let's examine the current task a bit:

    (gdb) p ().pid

when I do that, it says:

(gdb) p ().pid
A syntax error in expression, near `).pid'

Ouch, my git-send script ate all the "$foo" in the cover letter :(. It has to be $lx_current, $lx_per_cpu and $container_of. Will write an add-on patch that adds the tutorial as a text file later on.

Jan

Signature · 2 lines
Siemens AG, Corporate Technology, CT RTC ITP SDP-DE
Corporate Competence Center Embedded Linux
author maintainer
#27 lore raw

[PATCH v4 14/13] scripts/gdb: Add basic documentation

In reply to Jan Kiszka

---

Add-on patch to this series as requested during review.

 Documentation/gdb-kernel-debugging.txt |  145 ++++++++++++++++++++++++++++++++
 1 files changed, 145 insertions(+), 0 deletions(-)
 create mode 100644 Documentation/gdb-kernel-debugging.txt
Documentation/gdb-kernel-debugging.txt new file +145 -0
new file mode 100644
index 0000000..bf2adbf
@@ -0,0 +1,145 @@
+Debugging kernel and modules via gdb
+====================================
+
+The kernel debugger kgdb, hypervisors like QEMU or JTAG-based hardware
+interfaces allow to debug the Linux kernel and its modules during runtime
+using gdb. Gdb comes with a powerful scripting interface for python. The
+kernel provides a collection of helper scripts that can simplify typical
+kernel debugging steps. This is a short tutorial about how to enable and use
+them. It focuses on QEMU/KVM virtual machines as target, but the examples can
+be transferred to the other gdb stubs as well.
+
+
+Requirements
+------------
+
+ o gdb 7.1+ (recommended: 7.3+) with python support enabled (typically true
+   for distributions)
+
+
+Setup
+-----
+
+ o Create a virtual Linux machine for QEMU/KVM (see www.linux-kvm.org and
+   www.qemu.org for more details)
+
+ o Build the kernel with CONFIG_DEBUG_INFO enabled, but leave
+   CONFIG_DEBUG_INFO_REDUCED off
+
+ o Install that kernel on the guest.
+
+   Alternatively, QEMU allows to boot the kernel directly using -kernel,
+   -append, -initrd command line switches. This is generally only useful if
+   you do not depend on modules. See QEMU documentation for more details on
+   this mode.
+
+ o Enable the gdb stub of QEMU/KVM, either
+    - at VM startup time by appending "-s" to the QEMU command line
+   or
+    - during runtime by issuing "gdbserver" from the QEMU monitor
+      console
+
+ o cd /path/to/linux-build
+
+ o Start gdb: gdb vmlinux
+
+ o Attach to the booted guest:
+    (gdb) target remote :1234
+
+
+Examples of using the Linux-provided gdb helpers
+------------------------------------------------
+
+ o Load module (and main kernel) symbols:
+    (gdb) lx-symbols
+    loading vmlinux
+    scanning for modules in /home/user/linux/build
+    loading @0xffffffffa0020000: /home/user/linux/build/net/netfilter/xt_tcpudp.ko
+    loading @0xffffffffa0016000: /home/user/linux/build/net/netfilter/xt_pkttype.ko
+    loading @0xffffffffa0002000: /home/user/linux/build/net/netfilter/xt_limit.ko
+    loading @0xffffffffa00ca000: /home/user/linux/build/net/packet/af_packet.ko
+    loading @0xffffffffa003c000: /home/user/linux/build/fs/fuse/fuse.ko
+    ...
+    loading @0xffffffffa0000000: /home/user/linux/build/drivers/ata/ata_generic.ko
+
+ o Set a breakpoint on some not yet loaded module function, e.g.:
+    (gdb) b btrfs_init_sysfs
+    Function "btrfs_init_sysfs" not defined.
+    Make breakpoint pending on future shared library load? (y or [n]) y
+    Breakpoint 1 (btrfs_init_sysfs) pending.
+
+ o Continue the target
+    (gdb) c
+
+ o Load the module on the target and watch the symbols being loaded as well as
+   the breakpoint hit:
+    loading @0xffffffffa0034000: /home/user/linux/build/lib/libcrc32c.ko
+    loading @0xffffffffa0050000: /home/user/linux/build/lib/lzo/lzo_compress.ko
+    loading @0xffffffffa006e000: /home/user/linux/build/lib/zlib_deflate/zlib_deflate.ko
+    loading @0xffffffffa01b1000: /home/user/linux/build/fs/btrfs/btrfs.ko
+
+    Breakpoint 1, btrfs_init_sysfs () at /home/user/linux/fs/btrfs/sysfs.c:36
+    36              btrfs_kset = kset_create_and_add("btrfs", NULL, fs_kobj);
+
+ o Dump the log buffer of the target kernel:
+    (gdb) lx-dmesg
+    [     0.000000] Initializing cgroup subsys cpuset
+    [     0.000000] Initializing cgroup subsys cpu
+    [     0.000000] Linux version 3.8.0-rc4-dbg+ (...
+    [     0.000000] Command line: root=/dev/sda2 resume=/dev/sda1 vga=0x314
+    [     0.000000] e820: BIOS-provided physical RAM map:
+    [     0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable
+    [     0.000000] BIOS-e820: [mem 0x000000000009fc00-0x000000000009ffff] reserved
+    ....
+
+ o Examine fields of the current task struct:
+    (gdb) p $lx_current().pid
+    $1 = 4998
+    (gdb) p $lx_current().comm
+    $2 = "modprobe\000\000\000\000\000\000\000"
+
+ o Make use of the per-cpu helper for the current or a specified CPU:
+    (gdb) p $lx_per_cpu("runqueues").nr_running
+    $3 = 1
+    (gdb) p $lx_per_cpu("runqueues", 2).nr_running
+    $4 = 0
+
+ o Dig into hrtimers using the container_of helper:
+    (gdb) set $next = $lx_per_cpu("hrtimer_bases").clock_base[0].active.next
+    (gdb) p *$container_of($next, "struct hrtimer", "node")
+    $5 = {
+      node = {
+        node = {
+          __rb_parent_color = 18446612133355256072,
+          rb_right = 0x0 <irq_stack_union>,
+          rb_left = 0x0 <irq_stack_union>
+        },
+        expires = {
+          tv64 = 1835268000000
+        }
+      },
+      _softexpires = {
+        tv64 = 1835268000000
+      },
+      function = 0xffffffff81078232 <tick_sched_timer>,
+      base = 0xffff88003fd0d6f0,
+      state = 1,
+      start_pid = 0,
+      start_site = 0xffffffff81055c1f <hrtimer_start_range_ns+20>,
+      start_comm = "swapper/2\000\000\000\000\000\000"
+    }
+
+
+List of commands and helper
+---------------------------
+
+The number of commands and convenience helpers may evolve over the time, this
+is just a snapshot of the initial version:
+
+ (gdb) apropos lx
+ function lx_current -- Return current task
+ function lx_per_cpu -- Return per-cpu variable
+ function lx_task_by_pid -- Find Linux task by PID and return the task_struct variable
+ function lx_thread_info -- Calculate Linux thread_info from task variable
+ lx-dmesg -- Print Linux kernel log buffer
+ lx-symbols -- (Re-)load symbols of Linux kernel and currently loaded modules
Signature · 1 line
1.7.3.4