PCRESTACK(3)

πŸ’– PCRESTACK(3) β€” Library Functions Manual πŸ’–

okay bestie, so this is a page from the PCRE manual β€” y'know, Perl-compatible regular expressions? It's the one that explains what happens to your poor little process stack when you run a regex. And ngl, it's important. So sit down, grab a strawberry drink πŸ“, and let's get into it.


✨ NAME ✨

PCRE β€” Perl-compatible regular expressions


🌈 PCRE DISCUSSION OF STACK USAGE 🌈

okay so when you call pcre[16|32]_exec(), it's lowkey using an internal function called match() under the hood. And match() is that girl who calls herself β€” recursively, at branch points in the pattern β€” because she needs to remember the state of the match so she can back up and try a different alternative if the first one flops. πŸ’… And as matching goes deeper and deeper into the tree of possibilities, the recursion depth just keeps going up. Not me spiraling. 😭

match() also gets called in other circumstances too, like whenever a parenthesized sub-pattern is entered, and in certain cases of repetition.

And listen β€” not every call of match() increases the recursion depth. For an item like a* it might be called several times at the same level, after matching different numbers of a's. Also, in a bunch of cases where the result of the recursive call would immediately be passed right back as the result of the current call (what they call a "tail recursion"), the function just gets restarted instead. iconic behaviour, honestly.

Okay so all of the above applies when pcre[16|32]_exec() is running in its normal interpretive manner. But! If the pattern was studied with the PCRE_STUDY_JIT_COMPILE option, and the just-in-time compiling succeeded, and the options passed to pcre[16|32]_exec() were not incompatible, then the matching process uses the JIT-compiled code instead of the match() function. In that case, the memory requirements are handled entirely differently. See the pcrejit documentation for the deets. ✨

Now, pcre[16|32]_dfa_exec() is a whole different vibe β€” it operates in an entirely different way, and only uses recursion when there's a regular expression recursion or subroutine call in the pattern. That includes the processing of assertion and "once-only" subpatterns, which get handled like subroutine calls. Normally these never go very deep, and the limit on the complexity of pcre[16|32]_dfa_exec() is controlled by the amount of workspace you give it. However, it IS possible to write patterns with runaway infinite recursions, and those patterns will make pcre[16|32]_dfa_exec() run out of stack. At present, there is no protection against this. πŸ’€

heads up bestie: everything that follows does NOT apply to pcre[16|32]_dfa_exec(). It's only relevant for pcre[16|32]_exec() without the JIT optimization.

πŸ¦‹ Reducing pcre[16|32]_exec()'s stack usage πŸ¦‹

Every single time match() is actually called recursively, it uses memory from the process stack. And for certain kinds of pattern and data, very large amounts of stack may be needed β€” despite the recognition of "tail recursion". πŸ™ˆ

The good news? You can often reduce the amount of recursion (and therefore the amount of stack used) by modifying the pattern you're matching. Consider, for example, this pattern:

([^<]|<(?!inet))+

It matches from wherever it starts until it encounters "<inet" or the end of the data, and it's the kind of pattern that might be used when processing an XML file. Each iteration of the outer parentheses matches either one character that is not "<" or a "<" that is not followed by "inet". But here's the thing β€” each time a parenthesis is processed, a recursion occurs, so this formulation uses a stack frame for every single matched character. For a long string? That's a lot of stack, bestie. 😭

Now consider this rewritten pattern, which matches exactly the same strings:

([^<]++|<(?!inet))+

This one uses very much less stack, because runs of characters that don't contain "<" get "swallowed" in one item inside the parentheses. Recursion only happens when a "<" character that is not followed by "inet" is encountered (and we're assuming that's relatively rare ✨). A possessive quantifier is used to stop any backtracking into the runs of non-"<" characters, but that part is not related to stack usage. Just so you know.

So the takeaway from this example: one way of avoiding stack problems when matching long subject strings is to write repeated parenthesized subpatterns to match more than one character whenever possible. periodt. πŸ’…


🧚 Compiling PCRE to use heap instead of stack for pcre[16|32]_exec() 🧚

