From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from list by lists.gnu.org with archive (Exim 4.90_1) id 1p8w1K-0002rH-FD for mharc-grub-devel@gnu.org; Fri, 23 Dec 2022 23:20:26 -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 1p8w1J-0002qk-74 for grub-devel@gnu.org; Fri, 23 Dec 2022 23:20:25 -0500 Received: from mail-pl1-x62c.google.com ([2607:f8b0:4864:20::62c]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1p8w1H-0000Xt-0U for grub-devel@gnu.org; Fri, 23 Dec 2022 23:20:24 -0500 Received: by mail-pl1-x62c.google.com with SMTP id 17so6570196pll.0 for ; Fri, 23 Dec 2022 20:20:13 -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=QzzKrEolStWRtfTEOQuEVNcBD5ebpLHC6Ne2VyKL+TI=; b=Jez5hIJXdEbLUThhkPyzJO8cemp721opAPDa7DCJzSLOhYYjWVtO5z23ODg2PtEN3f yuXSU8NqvaSJa4Geq/7ltOytNra6b24D2wMyJp3MjBe01+sG8+A9/cycGDgCU+nBiIuw GV9JvJtfHyEqiiKpl/nNqbyfMQIdMQkEdEFTQ33m7Zzqqj6kkvli/Im6fv5EO8dxT25S Irbt5YIJmwDK1FMrq9ESpv5DIXDLWkG1ClEQ6us1VPXgdloLz6cNymQY9N9iRMdKIKRS yi8MzrRog6z/fIc2e51lTD5hlUDsovuk4FTae3OxKUCPmu1pLgwv+3Ltkr0Ox6Ib50HS ekIg== 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=QzzKrEolStWRtfTEOQuEVNcBD5ebpLHC6Ne2VyKL+TI=; b=x3BKs1ottL5WuROL+L7kiI3bashLrKONnqo8PUZFw3J3ICQeNhYaMMKGj38ge62d+r 6QEph/9Sz3SdMf2+cFIaTvQNT0yyxbC3Ic2KiXlWIKM6W0ydUjzb7Ms/5e5263yLQGKI wZFneAChkcxFcjR25e3xNKoLZHdhOVrB0hYMQBYON3AiolwTGqNo3Rop8LG5KNHWx19b jsNgbKgcaHl4mx7g7J7O9EI84BLbY2DcDOLuPAgTc0EjSfffWaSi6XuNyvrxm3lYbMH5 F7P/mYTASXYv2nUx+tFV114htVcWwPvM8UWaHwjT2yNFTbVUvLzpoac1tw3QYhbX7U6U QEPw== X-Gm-Message-State: AFqh2kojGsJ0q6GjUyYGOYtYaypJ6SR4hyhkKCqXUkii2zuAwGOZCr4m uvFtH8OYnUwKvnIu2Bc347FUKT8w0QgNudu+ X-Google-Smtp-Source: AMrXdXtM/eu9QobNUFIU8XoscG1/1uCMyYqq4SfFHBSz115Vp0ul82L9PWnEq1DkCML6tRRsqgAmiw== X-Received: by 2002:a05:6a20:9d90:b0:af:6f28:7c42 with SMTP id mu16-20020a056a209d9000b000af6f287c42mr13578863pzb.62.1671855612372; Fri, 23 Dec 2022 20:20:12 -0800 (PST) Received: from localhost.localdomain ([204.13.164.84]) by smtp.gmail.com with ESMTPSA id x19-20020aa79413000000b005743b5ebd7csm3324185pfo.92.2022.12.23.20.20.10 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 23 Dec 2022 20:20:11 -0800 (PST) From: Glenn Washburn To: grub-devel@gnu.org, Daniel Kiper Cc: Robbie Harwood , Peter Jones , Glenn Washburn Subject: [PATCH v5 07/14] gdb: Replace module symbol loading implementation with Python one Date: Fri, 23 Dec 2022 22:19:28 -0600 Message-Id: <20221224041935.787292-8-development@efficientek.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20221224041935.787292-1-development@efficientek.com> References: <20221224041935.787292-1-development@efficientek.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Received-SPF: pass client-ip=2607:f8b0:4864:20::62c; envelope-from=development@efficientek.com; helo=mail-pl1-x62c.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: Sat, 24 Dec 2022 04:20:25 -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 95942fc8c9..4951b049ec 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 4ca939f69a..fc201204de 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 0000000000..4306ef448a --- /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 78aa1e64eb..0000000000 --- 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