Skip to content

Instantly share code, notes, and snippets.

@royvandam
Created November 19, 2014 12:44
Show Gist options
  • Save royvandam/3018650530b708b1a798 to your computer and use it in GitHub Desktop.
Save royvandam/3018650530b708b1a798 to your computer and use it in GitHub Desktop.
Small application for quickly searching the location of files or chunks of a file in a physical disk image.
#define _GNU_SOURCE
#include <string.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#define die(msg) \
do { \
perror(msg); \
exit(EXIT_FAILURE); \
} while (0)
void usage(const char name[]) {
printf("Usage: %s <file> <needle> <offset> <length>\n", name);
}
int main(int argc, char *argv[]) {
if (argc < 5) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
size_t offset = 0;
size_t length = 0;
sscanf(argv[3], "%x", (unsigned int *)&offset);
sscanf(argv[4], "%zu", &length);
int fd;
if ((fd = open(argv[1], O_RDONLY)) < 0)
die("open");
struct stat sb;
if (fstat(fd, &sb) < 0)
die("fstat");
const char *mem = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED)
die("mmap");
const char *mem_end = mem + sb.st_size;
int needle_fd;
if ((needle_fd = open(argv[2], O_RDONLY)) < 0)
die("open");
const char *needle =
mmap(NULL, length, PROT_READ, MAP_SHARED, needle_fd, offset);
if (needle == MAP_FAILED)
die("mmap");
const char *mem_cur = mem;
for (;;) {
mem_cur = memmem(mem_cur, mem_end - mem_cur, needle, length);
if (mem_cur == NULL)
break;
printf("Found match starting @ address: 0x%08zx\n", mem_cur - mem);
++mem_cur;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment