Page MenuHomeFreeBSD

libc: Add missing size check to qsort_s(3)
ClosedPublic

Authored by hselasky on Apr 19 2023, 10:24 AM.
Tags
None
Referenced Files
Unknown Object (File)
Fri, May 17, 12:54 AM
Unknown Object (File)
Apr 8 2024, 5:36 PM
Unknown Object (File)
Mar 18 2024, 6:03 AM
Unknown Object (File)
Jan 17 2024, 6:25 AM
Unknown Object (File)
Jan 14 2024, 7:01 AM
Unknown Object (File)
Dec 18 2023, 10:54 AM
Unknown Object (File)
Nov 27 2023, 12:51 PM
Unknown Object (File)
Nov 23 2023, 7:43 AM
Subscribers
None

Details

Summary

I find it very strange both the C11 standard
(ISO/IEC 9899:2011, K.3.6.3.2) and the ISO/IEC JTC1 SC22 WG14 N1172 standard,
does not define sorting an array having objects of zero size,
as undefined behaviour.

Add proper checks for this. Found while working on bsort(3).

MFC after: 1 week
Sponsored by: NVIDIA Networking

Diff Detail

Repository
rG FreeBSD src repository
Lint
Lint Not Applicable
Unit
Tests Not Applicable

Event Timeline

hselasky created this revision.

Can I have a quick go on this one?

The qsort code actually use the object size for advancing for loops, so clearly we should catch this regardless of ISO definitions.

Interesting, https://en.cppreference.com/w/c/algorithm/qsort

Unlike other bounds-checked functions, qsort_s does not treat arrays of zero size as a runtime constraint violation and instead returns successfully without altering the array

I'd take this to mean n == 0 but I think it's ambiguous; their previous use of size is in reference to element size.

But Microsoft's docs https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/c-runtime-library/reference/qsort-s.md explicitly show width <= 0 as EINVAL.

I think your change is good.

kib added inline comments.
lib/libc/stdlib/qsort.3
273–277
This revision is now accepted and ready to land.Apr 19 2023, 1:18 PM

@emaste : "<= 0" is for the future, in case the type changes to be signed.

@emaste : "<= 0" is for the future, in case the type changes to be signed.

Yep, my point is just that the MS docs already have exactly this case.

hselasky marked an inline comment as done.

Thank you for your reviews!