Skip to content

Commit

Permalink
Use ascii encoding for char strings in string convenience functions
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbssa committed Dec 3, 2023
1 parent 1769cbc commit 1256c3a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
19 changes: 15 additions & 4 deletions gdb/python/lib/gdb/function/strfns.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ def invoke(self, a, b, length):
return a_ptr.dereference() == b_ptr.dereference()


def char_as_ascii_string(a):
t = a.type.strip_typedefs()
if (
t.code in [gdb.TYPE_CODE_ARRAY, gdb.TYPE_CODE_PTR]
and t.target().strip_typedefs().name == "char"
):
return a.string(encoding="ascii", errors="surrogateescape")
else:
return a.string(errors="surrogateescape")


class _StrLen(gdb.Function):
"""$_strlen - compute string length.
Expand All @@ -56,7 +67,7 @@ def __init__(self):
super(_StrLen, self).__init__("_strlen")

def invoke(self, a):
s = a.string()
s = char_as_ascii_string(a)
return len(s)


Expand All @@ -76,7 +87,7 @@ def __init__(self):
super(_StrEq, self).__init__("_streq")

def invoke(self, a, b):
return a.string() == b.string()
return char_as_ascii_string(a) == char_as_ascii_string(b)


class _RegEx(gdb.Function):
Expand All @@ -92,8 +103,8 @@ def __init__(self):
super(_RegEx, self).__init__("_regex")

def invoke(self, string, regex):
s = string.string()
r = re.compile(regex.string())
s = char_as_ascii_string(string)
r = re.compile(char_as_ascii_string(regex))
return bool(r.match(s))


Expand Down
2 changes: 2 additions & 0 deletions gdb/testsuite/gdb.python/py-strfns.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
const char str1[] = "Hello.";
const char str2[] = "Hello.";
const char str3[] = "Goodbye.";
const char str4[] = "\xed\x95\x9c";
const char str5[] = "\xff";

const char buf1[] = { 0, 1, 2, 3 };
const char buf2[] = { 0, 1, 2, 3 };
Expand Down
14 changes: 14 additions & 0 deletions gdb/testsuite/gdb.python/py-strfns.exp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ proc test_all_strfns { } {
gdb_test {p $_regex (str1, "Help")} " = 0"
gdb_test {p $_regex (str1, "^Hello")} " = 1"
gdb_test {p $_regex (str1, "^Hello.$")} " = 1"

foreach_with_prefix charset {CP1252 UTF-8 ASCII} {
gdb_test_no_output "set target-charset $charset"

gdb_test "p \$_strlen (str4)" " = 3"
gdb_test "p \$_strlen (str5)" " = 1"

gdb_test {p $_streq (str1, str4)} " = 0"
gdb_test {p $_streq (str5, "test")} " = 0"
gdb_test {p $_streq (str5, "\xff")} " = 1"
gdb_test {p $_streq (str1, "\xff")} " = 0"

gdb_test {p $_regex (str4, ".\x95")} " = 1"
}
}

test_all_strfns
Expand Down

0 comments on commit 1256c3a

Please sign in to comment.