Bug 98723 - On Windows with CP936 encoding, regex compiles very slow.
Summary: On Windows with CP936 encoding, regex compiles very slow.
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: libstdc++ (show other bugs)
Version: 10.2.0
: P3 normal
Target Milestone: 15.0
Assignee: Jonathan Wakely
URL: https://gcc.gnu.org/pipermail/gcc-pat...
Keywords: patch
Depends on:
Blocks: std::regex
  Show dependency tree / graph
 
Reported: 2021-01-18 10:37 UTC by goughost
Modified: 2025-01-08 13:12 UTC (History)
7 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-01-18 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description goughost 2021-01-18 10:37:34 UTC
example code:

#include <regex>
#include <iostream>
#include <locale>
int main() {
   std::setlocale(LC_ALL, "");
   std::regex rgx{"[a-z][a-z][a-z]"};
   std::cerr<<rgx.mark_count()<<std::endl;
   return 0;
}

build and run in mingw64 environment (gcc 10.2.0), the program blocks while compiling the regex for a long time.

my finding is that:

compiling '[a-z]' needs to cache info for all 256 chars;
for each char, a call to std::collate<char>::do_transform() is made;
do_transform() will use the result of strxfrm() to allocate buffer;
on Windows, strxfrm() returns INT_MAX to indicate error;
if char > 0x7f, and the system encoding is CP936, strxfrm() will fail;
thus, compiling '[a-z]' will repeatedly allocate large buffers.

issues:

1. the regex compilation will be affected by current locale even if std::regex::collate is not set, by calling strxfrm.

2. code in bits/locale_classes.tcc should handle documented return conditions of strxfrm() on Windows:

         size_t __res = _M_transform(__c, __p, __len); //*** calls strxfrm()
         // If the buffer was not large enough, try again with the
         // correct size.
         if (__res >= __len)
      {
        __len = __res + 1;
        delete [] __c, __c = 0;
        __c = new _CharT[__len];
        __res = _M_transform(__c, __p, __len);
      }
Comment 1 Jonathan Wakely 2021-01-18 11:39:42 UTC
The Windows behaviour fails to conform to the C and C++ standards. I think _M_transform should check errno and throw an exception on error (which means removing the non-throwing exceptions specification from that function).
Comment 2 goughost 2021-01-18 14:31:31 UTC
That may be acceptable for issue 2.
But additional fixes are need; otherwise, users cannot use regex after calling setlocale(LC_ALL,"") in such a situation.
Can regex compilers work without calling _M_transform? (at least when std::regex::collate is not set)

On the other hand, maybe the error condition can be handled by regex compiler code.
To some extent, the bug is in the regex compiler.
Building cache for '\xee' calls strxfrm() with "\xee\x00", which is not a valid string if current encoding is utf8.
Also, in GNU/Linux, resulting strings of such (successful) calls might not help building the cache.

Examples calling strxfrom in GNU/Linux with various locales.
(Note that, in cases when Windows fails, Linux gives trivial results.)

// C
input 61 00, errno 0, res 1, outbuf:  61
input 62 00, errno 0, res 1, outbuf:  62
input aa 00, errno 0, res 1, outbuf:  aa
input bb 00, errno 0, res 1, outbuf:  bb

// C.UTF-8
input 61 00, errno 0, res 1, outbuf:  63
input 62 00, errno 0, res 1, outbuf:  64
input aa 00, errno 0, res 1, outbuf:  03
input bb 00, errno 0, res 1, outbuf:  03

// en_US.UTF-8
input 61 00, errno 0, res 10, outbuf:  51 01 02 01 02 01 00 00 00 00
input 62 00, errno 0, res 10, outbuf:  5e 01 02 01 02 01 00 00 00 00
input aa 00, errno 0, res 5, outbuf:  01 01 01 01 03
input bb 00, errno 0, res 5, outbuf:  01 01 01 01 03

// zh_CN.GB2312 
input 61 00, errno 0, res 11, outbuf:  e1 a9 bd 01 02 01 02 01 00 00 61
input 62 00, errno 0, res 11, outbuf:  e1 a9 be 01 02 01 02 01 00 00 62
input aa 00, errno 0, res 5, outbuf:  01 01 01 01 03
input bb 00, errno 0, res 5, outbuf:  01 01 01 01 03
Comment 3 cqwrteur 2021-01-24 19:17:05 UTC
This should be reported as a CVE.
Comment 4 Eric Gallager 2021-11-26 13:34:28 UTC
This is affecting The Battle for Wesnoth: https://github.com/wesnoth/wesnoth/issues/6291
Comment 5 cqwrteur 2021-11-26 16:40:20 UTC
(In reply to Eric Gallager from comment #4)
> This is affecting The Battle for Wesnoth:
> https://github.com/wesnoth/wesnoth/issues/6291

C++ std::regex is just terrible and highly likely be deprecated in the future standard. I think you better switch to some 3rd party implementation
Comment 6 Jeroen Ooms 2022-05-29 11:13:57 UTC
This bug has become more problematic because it also affects any program running under recent versions of Windows UCRT in UTF-8 locale[1], and therefore all users of the R programming language.

The only solution right now seems to avoid std::rexex, e.g.: https://github.com/tesseract-ocr/tesseract/issues/3830


[1] https://docs.microsoft.com/en-us/windows/apps/design/globalizing/use-utf8-code-page
Comment 7 cqwrteur 2022-05-30 16:24:05 UTC
well the right solution is to write the regex by yourself. C++ regex might be deprecated in the future.
Comment 8 Luca Bacci 2023-12-09 13:52:01 UTC
(In reply to Jonathan Wakely from comment #1)
> The Windows behaviour fails to conform to the C and C++ standards. I think
> _M_transform should check errno and throw an exception on error (which means
> removing the non-throwing exceptions specification from that function).

Hi Jonathan! I'm giving it a go, but I have one question: which encoding are the strings passed to _M_transform() / _M_compare() in? (libstdc++-v3/config/locale/generic/collate_members.cc) is it the execution character set? Or is it always UTF-8?

I am asking because we have to convert to UTF-16 and call wcsxfrm().

Many thanks,
Luca
Comment 9 Luca Bacci 2024-11-15 12:58:07 UTC
To respond the my previous comment: the expected string encoding is determined by the C locale in use, which is either the global one or imbued in std::regex_traits.
Comment 10 Luca Bacci 2024-11-15 13:08:58 UTC
There's another report for Solaris which is essentially a duplicate: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85824.

> the regex compilation will be affected by current locale even if std::regex::collate is not set

Yes, std::regex ends up calling strxfrm even when std::regex::collate is not set, but that's not an issue.

std::regex::collate only determines if character ranges [a-b] will be locale sensitive; on the other hand, things like equivalence classes [=a=] have to work regardless of the collate flag. For equivalence classes you need locale data. The C++ standard delegates locale-sensitive processing to std::regex_traits, and that will be used regardless of the std::regex::collate flag.
Comment 11 Luca Bacci 2024-11-15 13:43:04 UTC
The problem happens in https://github.com/gcc-mirror/gcc/blob/releases/gcc-14.2.0/libstdc%2B%2B-v3/include/bits/regex_compiler.tcc#L612. _M_translator takes __collate (the std::regex::collate flag) in account, so it's not an issue; however _M_traits (which is the std::regex_traits) uses the locale.

We can see that _M_traits.transform_primary() is called to search into the _M_equiv_set vector, but in most cases _M_equiv_set is empty. So I'd suggest to add a check:

  if (!_M_equiv_set.empty() &&
      std::find(_M_equiv_set.begin(), _M_equiv_set.end(),
               _M_traits.transform_primary(&__ch, &__ch+1)) != _M_equiv_set.end())
    return true;

That way the locale-dependant _M_traits.transform_primary is only called if needed.
Comment 12 Jonathan Wakely 2024-11-15 14:41:14 UTC
Yes, that looks like nice improvement, thanks.

I think it would be easier to read as:

        if (!_M_equiv_set.empty())
          {
            auto __x = _M_traits.transform_primary(&__ch, &__ch+1);
            auto __p = std::find(_M_equiv_set.begin(), _M_equiv_set.end(), __x);
            if (__p != _M_equiv_set.end())
              return true;
          }

Could you send a patch to the mailing lists for review?
Comment 13 Luca Bacci 2024-11-15 17:41:08 UTC
Here we are: https://gcc.gnu.org/pipermail/gcc-patches/2024-November/668988.html

Let me know if anything is missing.

Best regards,
Luca
Comment 14 Jonathan Wakely 2024-11-15 20:46:08 UTC
Thanks! Please CC the libstdc++ list, as per https://gcc.gnu.org/lists.html

https://gcc.gnu.org/contribute.html lists the other requirements.

I think this is small enough to not need a copyright assignment or DCO sign-off.
Comment 15 GCC Commits 2024-12-18 08:26:54 UTC
The master branch has been updated by Jonathan Wakely <redi@gcc.gnu.org>:

https://gcc.gnu.org/g:eb339c29ee42aa59591fc50d6d8a1ab903d2a3fe

commit r15-6317-geb339c29ee42aa59591fc50d6d8a1ab903d2a3fe
Author: Luca Bacci <luca.bacci982@gmail.com>
Date:   Tue Dec 17 18:57:30 2024 +0000

    libstdc++: Call regex_traits::transform_primary() only when necessary [PR98723]
    
    This is both a performance optimization and a partial fix for PR 98723.
    
    This commit fixes the issue for bracket expressions that do not depend
    on the locale's collation facet. Examples:
    
     * Character ranges ([a-z]) when std::regex::collate is not set
     * Character classes ([:alnum:])
     * Individual characters ([abc])
    
    Signed-off-by: Luca Bacci <luca.bacci982@gmail.com>
    
    libstdc++-v3/ChangeLog:
    
            PR libstdc++/98723
            * include/bits/regex_compiler.tcc (_BracketMatcher::_M_apply):
            Only use transform_primary when an equivalence set is used.
Comment 16 Jonathan Wakely 2024-12-18 21:20:01 UTC
Patch posted for the remaining problem (i.e. when equivalence sets are used and so transform_primary really does need to be called):
https://gcc.gnu.org/pipermail/gcc-patches/2024-December/671963.html
Comment 17 GCC Commits 2025-01-08 12:58:48 UTC
The master branch has been updated by Jonathan Wakely <redi@gcc.gnu.org>:

https://gcc.gnu.org/g:fa6549c1f0e75ff33cb641d98af72ee354b04bbe

commit r15-6691-gfa6549c1f0e75ff33cb641d98af72ee354b04bbe
Author: Jonathan Wakely <jwakely@redhat.com>
Date:   Wed Dec 18 12:57:14 2024 +0000

    libstdc++: Handle errors from strxfrm in std::collate::transform [PR85824]
    
    std::regex builds a cache of equivalence classes by calling
    std::regex_traits<char>::transform_primary(c) for every char, which then
    calls std::collate<char>::transform which calls strxfrm. On several
    targets strxfrm fails for non-ASCII characters. Because strxfrm has no
    return value reserved to indicate an error, some implementations return
    INT_MAX or SIZE_MAX. This causes std::collate::transform to try to
    allocate a huge buffer, which is either very slow or throws
    std::bad_alloc. We should check errno after calling strxfrm to detect
    errors and then throw a more appropriate exception instead of trying to
    allocate a huge buffer.
    
    Unfortunately the std::collate<C>::_M_transform function has a
    non-throwing exception specifier, so we can't do the error handling
    there.
    
    As well as checking errno, this patch changes std::collate::do_transform
    to use __builtin_alloca for small inputs, and to use RAII to deallocate
    the buffers used for large inputs.
    
    This change isn't sufficient to fix the three std::regex bugs caused by
    the lack of error handling in std::collate::do_transform, we also need
    to make std::regex_traits::transform_primary handle exceptions. This
    change also attempts to make transform_primary closer to the effects
    described in the standard, by not even attempting to use std::collate if
    the locale's std::collate facet has been replaced (see PR 118105).
    Implementing the correct effects for transform_primary requires RTTI, so
    that we don't use some user-defined std::collate facet with unknown
    semantics. When -fno-rtti is used transform_primary just returns an
    empty string, making equivalence classes unusable in std::basic_regex.
    That's not ideal, but I don't have any better ideas.
    
    I'm unsure if std::regex_traits<C>::transform_primary is supposed to
    convert the string to lower case or not.  The general regex traits
    requirements ([re.req] p20) do say "when character case is not
    considered" but the specification for the std::regex_traits<char> and
    std::regex_traits<wchar_t> specializations ([re.traits] p7) don't say
    anything about that.
    
    With the r15-6317-geb339c29ee42aa change, transform_primary is not
    called unless the regex actually uses an equivalence class. But using an
    equivalence class would still fail (or be incredibly slow) on some
    targets. With this commit, equivalence classes should be usable on all
    targets, without excessive memory allocations.
    
    Arguably, we should not even try to call transform_primary for any char
    values over 127, since they're never valid in locales that use UTF-8 or
    7-bit ASCII, and probably for other charsets too. Handling 128
    exceptions for every std::regex compilation is very inefficient, but at
    least it now works instead of failing with std::bad_alloc, and no longer
    allocates 128 x 2GB. Maybe for C++26 we could check the locale's
    std::text_encoding and use that to decide whether to cache equivalence
    classes for char values over 127.
    
    libstdc++-v3/ChangeLog:
    
            PR libstdc++/85824
            PR libstdc++/94409
            PR libstdc++/98723
            PR libstdc++/118105
            * include/bits/locale_classes.tcc (collate::do_transform): Check
            errno after calling _M_transform. Use RAII type to manage the
            buffer and to restore errno.
            * include/bits/regex.h (regex_traits::transform_primary): Handle
            exceptions from std::collate::transform and do not try to use
            std::collate for user-defined facets.
Comment 18 Jonathan Wakely 2025-01-08 13:12:15 UTC
This should be fixed in GCC 15.