findprogramvar.c 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. /* This routine will return a pointer to the SYM_ENTRY of the running program,
  2. or NULL in case it isn't found (e.g. if the program was exe-packed).
  3. Note: Do not call anything which may cause a heap compression between when
  4. this routine is called and when the pointer to it is used. Otherwise, the
  5. pointer may become invalid, causing a crash or other random, unexpected
  6. behavior. You can also use FolderOp to avoid this problem.
  7. Contributed by Joel Thompson */
  8. #include <vat.h>
  9. #include <alloc.h>
  10. __ATTR_LIB_C__ SYM_ENTRY *FindProgramVar (void)
  11. {
  12. SYM_ENTRY *symptr;
  13. unsigned char *program_counter;
  14. asm volatile ("bsr 0f\n"
  15. "0:move.l (%%sp)+,%0"
  16. : "=g" (program_counter));
  17. // In case the program is in the ghost space, AND out the extra bit(s).
  18. ((unsigned long) program_counter) &= 0x3FFFF;
  19. for (symptr = SymFindFirst (NULL, FO_RECURSE); symptr; symptr = SymFindNext ())
  20. {
  21. HANDLE handle = symptr->handle;
  22. unsigned char *ptr = HeapDeref (symptr->handle);
  23. if ((program_counter >= ptr) && (program_counter < ptr + HeapSize (handle)))
  24. return symptr;
  25. }
  26. return NULL;
  27. }