From d2c1161d16d460f2098e06d33c1adc622c731422 Mon Sep 17 00:00:00 2001
From: Grazfather <grazfather@gmail.com>
Date: Thu, 24 Aug 2023 20:25:33 -0400
Subject: [PATCH 1/4] Fix gdb.execute not quoting paths

---
 gef.py | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)

diff --git a/gef.py b/gef.py
index 660c77f9f..def468938 100644
--- a/gef.py
+++ b/gef.py
@@ -1815,7 +1815,7 @@ def _show_code_line(fname: str, idx: int) -> str:
 
     try:
         lsb_release = which("lsb_release")
-        gdb.execute(f"!{lsb_release} -a")
+        gdb.execute(f"!'{lsb_release}' -a")
     except FileNotFoundError:
         gef_print("lsb_release is missing, cannot collect additional debug information")
 
@@ -1942,7 +1942,7 @@ def __init__(self, to: str = "/dev/null") -> None:
     def __enter__(self) -> None:
         """Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
         gdb.execute("set logging overwrite")
-        gdb.execute(f"set logging file {self.redirection_target_file}")
+        gdb.execute(f"set logging file '{self.redirection_target_file}'")
         gdb.execute("set logging redirect on")
         gdb.execute("set logging on")
         return
@@ -1957,7 +1957,7 @@ def __exit__(self, *exc: Any) -> None:
 def enable_redirect_output(to_file: str = "/dev/null") -> None:
     """Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
     gdb.execute("set logging overwrite")
-    gdb.execute(f"set logging file {to_file}")
+    gdb.execute(f"set logging file '{to_file}'")
     gdb.execute("set logging redirect on")
     gdb.execute("set logging on")
     return
@@ -2138,7 +2138,7 @@ def gef_execute_gdb_script(commands: str) -> None:
 
     fname = pathlib.Path(fname)
     if fname.is_file() and os.access(fname, os.R_OK):
-        gdb.execute(f"source {fname}")
+        gdb.execute(f"source '{fname}'")
         fname.unlink()
     return
 
@@ -3402,7 +3402,7 @@ def get_filepath() -> Optional[str]:
 
 def get_function_length(sym: str) -> int:
     """Attempt to get the length of the raw bytes of a function."""
-    dis = gdb.execute(f"disassemble {sym}", to_string=True).splitlines()
+    dis = gdb.execute(f"disassemble '{sym}'", to_string=True).splitlines()
     start_addr = int(dis[1].split()[0], 16)
     end_addr = int(dis[-2].split()[0], 16)
     return end_addr - start_addr
@@ -9538,7 +9538,7 @@ def load_extra_plugins(self) -> int:
         def load_plugin(fpath: pathlib.Path) -> bool:
             try:
                 dbg(f"Loading '{fpath}'")
-                gdb.execute(f"source {fpath}")
+                gdb.execute(f"source '{fpath}'")
             except Exception as e:
                 warn(f"Exception while loading {fpath}: {str(e)}")
                 return False
@@ -10154,11 +10154,11 @@ def tmux_setup(self) -> None:
         pane, pty = subprocess.check_output([tmux, "splitw", "-h", '-F#{session_name}:#{window_index}.#{pane_index}-#{pane_tty}', "-P"]).decode().strip().split("-")
         atexit.register(lambda : subprocess.run([tmux, "kill-pane", "-t", pane]))
         # clear the screen and let it wait for input forever
-        gdb.execute(f"! {tmux} send-keys -t {pane} 'clear ; cat' C-m")
-        gdb.execute(f"! {tmux} select-pane -L")
+        gdb.execute(f"!'{tmux}' send-keys -t {pane} 'clear ; cat' C-m")
+        gdb.execute(f"!'{tmux}' select-pane -L")
 
         ok(f"Setting `context.redirect` to '{pty}'...")
-        gdb.execute(f"gef config context.redirect {pty}")
+        gdb.execute(f"gef config context.redirect '{pty}'")
         ok("Done!")
         return
 
@@ -10178,13 +10178,13 @@ def screen_setup(self) -> None:
             f.write(f"screen bash -c 'tty > {tty_path}; clear; cat'\n")
             f.write("focus left\n")
 
