Skip to content

Instantly share code, notes, and snippets.

@orca-zhang
Created January 25, 2018 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orca-zhang/eaf066eac2e251d4237863fd26f95f1f to your computer and use it in GitHub Desktop.
Save orca-zhang/eaf066eac2e251d4237863fd26f95f1f to your computer and use it in GitHub Desktop.
A small tool used to inspect memory of remote active process under Linux without any side-effect (MAYBE, as tested).
/*
MIT License
Copyright (c) 2010-2017 <http://ez8.co> <orca.zhang@yahoo.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<sys/ptrace.h>
int main(int argc,char **argv)
{
if(argc < 4) {
fprintf(stdout, "Usage: memhex <pid> <mem_offset> <len>\n");
return 0;
}
int pid = atoi(argv[1]);
long offset = strtoll(argv[2], NULL, 16);
int len = atoi(argv[3]);
fprintf(stdout, "\nmemhex v1.0 - print memory of remote process\n\n");
fprintf(stdout, "Process ID: %d\n", pid);
fprintf(stdout, "Offset: %lx\n", offset);
fprintf(stdout, "Length: %d\n\n", len);
if(ptrace(PTRACE_ATTACH, pid, 0, 0)) {
fprintf(stdout, "Attach process(pid:%d) failed. %m", pid);
return 0;
}
unsigned char buf[0x10] = {'.'};
for(int i = 0; i < len; ++i) {
if((i & 1) == 0) {
unsigned short s = (unsigned short)ptrace(PTRACE_PEEKDATA, pid, (void*)(offset + i), 0);
buf[i & 0xF] = s & 0xFF;
buf[(i & 0xF) + 1] = (s >> 8) & 0xFF;
}
if(((i & 0xF) == 0xF) || (i == len - 1)) {
fprintf(stdout, "%lx: ", offset + (i >> 4 << 4));
int j = 0;
for(; j <= (i & 0xF); ++j)
fprintf(stdout, "%02x ", buf[j]);
for(; j <= 0xF; ++j)
fprintf(stdout, ".. ");
fprintf(stdout, " [");
for(j = 0; j <= 0xF; ++j) {
if(!isprint(buf[j]))
fprintf(stdout, ".");
else
fprintf(stdout, "%c", buf[j]);
buf[j] = '.';
}
fprintf(stdout, "]\n");
}
}
fprintf(stdout, "\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment