Skip to content

Commit 97eaf2b

Browse files
bpo-41524: fix pointer bug in PyOS_mystr{n}icmp (GH-21845)
* bpo-41524: fix pointer bug in PyOS_mystr{n}icmp The existing implementations of PyOS_mystrnicmp and PyOS_mystricmp can increment pointers beyond the end of a string. This commit fixes those cases by moving the mutation out of the condition. * 📜🤖 Added by blurb_it. * Address comments Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com>
1 parent 022bc75 commit 97eaf2b

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix bug in PyOS_mystrnicmp and PyOS_mystricmp that incremented
2+
pointers beyond the end of a string.

Python/pystrcmp.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,25 @@
66
int
77
PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size)
88
{
9+
const unsigned char *p1, *p2;
910
if (size == 0)
1011
return 0;
11-
while ((--size > 0) &&
12-
(tolower((unsigned)*s1) == tolower((unsigned)*s2))) {
13-
if (!*s1++ || !*s2++)
14-
break;
12+
p1 = (const unsigned char *)s1;
13+
p2 = (const unsigned char *)s2;
14+
for (; (--size > 0) && *p1 && *p2 && (tolower(*p1) == tolower(*p2));
15+
p1++, p2++) {
16+
;
1517
}
16-
return tolower((unsigned)*s1) - tolower((unsigned)*s2);
18+
return tolower(*p1) - tolower(*p2);
1719
}
1820

1921
int
2022
PyOS_mystricmp(const char *s1, const char *s2)
2123
{
22-
while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) {
24+
const unsigned char *p1 = (const unsigned char *)s1;
25+
const unsigned char *p2 = (const unsigned char *)s2;
26+
for (; *p1 && *p2 && (tolower(*p1) == tolower(*p2)); p1++, p2++) {
2327
;
2428
}
25-
return (tolower((unsigned)*s1) - tolower((unsigned)*s2));
29+
return (tolower(*p1) - tolower(*p2));
2630
}

0 commit comments

Comments
 (0)