Repository navigation
feat(libc): implement lfind and lsearch - #11621
Conversation
Add FreeBSD/POSIX lfind and lsearch for the libc PRX, with explicit guards against null arguments, zero element size, and span arithmetic that would overflow size_t. lsearch validates the existing search range before any comparator call, then separately checks the append capacity so a matched element never requires room for an extra one. Extend guest_search to cover first-match on duplicate keys, zero-count no-op, byte-exact appended payload, zero-count seed, and that the overflow guard fires without touching element memory or invoking the callback. Document the exports in docs/dev/debt/libc.md. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
AGENTS.md allows only #endif and namespace-end comments. Drop the explanatory lines added alongside the new lfind/lsearch exports and their guest_search coverage, and tighten the debt entry below the 1000-character limit flagged by tools/check_conventions.py. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed head 921acc674910090fb1368b6fd313cfc541f54398. The search loops compare the key against elements in table order, return the first match, leave nelp unchanged on a hit, and append/increment only on an lsearch miss. The checked multiplication bounds are applied before element access; the append bound is applied only after a miss. The tests cover duplicate first-match behavior, unchanged data/count on a hit, append payload/count, empty-table behavior, and overflow rejection before comparator or memory access. I also checked the public declaration and debt entry against the implementation.
Validation run locally on Linux (Release): configured the PR worktree, built guest_search_tests (which also built libc.prx), and ran ctest -R ^guest_search$ → 1/1 passed. The public-header audit and all 64 compile batches passed (65/65). Hosted conventions, intake, labels, report, register-context, write-watch, ASan, and the completed relinker jobs pass; hosted Linux/Windows full product builds are skipped by path policy. I attempted the documented manual full-build dispatch, but GitHub denied it because the account lacks repository admin rights. The author reports the focused Windows test; I did not independently rerun it.
|
Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.
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.
|
|
In |
Treat a zero *nelp as a miss before validating key, base, compare or size, matching bsearch so a lookup against a not-yet-allocated table (base null, count zero) returns null instead of throwing. Cover it with a GuestSearch case that exercises null base with zero count and zero comparator calls. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
|
Addressed in a5be9ab on
Diff of the behavior change: void* APS5_VABI lfind_nid_postfix(const void* key, const void* base, size_t* count,
size_t size, int (APS5_VABI *compare)(const void*, const void*)) {
if (!count) throw std::invalid_argument("lfind: null element count");
if (*count == 0) return nullptr;
if (!key || !base || !compare || size == 0)
throw std::invalid_argument("lfind: invalid arguments");
...New test lines (GuestSearch.cpp): calls = 0;
Require(lfind_nid_postfix(&probe, nullptr, &empty, sizeof(Record), Compare) == nullptr);
Require(calls == 0);
AI-assisted: yes (Claude Opus 4.7). |
|
Local test results for a5be9ab, Linux (WSL Ubuntu 22.04, GCC 11.4, Release,
The new zero-count case (null base, AI-assisted (Claude Code). |
|
Manual follow-up to the skipped comparisons in the overlap report (comment6430605462). Reviewed target head: I inspected the listed shared-file patches for all 26 candidates. No duplicate target export/implementation was found in this scoped review. The table records the specific shared-file changes and integration requirements; shared debt/header changes still need to preserve both sides. This is not a claim that every pair merges cleanly or that a combined branch has been built/tested. This follow-up addresses the skipped-comparison request only. Existing CI limitations, dependency ordering and outstanding re-review requirements remain in force; approvals or tests from older heads do not become current-head evidence through this audit. Update: the refreshed bot report added #10002 and #12397. Their listed debt patches are now included below at the recorded heads; the earlier24candidate assessment remains unchanged. This delta review does not close the separate landing-order coordination. Candidate heads, shared files and manual dispositions
AI-assisted: yes (Codex). Current-target delta addendum (October 28): target The refreshed skipped list adds #11270 at Retained #7648 moved to The four compared heads in comment6475613786 are unchanged. Comment6475838866 confirms #11621 first for #9087/#9935/#10270, with those authors retaining the search paragraph and rerunning after integration. #9688's order remains unconfirmed; no agreement is inferred from adjacent debt. Current-head local AI-assisted: yes (Codex). |
|
Follow-up to the actual compared conflicts in overlap comment6430605462, for this PR at I inspected the listed shared-file patches for 4 compared candidates at the heads below. This is separate from the earlier skipped-comparison review.
These scoped findings do not establish clean pairwise merges or a successful combined build/test. They do not clear other review, CI, dependency or current-head verification obligations. @orezraey @JJenkx To settle the landing order required by CONTRIBUTING, I propose #11621 first, then #9087/#9688/#9935/#10270 preserve the search paragraph while reconciling their debt edits. These scoped documentation overlaps do not require their implementations for this search fix. Please confirm or propose another order; this is a proposal, not an agreement. I will record the confirmed order and refresh my affected branches before readiness. AI-assisted: yes (Codex). New compared-scope delta (October 28): #11621 target I reviewed only #12574’s listed Resolve this documentation conflict by retaining both the candidate’s revised constraint-handler paragraph and the complete target search paragraph, including its first-match/append behavior, argument and overflow limits, and unverified console behavior. This scoped review does not validate #12574’s implementation or repeat its reported measurements. It establishes no implementation dependency or landing order and no clean whole-PR merge or combined build/test result. Existing author orders and remaining actions stay as recorded; #9688’s order remains unconfirmed. The separately recorded current-head AI-assisted: yes (Codex). Dependency-chain check: #9935 at October 29 current-main and new compared-scope follow-upCurrent integration I read the complete listed
The current bot scope is not fully cleared: retained candidate heads and newly skipped rows still need current-patch reconciliation. Historical rows and test pins remain unchanged. #9688 now has head AI-assisted: yes (Codex). Current dependency scope clarification — October 29At #11621 #9935 still declares #11621 for merge order only, and its author confirmed #11621 first in comment6475838866. It changes the default handler and its dedicated safe-errors fixture, not either search loop. Its revised handler paragraph and the complete search paragraph must both survive the adjacent documentation edit. #12574 currently at No #9688 author agreement was found. The old proposal remains unanswered; source inspection does not convert it into consent, but it also does not establish a runtime dependency or a standalone requirement to hold this search PR. No duplicate author ping or private combined build was needed to answer this scoped dependency question. Current unrelated bot rows, other integration questions and approvals remain outside this clarification; historical tests retain their original pins. No new test, all-overlaps-clear or readiness claim. AI-assisted: yes (Codex). October 30 - additional scoped overlap follow-throughFrozen target #11621: The source heads that moved during preparation have been refreshed at the exact pins below, including additional actual shared paths discovered in complete file indices. Shared code/declarations and debt text are assessed separately. Retained references remain identified as retained. Shared code and declarationsRefreshed non-debt shared-source scopes for searchTarget #11621 remains
The Locinfo prototypes introduce This is source-only frozen-scope preservation: no clean merge/compile/runtime, arbitrary guest comparator behavior, foreign implementation correctness, author agreement or all captured42-row clearance. The retained sort rows are refreshed because their source scope actually expanded, not because prior tests were retargeted. No new runtime experiment is established by these intersections. Shared debt documentationRefreshed pinned shared libc debt scopes for #11621Target Preserve the target's debt contract verbatim:
Additional current shared-debt content (the affected candidate numbers are explicit):
For search, set A's bsearch_s zero-stride acceptance is a separate documented API contract; do not overwrite lfind/lsearch's zero-size validation or overflow timing with it. These are documentation distinctions, not a fresh candidate-code audit.
The expm1f wording conflict was rechecked at #10229 All source identities use raw Git bytes with explicit UTF-8 decoding. Eleven heads and bases stayed stable across their bounded reads; four omitted primary patches were reconstructed from exact merge-base/head raw blobs and match complete pull-file counts. Existing runtime/console/reviewer evidence retains its original pins. No combined build, runtime, same-export, console/firmware validation, author consent, dependency or readiness conclusion follows from this shared-document review. No tests/code/cache/refs/public/central state were changed. These are pinned shared-source preservation findings only. Existing runtime evidence keeps its tested commits and platforms. No combined build/runtime, console measurement, whole-table clearance, author consent or new implementation dependency follows from sharing these files; unshared foreign implementations are outside this note. Other retained-head and review/CI obligations remain separate. AI-assisted: yes (Codex). Scoped libc API preservation follow-up — #11621Source-only review against owned Preserve exactly:
Apply declarations as scoped edits while preserving our own declarations; copying an older complete header could discard them. This does not establish implementation dependencies, agreed merge order, source compatibility of uninspected files, a successful merge/build, or runtime/console behavior. Other table paths and outstanding integration obligations remain separate. AI-assisted (Claude Code). Bounded libc debt-source supplement for #11621Target source Keep lfind/lsearch POSIX/FreeBSD first-match and append-on-miss semantics; the console/export uncertainty, null/zero validation, before-access span overflow and after-scan append overflow remain as recorded. The selected added/deleted debt paragraphs concern the following separate subjects; none replaces this target's own debt paragraph. During composition preserve both, and resolve overlapping foreign replacement paragraphs against the actual implementation rather than restoring stale text from hunk context.
Specific source distinctions:
This is AI-assisted source/documentation review. Shared prose supplies no new prerequisite, author consent or runtime qualification. Existing source/interface, CI and explicit dependency obligations remain separate. Main refresh at
|
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
CI at eb364c8 (the main refresh above): 16 jobs pass, including all macOS |
|
Linux check for this head, since PR CI skips the Linux test jobs: |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What
Implement
lfindandlsearchfor the libc PRX, matching POSIX.1-2008 and FreeBSD 11lsearch.c: linear scan returning the first matching element, and forlsearch, append the key and increment*nelpon a miss. A nullnelpthrowsstd::invalid_argument.lfindreturns null for*nelp == 0before checking unused arguments. For nonemptylfindand everylsearchcall, nullbase/key/compareor a zerosizethrowstd::invalid_argument. A*nelp * sizespan pastSIZE_MAXthrowsstd::overflow_errorbefore comparator calls or element access. Forlsearch, a successful match returns immediately; only after the linear scan finishes with no match does the append path check that(*nelp + 1) * sizestill fits inSIZE_MAX, so an existing-element match never requires space for an extra element. Documented indocs/dev/debt/libc.md.Tested
Main refresh at
eb364c8536b8(2026-11-02)Head
eb364c8536b83b72d8f8754a75488bb0ed2e198aordinarily merges previous head0aecada0f0fe8dd2ea79a85f5983d7fb1ce34b2ewith upstream main88e804b0a7df1f1ac373a9e2f72fb378d925fdd4, after #9688 rewrote the neighbouringqsort_sentry indocs/dev/debt/libc.md. That entry was the only conflict: this PR'slfind and lsearchentry stays directly before main's new text, which is kept verbatim. The diff against main is still the four owned files, and its added lines are identical to the previous head's.tools/check_conventions.pyfrom this main passed. No new local build or runtime result is claimed for this head; hosted CI at this head is pending after push.Main refresh at
0aecada0f0fe(2026-11-01)Head
0aecada0f0fe8dd2ea79a85f5983d7fb1ce34b2e/ tree5e2ad2f2207125ea17b4c9d8571ad941f94ed4b1ordinarily merges previous public headb8106dd96f42c6ba387036d6d06bc7faa1daf6dcwith upstream mainb6e3f68173c767f692f6c04eef04c73eab424e04. #13220 has landed: its original commite9f09f54fabb6408d3e2711b8df10c10112ab00eis an ancestor of that main, so the write-watch registration fix now comes from main and this PR no longer changescore/libs/tests/write_watch/CMakeLists.txt. The remaining diff against main is the four owned files (Api.hpp,FileAndHeap.cpp,GuestSearch.cpp,docs/dev/debt/libc.md); its added and removed lines in those files are identical to the previous head's changes. Git's three-way merge was clean; GitHub reported the previous head as conflicting, and a merge using only the older main base conflicts on that shared CMake file.tools/check_conventions.pyfrom this main passed against this head. No new local build or runtime result is claimed for this head; hosted CI at this head is pending after push. Earlier results below keep their original pins.Main refresh at
e4b645a6f531Head
e4b645a6f5316e9aff461654f7f5dcb9b43000c9, tree45ac9db4e287db5761749db5cbaa23491e11f121, ordinarily merges0b349fa4c140634267345d7d43ee18cb02de48b8with mainc0fb4a6aad1012b7e2abecaf2949e3d26c0e525d, observed at 2026-10-30 20:15:30 UTC; published4eff863bc8d0a6d6b2388cd4083bb9c5636f62a7remains an ancestor. This is the documented main baseline for this refresh; later remote-main advances are not certified. The four owned contribution files and their additions remain unchanged. Earlier evidence below keeps its original pins.This new head has source-equivalence evidence: all 82 direct compiled libc/search/nid_patcher source inputs match tested
0b349fa4c140634267345d7d43ee18cb02de48b8, and the libc, NID and third-party source trees match. This is not a new-head binary or test pass. Runtime evidence stays at that exact0b349fa4head: Windows/WinLibs GCC 15.2.0 r7 and WSL Ubuntu 22.04/GCC 11.4, Release, focused build andctest -R '^(guest_search|public_headers)$' -V -j1 --repeat until-fail:3 --timeout 30 --no-tests=errorpassed 12 selected executions across both OS = 6 native guest runs + 6 audit-only header runs, with no failures/skips. No fresh global-header audit ate4b645a6is claimed.The #11621-before-#9935-before-#12574 order, other scoped/shared-file qualifications, future combined validation, reviewer acceptance and actual upstream landing remain separate. The historical approval at
921acc6is not approval of this new head.The audit-only case retains its generated 90-second timeout; the 64 header compile batches are excluded. Fresh hosted CI at the new head is pending after push. No new console, GPU, title, macOS, whole-product or full-suite result is claimed.
Current main integration:
4eff863bc8d0a6d6b2388cd4083bb9c5636f62a7, tree33e9ef395f6582282fd4a72b579efc15480547f4, normally merges main4c8cff191609bc5f28bf9ee2f93672b531285aa4into published head9e09e7efe714275ca7cce7b2f48c3282b38bee07. The owned implementation, declaration and fixture additions are unchanged.Windows 11, WinLibs GCC 15.2.0 r7, Release:
cmake --build build --target guest_search_tests --parallel 2passes.ctest --test-dir build -R '^(guest_search|public_headers)$' -V --repeat until-fail:3passes 2/2 cases, each three repetitions (six passes, no skips), in 46.62 seconds. Conventions against current main pass. No fresh Linux, console, full-suite, title or GPU result is claimed.The historical evidence below retains its original pins/toolchains. The declared #11621-before-#9935-before-#12574 chain remains visible in the later PRs. Current #9688 at
1c8ac1874c0ed5ccafef5112d59da6739d4a2fb6changes independent qsort/qsort_s helpers and adjacent debt; complete shared-file patches show no lfind/lsearch implementation dependency. Its earlier order proposal is unanswered, not an established dependency or a standalone readiness blocker. Preserve both search and sort debt when reconciling the adjacent lines. Other current-head overlap deltas, future combinations and reviewer acceptance remain separately qualified. No all-comments-complete or readiness claim is made.Earlier integrated-head evidence:
Windows 11 Pro, MSYS2 UCRT64 GCC 16.2.0, integrated head
9e09e7efe714275ca7cce7b2f48c3282b38bee07(main319621ba2e578bd053b0baba2877fe70520e0737):cmake --build build-focused --target guest_search_tests --parallel 2passed;ctest --test-dir build-focused -R '^guest_search$' -Vpassed 1/1 (guest_search, test 515, 0.03 sec).python tools/check_conventions.py --base origin/mainpassed after the merge commit. No new Linux or console execution is claimed for this integrated head.Earlier published-head Windows evidence: Windows 11 Pro, MinGW UCRT64 (gcc 16.2.0): built
guest_search_testsand ranctest -R "^guest_search$"->1/1 Test #414: guest_search ..... Passed 0.05 sec. Covers duplicate-first-match, zero-count no-op, byte-exact appended payload, zero-count seed, and that the pre-loop overflow guard fires withcalls == 0and*nelpunchanged. Not run on a console.Linux (WSL Ubuntu 22.04, GCC 11.4, Release) at a5be9ab:
ctest -R '^guest_search$'passed. With the previous head 921acc6 and this head'sGuestSearch.cpp, the same test aborts withlfind: invalid arguments, so the null-base zero-count case is covered by the reallibc.prxbuild.Write-watch CI prerequisite
This update merges the original #13220 commit (e9f09f5) as a second parent. It removes only the duplicate execute-fault and read-fault registrations from the shared write-watch CMake file; the function change remains the first-parent history. Historical function-test results retain their original pins as recorded above; the latest paired runtime evidence for #11621 is at 0b349fa, not e4b645a or this prerequisite merge. A separate configure-only Windows/Linux comparison generated all 18 unique test registrations after the fix, with no fixture build or runtime tests. The hosted macOS checks on this updated head are pending; no macOS runtime result is claimed here.
#13220 landed in upstream main on 2026-11-01. Earlier heads carried its original commit
e9f09f54fabb6408d3e2711b8df10c10112ab00eas a second parent; after the 2026-11-01 main refresh above, the fix comes from main and this PR no longer changes the write-watch CMake file. The historical configure-only comparison and the pins recorded here are unchanged.Candidate qualification at
b8106dd96f42Candidate
b8106dd96f42c6ba387036d6d06bc7faa1daf6dc/ tree452bc21d8a66b75bf5f40d662471a882a1a37512ordinarily merges previous public head9c151b9c5892a1c00749af1614a7bcc5fd04c59dwith frozen upstream-main snapshotf776fddcffd1cfece220ecdd894371988b164f6a. This result is for that frozen composition, not later upstream-main tips. Windows Release with WinLibs GCC 15.2.0 r7, CMake 4.4.4 and Ninja 1.13.2 configured the existingb12250acache and builtguest_search_testswith two jobs.ctest --test-dir b12250a -R '^guest_search$' --output-on-failure -Vpassed 1/1 (guest_search, test 681; 0.04 seconds for the test, 0.14 seconds total), using the freshly built candidatelibc.prxfrom CTest's generated working directory.python tools/check_conventions.py --base origin/maincompleted with 0 errors and two existing debt-length warnings. This is a focused candidate-only Windows result, not a main-vs-candidate comparison, Linux result, full-suite result or hosted-CI result.Checklist
Based on current
main; no other open PR implements the same functionsOne topic per PR; follow-ups go in a new PR
No comments in code except technical debt
Unimplemented paths throw (
NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt fileNo notes, investigation
.mdfiles or images added to the repository (attach them to this PR)New third-party code is a submodule built from source
Generic behaviour, not specific to one title
Depends on: none
Fixes: none
Unblocks: none
GPUs tested: n/a
AI-assisted: yes (Claude Opus 4.7 + Codex)