0

I'm trying to have a program alter what 'ps' displays as the process's CMD name, using the technique I've seen recommended of simply overlaying the memory pointed to by argv[0]. Here is the sample program I wrote.

#include <iostream>
#include <cstring>
#include <sys/prctl.h>
#include <linux/prctl.h>
using std::cout;
using std::endl;
using std::memcpy;

int main(int argc, char** argv)  {
    if ( argc < 2 ) {
        cout << "You forgot to give new name." << endl;
        return 1;
    }

    // Set new 'ps' command name - NOTE that it can't be longer than
    // what was originally in argv[0]!

    const char *ps_name = argv[1];
    size_t arg0_strlen = strlen(argv[0]);
    size_t ps_strlen = strlen(ps_name);
    cout << "Original argv[0] is '" << argv[0] << "'" << endl;

    // truncate if needed
    size_t copy_len = (ps_strlen < arg0_strlen) ? ps_strlen+1 : arg0_strlen;
    memcpy((void *)argv[0], ps_name, copy_len);
    cout << "New name for ps is '" << argv[0] << "'" << endl;

    cout << "Now spin.  Go run ps -ef and see what command is." << endl;
    while (1) {};
}

The output is:

$ ./ps_test2 foo
Original argv[0] is './ps_test2'
New name for ps is 'foo'
Now spin.  Go run ps -ef and see what command is.

The output of ps -ef is:

5079     28952  9142 95 15:55 pts/20   00:00:08 foo _test2 foo

Clearly, "foo" was inserted, but its null terminator was either ignored or turned into a blank. The trailing portion of the original argv[0] is still visible.

How can I replace the string that 'ps' prints?

Chap
  • 3,649
  • 2
  • 46
  • 84
  • Chap, what is inside the `/proc/$pid/cmdline` special file? Can you do `hexdump -C` of it? – osgx May 01 '14 at 00:05
  • 00000000 66 6f 6f 00 5f 74 65 73 74 00 66 6f 6f 00 62 61 |foo._test.foo.ba| 00000010 72 00 |r.| – Chap May 01 '14 at 19:34
  • @osgx: Well, I can't seem to format it properly, but it corresponds to tetromino's description below. – Chap May 01 '14 at 19:35

1 Answers1

2

You need to rewrite the entire command line, which in Linux is stored as a contiguous buffer with arguments separated by zeros.

Something like:

size_t cmdline_len = argv[argc-1] + strlen(argv[argc-1]) - argv[0];
size_t copy_len = (ps_strlen + 1 < cmdline_len) ? ps_strlen + 1 : cmdline_len;
memcpy(argv[0], ps_name, copy_len);
memset(argv[0] + copy_len, 0, cmdline_len - copy_len);
tetromino
  • 3,490
  • 1
  • 15
  • 8
  • 1
    That appears to be correct. And I've verified that argv[1..n] point to those null-terminated arguments, which means that I'll end up clobbering argv[1..n]. Something to be aware of. – Chap May 01 '14 at 19:41