In environments where stack memory is constrained, you might wanna compile PCRE to use heap memory instead of stack for remembering back-up points when pcre[16|32]_exec() is running. Warning though: this makes it run a lot more slowly. 😭 Details of how to do this are in the pcrebuild documentation.

When built in this way, instead of using the stack, PCRE obtains and frees memory by calling the functions that are pointed to by the pcre[16|32]_stack_malloc and pcre[16|32]_stack_free variables. By default, these point to malloc() and free(), but you can replace the pointers to make PCRE use your own functions. And since the block sizes are always the same, and are always freed in reverse order, it may be possible to implement customized memory handlers that are more efficient than the standard functions. ✨ slay.


πŸŽ€ Limiting pcre[16|32]_exec()'s stack usage πŸŽ€

You can set limits on the number of times that match() is called β€” both in total and recursively. If a limit is exceeded, pcre[16|32]_exec() returns an error code. Setting suitable limits should prevent it from running out of stack. 🫢

The default values of the limits are very large, and unlikely ever to operate. They can be changed when PCRE is built, and they can also be set when pcre[16|32]_exec() is called. For details of these interfaces, see the pcrebuild documentation and the section on extra data for pcre[16|32]_exec() in the pcreapi documentation.

As a very rough rule of thumb, you should reckon on about 500 bytes per recursion. So if you want to limit your stack usage to 8Mb, you should set the limit at 16000 recursions. A 64Mb stack, on the other hand, can support around 128000 recursions. math is mathing. πŸ”₯

In Unix-like environments, the pcretest test program has a command line option (-S) that can be used to increase the size of its stack. And as long as the stack is large enough, another option (-M) can be used to find the smallest limits that allow a particular pattern to match a given subject string. It does this by calling pcre[16|32]_exec() repeatedly with different limits. cute.


⭐ Obtaining an estimate of stack usage ⭐

The actual amount of stack used per recursion can vary quite a lot, depending on the compiler that was used to build PCRE and the optimization or debugging options that were set for it. That rule of thumb value of 500 bytes mentioned above may be larger or smaller than what's actually needed. A better approximation can be obtained by running this command:

pcretest -m -C

The -C option makes pcretest output information about the options with which PCRE was compiled. When -m is also given (before -C), information about stack use is given in a line like this:

Match recursion uses stack: approximate frame size = 640 bytes

The value is approximate because some recursions need a bit more (up to perhaps 16 more bytes).

And if the above command is given when PCRE is compiled to use the heap instead of the stack for recursion, the value that is output is the size of each block that is obtained from the heap. 🌸


🌈 Changing stack size in Unix-like systems 🌈

In Unix-like environments, there's not often a problem with the stack unless very long strings are involved β€” though the default limit on stack size varies from system to system. Values from 8Mb to 64Mb are common. You can find your default limit by running this command:

ulimit -s

Unfortunately, the effect of running out of stack is often SIGSEGV πŸ’€, though sometimes a more explicit error message is given. You can normally increase the limit on stack size with code such as this:

struct rlimit rlim;
getrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = 100*1024*1024;
setrlimit(RLIMIT_STACK, &rlim);

This reads the current limits (soft and hard) using getrlimit(), then attempts to increase the soft limit to 100Mb using setrlimit(). You must do this before calling pcre[16|32]_exec(). no cap. πŸ’…


πŸ“ Changing stack size in Mac OS X πŸ“

Using setrlimit(), as described above, should also work on Mac OS X. It's also possible to set a stack size when linking a program. There's a discussion about stack sizes in Mac OS X at this web site: http://developer.apple.com/qa/qa2005/qa1419.html.


πŸ‘‘ AUTHOR πŸ‘‘

Philip Hazel University Computing Service Cambridge CB2 3QH, England.


πŸ’œ REVISION πŸ’œ

Last updated: 24 June 2012 Copyright (c) 1997-2012 University of Cambridge.


and that's the whole page, bestie 🫢 this was PCRE 8.30, dated 24 June 2012, and the manual page itself is PCRESTACK(3) from the Library Functions Manual. go forth and not blow your stack. literally. πŸ’–βœ¨πŸŽ€