Repository navigation
feat(libc): implement getdelim and getline - #12920
Conversation
|
@heditrigui thanks. Using the guest application heap and holding the stream lock look right. A few differences from FreeBSD 11.4's
For the tests: please add a line longer than the initial 128-byte buffer (the growth path isn't exercised yet), the |
|
Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.
|
|
@oneandonlydean Thank you for the thorough and detailed review! In commit faf2386:
|
rooklz
left a comment
There was a problem hiding this comment.
Thanks @heditrigui. I checked head faf2386aa9 on macOS arm64 against FreeBSD 11.4 lib/libc/stdio/getdelim.c @8c639945a4. There are two blockers and two smaller differences from FreeBSD.
1. Build break (this is the windows failure). StandardStreams.cpp on main opens extern "C" { at L84 and doesn't close it before the new code. That puts LibcDetail::ExpandLineBufferCapacity inside C linkage, while FileStream.hpp:413 declares it with C++ linkage:
StandardStreams.cpp:259:6: error: conflicting declaration of 'bool LibcDetail::ExpandLineBufferCapacity(...)' with 'C' linkage (g++ 15, windows job 123543241167)
StandardStreams.cpp:259:6: error: declaration of 'ExpandLineBufferCapacity' has a different language linkage (Apple clang, -fsyntax-only)
Every lane that builds libc fails here. The relinker lanes only pass because they never build it. To fix it, close the outer block before your namespace {, and drop the extra } after getline_nid_postfix (the new extern "C" { already wraps both functions). With that change, clang++ -fsyntax-only is clean.
2. The EOVERFLOW test row can't pass once the file compiles. overCap = INT64_MAX with a 16-byte buffer and the line "overflow test\n": pos + 2 > *n is never true, so no growth happens and getline returns 14 with errno 0. I ran the PR's function body verbatim in a harness and got 14 errno 0, but the test requires -1 && errno == 84. FreeBSD also returns 14 here, because expandtofit is only called when len > *capp. I'd drop that row. The ExpandLineBufferCapacity(…, limit) rows already cover the overflow branch.
3. Delimiter comparison. FreeBSD uses memchr(…, delim, …), which compares against (unsigned char)delim. The PR compares an fgetc result in 0..255 with the raw int. In my harness on "a\xE9b\nc":
delim = -23: PR returns 5 (no match, reads to EOF), FreeBSD returns 2.delim = 0x10A: PR returns 5, FreeBSD returns 4 (matches'\n').
Fix: if (ch == static_cast<unsigned char>(delimiter)) break;
4. A null *lineptr with a non-zero *n. FreeBSD sets *linecapp = 0 when *linep == NULL, so the caller's *n is ignored. The PR instead allocates max(*n, 128) bytes. With line = nullptr, n = SIZE_MAX it requests 0x7fffffffffffffff bytes and returns -1/ENOMEM, where FreeBSD returns the line. Fix: *n = 0; std::size_t initialSize = 128;
With 1, 3 and 4 applied (diff below), the harness passes all of the above under ASan+UBSan. It also rechecks the 300-byte growth case (n = 512) and the read error after partial data (-1).
@@
-namespace {
+}
+namespace {
void* SafeAllocate(std::size_t size) {
@@ if (*lineptr == nullptr) {
- std::size_t initialSize = *n >= 128 ? *n : 128;
- if (initialSize > maxLineSize) initialSize = maxLineSize;
+ *n = 0;
+ std::size_t initialSize = 128;
@@
- if (ch == delimiter) break;
+ if (ch == static_cast<unsigned char>(delimiter)) break;
@@ getline_nid_postfix
return getdelim_nid_postfix(lineptr, n, '\n', stream);
}
-}Suggested rows (each one fails on the current head):
FileStream delimStream(std::tmpfile());
Require(fwrite_nid_postfix("a\xE9" "b\nc", 1, 5, &delimStream) == 5);
rewind_nid_postfix(&delimStream);
char* delimLine = nullptr;
size_t delimCap = 0;
Require(getdelim_nid_postfix(&delimLine, &delimCap, -23, &delimStream) == 2);
Require(getdelim_nid_postfix(&delimLine, &delimCap, 0x10A, &delimStream) == 2 && std::strcmp(delimLine, "b\n") == 0);
free_nid_postfix(delimLine);
delimStream.Close();
FileStream hugeStream(std::tmpfile());
Require(fwrite_nid_postfix("x\n", 1, 2, &hugeStream) == 2);
rewind_nid_postfix(&hugeStream);
char* hugeLine = nullptr;
size_t hugeCap = std::numeric_limits<size_t>::max();
Require(getline_nid_postfix(&hugeLine, &hugeCap, &hugeStream) == 2 && hugeCap < 4096);
free_nid_postfix(hugeLine);
hugeStream.Close();Optional notes:
- FreeBSD sets the stream error flag (
__SERR) on every error path, including EINVAL with a validfp, ENOMEM and EOVERFLOW. Here those paths leaveferror()at 0.FileStream::SetError()exists if you want to match. - With a null
stream, FreeBSD dereferences it inFLOCKFILE. Returning EINVAL is an invented result, and the debt line's "Null pointers return EINVAL" covers it. The project rule prefers throwing for unmeasured invalid input (same request as on #12924). - The
conventionscheck fails only because the PR template'sAI-assisted:answer is missing from the body.
How I tested: git fetch upstream pull/12920/head, clang++ -std=gnu++20 -fsyntax-only of StandardStreams.cpp (RED on the head, clean with the fix), plus a standalone ASan+UBSan harness containing the PR's namespace {…} … getline_nid_postfix block verbatim and a minimal FileStream/heap shim (heap throws bad_alloc like requireAllocation). I couldn't build the full guest_standard_streams target here because the submodules aren't initialized, so please post that target's output on the next head.
AI-assisted: yes
|
Windows build of this head ( The definition AI-assisted: yes (Claude Code). |
|
@rooklz @JJenkx Thank you both for the quick review and diagnosis! In commit
|
rooklz
left a comment
There was a problem hiding this comment.
Re-checked head eba4ca6858. Points 1, 2, 3 and 4 from my last review are all fixed as suggested, and the two rows I proposed are in the test verbatim.
- Build:
clang++ -std=gnu++20 -fsyntax-onlyis now clean on bothStandardStreams.cpp(it was RED onfaf2386aa9) andGuestStandardStreams.cpp.LibcDetail::ExpandLineBufferCapacityhas C++ linkage again, and both exports stay insideextern "C". - Behaviour: the
namespace {…getline_nid_postfixblock, copied verbatim into a standalone ASan+UBSan harness on macOS arm64, passes these cases:-23and0x10Adelimiters: returns 2, then"b\n"- null line with
n = SIZE_MAX: returns 2 and the capacity is small - 300-byte growth from a 4-byte buffer
- exact fill (
"abcd"into a 4-byte buffer) - read error after partial data returns -1
- EOF on a null or zero-capacity buffer writes
'\0' - closed stream gives EBADF, null argument gives EINVAL
- lock/unlock balanced on every path
- Mutants: I ran 10 single-line mutants. 7 are killed. The other 3 are equivalent:
- dropping
*n = 0: it gets overwritten by*n = initialSize initialSize = max(*n, 128):*nis already 0 at that point- dropping
needed > limit: thenext > limitcheck covers it, sincenext >= needed
- dropping
- Gates:
git diff --check,merge-treeagainstbb04a4f1eaandcheck_conventions --base upstream/mainare all clean.pr_overlaponly reports the usualdocs/dev/debt/libc.mdL242 append-point neighbours (merge order) and no shared exports.
The earlier optional notes are still open but don't block this: __SERR isn't set on the error paths, and a null stream returns EINVAL where the project would rather throw. A follow-up is fine for both.
I still can't build guest_standard_streams here because the submodules aren't initialized, so the libc lanes in CI will be the final check.
AI-assisted: yes
|
@heditrigui thanks for the allocation, delimiter, growth and linkage fixes. Two points remain at eba4ca6. The new failed-growth fixture in GuestStandardStreams.cpp:409–415 starts with an eight-byte buffer containing "preserve" and reads "alloc test line\n". getdelim stores seven characters before it attempts the failing growth, leaving "alloc te". The assertion that all eight bytes still equal "preserve" therefore contradicts the submitted implementation. Preserve and assert the original pointer and capacity on realloc failure, and test the allowed partial-buffer contents rather than requiring the read to be transactional. Please run the actual registered guest_standard_streams case after fixing that assertion; the production-library compile job does not execute it. The earlier stream-error-state request is still open: ENOMEM/EOVERFLOW paths return -1 and set errno, but do not mark the valid stream as errored. Please implement and test the stated FreeBSD error-state behavior, including allocation failure and a controlled read error after partial data. The current error fixture pre-sets the stream error before reading; it does not inject a midstream read failure. |
|
@oneandonlydean Thank you for the review and guidance on FreeBSD error-state semantics! Updated in this head:
Conventions and header audit passed cleanly. |
b72b617 to
e007643
Compare
|
@heditrigui thanks for correcting the buffer contents after a failed growth, adding stream error flags on allocation/overflow failures, and adding a real descriptor-backed partial-read error case. These address the latest source/test points. The earlier FreeBSD error-state point is not fully covered: StandardStreams.cpp:274–277 returns EINVAL for a null lineptr or capacity with a valid open stream without setting that stream's error flag. FreeBSD 11.4 getdelim.c:118–120 takes the error path, which sets __SERR at 157–159. Please mark the valid stream errored for those two invalid arguments and test ferror after clearing the flag between cases; the null-stream defensive path remains distinct. Please also provide the actual registered guest_standard_streams runtime result, including the allocation and new partial-read controls. The body still lists source/header checks and fixture additions rather than that execution. The red macOS write-watch checks come from a duplicate test name on current main (fixed by #13220), not from this PR. |
e007643 to
03178d3
Compare
|
@oneandonlydean Thank you for the follow-up review! Updated in head
Conventions and git diff checks passed cleanly. |
03178d3 to
722cd58
Compare
|
Reviewed at |
|
@heditrigui one more thing alongside the review points above: |
✅ AMD GPU test: passedPR head
Unstable on main (9, these also failed in recent main runs on this machine; not counted against this PR)Failing on main too (11, not counted against this PR)Passed on retry (3, failed in the parallel run, passed when re-run with a 360 s timeout; not counted against this PR)Validation IDs already present on main (8 IDs in 777 tests)Skipped (62)ReproduceAutomated build and test on a contributor's AMD machine; it does not replace upstream CI. A new comment is posted for each new push. Full logs. |
|
The hosted The abort is the second pushback in this PR's new mid-read error case in setvbuf_nid_postfix(midReadStream, nullptr, 2, 0);
Require(ungetc_nid_postfix('b', midReadStream) == 'b');
Require(ungetc_nid_postfix('a', midReadStream) == 'a');
The selection was 4,072 tests: 3,992 passed, 76 skipped and 4 failed.
AI-assisted: yes. Claude Code ran the builds and tests, located the failing check and drafted this comment; a separate review agent checked it against the logs. The results are from this machine. |
|
@adam25136 Thank you very much for the pinpoint diagnostic and toolchain reproducer! Updated in head
|
❌ AMD GPU test: failedPR head
Failing testsThis PR changes test files, so each failing test was also built and run on main with only the PR's test changes applied. ✅ there means the failure comes from the PR's other changes; ❌ means the test fails on main too, so this run does not show the PR caused it.
agc_graphics_profile_draw: Timeout (also failed when re-run alone), assertion and diagnosticsUnstable on main (7, these also failed in recent main runs on this machine; not counted against this PR)Failing on main too (10, not counted against this PR)Passed on retry (1, failed in the parallel run, passed when re-run with a 360 s timeout; not counted against this PR)Validation IDs already present on main (4 IDs in 805 tests)Skipped (71)ReproduceAutomated build and test on a contributor's AMD machine; it does not replace upstream CI. A new comment is posted for each new push. Full logs. |
|
Head The selection was 4,098 tests: 4,083 passed, 12 skipped and 3 failed.
One gap remains, since the fix changes the test rather than AI-assisted: yes. Claude Code ran the builds and tests and drafted this comment; a separate review agent checked it. |
|
@adam25136 Thank you for verifying the Windows run and for the suggestion! Updated in head
|
❌ AMD GPU test: failedPR head
Failing testsThis PR changes test files, so each failing test was also built and run on main with only the PR's test changes applied. ✅ there means the failure comes from the PR's other changes; ❌ means the test fails on main too, so this run does not show the PR caused it.
agc_graphics_profile_draw: Timeout (also failed when re-run alone), assertion and diagnosticsUnstable on main (5, these also failed in recent main runs on this machine; not counted against this PR)Failing on main too (10, not counted against this PR)Validation IDs already present on main (4 IDs in 805 tests)Skipped (71)ReproduceAutomated build and test on a contributor's AMD machine; it does not replace upstream CI. A new comment is posted for each new push. Full logs. |
ahmadmuj
left a comment
There was a problem hiding this comment.
Checked head 166570e1087d69fbd0c11a975cff7d46e06c9f42, base e772fb25cc72ee5faf77847f06bbc69533016e82. Built the actual libc module on Linux; all five guest_standard_streams tests pass.
One extra byte is lost when growth fails. With unbuffered input ABCDEFGH\n, an eight-byte guest buffer, and a one-shot realloc failure, getline returns -1/ENOMEM and sets ferror. The pointer/capacity stay unchanged, bytes 0-6 contain ABCDEFG, and byte 7 keeps its canary. After restoring allocation and clearing the error, exported fgetc returns newline: H is gone. With ABCDEFG\nZ, the lost byte is the delimiter and the next read returns Z.
The declared FreeBSD source attempts sappend before advancing/refilling the input. Its unbuffered setup selects one-byte refills. A source adapter preserving that order leaves H or the delimiter for the next read. Custom : cases reproduce the difference; successful-growth and no-growth controls pass.
Could you preserve the current input byte when growth fails and add a next-byte assertion? This comparison covers unbuffered input against the pinned FreeBSD source, not arbitrary buffered positions or measured console behavior.
|
@ahmadmuj Thank you very much for the thorough review, testing the Linux build, and tracing the unbuffered stream behavior! Updated in head
|
|
Hi @heditrigui, thanks for the getdelim work. After this merged, We are reverting the merge in #17531 to get main's Windows job green again. You're very welcome to open it again as a new PR on current main. A Windows run that passes |
…reams This reverts merge commit b7caf86, reversing changes made to dd7c8de. Since this merge, guest_standard_streams aborts on Windows with 0xc0000409 (abort() in libc.prx after the fscanf checks) on main and on every later run of it. The change was green on its own older base, so it interacts with something merged since. Reverting puts main back to green; the change is welcome again as a new PR on current main.
revert(libc): revert getdelim (#12920), red Windows guest_standard_streams
|
@heditrigui, are you planning to open this again? #17459 fixed the Windows I have it re-applied on current
If you'd rather re-land it yourself, I'm happy to send these over. Otherwise I can open it, crediting you as the original author. |
What
Export
getdelim(NIDe0iUSkl6-uU) andgetline(NIDEFEe73sCz-8) inlibc, implementing POSIX.1-2008 and FreeBSD 11.4getdelim.cstream reading.ApplicationHeapAllocate_nid_no_patch,ApplicationHeapReallocate_nid_no_patch) and synchronizes throughflockfile.errnotoEINVAL(22).errnotoEBADF(9).unsigned char), or stops at EOF without a delimiter, terminating with\0in both cases.docs/dev/debt/libc.md.Tested
python tools/check_conventions.py --base upstream/mainpassed with 0 findings.python core/libs/tests/test_public_headers.py --audit-onlyverified all 373 libraries and 14,002 exports (+2 exports) with unique declarations.core/libs/tests/GuestStandardStreams.cpp(CheckGetdelimAndGetline):nullptrlineptr, capacity, and stream return -1 and seterrno = 22).stream.Close(), returns -1 and setserrno = 9).getlineand custom-delimiter chunking viagetdelim(:).feof.feofpreservation.free_nid_postfix.-23and0x10A).*lineptr == nullptrwithcapacity == SIZE_MAXinitializing to default buffer.Checklist