-        gdb.execute(f"! {screen} -r {sty} -m -d -X source {script_path}")
+        gdb.execute(f"!'{screen}' -r '{sty}' -m -d -X source '{script_path}'")
         # artificial delay to make sure `tty_path` is populated
         time.sleep(0.25)
         with open(tty_path, "r") as f:
             pty = f.read().strip()
         ok(f"Setting `context.redirect` to '{pty}'...")
-        gdb.execute(f"gef config context.redirect {pty}")
+        gdb.execute(f"gef config context.redirect '{pty}'")
         ok("Done!")
         os.unlink(script_path)
         os.unlink(tty_path)
@@ -10241,7 +10241,7 @@ def __install_extras_script(self, script: str) -> bool:
                 fd.flush()
 
         old_command_set = set(gef.gdb.commands)
-        gdb.execute(f"source {fpath}")
+        gdb.execute(f"source '{fpath}'")
         new_command_set = set(gef.gdb.commands)
         new_commands = [f"`{c[0]}`" for c in (new_command_set - old_command_set)]
         ok(f"Installed file '{fpath}', new command(s) available: {', '.join(new_commands)}")
@@ -11111,7 +11111,7 @@ def setup(self) -> None:
         self.gdb.setup()
         tempdir = self.config["gef.tempdir"]
         gef_makedirs(tempdir)
-        gdb.execute(f"save gdb-index {tempdir}")
+        gdb.execute(f"save gdb-index '{tempdir}'")
         return
 
     def reset_caches(self) -> None:
@@ -11209,4 +11209,4 @@ def reset_caches(self) -> None:
     # restore saved breakpoints (if any)
     bkp_fpath = pathlib.Path(gef.config["gef.autosave_breakpoints_file"]).expanduser().absolute()
     if bkp_fpath.exists() and bkp_fpath.is_file():
-        gdb.execute(f"source {bkp_fpath}")
+        gdb.execute(f"source '{bkp_fpath}'")

From fe7778cb6eec7fd3e8f0e4d04e52355a846ff4c3 Mon Sep 17 00:00:00 2001
From: Grazfather <grazfather@gmail.com>
Date: Fri, 25 Aug 2023 20:22:04 -0400
Subject: [PATCH 2/4] Handle GDB hating quotes for set logging

---
 gef.py | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/gef.py b/gef.py
index def468938..9d31678b0 100644
--- a/gef.py
+++ b/gef.py
@@ -1935,14 +1935,15 @@ def __exit__(self, *exc: Any) -> None:
 
 
 class RedirectOutputContext:
-    def __init__(self, to: str = "/dev/null") -> None:
-        self.redirection_target_file = to
+    def __init__(self, to_file: str = "/dev/null") -> None:
+        if " " in to_file: raise Exception("Target filepath cannot contain spaces")
+        self.redirection_target_file = to_file
         return
 
     def __enter__(self) -> None:
         """Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
         gdb.execute("set logging overwrite")
-        gdb.execute(f"set logging file '{self.redirection_target_file}'")
+        gdb.execute(f"set logging file {self.redirection_target_file}")
         gdb.execute("set logging redirect on")
         gdb.execute("set logging on")
         return
@@ -1956,8 +1957,9 @@ def __exit__(self, *exc: Any) -> None:
 
 def enable_redirect_output(to_file: str = "/dev/null") -> None:
     """Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
+    if " " in to_file: raise Exception("Target filepath cannot contain spaces")
     gdb.execute("set logging overwrite")
-    gdb.execute(f"set logging file '{to_file}'")
+    gdb.execute(f"set logging file {to_file}")
     gdb.execute("set logging redirect on")
     gdb.execute("set logging on")
     return
@@ -8786,7 +8788,7 @@ def get_frames_size(self) -> int:
     def trace(self, loc_start: int, loc_end: int, depth: int) -> None:
         info(f"Tracing from {loc_start:#x} to {loc_end:#x} (max depth={depth:d})")
         logfile = f"{self['tracefile_prefix']}{loc_start:#x}-{loc_end:#x}.txt"
-        with RedirectOutputContext(to=logfile):
+        with RedirectOutputContext(to_file=logfile):
             hide_context()
             self.start_tracing(loc_start, loc_end, depth)
             unhide_context()
@@ -9184,7 +9186,7 @@ def do_invoke(self, _: List[str]) -> None:
 
         nb_installed_breaks = 0
 
