| 213 | super(Redirect, self).__init__("redirect", gdb.COMMAND_USER) |
| 214 | |
| 215 | def invoke(self, subcommand, from_tty): |
| 216 | old_stdout = gdb.execute("p (int)dup(1)", |
| 217 | to_string=True).split("=")[-1].strip() |
| 218 | try: |
| 219 | time_suffix = time.strftime("%Y%m%d-%H%M%S") |
| 220 | fd, file = tempfile.mkstemp(suffix="-%s.gdbout" % time_suffix) |
| 221 | try: |
| 222 | # Temporarily redirect stdout to the created tmp file for the |
| 223 | # duration of the subcommand. |
| 224 | gdb.execute('p (int)dup2((int)open("%s", 1), 1)' % file, |
| 225 | to_string=True) |
| 226 | # Execute subcommand non interactively. |
| 227 | result = gdb.execute(subcommand, from_tty=False, to_string=True) |
| 228 | # Write returned string results to the temporary file as well. |
| 229 | with open(file, 'a') as f: |
| 230 | f.write(result) |
| 231 | # Open generated result. |
| 232 | if 'GDB_EXTERNAL_EDITOR' in os.environ: |
| 233 | open_cmd = os.environ['GDB_EXTERNAL_EDITOR'] |
| 234 | print("Opening '%s' with %s" % (file, open_cmd)) |
| 235 | subprocess.call([open_cmd, file]) |
| 236 | else: |
| 237 | print("Output written to:\n '%s'" % file) |
| 238 | finally: |
| 239 | # Restore original stdout. |
| 240 | gdb.execute("p (int)dup2(%s, 1)" % old_stdout, to_string=True) |
| 241 | # Close the temporary file. |
| 242 | os.close(fd) |
| 243 | finally: |
| 244 | # Close the originally duplicated stdout descriptor. |
| 245 | gdb.execute("p (int)close(%s)" % old_stdout, to_string=True) |
| 246 | |
| 247 | |
| 248 | Redirect() |