getcwd.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <errno.h>
  4. #include <linux/limits.h>
  5. #include <sys/mman.h>
  6. static char bss_cwd_buf[PATH_MAX];
  7. int main(int argc, char** argv) {
  8. char* cwd = NULL;
  9. /* Option 1: use global variable.
  10. * bss_cwd_buf resides in BSS section which starts right after DATA section;
  11. * under Linux-SGX, BSS section is in a separate VMA from DATA section but
  12. * cwd_buf spans both sections. This checks the correctness of internal
  13. * test_user_memory() spanning several adjacent VMAs. */
  14. cwd = getcwd(bss_cwd_buf, sizeof(bss_cwd_buf));
  15. if (!cwd) {
  16. perror("[bss_cwd_buf] getcwd failed\n");
  17. } else {
  18. printf("[bss_cwd_buf] getcwd succeeded: %s\n", cwd);
  19. }
  20. /* Option 2: use 2-page mmapped variable.
  21. * mmapped_cwd_buf resides on the heap and occupies two consecutive pages;
  22. * we divide the original single VMA into two adjacent VMAs via mprotect().
  23. * This checks the correctness of internal test_user_memory() spanning
  24. * several adjacent VMAs. */
  25. void* mmapped_cwd_buf = mmap(NULL, 4096 * 2, PROT_READ | PROT_WRITE | PROT_EXEC,
  26. MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  27. if (mmapped_cwd_buf == MAP_FAILED) {
  28. perror("mmap failed\n");
  29. return 1;
  30. }
  31. int ret = mprotect(mmapped_cwd_buf, 4096, PROT_READ | PROT_WRITE);
  32. if (ret < 0) {
  33. perror("mprotect failed\n");
  34. return 1;
  35. }
  36. cwd = getcwd(mmapped_cwd_buf, 4096 * 2);
  37. if (!cwd) {
  38. perror("[mmapped_cwd_buf] getcwd failed\n");
  39. } else {
  40. printf("[mmapped_cwd_buf] getcwd succeeded: %s\n", cwd);
  41. }
  42. munmap(mmapped_cwd_buf, 4096 * 2);
  43. return 0;
  44. }