Rewrite getcwd()

This change addresses a bug that was reported in #923 where bash on
Windows behaved strangely. It turned out that our weak linking of
malloc() caused bash's configure script to favor its own getcwd()
function, which is implemented in the most astonishing way, using
opendir() and readdir() to recursively construct the current path.

This change moves getcwd() into LIBC_STDIO so it can strongly link
malloc(). A new __getcwd() function is now introduced, so all the
low-level runtime services can still use the actual system call. It
provides the Linux Kernel API convention across platforms, and is
overall a higher-quality implementation than what we had before.

In the future, we should probably take a closer look into why bash's
getcwd() polyfill wasn't working as intended on Windows, since there
might be a potential opportunity there to improve our readdir() too.
This commit is contained in:
Justine Tunney 2023-11-02 13:06:23 -07:00
parent a46ec61787
commit 1eb6484c9c
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
13 changed files with 251 additions and 211 deletions

View file

@ -17,21 +17,57 @@
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/calls/calls.h"
#include "libc/fmt/fmt.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/fmt/libgen.h"
#include "libc/intrin/bits.h"
#include "libc/limits.h"
#include "libc/log/check.h"
#include "libc/macros.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/str/str.h"
#include "libc/testlib/testlib.h"
#include "libc/x/x.h"
void SetUpOnce(void) {
testlib_enable_tmp_setup_teardown();
ASSERT_SYS(0, 0, pledge("stdio rpath cpath fattr", 0));
}
TEST(__getcwd, zero) {
ASSERT_SYS(ERANGE, -1, __getcwd(0, 0));
}
TEST(__getcwd, returnsLengthIncludingNul) {
char cwd1[PATH_MAX];
char cwd2[PATH_MAX];
ASSERT_NE(-1, __getcwd(cwd1, PATH_MAX));
ASSERT_EQ(strlen(cwd1) + 1, __getcwd(cwd2, PATH_MAX));
}
TEST(__getcwd, tooShort_negOneReturned_bufferIsntModified) {
char cwd[4] = {0x55, 0x55, 0x55, 0x55};
ASSERT_SYS(ERANGE, -1, __getcwd(cwd, 4));
ASSERT_EQ(0x55555555, READ32LE(cwd));
}
TEST(__getcwd, noRoomForNul) {
char cwd1[PATH_MAX];
char cwd2[PATH_MAX];
ASSERT_NE(-1, __getcwd(cwd1, PATH_MAX));
ASSERT_SYS(ERANGE, -1, __getcwd(cwd2, strlen(cwd1)));
}
TEST(__getcwd, alwaysStartsWithSlash) {
char cwd[PATH_MAX];
ASSERT_NE(-1, __getcwd(cwd, PATH_MAX));
ASSERT_EQ('/', *cwd);
}
TEST(__getcwd, notInRootDir_neverEndsWithSlash) {
char cwd[PATH_MAX];
ASSERT_NE(-1, __getcwd(cwd, PATH_MAX));
ASSERT_FALSE(endswith(cwd, "/"));
}
TEST(getcwd, test) {
char buf[PATH_MAX];
EXPECT_SYS(0, 0, mkdir("subdir", 0755));