[libc-commits] [libc] [libc][search] implement POSIX `lsearch` function (PR #116870)

via libc-commits libc-commits at lists.llvm.org
Tue Nov 19 14:28:10 PST 2024


================
@@ -0,0 +1,79 @@
+//===-- Unittests for lsearch ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/search/lsearch.h"
+#include "test/UnitTest/Test.h"
+
+int compar(const void *a, const void *b) {
+  return *reinterpret_cast<const int *>(a) != *reinterpret_cast<const int *>(b);
+}
+
+TEST(LlvmLibcLsearchTest, SearchHead) {
+  int list[4] = {1, 2, 3, 4};
+  size_t len = 3;
+  int key = 1;
+  void *ret = LIBC_NAMESPACE::lsearch(&key, list, &len, sizeof(int), compar);
+
+  ASSERT_EQ(static_cast<int *>(ret), &list[0]);
+  ASSERT_EQ(len, static_cast<size_t>(3));
+  ASSERT_EQ(list[1], 2);
+  ASSERT_EQ(list[2], 3);
+  ASSERT_EQ(list[3], 4);
+  ASSERT_EQ(list[3], 4);
+}
+
+TEST(LlvmLibcLsearchTest, SearchMiddle) {
+  int list[4] = {1, 2, 3, 4};
+  size_t len = 3;
+  int key = 2;
+  void *ret = LIBC_NAMESPACE::lsearch(&key, list, &len, sizeof(int), compar);
+  ASSERT_EQ(static_cast<int *>(ret), &list[1]);
+  ASSERT_EQ(len, static_cast<size_t>(3));
+  ASSERT_EQ(list[0], 1);
+  ASSERT_EQ(list[1], 2);
+  ASSERT_EQ(list[2], 3);
+  ASSERT_EQ(list[3], 4);
+}
+
+TEST(LlvmLibcLsearchTest, SearchTail) {
+  int list[4] = {1, 2, 3, 4};
+  size_t len = 3;
+  int key = 3;
+  void *ret = LIBC_NAMESPACE::lsearch(&key, list, &len, sizeof(int), compar);
+  ASSERT_EQ(static_cast<int *>(ret), &list[2]);
+  ASSERT_EQ(len, static_cast<size_t>(3));
+  ASSERT_EQ(list[0], 1);
+  ASSERT_EQ(list[1], 2);
+  ASSERT_EQ(list[2], 3);
+  ASSERT_EQ(list[3], 4);
+}
+
+TEST(LlvmLibcLsearchTest, SearchNonExistent) {
+  int list[4] = {1, 2, 3, 4};
+  size_t len = 3;
----------------
duncpro wrote:

The [glibc implementation](
https://sourceware.org/git/?p=glibc.git;a=blob;f=misc/lsearch.c;h=2783f52b3859aa98a0c277ca1c25a6d068b90ae7;hb=HEAD)  will write out of bounds as well, unless their [`memcpy`](https://sourceware.org/git/?p=glibc.git;a=blob;f=string/memcpy.c;h=f221d4e6000d106fc496d6200422eb21600d1f0c;hb=HEAD) somehow knows the address is OOB and ignores the call.



https://github.com/llvm/llvm-project/pull/116870


More information about the libc-commits mailing list