Skip to content

Instantly share code, notes, and snippets.

@minkione
Forked from 0bs3n/bincmp.c
Created February 1, 2021 07:52
Show Gist options
  • Save minkione/b11f80e2ed13aaa4d855a362899ca1f4 to your computer and use it in GitHub Desktop.
Save minkione/b11f80e2ed13aaa4d855a362899ca1f4 to your computer and use it in GitHub Desktop.
Quick and dirty program for finding binary sequences from one file in another
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#define LOADOFFSET 0x40000000 // RAM is mapped to 0x40000000, added to account for this
int main(int argc, char **argv) {
FILE *needle;
FILE *haystack;
int search_size;
int phrase_size;
struct stat sfile_info;
if (argc != 5) {
printf("Usage: %s <needle> <haystack> <needle offset> <needle size>\n", argv[0]);
exit(-1);
}
char *search_phrase = argv[1];
char *search_space = argv[2];
int needle_offset = strtol(argv[3], NULL, 0);
int search_phrase_size_limit = strtol(argv[4], NULL, 0);
if (search_phrase_size_limit < 0 || needle_offset < 0) {
puts("Needle length and length must be greater than 0.");
exit(1);
}
needle = fopen(search_phrase, "r");
haystack = fopen(search_space, "r");
stat(search_space, &sfile_info);
search_size = sfile_info.st_size;
if (search_phrase_size_limit > 0) {
phrase_size = search_phrase_size_limit;
} else {
stat(search_phrase, &sfile_info);
phrase_size = sfile_info.st_size;
}
char *needle_buf = malloc(phrase_size);
fseek(needle, needle_offset, SEEK_SET);
fread(needle_buf, 1, phrase_size, needle);
char *haystack_buf = malloc(search_size);
fread(haystack_buf, 1, search_size, haystack);
for (int i = 0; i < search_size; ++i) {
int status = memcmp(needle_buf, haystack_buf + i, phrase_size);
if (status == 0) {
printf("found matching sequence in file %s at offset: 0x%08x\n", search_space, i + LOADOFFSET);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment