getcwd.c 1.7 KB

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