From 83ac4caa846166a8b08dd643d18b64c59cabad6d Mon Sep 17 00:00:00 2001
From: "Tobias S. Josefowitz" <tobij@tobij.de>
Date: Tue, 11 Aug 2020 22:39:58 +0200
Subject: [PATCH] Array: array_search() may not change needle's type

If the needle supplied to array_search() was a destructed object,
array_search() would convert it to (PIKE_T_INT,NUMBER_DESTRUCTED)-type 0
in-place.

Since array_search() is sometimes called with the needle residing in
another array - for example when ORing arrays - this would introduce
PIKE_T_INT items into such arrays without reflecting this in said
array's type_field.

If the type_field would then later on (still) only have BIT_OBJECT set,
we would call free_object() on the thus introduced PIKE_T_INT when
freeing array items, leading straight to a segmentation fault.
---
 src/array.c | 7 ++++---
 src/array.h | 2 +-
 2 files changed, 5 insertions(+), 4 deletions(-)

diff --git a/src/array.c b/src/array.c
index be6a437049..04f53fcf7e 100644
--- a/src/array.c
+++ b/src/array.c
@@ -646,7 +646,8 @@ PMOD_EXPORT struct array *array_remove(struct array *v,INT32 index)
   }
 }
 
-static ptrdiff_t fast_array_search( struct array *v, struct svalue *s, ptrdiff_t start )
+static ptrdiff_t fast_array_search( struct array *v, const struct svalue *s,
+                                    ptrdiff_t start )
 {
   ptrdiff_t e;
   struct svalue *ip = ITEM(v);
@@ -663,7 +664,7 @@ static ptrdiff_t fast_array_search( struct array *v, struct svalue *s, ptrdiff_t
  * @param start the index to start search at
  * @return the index if found, -1 otherwise
  */
-PMOD_EXPORT ptrdiff_t array_search(struct array *v, struct svalue *s,
+PMOD_EXPORT ptrdiff_t array_search(struct array *v, const struct svalue *s,
 				   ptrdiff_t start)
 {
 #ifdef PIKE_DEBUG
@@ -673,7 +674,7 @@ PMOD_EXPORT ptrdiff_t array_search(struct array *v, struct svalue *s,
 #ifdef PIKE_DEBUG
   if(d_flag > 1)  array_check_type_field(v);
 #endif
-  check_destructed(s);
+  safe_check_destructed(s);
 
   /* Why search for something that is not there?
    * however, we must explicitly check for searches
diff --git a/src/array.h b/src/array.h
index 6e820bc3d2..94fd8e1538 100644
--- a/src/array.h
+++ b/src/array.h
@@ -125,7 +125,7 @@ void o_append_array(INT32 args);
 PMOD_EXPORT struct array *resize_array(struct array *a, INT32 size);
 PMOD_EXPORT struct array *array_shrink(struct array *v, ptrdiff_t size);
 PMOD_EXPORT struct array *array_remove(struct array *v,INT32 ind);
-PMOD_EXPORT ptrdiff_t array_search(struct array *v, struct svalue *s,
+PMOD_EXPORT ptrdiff_t array_search(struct array *v, const struct svalue *s,
 				   ptrdiff_t start);
 PMOD_EXPORT struct array *slice_array(struct array *v, ptrdiff_t start,
 				      ptrdiff_t end);
-- 
GitLab