20

I'm trying to get gdb to run programs with input redirection to stdin. For example, without gdb I would run a program like this:

prog < input.txt

Now in gdb, the usual way to do this is run < input.txt. However, it doesn't work for me and when doing this nothing gets redirected into stdin.

I'm using Windows with MinGW. What could be the problem?

Ran
  • 515
  • 1
  • 5
  • 8

3 Answers3

15

As far back as the late '90s, broken command line redirection was a known and assumed limitation. My suspicion is that it remains that way, since the mingw32 port of gdb still gleefully passes on verbatim all run arguments (including redirects) to the debugee.

Several possible workarounds:

  1. if you have the option to alter the command line interface, then implement bbadour's suggestion
  2. otherwise, if you can easily suspend the process before the point you want to debug at, invoke the debugee (with redirection) from a shell and attach to it while it is already running
  3. otherwise, if you have symbols for the debugee (gcc -g) or you know the address of main() (gcc -Wl,-Map,mapfile) and can set a breakpoint there, proceed in the following manner (tested with mingw gdb 6.8.0):

    # gdb debugee.exe
    (gdb) b main
    (gdb) run non-redirect-arguments-if-any
    (gdb) p dup2(open("/tmp/input.txt", 0), 0) 
    (gdb) c
    
vladr
  • 65,483
  • 18
  • 129
  • 130
  • I'm running into the same problem as the OP. However, I am unable to get the 3rd solution to work for me. This is on `gdb 7.5.50`. How does the 2nd solution work? How do you ensure that when the debuggee is started, it doesn't just run to completion before you have a chance to attach gdb to it? – greatwolf Aug 20 '13 at 03:57
  • @greatwolf it depends on your program specifics. Say, in C/C++ it could be achieved by raising a signal - see https://stackoverflow.com/questions/4326414/set-breakpoint-in-c-or-c-code-programmatically-for-gdb-on-linux – Gleb Varenov Nov 03 '18 at 23:35
2

I ran into the same issue here, and I just got into the habit of adding a command-line argument to allow grabbing input from a file.

e.g. Parsing a "-i ifile" argument using argc and argv to get input from ifile instead of stdin and parsing a "-o ofile" to write output to ofile instead of stdout.

Then I just use those arguments instead of redirects.

The tools that come with MinGW often are not the latest versions and often have features omitted. ::shrug::

bbadour
  • 616
  • 1
  • 4
  • 19
0

Input redirection is supported starting with GDB 8.0. From the NEWS file:

  • Native debugging on MS-Windows supports command-line redirection

    Command-line arguments used for starting programs on MS-Windows can now include redirection symbols supported by native Windows shells, such as '<', '>', '>>', '2>&1', etc. This affects GDB commands such as "run", "start", and "set args", as well as the corresponding MI features.