Set stack size with setrlimit() and provoke a stack overflow/segfault

前端 未结 2 724
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 06:24

In the given example below I try to set the stacksize to 1kb.

Why is it now possible to allocate an array of ints on the stack with size 8kb in foo()

2条回答
  •  忘掉有多难
    2021-01-31 06:41

    I think setrlimit moves the "resource pointers" but doesn't apply the new limits until you exec a new copy of the program.

    #include 
    #include 
    #include 
    #include 
    
    void foo(int chk) {
      unsigned ints[2048];
      ints[2047] = 42;
      printf("foo %d: %u\n", chk, ints[2047]);
    }
    
    int main(int argc, char **argv) {
      char *newarg[] = { "argv[0]", "one", "two" };
      char *newenv[] = { NULL };
      struct rlimit lim;
    
      newarg[0] = argv[0];
      getrlimit(RLIMIT_STACK, &lim);
      printf("lim: %d / %d\n", (int)lim.rlim_cur, (int)lim.rlim_max);
      switch (argc) {
        case 1: /* first call from command line */
          lim.rlim_cur = 65536;
          lim.rlim_max = 65536;
          if (setrlimit(RLIMIT_STACK, &lim) == -1) return EXIT_FAILURE;
          newarg[2] = NULL;
          foo(1);
          execve(argv[0], newarg, newenv);
          break;
        case 2: /* second call */
          lim.rlim_cur = 1024;
          lim.rlim_max = 1024;
          if (setrlimit(RLIMIT_STACK, &lim) == -1) return EXIT_FAILURE;
          foo(2);
          execve(argv[0], newarg, newenv);
          break;
        default: /* third call */
          foo(3);
          break;
      }
      return 0;
    }
    

    And a test run:

    $ ./a.out 
    lim: 8388608 / -1
    foo 1: 42
    lim: 65536 / 65536
    foo 2: 42
    Killed
    

    Why the process gets killed before printing the limits (and before calling foo), I don't know.

提交回复
热议问题