Better Signature Scanning

The other day, stat() was returning a filesize too large for an SO’s mapped memory on AMD64. I had to make a new function to calculate the size. This is what I came up with. Given “allocBase” is a pointer to the allocation base and “memSize” is the output, you can parse /proc/<pid>/maps/. Note that you could also use /proc/self/maps so the getpid() portion isn’t entirely necessary.

	pid_t pid = getpid();
	char file[255];
	char buffer[2048];
	snprintf(file, sizeof(file)-1, "/proc/%d/maps", pid);
	FILE *fp = fopen(file, "rt");
	if (!fp)
		return false;
	void *start=NULL;
	void *end=NULL;
	void *found=NULL;
	while (!feof(fp))
	{
		fgets(buffer, sizeof(buffer)-1, fp);
#if defined AMD64
		sscanf(buffer, "%Lx-%Lx", &start, &end);
#else
		sscanf(buffer, "%lx-%lx", &start, &end);
#endif

		if (start == allocBase)
		{
			found = end;
			break;
		}
	}
	fclose(fp);

	if (!found)
		return false;

	memSize = (unsigned long)end - (unsigned long)start;

Leave a Reply

You must be logged in to post a comment.