main.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #define _XOPEN_SOURCE 700
  2. #include <fcntl.h>
  3. #include <regex.h>
  4. #include <sys/mman.h>
  5. #include <stdbool.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. #include "maje.h"
  10. static bool matches(const struct majefile * restrict file, const regex_t * restrict re)
  11. {
  12. bool ret = false;
  13. int fd = open(file->path, O_RDONLY);
  14. if (fd == -1) {
  15. return false;
  16. }
  17. void *map = mmap(NULL, (size_t)file->st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  18. if (map == MAP_FAILED) {
  19. close(fd);
  20. return false;
  21. }
  22. if (regexec(re, map, (size_t)file->st.st_size, NULL, 0) == 0) {
  23. ret = true;
  24. }
  25. munmap(map, file->st.st_size);
  26. close(fd);
  27. return ret;
  28. }
  29. char *find_main(struct majefile *sources)
  30. {
  31. regex_t re;
  32. int rc = regcomp(&re, "int[[:space:]]+main[[:space:]]*\\(",
  33. REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
  34. if (rc != 0) {
  35. fprintf(stderr, "maje: regcomp() failed\n");
  36. abort();
  37. }
  38. char *ret = NULL;
  39. for (struct majefile *src = sources; src != NULL; src = src->next) {
  40. if (matches(src, &re)) {
  41. ret = src->path;
  42. break;
  43. }
  44. }
  45. regfree(&re);
  46. return ret;
  47. }