Skip to content

Commit 69340fe

Browse files
authored
Fix lexer edge cases and string handling (#505)
## Summary This PR fixes lexer edge cases and related string handling: - **String values:** Preserve binary and single-byte charset payloads and correctly decode escaped newlines. - **Function names:** Exclude trailing whitespace from function-name token ranges under `IGNORE_SPACE`. - **Version comments:** Support six-digit versions from MySQL 8.1, preserve five-digit fallback parsing and unversioned numeric content, and recognize vertical tabs as whitespace. - **WordPress validation:** Mirror the parent `wpdb::query()` charset checks, retaining its binary-data and prevalidated-query exemptions. - **`LIKE BINARY` patterns:** Preserve raw bytes instead of producing `NULL` during GLOB conversion, and handle escaped newlines. The lexer fixes cover both PHP packages and the native extension. ## Why The token decoder's UTF-8 regex modifier caused an accidental `TypeError` for legitimate binary data as well as malformed text. Decoding must preserve bytes; charset enforcement needs column types and SQL mode. Mirroring WordPress's checks restores its expected validation behavior. Regression tests cover decoding, token ranges, version comments, and pattern conversion. CI expectations remove the `test_strip_invalid_text` cases fixed by decoding and the two invalid-query tests fixed by WordPress validation. ## Remaining limitations - Direct MySQL-on-SQLite writes can still accept invalid text under strict mode; full charset enforcement remains driver work. WordPress's checks retain their exemptions, including tables containing binary columns. - SQLite GLOB can still treat distinct invalid UTF-8 sequences as equal. The `LIKE BINARY` fix preserves pattern bytes but does not provide fully byte-correct matching. - Legacy multibyte charsets such as Big5 and GBK remain unsupported by the decoder.
1 parent bf181a2 commit 69340fe

15 files changed

Lines changed: 443 additions & 87 deletions

‎.github/workflows/wp-tests-phpunit-run.js‎

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ const path = require( 'path' );
1212
const requiresNativeParserExtension = process.env.WP_SQLITE_REQUIRE_NATIVE_PARSER_EXTENSION === '1';
1313

1414
const expectedErrors = [
15-
'Tests_DB_Charset::test_invalid_characters_in_query',
1615
'Tests_DB_Charset::test_set_charset_changes_the_connection_collation',
1716
];
1817

@@ -38,25 +37,10 @@ const expectedFailures = [
3837
'Tests_DB_Charset::test_get_column_charset_non_mysql with data set #5',
3938
'Tests_DB_Charset::test_get_column_charset_non_mysql with data set #6',
4039
'Tests_DB_Charset::test_get_column_charset_non_mysql with data set #7',
41-
'Tests_DB_Charset::test_strip_invalid_text with data set #21',
42-
'Tests_DB_Charset::test_strip_invalid_text with data set #22',
43-
'Tests_DB_Charset::test_strip_invalid_text with data set #23',
44-
'Tests_DB_Charset::test_strip_invalid_text with data set #24',
45-
'Tests_DB_Charset::test_strip_invalid_text with data set #25',
46-
'Tests_DB_Charset::test_strip_invalid_text with data set #26',
47-
'Tests_DB_Charset::test_strip_invalid_text with data set #27',
48-
'Tests_DB_Charset::test_strip_invalid_text with data set #28',
49-
'Tests_DB_Charset::test_strip_invalid_text with data set #30',
50-
'Tests_DB_Charset::test_strip_invalid_text with data set #31',
51-
'Tests_DB_Charset::test_strip_invalid_text with data set #32',
52-
'Tests_DB_Charset::test_strip_invalid_text with data set #33',
53-
'Tests_DB_Charset::test_strip_invalid_text with data set #34',
54-
'Tests_DB_Charset::test_strip_invalid_text with data set #39',
5540
'Tests_DB_Charset::test_strip_invalid_text with data set #40',
5641
'Tests_DB_Charset::test_strip_invalid_text with data set #41',
5742
'Tests_DB_dbDelta::test_column_type_change',
5843
'Tests_DB::test_mysqli_flush_sync',
59-
'Tests_DB::test_query_value_contains_invalid_chars',
6044
'Tests_DB::test_replace',
6145
'Tests_Menu_Walker_Nav_Menu::test_start_el_with_empty_attributes with data set #1',
6246
'Tests_Menu_Walker_Nav_Menu::test_start_el_with_empty_attributes with data set #2',

‎packages/mysql-on-sqlite/src/mysql/class-wp-mysql-lexer.php‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ class WP_MySQL_Lexer {
4242
* These are intended to be used with "strspn()" and "strcspn()" functions
4343
* for fast character class matching in the SQL payload.
4444
*/
45-
const WHITESPACE_MASK = " \t\n\r\f";
45+
const WHITESPACE_MASK = " \t\n\r\f\v";
4646
const DIGIT_MASK = '0123456789';
4747
const HEX_DIGIT_MASK = '0123456789abcdefABCDEF';
4848

@@ -2993,29 +2993,34 @@ private function read_line_comment(): int {
29932993
private function read_mysql_comment(): int {
29942994
// @TODO: Consider supporting optimizer hints (/*+ ... */) or document
29952995
// that they are not supported.
2996-
// @TODO: Implement six-digit version number support (from MySQL 8.4).
29972996

2998-
// MySQL-specific comment in one of the following forms:
2999-
// 1. /*! ... */ - The content is treated as SQL.
3000-
// 2. /*!12345 ... */ - The content is treated as SQL when "MySQL version >= 12345".
2997+
// MySQL-specific comments in the following forms:
2998+
// 1. /*! ... */ - The content is treated as SQL.
2999+
// 2. /*!80400 ... */ - SQL when the server version is at least 8.4.0.
3000+
// 3. /*!080400 ... */ - The same version in six-digit form (MySQL 8.1+).
3001+
//
3002+
// See: https://dev.mysql.com/doc/refman/8.4/en/comments.html
30013003
$this->bytes_already_read += 3; // Consume the '/*!'.
30023004

3003-
// Check if the next 5 characters are digits.
3004-
$digit_count = strspn( $this->sql, self::DIGIT_MASK, $this->bytes_already_read, 5 );
3005-
$is_version_comment = 5 === $digit_count;
3006-
3007-
// For version comments, extract the version number.
3008-
$version = $is_version_comment
3009-
? (int) substr( $this->sql, $this->bytes_already_read, $digit_count )
3010-
: 0;
3005+
// Version has 5 digits (Mmmrr) or 6 digits (MMmmrr + whitespace, MySQL 8.1+).
3006+
$digit_count = strspn( $this->sql, self::DIGIT_MASK, $this->bytes_already_read, 6 );
3007+
$version_length = $digit_count < 5 ? 0 : 5;
3008+
if (
3009+
6 === $digit_count
3010+
&& $this->mysql_version >= 80100
3011+
&& 1 === strspn( $this->sql, self::WHITESPACE_MASK, $this->bytes_already_read + 6, 1 )
3012+
) {
3013+
$version_length = 6;
3014+
}
3015+
$version = (int) substr( $this->sql, $this->bytes_already_read, $version_length );
30113016

30123017
if ( $this->mysql_version < $version ) {
30133018
// Version not satisfied. Treat the content as a regular comment.
30143019
$this->read_comment_content();
30153020
return self::COMMENT;
30163021
} else {
30173022
// Version satisfied or not specified. Treat the content as SQL code.
3018-
$this->bytes_already_read += $digit_count; // Skip the version number.
3023+
$this->bytes_already_read += $version_length; // Skip the version number.
30193024
$this->in_mysql_comment = true;
30203025
return self::MYSQL_COMMENT_START;
30213026
}
@@ -3078,11 +3083,12 @@ private function resolve_keyword_type( int $type ): int {
30783083

30793084
// Determine function calls.
30803085
if ( isset( self::FUNCTIONS[ $type ] ) ) {
3081-
// Skip any whitespace character if the SQL mode says they should be ignored.
3086+
// Keep ignored whitespace outside the current token range.
3087+
$peek = $this->bytes_already_read;
30823088
if ( $this->is_sql_mode_active( self::SQL_MODE_IGNORE_SPACE ) ) {
3083-
$this->bytes_already_read += strspn( $this->sql, self::WHITESPACE_MASK, $this->bytes_already_read );
3089+
$peek += strspn( $this->sql, self::WHITESPACE_MASK, $peek );
30843090
}
3085-
if ( '(' !== ( $this->sql[ $this->bytes_already_read ] ?? null ) ) {
3091+
if ( '(' !== ( $this->sql[ $peek ] ?? null ) ) {
30863092
return self::IDENTIFIER;
30873093
}
30883094
}

‎packages/mysql-on-sqlite/src/mysql/class-wp-mysql-token.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,14 @@ public function get_value(): string {
172172
/*
173173
* A backslash with any other character represents the character itself.
174174
* That is, \x evaluates to x, \\ evaluates to \, and \🙂 evaluates to 🙂.
175+
*
176+
* Use "s" (DOTALL) to match all characters including newlines. Do not use
177+
* "u", so non-UTF-8 bytes are preserved (binary or single-byte charsets).
178+
* Legacy multi-byte charsets like big5 or gbk, where a trail byte can be
179+
* a backslash, are not supported.
175180
*/
176181
$preg_quoted_backslash = preg_quote( $backslash );
177-
$value = preg_replace( "/$preg_quoted_backslash(.)/u", '$1', $value );
182+
$value = preg_replace( "/$preg_quoted_backslash(.)/s", '$1', $value );
178183
}
179184
return $value;
180185
}

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4943,6 +4943,8 @@ private function translate_like( WP_Parser_Node $node ): string {
49434943
$is_binary = isset( $tokens[1] ) && WP_MySQL_Lexer::BINARY_SYMBOL === $tokens[1]->id;
49444944

49454945
if ( true === $is_binary ) {
4946+
// TODO: GLOB can match different invalid UTF-8 bytes as equal.
4947+
// Use byte-wise matching for full LIKE BINARY compatibility.
49464948
$children = $node->get_children();
49474949
return sprintf(
49484950
'GLOB _helper_like_to_glob_pattern(%s)',

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -950,8 +950,8 @@ public function reverse( $str ) {
950950
* affect also other patterns than just "LIKE BINARY". We should
951951
* consider applying some of the conversions more broadly.
952952
*
953-
* @param string $pattern
954-
* @return string
953+
* @param string|null $pattern
954+
* @return string|null
955955
*/
956956
public function _helper_like_to_glob_pattern( $pattern ) {
957957
if ( null === $pattern ) {
@@ -991,10 +991,9 @@ public function _helper_like_to_glob_pattern( $pattern ) {
991991
* This is true also for multi-byte characters:
992992
* SELECT '\\©' prints '\©', but LIKE '\\©' is equivalent to LIKE '©'.
993993
*
994-
* However, the multi-byte behavior is likely to depend on the charset.
995-
* For now, we'll assume UTF-8 and thus the "u" modifier for the regex.
994+
* Use "s" to include escaped newlines and omit "u" to preserve raw bytes.
996995
*/
997-
$pattern = preg_replace( '/\\\\(.)/u', '$1', $pattern );
996+
$pattern = preg_replace( '/\\\\(.)/s', '$1', $pattern );
998997

999998
return $pattern;
1000999
}

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4875,6 +4875,63 @@ public function testTranslateLikeBinary() {
48754875
$this->assertCount( 2, $result ); // Should match both 'first' and 'FIRST'
48764876
}
48774877

4878+
/**
4879+
* @dataProvider dataLikePatterns
4880+
*/
4881+
public function testLikePatternPreservesBytes( $pattern, $expected ): void {
4882+
$functions = new WP_SQLite_PDO_User_Defined_Functions();
4883+
4884+
$this->assertSame( $expected, $functions->_helper_like_to_glob_pattern( $pattern ) );
4885+
}
4886+
4887+
public function dataLikePatterns(): array {
4888+
return array(
4889+
'null' => array( null, null ),
4890+
'empty' => array( '', '' ),
4891+
'raw bytes' => array( "\xff\xfe\x80", "\xff\xfe\x80" ),
4892+
'escaped byte' => array( "\\\xff", "\xff" ),
4893+
'truncated UTF-8' => array( "\xe2\x82", "\xe2\x82" ),
4894+
'overlong UTF-8' => array( "\xc0\xaf", "\xc0\xaf" ),
4895+
'surrogate' => array( "\xed\xa0\x80", "\xed\xa0\x80" ),
4896+
'escaped newline' => array( "\\\n", "\n" ),
4897+
'escaped CRLF' => array( "\\\r\\\n", "\r\n" ),
4898+
'escaped null byte' => array( "\\\0", "\0" ),
4899+
'escaped Unicode' => array( '\\©\\🙂', '©🙂' ),
4900+
'wildcards with bytes' => array( "\xff%_\xfe", "\xff*?\xfe" ),
4901+
'escaped wildcards' => array( "\xff\\%\\_", "\xff%_" ),
4902+
'escaped backslash' => array( "\xff\\\\", "\xff\\" ),
4903+
'GLOB metacharacters' => array( "\xff*?]", "\xff[*][?][]]" ),
4904+
);
4905+
}
4906+
4907+
/**
4908+
* @dataProvider dataLikeBinaryPatterns
4909+
*/
4910+
public function testLikeBinaryPreservesPatternBytes( $value, $pattern, $expected ): void {
4911+
$query = sprintf(
4912+
'SELECT %s LIKE BINARY %s',
4913+
null === $value ? 'NULL' : $this->engine->quote( $value ),
4914+
null === $pattern ? 'NULL' : $this->engine->quote( $pattern )
4915+
);
4916+
4917+
$this->assertSame( $expected, $this->engine->query( $query )->fetchColumn() );
4918+
}
4919+
4920+
public function dataLikeBinaryPatterns(): array {
4921+
return array(
4922+
'raw byte' => array( "\xff", "\xff", '1' ),
4923+
'escaped byte' => array( "\xff", "\\\xff", '1' ),
4924+
'nonmatching text' => array( "\xffa", "\xffb", '0' ),
4925+
'percent wildcard' => array( "\xfftail", "\xff%", '1' ),
4926+
'underscore' => array( "\xffx", "\xff_", '1' ),
4927+
'escaped wildcards' => array( "\xff%_", "\xff\\%\\_", '1' ),
4928+
'escaped newline' => array( "\n", "\\\n", '1' ),
4929+
'escaped Unicode' => array( '©🙂', '\\©\\🙂', '1' ),
4930+
'null pattern' => array( 'x', null, null ),
4931+
'null value' => array( null, 'x', null ),
4932+
);
4933+
}
4934+
48784935
public function testUniqueConstraints() {
48794936
$this->assertQuery(
48804937
"CREATE TABLE _tmp_table (

‎packages/mysql-on-sqlite/tests/mysql/WP_MySQL_Lexer_Tests.php‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,30 @@ public function data_valid_escaped_strings(): array {
325325
);
326326
}
327327

328+
public function test_get_value_preserves_non_utf8_bytes_in_string_literals(): void {
329+
// A quoted literal may legitimately carry non-UTF-8 bytes (binary or
330+
// other-charset payloads). Value extraction must return them unchanged.
331+
$raw = chr( 0xFF ) . chr( 0xFE );
332+
$tokens = ( new WP_MySQL_Lexer( "SELECT '$raw'" ) )->remaining_tokens();
333+
$this->assertSame( $raw, $tokens[1]->get_value() );
334+
335+
// A backslash escape strips the backslash and preserves the following non-UTF-8 byte.
336+
$tokens = ( new WP_MySQL_Lexer( "SELECT '\\" . chr( 0xE9 ) . "'" ) )->remaining_tokens();
337+
$this->assertSame( chr( 0xE9 ), $tokens[1]->get_value() );
338+
339+
// Valid multibyte UTF-8 still round-trips.
340+
$tokens = ( new WP_MySQL_Lexer( "SELECT 'café 🙂'" ) )->remaining_tokens();
341+
$this->assertSame( 'café 🙂', $tokens[1]->get_value() );
342+
}
343+
344+
public function test_get_value_unescapes_newlines_and_multibyte_characters(): void {
345+
$tokens = ( new WP_MySQL_Lexer( "SELECT '\\\n'" ) )->remaining_tokens();
346+
$this->assertSame( "\n", $tokens[1]->get_value() );
347+
348+
$tokens = ( new WP_MySQL_Lexer( "SELECT '\\🙂'" ) )->remaining_tokens();
349+
$this->assertSame( '🙂', $tokens[1]->get_value() );
350+
}
351+
328352
/**
329353
* Test that a chunk boundary splitting a quoted string with a trailing
330354
* backslash does not cause an out-of-bounds string access.
@@ -398,6 +422,110 @@ public function data_underscore_charset_after_dot(): array {
398422
);
399423
}
400424

425+
public function test_ignore_space_preserves_function_name_ranges(): void {
426+
// Without "(", COUNT is an identifier whose range excludes trailing whitespace.
427+
$sql = 'SELECT COUNT FROM t';
428+
$tokens = ( new WP_MySQL_Lexer( $sql, 80400, array( 'IGNORE_SPACE' ) ) )->remaining_tokens();
429+
$this->assertSame( WP_MySQL_Lexer::IDENTIFIER, $tokens[1]->id, $sql );
430+
$this->assertSame( 'COUNT', $tokens[1]->get_value(), $sql );
431+
$this->assertSame( 5, $tokens[1]->length, $sql );
432+
$this->assertSame( 13, $tokens[2]->start, $sql );
433+
434+
$sql = "SELECT COUNT\t\n FROM t";
435+
$tokens = ( new WP_MySQL_Lexer( $sql, 80400, array( 'IGNORE_SPACE' ) ) )->remaining_tokens();
436+
$this->assertSame( WP_MySQL_Lexer::IDENTIFIER, $tokens[1]->id, $sql );
437+
$this->assertSame( 'COUNT', $tokens[1]->get_value(), $sql );
438+
$this->assertSame( 5, $tokens[1]->length, $sql );
439+
$this->assertSame( 15, $tokens[2]->start, $sql );
440+
441+
// With "(", COUNT is a function whose range still excludes the whitespace.
442+
$tokens = ( new WP_MySQL_Lexer( 'SELECT COUNT (1)', 80400, array( 'IGNORE_SPACE' ) ) )->remaining_tokens();
443+
$this->assertSame( WP_MySQL_Lexer::COUNT_SYMBOL, $tokens[1]->id );
444+
$this->assertSame( 5, $tokens[1]->length );
445+
$this->assertSame( WP_MySQL_Lexer::OPEN_PAR_SYMBOL, $tokens[2]->id );
446+
$this->assertSame( 13, $tokens[2]->start );
447+
448+
$sql = "SELECT COUNT \t\n";
449+
$tokens = ( new WP_MySQL_Lexer( $sql, 80400, array( 'IGNORE_SPACE' ) ) )->remaining_tokens();
450+
$this->assertSame( WP_MySQL_Lexer::IDENTIFIER, $tokens[1]->id, $sql );
451+
$this->assertSame( 'COUNT', $tokens[1]->get_value(), $sql );
452+
$this->assertSame( 5, $tokens[1]->length, $sql );
453+
$this->assertSame( WP_MySQL_Lexer::EOF, $tokens[2]->id, $sql );
454+
$this->assertSame( strlen( $sql ), $tokens[2]->start, $sql );
455+
}
456+
457+
/**
458+
* @dataProvider data_version_comments
459+
*/
460+
public function test_version_comments( string $sql, int $mysql_version, array $expected_bytes ): void {
461+
$tokens = ( new WP_MySQL_Lexer( $sql, $mysql_version ) )->remaining_tokens();
462+
$this->assertSame( WP_MySQL_Lexer::EOF, array_pop( $tokens )->id );
463+
$this->assertSame(
464+
$expected_bytes,
465+
array_map(
466+
static function ( WP_MySQL_Token $token ): string {
467+
return $token->get_bytes();
468+
},
469+
$tokens
470+
)
471+
);
472+
}
473+
474+
public function data_version_comments(): array {
475+
$cases = array(
476+
'five digits below version' => array( 'SELECT /*!80038 1 + */ 2', 80037, array( 'SELECT', '2' ) ),
477+
'five digits at version' => array( 'SELECT /*!80038 1 + */ 2', 80038, array( 'SELECT', '1', '+', '2' ) ),
478+
'six digits on MySQL 5.7' => array( 'SELECT /*!080005 + */ 1', 50744, array( 'SELECT', '5', '+', '1' ) ),
479+
'six digits on MySQL 8.0' => array( 'SELECT /*!080005 + */ 1', 80038, array( 'SELECT', '5', '+', '1' ) ),
480+
'six digits before 8.1' => array( 'SELECT /*!080005 + */ 1', 80099, array( 'SELECT', '5', '+', '1' ) ),
481+
'six digits on MySQL 8.1' => array( 'SELECT /*!080005 + */ 1', 80100, array( 'SELECT', '+', '1' ) ),
482+
'six digits on MySQL 8.4' => array( 'SELECT /*!080400 1 + */ 2', 80400, array( 'SELECT', '1', '+', '2' ) ),
483+
'six digits future major' => array( 'SELECT /*!100000 1 + */ 2', 80400, array( 'SELECT', '2' ) ),
484+
'six digits at major' => array( 'SELECT /*!100000 1 + */ 2', 100000, array( 'SELECT', '1', '+', '2' ) ),
485+
'six digits without space' => array( 'SELECT /*!080100+ */ 1', 80100, array( 'SELECT', '0', '+', '1' ) ),
486+
'six digits at comment end' => array( 'SELECT /*!080100*/ + 1', 80100, array( 'SELECT', '0', '+', '1' ) ),
487+
'seven digits' => array( 'SELECT /*!0801007 + */ 1', 80100, array( 'SELECT', '07', '+', '1' ) ),
488+
);
489+
490+
foreach ( array(
491+
'space' => ' ',
492+
'tab' => "\t",
493+
'LF' => "\n",
494+
'CR' => "\r",
495+
'FF' => "\f",
496+
'VT' => "\v",
497+
) as $name => $space ) {
498+
$cases[ "six digits before 8.1 with $name" ] = array(
499+
"SELECT /*!080100$space+ */ 1",
500+
80038,
501+
array( 'SELECT', '0', '+', '1' ),
502+
);
503+
$cases[ "six digits at version with $name" ] = array(
504+
"SELECT /*!080100$space+ */ 1",
505+
80100,
506+
array( 'SELECT', '+', '1' ),
507+
);
508+
$cases[ "six digits above version with $name" ] = array(
509+
"SELECT /*!080101$space+ */ 1",
510+
80100,
511+
array( 'SELECT', '1' ),
512+
);
513+
}
514+
515+
// Without five leading digits, the entire comment body remains SQL.
516+
foreach ( array( 80038, 80100 ) as $version ) {
517+
$cases[ "no version on $version" ] = array( 'SELECT /*! + */ 2', $version, array( 'SELECT', '+', '2' ) );
518+
foreach ( array( '1', '12', '123', '1234' ) as $digits ) {
519+
$cases[ "$digits as content on $version" ] = array(
520+
"SELECT /*!$digits + */ 2",
521+
$version,
522+
array( 'SELECT', $digits, '+', '2' ),
523+
);
524+
}
525+
}
526+
return $cases;
527+
}
528+
401529
/**
402530
* @dataProvider data_ansi_quotes_tokenization
403531
*/

0 commit comments

Comments
 (0)