Received: from list by lists.gnu.org with archive (Exim 4.90_1) id 1pWkr4-0007X9-IV for mharc-grub-devel@gnu.org; Mon, 27 Feb 2023 16:16:18 -0500 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1pWkqz-0007T6-Jt for grub-devel@gnu.org; Mon, 27 Feb 2023 16:16:16 -0500 Received: from mail-qv1-xf36.google.com ([2607:f8b0:4864:20::f36]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1pWkqx-0000PJ-IX for grub-devel@gnu.org; Mon, 27 Feb 2023 16:16:13 -0500 Received: by mail-qv1-xf36.google.com with SMTP id bo10so5431479qvb.12 for ; Mon, 27 Feb 2023 13:16:11 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=efficientek-com.20210112.gappssmtp.com; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=sYrW9t7LmSnssRO59O3iEcPg+whp1tNQgHCnbeygB6A=; b=zYREr7/3jhzSAKntI2fA1qT25dOiK7HOKnoVR8fWa75ey2ALuBzk+zzcqxiPEeGCie hUNs2UlqrxdQkGxoirbDeAMbWJLAZ1yzwzEit/LSRrd2Q+7rU0Rkf0jYzc3UoIsl7FoE cG3VXCijqM0F1R7+36hcQcAkT9XjemUXDstZ6baAMZ7Pk04ItgHrKwYxsEyEVWlRW8W2 Qjzxzyap4sZai9e+HCgG+VTw61ODUlezxOnWpgEXV0HEvetcui4HEUI9BPm2xYPRFWXY X7MC8B8sNOf8GJm7Z7hM1q0+5S27sWQEY1YxCt3PtW5wmPloLg+k+U27mCizSZvZzNH2 vB9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=sYrW9t7LmSnssRO59O3iEcPg+whp1tNQgHCnbeygB6A=; b=dgg0fEPxfCp6uftVu2Og+73xjwGhkWiV1ttx/XaMVxW6yE/g4jkM2Cun4Ex1CB78Db yoH7PiV1M9ijalVVDo3UPH/xstu+twsiANHU0jIMCe6dql94rTWDV/gWy+S8qp8jH9nx x7gdZyn4j+BwNbIjkAJ6dL7rT14URA2iUF/7gxO0Rn20K/Buu0gZe+gnHQBxzoSGRJBN XtlX42eZyooWrebdc3PgBe/PzGMX8jYouc40xWSFZXwpNZiIErCUdz/C2wjRZLcOradO qpHwS6J/Dt/l6bKrsXP8W/oMEpttQqrSEzBxAX8Q1Pt2sERkLI37RSRatXTncXLe7bKS ulFQ== X-Gm-Message-State: AO0yUKWzwNv+kgw4jUigga8vY8iQ7Z1Ybr/ClQMWXX53nF+tBQAq2oAF /YIXE1Ysjz37OS5zU1BgDM2TDgAobHkoAU7z X-Google-Smtp-Source: AK7set+nvJev6cdoTBDaRVbNwY6T6WDZlBsGUsElL/14ixO3evKa91zLn+fd0/I+3RhOMz0C6e2Waw== X-Received: by 2002:a05:6214:2028:b0:56c:20c:f2f4 with SMTP id 8-20020a056214202800b0056c020cf2f4mr1833348qvf.45.1677532570239; Mon, 27 Feb 2023 13:16:10 -0800 (PST) Received: from localhost.localdomain ([37.218.244.251]) by smtp.gmail.com with ESMTPSA id n76-20020a37404f000000b0071aacb2c76asm5475080qka.132.2023.02.27.13.16.08 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 27 Feb 2023 13:16:09 -0800 (PST) From: Glenn Washburn To: grub-devel@gnu.org, Daniel Kiper Cc: Glenn Washburn Subject: [PATCH 4/8] gdb: Replace module symbol loading implementation with Python one Date: Mon, 27 Feb 2023 15:15:34 -0600 Message-Id: X-Mailer: git-send-email 2.34.1 In-Reply-To: References: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Received-SPF: pass client-ip=2607:f8b0:4864:20::f36; envelope-from=development@efficientek.com; helo=mail-qv1-xf36.google.com X-Spam_score_int: -18 X-Spam_score: -1.9 X-Spam_bar: - X-Spam_report: (-1.9 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, RCVD_IN_DNSWL_NONE=-0.0001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: grub-devel@gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: The development of GNU GRUB List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 27 Feb 2023 21:16:17 -0000 Remove gmodule.pl and rewrite as a python in gdb_helper.py. This removes PERL dependency for the GRUB GDB script, but adds Python as a dependency. This is more desirable because Python is tightly integrated with GDB and can do things not even available to GDB native scripting language. GDB must be built with Python, however this is not a major limitation because every major distro non-end-of-life versions build GDB with Python support. And GDB has had support for Python since around 7.1-ish, which is about a decade. This re-implementation has an added feature. If there is a user defined command named "onload_", then that command will be executed after the symbols for the specified module are loaded. When debugging a module it can be desirable to set break points on code in the module. This is difficult in GRUB because, at GDB start, the module is not loaded and on EFI platforms its not known ahead of time where the module will be loaded. So allow users to create an "onload_" command which will be run when the module with name "modname" is loaded. Another addition is a new convenience function is defined $is_user_command(), which returns true if its string argument is the name of a user-defined command. A secondary benefit of these changes is that the script does not write temporary files and has better error handling capabilities. Signed-off-by: Glenn Washburn --- grub-core/Makefile.core.def | 4 +- grub-core/gdb_grub.in | 54 ++---------------------- grub-core/gdb_helper.py.in | 82 +++++++++++++++++++++++++++++++++++++ grub-core/gmodule.pl.in | 30 -------------- 4 files changed, 87 insertions(+), 83 deletions(-) create mode 100644 grub-core/gdb_helper.py.in delete mode 100644 grub-core/gmodule.pl.in diff --git a/grub-core/Makefile.core.def b/grub-core/Makefile.core.def index 71093a1003dd..d2b1c3e9e44d 100644 --- a/grub-core/Makefile.core.def +++ b/grub-core/Makefile.core.def @@ -20,8 +20,8 @@ transform_data = { transform_data = { installdir = platform; - name = gmodule.pl; - common = gmodule.pl.in; + name = gdb_helper.py; + common = gdb_helper.py.in; }; transform_data = { diff --git a/grub-core/gdb_grub.in b/grub-core/gdb_grub.in index 4ca939f69a89..fc201204debc 100644 --- a/grub-core/gdb_grub.in +++ b/grub-core/gdb_grub.in @@ -1,6 +1,6 @@ ### ### Load debuging information about GNU GRUB 2 modules into GDB -### automatically. Needs readelf, Perl and gmodule.pl script +### automatically. Needs readelf, Python and gdb_helper.py script ### ### Has to be launched from the writable and trusted ### directory containing *.image and *.module @@ -9,63 +9,15 @@ ### Lubomir Kundrak ### -# Add section numbers and addresses to .segments.tmp -define dump_module_sections_helper - set $mod = $arg0 - printf "%s", $mod->name - set $segment = $mod->segment - while ($segment) - printf " %i 0x%lx", $segment->section, $segment->addr - set $segment = $segment->next - end - printf "\n" -end +source gdb_helper.py -define dump_module_sections - # Set unlimited width so that lines don't get wrapped writing - # to .segments.tmp - with width 0 -- \ - with trace-commands off -- \ - pipe dump_module_sections_helper $arg0 | sh -c 'cat >>.segments.tmp' -end -document dump_module_sections - Gather information about module whose mod structure was - given for use with match_and_load_symbols -end - -# Generate and execute GDB commands and delete temporary files -# afterwards -define match_and_load_symbols - shell perl gmodule.pl <.segments.tmp >.loadsym.gdb - source .loadsym.gdb - shell rm -f .segments.tmp .loadsym.gdb -end -document match_and_load_symbols - Launch script, that matches section names with information - generated by dump_module_sections and load debugging info - apropriately -end - -### - -define load_module - dump_module_sections $arg0 - match_and_load_symbols -end -document load_module - Load debugging information for module given as argument. -end define load_all_modules - shell rm -f .segments.tmp set $this = grub_dl_head while ($this != 0) - dump_module_sections $this + load_module $this set $this = $this->next end - if (grub_dl_head != 0) - match_and_load_symbols - end end document load_all_modules Load debugging information for all loaded modules. diff --git a/grub-core/gdb_helper.py.in b/grub-core/gdb_helper.py.in new file mode 100644 index 000000000000..4306ef448aa6 --- /dev/null +++ b/grub-core/gdb_helper.py.in @@ -0,0 +1,82 @@ +import os +import re +import subprocess + +##### Convenience functions ##### + +class IsUserCommand (gdb.Function): + """Set the second argument to true value if first argument is the name +of a user-defined command. +""" + + def __init__ (self): + super (IsUserCommand, self).__init__ ("is_user_command") + + def invoke (self, fmt, *args): + name = fmt.string () % tuple(a.string () for a in args) + for line in gdb.execute ("help user-defined", to_string=True).splitlines (): + line_parts = line.split(' -- ', 1) + if len (line_parts) > 1 and line_parts[0] == name: + return True + return False + +is_user_command = IsUserCommand () + +##### Commands ##### + +class GrubLoadModuleSymbols (gdb.Command): + """Load module symbols at correct locations. +Takes one argument which is a pointer to a grub_dl_t struct.""" + + def __init__ (self): + super (GrubLoadModuleSymbols, self).__init__ ("load_module", + gdb.COMMAND_USER, + gdb.COMPLETE_EXPRESSION) + + def invoke (self, arg, from_tty): + self.dont_repeat () + args = gdb.string_to_argv (arg) + self.mod = gdb.parse_and_eval (args[0]) + sections = self.get_section_offsets () + section_names = self.get_section_names () + + sym_load_cmd_parts = ["add-symbol-file", + "%s.module" % (self.mod['name'].string (),)] + for idx, addr in sections: + section_name = section_names[idx] + if section_name == ".text": + sym_load_cmd_parts.append (addr) + else: + sym_load_cmd_parts.extend (["-s", section_name, addr]) + gdb.execute (' '.join (sym_load_cmd_parts)) + + if is_user_command.invoke (gdb.Value ("onload_%s"), self.mod['name']): + gdb.execute ("onload_%s (grub_dl_t)%s" % (self.mod['name'].string (), + self.mod.format_string (format='x'))) + + def get_section_offsets (self): + sections = [] + segment = self.mod['segment'] + while segment: + sections.append ((int (segment['section']), segment['addr'].format_string (format='x'))) + segment = segment['next'] + return sections + + def get_section_names (self): + re_index = re.compile ("^\s+\[\s*(\d+)\] (\S*)") + names = {} + modfilename = "%s.mod" % (self.mod['name'].string (),) + + if not os.path.exists (modfilename): + raise RuntimeError ("%s not found in current directory" % (modfilename,)) + + c = subprocess.run (["readelf", "-SW", modfilename], text=True, capture_output=True) + for line in c.stdout.splitlines ()[4:]: + m = re_index.match (line) + if not m: + continue + idx, name = m.groups () + names[int (idx)] = name + return names + +grub_load_module = GrubLoadModuleSymbols () diff --git a/grub-core/gmodule.pl.in b/grub-core/gmodule.pl.in deleted file mode 100644 index 78aa1e64eb29..000000000000 --- a/grub-core/gmodule.pl.in +++ /dev/null @@ -1,30 +0,0 @@ -### -### Generate GDB commands, that load symbols for specified module, -### with proper section relocations. See .gdbinit -### -### $Id: gmodule.pl,v 1.2 2006/05/14 11:38:42 lkundrak Exp lkundrak $ -### Lubomir Kundrak -### - -use strict; - -while (<>) { - my ($name, %sections) = split; - - print "add-symbol-file $name.module"; - - open (READELF, "readelf -S $name.mod |") or die; - while () { - /\[\s*(\d+)\]\s+(\.\S+)/ or next; - - if ($2 eq '.text') { - print " $sections{$1}"; - next; - } - - print " -s $2 $sections{$1}" - if ($sections{$1} ne '0x0' and $sections{$1} ne ''); - }; - close (READELF); - print "\n"; -} -- 2.34.1