-        with RedirectOutputContext(to="/dev/null"):
+        with RedirectOutputContext(to_file="/dev/null"):
             for function_name in dangerous_functions:
                 argument_number = dangerous_functions[function_name]
                 FormatStringBreakpoint(function_name, argument_number)

From 9c6d0fcfb9c8715139fe6523b37385bd3b9fdd5f Mon Sep 17 00:00:00 2001
From: Grazfather <grazfather@gmail.com>
Date: Fri, 25 Aug 2023 21:05:03 -0400
Subject: [PATCH 3/4] Fix more gdb execute we can't quote

---
 gef.py | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/gef.py b/gef.py
index 9d31678b0..ecd88c018 100644
--- a/gef.py
+++ b/gef.py
@@ -2140,7 +2140,7 @@ def gef_execute_gdb_script(commands: str) -> None:
 
     fname = pathlib.Path(fname)
     if fname.is_file() and os.access(fname, os.R_OK):
-        gdb.execute(f"source '{fname}'")
+        gdb.execute(f"source {fname}")
         fname.unlink()
     return
 
@@ -10160,7 +10160,7 @@ def tmux_setup(self) -> None:
         gdb.execute(f"!'{tmux}' select-pane -L")
 
         ok(f"Setting `context.redirect` to '{pty}'...")
-        gdb.execute(f"gef config context.redirect '{pty}'")
+        gdb.execute(f"gef config context.redirect {pty}")
         ok("Done!")
         return
 
@@ -10186,7 +10186,7 @@ def screen_setup(self) -> None:
         with open(tty_path, "r") as f:
             pty = f.read().strip()
         ok(f"Setting `context.redirect` to '{pty}'...")
-        gdb.execute(f"gef config context.redirect '{pty}'")
+        gdb.execute(f"gef config context.redirect {pty}")
         ok("Done!")
         os.unlink(script_path)
         os.unlink(tty_path)
@@ -10243,7 +10243,7 @@ def __install_extras_script(self, script: str) -> bool:
                 fd.flush()
 
         old_command_set = set(gef.gdb.commands)
-        gdb.execute(f"source '{fpath}'")
+        gdb.execute(f"source {fpath}")
         new_command_set = set(gef.gdb.commands)
         new_commands = [f"`{c[0]}`" for c in (new_command_set - old_command_set)]
         ok(f"Installed file '{fpath}', new command(s) available: {', '.join(new_commands)}")
@@ -11211,4 +11211,4 @@ def reset_caches(self) -> None:
     # restore saved breakpoints (if any)
     bkp_fpath = pathlib.Path(gef.config["gef.autosave_breakpoints_file"]).expanduser().absolute()
     if bkp_fpath.exists() and bkp_fpath.is_file():
-        gdb.execute(f"source '{bkp_fpath}'")
+        gdb.execute(f"source {bkp_fpath}")

From 45c7dacfaa7878004d7fa78374cc3a9f55aa0463 Mon Sep 17 00:00:00 2001
From: Grazfather <grazfather@gmail.com>
Date: Sat, 26 Aug 2023 11:39:19 -0400
Subject: [PATCH 4/4] Raise ValueErrors

---
 gef.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/gef.py b/gef.py
index ecd88c018..c152ce45f 100644
--- a/gef.py
+++ b/gef.py
@@ -1936,7 +1936,7 @@ def __exit__(self, *exc: Any) -> None:
 
 class RedirectOutputContext:
     def __init__(self, to_file: str = "/dev/null") -> None:
-        if " " in to_file: raise Exception("Target filepath cannot contain spaces")
+        if " " in to_file: raise ValueEror("Target filepath cannot contain spaces")
         self.redirection_target_file = to_file
         return
 
@@ -1957,7 +1957,7 @@ def __exit__(self, *exc: Any) -> None:
 
 def enable_redirect_output(to_file: str = "/dev/null") -> None:
     """Redirect all GDB output to `to_file` parameter. By default, `to_file` redirects to `/dev/null`."""
-    if " " in to_file: raise Exception("Target filepath cannot contain spaces")
+    if " " in to_file: raise ValueEror("Target filepath cannot contain spaces")
     gdb.execute("set logging overwrite")
     gdb.execute(f"set logging file {to_file}")
     gdb.execute("set logging redirect on")