From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mail-oa1-x2b.google.com (mail-oa1-x2b.google.com [IPv6:2001:4860:4864:20::2b]) by sourceware.org (Postfix) with ESMTPS id 0AD493858D20 for ; Tue, 20 Feb 2024 00:15:54 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 0AD493858D20 Authentication-Results: sourceware.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=gmail.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org 0AD493858D20 Authentication-Results: server2.sourceware.org; arc=none smtp.remote-ip=2001:4860:4864:20::2b ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1708388157; cv=none; b=JQKN+5QMx8BOMgRtUdXn1x9W3tDQM8DDaKkW3Pxqr/8GqoRFncYePQicRHcW7fxwaAMSr4amUeMKqiN0NdF/sDFdRB7HCes5UIB64cG01wTpceEkGS2b2SvtZX+crVDqThTZMP1Dw2Utz3iVfuds6B/bojLOncJXtFQLBl+DWzE= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1708388157; c=relaxed/simple; bh=p/4sCG9NnduCAhp4sb0XnxDvO0UMuNJdfQpkG/0n88w=; h=DKIM-Signature:MIME-Version:From:Date:Message-ID:Subject:To; b=q4rlG8EDVgrVu1mP0LGIHKeLcVd9WvnkBY4qBPmAaDBOn5hPt+mqAMoCHM/OOHu1u79WNGcJmWYMbRJ3DF079j7BxyiOXORB0KLJkody1HO+xbaL9fJltKNL1YpyfFUGb/zCBopMvzCFFnOGriX3PoBEO/i0LBXcnuK9qZL6sWU= ARC-Authentication-Results: i=1; server2.sourceware.org Received: by mail-oa1-x2b.google.com with SMTP id 586e51a60fabf-21ef7be6772so718715fac.0 for ; Mon, 19 Feb 2024 16:15:54 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1708388153; x=1708992953; darn=sourceware.org; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:from:to:cc:subject:date :message-id:reply-to; bh=vHsz38Gh5Sxc2gRjxieQYIQYBHofAqciRYOJKwyvahQ=; b=HWwczhjW4p7bJOqupqUMZq2hVFnNgcIm42y4ZIyHyWfwZ0AYDWOQXMaPwela/aRKfd sE1ORuMzwKpTgQS9bMrRTNjlSHqKQdGsERdRHke2dpW0gcaEjWKGnmGzBSfb7EB2k+zz hjvib4EXzkeQ5MhNCT39h+bZeCBuFdQddNC9m7ygT6OqM2KpcAa0/fyAADsLIfPgrQmZ 8dr9EuHiuARK7rX/9ZgVNNcq2E2IdgbOvXlzwxqLiPOi9yWYXXfDrNkQUq2V2g9VlCx4 Ka5Q+2aZMXruUMjj3D4ehcVKKp1S6KggoOuid9hZqtbTdBammdL72YUFRkpXBbYlIJ6k kLTw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1708388153; x=1708992953; h=content-transfer-encoding:cc:to:subject:message-id:date:from :in-reply-to:references:mime-version:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=vHsz38Gh5Sxc2gRjxieQYIQYBHofAqciRYOJKwyvahQ=; b=GI+faCDnlpUa5hMhbS30gbvIr/Kc1CsqJiLAm7nvlXo0QDYFBmv8izIt7z/oi1Ywkb /M3PqGJHwJs+llZpmDfmDsfSiZ6ugDudIckyCYJHhCU+G5ytmd37mEGDxiNfuEGBfqVX IKmChXu7o6Jrm1BcPzt1voqv2faRvj0GWRK4CsWn90umWt4llVNlnO4hlHXxsbOn1w/H R2nMpYA4pBq8FXcaKUKkvnkw/m2DYBFRg2RshJKuyy9LUwrwDFVPAIEAEWlQ9IP6waid FMLyPdB5UzuW2t+y4mdDNTCMfyGNcRD4SnxT10w+4Usv7hfDjAbvvEvyUnqlPcOjrAmx hghw== X-Gm-Message-State: AOJu0YwIvjF/6z/5Afo0H1km+a2wXhoVpy890+XHlV5Z4buz/1v9tUL8 Dkn5DUXrlnQqs7DI5s0Fsk77mcUOMqmpE0w4/sEramKJqOPN+yuxfzKNyONFG8x4KlwkDKkGTb4 INZy1atop+3PC+5ibW/L22++oq+NxzeJg X-Google-Smtp-Source: AGHT+IF+vfKKUzmX5lU7O7VecjOieB911zmA0Y/2hn/KEPmxdf/STFBbOfbmm74zee36FwGALXAO4X4USlDmbbWMDYM= X-Received: by 2002:a05:6870:9a14:b0:21e:9df9:2596 with SMTP id fo20-20020a0568709a1400b0021e9df92596mr7689859oab.42.1708388152979; Mon, 19 Feb 2024 16:15:52 -0800 (PST) MIME-Version: 1.0 References: <20240219204502.3095343-1-adhemerval.zanella@linaro.org> <20240219204502.3095343-4-adhemerval.zanella@linaro.org> In-Reply-To: <20240219204502.3095343-4-adhemerval.zanella@linaro.org> From: Noah Goldstein Date: Tue, 20 Feb 2024 00:15:41 +0000 Message-ID: Subject: Re: [PATCH 3/3] wcsmbs: Ensure wcstr worst-case linear execution time (BZ 23865) To: Adhemerval Zanella Cc: libc-alpha@sourceware.org Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: quoted-printable X-Spam-Status: No, score=-9.6 required=5.0 tests=BAYES_00,DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,FREEMAIL_FROM,GIT_PATCH_0,KAM_SHORT,RCVD_IN_DNSWL_NONE,SPF_HELO_NONE,SPF_PASS,TXREP,T_SCC_BODY_TEXT_LINE autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org List-Id: On Mon, Feb 19, 2024 at 8:45=E2=80=AFPM Adhemerval Zanella wrote: > > It uses the same two-way algorithm used on strstr, strcasestr, and > memmem. Different than strstr, neither the "shift table" optimization > nor the self-adapting filtering check is used because it would result in > a too-large shift table (and it also simplifies the implementation bit). > > Checked on x86_64-linux-gnu and aarch64-linux-gnu. > --- > wcsmbs/wcs-two-way.h | 312 +++++++++++++++++++++++++++++++++++++++++++ > wcsmbs/wcsstr.c | 104 +++++---------- > 2 files changed, 344 insertions(+), 72 deletions(-) > create mode 100644 wcsmbs/wcs-two-way.h > > diff --git a/wcsmbs/wcs-two-way.h b/wcsmbs/wcs-two-way.h > new file mode 100644 > index 0000000000..2dcee7fc1a > --- /dev/null > +++ b/wcsmbs/wcs-two-way.h > @@ -0,0 +1,312 @@ > +/* Byte-wise substring search, using the Two-Way algorithm. > + Copyright (C) 2024 Free Software Foundation, Inc. > + This file is part of the GNU C Library. > + > + The GNU C Library is free software; you can redistribute it and/or > + modify it under the terms of the GNU Lesser General Public > + License as published by the Free Software Foundation; either > + version 2.1 of the License, or (at your option) any later version. > + > + The GNU C Library is distributed in the hope that it will be useful, > + but WITHOUT ANY WARRANTY; without even the implied warranty of > + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU > + Lesser General Public License for more details. > + > + You should have received a copy of the GNU Lesser General Public > + License along with the GNU C Library; if not, see > + . */ > + > +/* Before including this file, you need to include (and > + before that, if not part of libc), and define: > + AVAILABLE(h, h_l, j, n_l) > + A macro that returns nonzero if there are > + at least N_L characters left starting at H[J= ]. > + H is 'wchar_t *', H_L, J, and N_L are 'size_= t'; > + H_L is an lvalue. For NUL-terminated search= es, > + H_L can be modified each iteration to avoid > + having to compute the end of H up front. > + > + For case-insensitivity, you may optionally define: > + CMP_FUNC(p1, p2, l) A macro that returns 0 iff the first L > + characters of P1 and P2 are equal. > + CANON_ELEMENT(c) A macro that canonicalizes an element right= after > + it has been fetched from one of the two stri= ngs. > + The argument is an 'wchar_t'; the result mus= t > + be an 'wchar_t' as well. > +*/ > + > +#include > +#include > +#include /* Defines MAX. */ > + > +/* We use the Two-Way string matching algorithm, which guarantees > + linear complexity with constant space. > + > + See http://www-igm.univ-mlv.fr/~lecroq/string/node26.html#SECTION0026= 0 > + and http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm > +*/ > + > +#ifndef CANON_ELEMENT > +# define CANON_ELEMENT(c) c > +#endif > +#ifndef CMP_FUNC > +# define CMP_FUNC __wmemcmp > +#endif > + > +/* Perform a critical factorization of NEEDLE, of length NEEDLE_LEN. > + Return the index of the first character in the right half, and set > + *PERIOD to the global period of the right half. > + > + The global period of a string is the smallest index (possibly its > + length) at which all remaining bytes in the string are repetitions > + of the prefix (the last repetition may be a subset of the prefix). > + > + When NEEDLE is factored into two halves, a local period is the > + length of the smallest word that shares a suffix with the left half > + and shares a prefix with the right half. All factorizations of a > + non-empty NEEDLE have a local period of at least 1 and no greater > + than NEEDLE_LEN. > + > + A critical factorization has the property that the local period > + equals the global period. All strings have at least one critical > + factorization with the left half smaller than the global period. > + > + Given an ordered alphabet, a critical factorization can be computed > + in linear time, with 2 * NEEDLE_LEN comparisons, by computing the > + larger of two ordered maximal suffixes. The ordered maximal > + suffixes are determined by lexicographic comparison of > + periodicity. */ > +static size_t > +critical_factorization (const wchar_t *needle, size_t needle_len, > + size_t *period) > +{ > + /* Index of last character of left half, or SIZE_MAX. */ > + size_t max_suffix, max_suffix_rev; > + size_t j; /* Index into NEEDLE for current candidate suffix. */ > + size_t k; /* Offset into current period. */ > + size_t p; /* Intermediate period. */ > + wchar_t a, b; /* Current comparison bytes. */ > + > + /* Special case NEEDLE_LEN of 1 or 2 (all callers already filtered > + out 0-length needles. */ > + if (needle_len < 3) > + { > + *period =3D 1; > + return needle_len - 1; > + } > + > + /* Invariants: > + 0 <=3D j < NEEDLE_LEN - 1 > + -1 <=3D max_suffix{,_rev} < j (treating SIZE_MAX as if it were sign= ed) > + min(max_suffix, max_suffix_rev) < global period of NEEDLE > + 1 <=3D p <=3D global period of NEEDLE > + p =3D=3D global period of the substring NEEDLE[max_suffix{,_rev}+1.= ..j] > + 1 <=3D k <=3D p > + */ > + > + /* Perform lexicographic search. */ > + max_suffix =3D SIZE_MAX; > + j =3D 0; > + k =3D p =3D 1; > + while (j + k < needle_len) > + { > + a =3D CANON_ELEMENT (needle[j + k]); > + b =3D CANON_ELEMENT (needle[max_suffix + k]); > + if (a < b) > + { > + /* Suffix is smaller, period is entire prefix so far. */ > + j +=3D k; > + k =3D 1; > + p =3D j - max_suffix; > + } > + else if (a =3D=3D b) > + { > + /* Advance through repetition of the current period. */ > + if (k !=3D p) > + ++k; > + else > + { > + j +=3D p; > + k =3D 1; > + } > + } > + else /* b < a */ > + { > + /* Suffix is larger, start over from current location. */ > + max_suffix =3D j++; > + k =3D p =3D 1; > + } > + } > + *period =3D p; > + > + /* Perform reverse lexicographic search. */ > + max_suffix_rev =3D SIZE_MAX; > + j =3D 0; > + k =3D p =3D 1; > + while (j + k < needle_len) > + { > + a =3D CANON_ELEMENT (needle[j + k]); > + b =3D CANON_ELEMENT (needle[max_suffix_rev + k]); > + if (b < a) > + { > + /* Suffix is smaller, period is entire prefix so far. */ > + j +=3D k; > + k =3D 1; > + p =3D j - max_suffix_rev; > + } > + else if (a =3D=3D b) > + { > + /* Advance through repetition of the current period. */ > + if (k !=3D p) > + ++k; > + else > + { > + j +=3D p; > + k =3D 1; > + } > + } > + else /* a < b */ > + { > + /* Suffix is larger, start over from current location. */ > + max_suffix_rev =3D j++; > + k =3D p =3D 1; > + } > + } > + > + /* Choose the shorted suffix. Return the first character of the right > + half, rather than the last character of the left half. */ > + if (max_suffix_rev + 1 < max_suffix + 1) > + return max_suffix + 1; > + *period =3D p; > + return max_suffix_rev + 1; > +} > + > +/* Return the first location of non-empty NEEDLE within HAYSTACK, or > + NULL. HAYSTACK_LEN is the minimum known length of HAYSTACK. > + > + If AVAILABLE does not modify HAYSTACK_LEN (as in memmem), then at > + most 2 * HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. > + If AVAILABLE modifies HAYSTACK_LEN (as in strstr), then at most 3 * > + HAYSTACK_LEN - NEEDLE_LEN comparisons occur in searching. */ > +static inline wchar_t * > +two_way_short_needle (const wchar_t *haystack, size_t haystack_len, > + const wchar_t *needle, size_t needle_len) > +{ > + size_t i; /* Index into current character of NEEDLE. */ > + size_t j; /* Index into current window of HAYSTACK. */ > + size_t period; /* The period of the right half of needle. */ > + size_t suffix; /* The index of the right half of needle. */ > + > + /* Factor the needle into two halves, such that the left half is > + smaller than the global period, and the right half is > + periodic (with a period as large as NEEDLE_LEN - suffix). */ > + suffix =3D critical_factorization (needle, needle_len, &period); > + > + /* Perform the search. Each iteration compares the right half > + first. */ > + if (CMP_FUNC (needle, needle + period, suffix) =3D=3D 0) > + { > + /* Entire needle is periodic; a mismatch can only advance by the > + period, so use memory to avoid rescanning known occurrences > + of the period. */ > + size_t memory =3D 0; > + j =3D 0; > + while (AVAILABLE (haystack, haystack_len, j, needle_len)) > + { > + const wchar_t *pneedle; > + const wchar_t *phaystack; > + > + /* Scan for matches in right half. */ > + i =3D MAX (suffix, memory); > + pneedle =3D &needle[i]; > + phaystack =3D &haystack[i + j]; > + while (i < needle_len && (CANON_ELEMENT (*pneedle++) > + =3D=3D CANON_ELEMENT (*phaystack++))) > + ++i; > + if (needle_len <=3D i) > + { > + /* Scan for matches in left half. */ > + i =3D suffix - 1; > + pneedle =3D &needle[i]; > + phaystack =3D &haystack[i + j]; > + while (memory < i + 1 && (CANON_ELEMENT (*pneedle--) > + =3D=3D CANON_ELEMENT (*phaystack-= -))) > + --i; > + if (i + 1 < memory + 1) > + return (wchar_t *) (haystack + j); > + /* No match, so remember how many repetitions of period > + on the right half were scanned. */ > + j +=3D period; > + memory =3D needle_len - period; > + } > + else > + { > + j +=3D i - suffix + 1; > + memory =3D 0; > + } > + } > + } > + else > + { > + const wchar_t *phaystack; > + /* The comparison always starts from needle[suffix], so cache it > + and use an optimized first-character loop. */ > + wchar_t needle_suffix =3D CANON_ELEMENT (needle[suffix]); > + > + /* The two halves of needle are distinct; no extra memory is > + required, and any mismatch results in a maximal shift. */ > + period =3D MAX (suffix, needle_len - suffix) + 1; > + j =3D 0; > + while (AVAILABLE (haystack, haystack_len, j, needle_len)) > + { > + wchar_t haystack_char; > + const wchar_t *pneedle; > + > + phaystack =3D &haystack[suffix + j]; > + > + while (needle_suffix > + !=3D (haystack_char =3D CANON_ELEMENT (*phaystack++))) > + { > + ++j; > + if (!AVAILABLE (haystack, haystack_len, j, needle_len)) > + goto ret0; > + } > + > + /* Scan for matches in right half. */ > + i =3D suffix + 1; > + pneedle =3D &needle[i]; > + while (i < needle_len) > + { > + if (CANON_ELEMENT (*pneedle++) > + !=3D (haystack_char =3D CANON_ELEMENT (*phaystack++))) > + break; > + ++i; > + } > + if (needle_len <=3D i) > + { > + /* Scan for matches in left half. */ > + i =3D suffix - 1; > + pneedle =3D &needle[i]; > + phaystack =3D &haystack[i + j]; > + while (i !=3D SIZE_MAX) > + { > + if (CANON_ELEMENT (*pneedle--) > + !=3D (haystack_char =3D CANON_ELEMENT (*phaystack--= ))) > + break; > + --i; > + } > + if (i =3D=3D SIZE_MAX) > + return (wchar_t *) (haystack + j); > + j +=3D period; > + } > + else > + j +=3D i - suffix + 1; > + } > + } > +ret0: __attribute__ ((unused)) > + return NULL; > +} > + > +#undef AVAILABLE > +#undef CANON_ELEMENT > +#undef CMP_FUNC > diff --git a/wcsmbs/wcsstr.c b/wcsmbs/wcsstr.c > index 78f1cc9ce0..7e791a5356 100644 > --- a/wcsmbs/wcsstr.c > +++ b/wcsmbs/wcsstr.c > @@ -1,4 +1,5 @@ > -/* Copyright (C) 1995-2024 Free Software Foundation, Inc. > +/* Locate a substring in a wide-character string. > + Copyright (C) 1995-2024 Free Software Foundation, Inc. > This file is part of the GNU C Library. > > The GNU C Library is free software; you can redistribute it and/or > @@ -15,82 +16,41 @@ > License along with the GNU C Library; if not, see > . */ > > -/* > - * The original strstr() file contains the following comment: > - * > - * My personal strstr() implementation that beats most other algorithms. > - * Until someone tells me otherwise, I assume that this is the > - * fastest implementation of strstr() in C. > - * I deliberately chose not to comment it. You should have at least > - * as much fun trying to understand it, as I had to write it :-). > - * > - * Stephen R. van den Berg, berg@pool.informatik.rwth-aachen.de */ > - > #include > +#include > + > +#define AVAILABLE(h, h_l, j, n_l) \ > + (((j) + (n_l) <=3D (h_l)) \ > + || ((h_l) +=3D __wcsnlen ((void*)((h) + (h_l)), (n_l) + 128), \ > + (j) + (n_l) <=3D (h_l))) > +#include "wcs-two-way.h" > + > +/* Hash character pairs so a small shift table can be used. All bits of > + p[0] are included, but not all bits from p[-1]. So if two equal hash= es > + match on p[-1], p[0] matches too. Hash collisions are harmless and r= esult > + in smaller shifts. */ > +#define hash2(p) (((size_t)(p)[0] - ((size_t)(p)[-1] << 3)) % sizeof (sh= ift)) > > wchar_t * > wcsstr (const wchar_t *haystack, const wchar_t *needle) > { any issue with just doing? ``` memmem(haystack, sizeof(wchar_t) * wcslen(haystack), needle, sizeof(wchar_t) * wcslen(needle)) ``` > - wchar_t b, c; > - > - if ((b =3D *needle) !=3D L'\0') > - { > - haystack--; /* possible ANSI violatio= n */ > - do > - if ((c =3D *++haystack) =3D=3D L'\0') > - goto ret0; > - while (c !=3D b); > - > - if (!(c =3D *++needle)) > - goto foundneedle; > - ++needle; > - goto jin; > - > - for (;;) > - { > - wchar_t a; > - const wchar_t *rhaystack, *rneedle; > - > - do > - { > - if (!(a =3D *++haystack)) > - goto ret0; > - if (a =3D=3D b) > - break; > - if ((a =3D *++haystack) =3D=3D L'\0') > - goto ret0; > -shloop: ; > - } > - while (a !=3D b); > - > -jin: if (!(a =3D *++haystack)) > - goto ret0; > - > - if (a !=3D c) > - goto shloop; > - > - if (*(rhaystack =3D haystack-- + 1) =3D=3D (a =3D *(rneedle =3D= needle))) > - do > - { > - if (a =3D=3D L'\0') > - goto foundneedle; > - if (*++rhaystack !=3D (a =3D *++needle)) > - break; > - if (a =3D=3D L'\0') > - goto foundneedle; > - } > - while (*++rhaystack =3D=3D (a =3D *++needle)); > - > - needle =3D rneedle; /* took the register-poor app= roach */ > - > - if (a =3D=3D L'\0') > - break; > - } > - } > -foundneedle: > - return (wchar_t*) haystack; > -ret0: > - return NULL; > + const wchar_t *hs =3D (const wchar_t *) haystack; > + const wchar_t *ne =3D (const wchar_t *) needle; > + > + /* Ensure haystack length is at least as long as needle length. > + Since a match may occur early on in a huge haystack, use strnlen > + and read ahead a few cachelines for improved performance. */ > + size_t ne_len =3D __wcslen (ne); > + size_t hs_len =3D __wcsnlen (hs, ne_len | 128); > + if (hs_len < ne_len) > + return NULL; > + > + /* Check whether we have a match. This improves performance since we > + avoid initialization overheads. */ > + if (__wmemcmp (hs, ne, ne_len) =3D=3D 0) > + return (wchar_t *) hs; > + > + return two_way_short_needle (hs, hs_len, ne, ne_len); > } > /* This alias is for backward compatibility with drafts of the ISO C > standard. Unfortunately the Unix(TM) standard requires this name. *= / > -- > 2.34.1 >