summaryrefslogtreecommitdiff
path: root/main.c
blob: 378614c32339668d1379c88d6f6986eef78995f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <fcntl.h>
#include <regex.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <unistd.h>

#include "maje.h"

static bool matches(const char * restrict path, const regex_t * restrict re)
{
	bool ret = false;

	int fd = open(path, O_RDONLY);
	if (fd == -1) {
		return false;
	}

	struct stat st = { 0 };
	if (fstat(fd, &st) != 0) {
		close(fd);
		return false;
	}

	void *map = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
	if (map == MAP_FAILED) {
		close(fd);
		return false;
	}

	
	if (regexec(re, map, (size_t)st.st_size, NULL, 0) == 0) {
		ret = true;
	}

	munmap(map, st.st_size);
	close(fd);

	return ret;
}

char *find_main(char **sources)
{
	regex_t re;
	int rc = regcomp(&re, "int[[:space:]]+main[[:space:]\\(]", REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
	assert(rc == 0);
	char *ret = NULL;

	for (char **src = sources; *src != NULL; src++) {
		if (matches(*src, &re)) {
			ret = *src;
			break;
		}
	}

	regfree(&re);

	return ret;
}