From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from list by lists.gnu.org with archive (Exim 4.90_1) id 1pFMWj-0004j4-Jb for mharc-grub-devel@gnu.org; Tue, 10 Jan 2023 16:51:25 -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 1pFMWi-0004iw-Et for grub-devel@gnu.org; Tue, 10 Jan 2023 16:51:24 -0500 Received: from mail-pl1-x634.google.com ([2607:f8b0:4864:20::634]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1pFMWg-0002KW-If for grub-devel@gnu.org; Tue, 10 Jan 2023 16:51:24 -0500 Received: by mail-pl1-x634.google.com with SMTP id 17so14700027pll.0 for ; Tue, 10 Jan 2023 13:51:22 -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=u439wk7cguVg2tcZA7mNIk4U80EvNQe+qZKFxcqRGbw=; b=LmfV2Io69df3AaDgK1rO62KIkPUy7AAfVMzT/kJqrUUSReXmJQkF6uI/wU/MFPbULa SDJdhAof7NqxLZqCpdStWLC19QkkxQcUXpGp/gJ5STk9XTWYU+Kn3Xc2b5YEoe+cuftZ sqMN5E0DmrzbtqQTjv3YAn503/gUcH0swN/6s0zAUYnQHpTif4kUpRwuQbp8xmZqqYU6 Udf2nVeA5/4E+RgrwiDEpOwnnlJN0ZIvngZBfbCM3vX68yxXVi7XEG+JqsNwNT42g+A7 Ha0s8dGCkPoCDQ9AnmO7T/YO7BTDzvZhz/Kn/0bEfUgD5Q5zVxxpXFhpmuS/UffT8An/ MdeA== 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=u439wk7cguVg2tcZA7mNIk4U80EvNQe+qZKFxcqRGbw=; b=g/s9TBLerar58vnCp/7BKls4OzbmrTh1oRz4R9f5GyweE2Xmoq218zTpUsxQCIUG4+ lE2oUSNc1/r2EMPZJQRvvMFBmVjiJCEGqt3xnhRwnyFUf4X2lGZBUR7lJp46jYxA5wN1 LaImSupeAq2S4SrUXpBAiv01UqNLD6E2aJXP00jWR0tw1ZPRHMdWjYafadxStlpFTnZC 05saBv4ZNhpKVyZWLQ+3eWMIPpqCdk/ZdDON8GiFFWZ2byjBC8KW4yYOr3yyoKvBeq8G unMNx2B1bjYMSXXT27K4EGVKAhlzsNCrqBNvJinLXrOhFZbFarfDd1UHhN2Y9pBpFKpN Tl9g== X-Gm-Message-State: AFqh2koPpl2LZCaczGOb7Ha5Ka0SaHoGEl/yGsFB7DdysXcPHd0YeJSi fREti2577jxhg1XbcQPYAXQln6oNyLv51jdu X-Google-Smtp-Source: AMrXdXsZ+jk80/yzHAaCzX1MoYiJYWSf0oPFewxJU7Pbc9QL2aqTbkgckv4fWAFzmgxFIRqTqVqIHg== X-Received: by 2002:a17:903:3311:b0:189:9cfd:be73 with SMTP id jk17-20020a170903331100b001899cfdbe73mr72038424plb.44.1673387481225; Tue, 10 Jan 2023 13:51:21 -0800 (PST) Received: from crass-HP-ZBook-15-G2.lan ([199.254.238.56]) by smtp.gmail.com with ESMTPSA id u15-20020a1709026e0f00b00186c3af9644sm7760798plk.273.2023.01.10.13.51.19 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 10 Jan 2023 13:51:20 -0800 (PST) From: Glenn Washburn To: grub-devel@gnu.org, Daniel Kiper Cc: Robbie Harwood , Peter Jones , Glenn Washburn Subject: [PATCH v6 08/14] gdb: Add functions to make loading from dynamically positioned targets easier Date: Tue, 10 Jan 2023 15:50:35 -0600 Message-Id: <20230110215041.1247699-9-development@efficientek.com> X-Mailer: git-send-email 2.34.1 In-Reply-To: <20230110215041.1247699-1-development@efficientek.com> References: <20230110215041.1247699-1-development@efficientek.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Received-SPF: pass client-ip=2607:f8b0:4864:20::634; envelope-from=development@efficientek.com; helo=mail-pl1-x634.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: Tue, 10 Jan 2023 21:51:24 -0000 Many targets, such as EFI, load GRUB at addresses that are determined at runtime. So the load addresses in kernel.exec will almost certainly be wrong. Given the address of the start of the text segment, these functions will tell GDB to load the symbols at the proper locations. It is left up to the user to determine how to get the text address of the loaded GRUB image. Signed-off-by: Glenn Washburn --- grub-core/gdb_grub.in | 21 ++++++++- grub-core/gdb_helper.py.in | 87 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) diff --git a/grub-core/gdb_grub.in b/grub-core/gdb_grub.in index fc201204de..18ce6b0eb2 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, Python and gdb_helper.py script +### automatically. Needs readelf, objdump, Python and gdb_helper.py script ### ### Has to be launched from the writable and trusted ### directory containing *.image and *.module @@ -12,6 +12,25 @@ source gdb_helper.py +define dynamic_load_symbols + dynamic_load_kernel_exec_symbols $arg0 + + # We may have been very late to loading the kernel.exec symbols and + # and modules may already be loaded. So load symbols for any already + # loaded. + load_all_modules + + if $is_grub_loaded() + runtime_load_module + end +end +document dynamic_load_symbols + Load debugging symbols from kernel.exec and any loaded modules given + the address of the .text segment of the UEFI binary in memory. Also + setup session to automatically load module symbols for modules loaded + in the future. +end + define load_all_modules set $this = grub_dl_head while ($this != 0) diff --git a/grub-core/gdb_helper.py.in b/grub-core/gdb_helper.py.in index 4306ef448a..8d5ee1d292 100644 --- a/grub-core/gdb_helper.py.in +++ b/grub-core/gdb_helper.py.in @@ -4,6 +4,23 @@ import subprocess ##### Convenience functions ##### +class IsGrubLoaded (gdb.Function): + """Return 1 if GRUB has been loaded in memory, otherwise 0. +The hueristic used is checking if the first 4 bytes of the memory pointed +to by the _start symbol are not 0. This is true for QEMU on the first run +of GRUB. This may not be true on physical hardware, where memory is not +necessarily cleared on soft reset. This may not also be true in QEMU on +soft resets. Also this many not be true when chainloading GRUB. +""" + + def __init__ (self): + super (IsGrubLoaded, self).__init__ ("is_grub_loaded") + + def invoke (self): + return int (gdb.parse_and_eval ("*(int *) _start")) != 0 + +is_grub_loaded = IsGrubLoaded () + class IsUserCommand (gdb.Function): """Set the second argument to true value if first argument is the name of a user-defined command. @@ -24,6 +41,76 @@ is_user_command = IsUserCommand () ##### Commands ##### +# Loading symbols is complicated by the fact that kernel.exec is an ELF +# ELF binary, but the UEFI runtime is PE32+. All the data sections of +# the ELF binary are concatenated (accounting for ELF section alignment) +# and put into one .data section of the PE32+ runtime image. So given +# the load address of the .data PE32+ section we can determine the +# addresses each ELF data section maps to. The UEFI application is +# loaded into memory just as it is laid out in the file. It is not +# assumed that the binary is available, but it is known that the .text +# section directly precedes the .data section and that .data is EFI +# page aligned. Using this, the .data offset can be found from the .text +# address. +class GrubLoadKernelExecSymbols (gdb.Command): + """Load debugging symbols from kernel.exec given the address of the +.text segment of the UEFI binary in memory.""" + + PE_SECTION_ALIGN = 12 + + def __init__ (self): + super (GrubLoadKernelExecSymbols, self).__init__ ("dynamic_load_kernel_exec_symbols", + gdb.COMMAND_USER, + gdb.COMPLETE_EXPRESSION) + + def invoke (self, arg, from_tty): + self.dont_repeat () + args = gdb.string_to_argv (arg) + + if len (args) != 1: + raise RuntimeError ("dynamic_load_kernel_exec_symbols expects exactly one argument") + + sections = self.parse_objdump_sections ("kernel.exec") + pe_text = args[0] + text_size = [s['size'] for s in sections if s['name'] == '.text'][0] + pe_data_offset = self.alignup (text_size, self.PE_SECTION_ALIGN) + + sym_load_cmd_parts = ["add-symbol-file", "kernel.exec", pe_text] + offset = 0 + for section in sections: + if 'DATA' in section["flags"] or section["name"] == ".bss": + offset = self.alignup (offset, section["align"]) + sym_load_cmd_parts.extend (["-s", section["name"], "(%s+0x%x+0x%x)" % (pe_text, pe_data_offset, offset)]) + offset += section["size"] + gdb.execute (' '.join (sym_load_cmd_parts)) + + @staticmethod + def parse_objdump_sections (filename): + fields = ("idx", "name", "size", "vma", "lma", "fileoff", "align") + re_section = re.compile ("^\s*" + "\s+".join(["(?P<%s>\S+)" % f for f in fields])) + c = subprocess.run (["objdump", "-h", filename], text=True, capture_output=True) + section_lines = c.stdout.splitlines ()[5:] + sections = [] + + for i in range (len (section_lines) >> 1): + m = re_section.match (section_lines[i * 2]) + s = dict (m.groupdict ()) + for f in ("size", "vma", "lma", "fileoff"): + s[f] = int (s[f], 16) + s["idx"] = int (s["idx"]) + s["align"] = int (s["align"].split ("**", 1)[1]) + s["flags"] = section_lines[(i * 2) + 1].strip ().split (", ") + sections.append (s) + return sections + + @staticmethod + def alignup (addr, align): + pad = (addr % (1 << align)) and 1 or 0 + return ((addr >> align) + pad) << align + +dynamic_load_kernel_exec_symbols = GrubLoadKernelExecSymbols () + + class GrubLoadModuleSymbols (gdb.Command): """Load module symbols at correct locations. Takes one argument which is a pointer to a grub_dl_t struct.""" -- 2.34.1