Fix sysconf(_SC_ARG_MAX).

ARG_MAX hasn't been a constant since Linux 2.6.23.

Bug: http://lists.landley.net/pipermail/toybox-landley.net/2016-August/008592.html
Change-Id: I1eddb562751604c75b89fa610d79be0655c53693
Test: ran the bionic tests on device and against glibc
diff --git a/tests/unistd_test.cpp b/tests/unistd_test.cpp
index 3a87e88..32b1626 100644
--- a/tests/unistd_test.cpp
+++ b/tests/unistd_test.cpp
@@ -857,6 +857,39 @@
   ASSERT_EQ(online_cpus, sysconf(_SC_NPROCESSORS_ONLN));
 }
 
+TEST(UNISTD_TEST, sysconf_SC_ARG_MAX) {
+  // Since Linux 2.6.23, ARG_MAX isn't a constant and depends on RLIMIT_STACK.
+
+  // Get our current limit, and set things up so we restore the limit.
+  rlimit rl;
+  ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl));
+  uint64_t original_rlim_cur = rl.rlim_cur;
+  if (rl.rlim_cur == RLIM_INFINITY) {
+    rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB.
+  }
+  auto guard = make_scope_guard([&rl, original_rlim_cur]() {
+    rl.rlim_cur = original_rlim_cur;
+    ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
+  });
+
+  // _SC_ARG_MAX should be 1/4 the stack size.
+  EXPECT_EQ(static_cast<long>(rl.rlim_cur / 4), sysconf(_SC_ARG_MAX));
+
+  // If you have a really small stack, the kernel still guarantees "32 pages" (fs/exec.c).
+  rl.rlim_cur = 1024;
+  rl.rlim_max = RLIM_INFINITY;
+  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
+
+  EXPECT_EQ(static_cast<long>(32 * sysconf(_SC_PAGE_SIZE)), sysconf(_SC_ARG_MAX));
+
+  // With a 128-page stack limit, we know exactly what _SC_ARG_MAX should be...
+  rl.rlim_cur = 128 * sysconf(_SC_PAGE_SIZE);
+  rl.rlim_max = RLIM_INFINITY;
+  ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl));
+
+  EXPECT_EQ(static_cast<long>((128 * sysconf(_SC_PAGE_SIZE)) / 4), sysconf(_SC_ARG_MAX));
+}
+
 TEST(UNISTD_TEST, dup2_same) {
   // POSIX says of dup2:
   // If fildes2 is already a valid open file descriptor ...