diff --git a/base/strings/util.jl b/base/strings/util.jl index d624c612cd29c..b97a76a24b3e8 100644 --- a/base/strings/util.jl +++ b/base/strings/util.jl @@ -243,7 +243,7 @@ function lpad( n::Integer, p::Union{AbstractChar,AbstractString}=' ', ) :: String - m = n - length(s) + m = signed(n) - length(s) m ≤ 0 && return string(s) l = length(p) q, r = divrem(m, l) @@ -270,7 +270,7 @@ function rpad( n::Integer, p::Union{AbstractChar,AbstractString}=' ', ) :: String - m = n - length(s) + m = signed(n) - length(s) m ≤ 0 && return string(s) l = length(p) q, r = divrem(m, l) diff --git a/src/array.c b/src/array.c index 1afceb7054a56..5256ccf7266d0 100644 --- a/src/array.c +++ b/src/array.c @@ -471,6 +471,8 @@ JL_DLLEXPORT jl_value_t *jl_array_to_string(jl_array_t *a) JL_DLLEXPORT jl_value_t *jl_pchar_to_string(const char *str, size_t len) { size_t sz = sizeof(size_t) + len + 1; // add space for trailing \nul protector and size + if (sz < len) // overflow + jl_throw(jl_memory_exception); if (len == 0) return jl_an_empty_string; jl_value_t *s = jl_gc_alloc_(jl_get_ptls_states(), sz, jl_string_type); // force inlining @@ -483,6 +485,8 @@ JL_DLLEXPORT jl_value_t *jl_pchar_to_string(const char *str, size_t len) JL_DLLEXPORT jl_value_t *jl_alloc_string(size_t len) { size_t sz = sizeof(size_t) + len + 1; // add space for trailing \nul protector and size + if (sz < len) // overflow + jl_throw(jl_memory_exception); if (len == 0) return jl_an_empty_string; jl_value_t *s = jl_gc_alloc_(jl_get_ptls_states(), sz, jl_string_type); // force inlining diff --git a/test/strings/basic.jl b/test/strings/basic.jl index af17c4dee095a..25ee4c9ea8ea0 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -606,6 +606,8 @@ end @test repeat(s, 3) === S @test repeat(S, 3) === S*S*S end + # Issue #32160 (string allocation unsigned overflow) + @test_throws OutOfMemoryError repeat('x', typemax(Csize_t)) end @testset "issue #12495: check that logical indexing attempt raises ArgumentError" begin @test_throws ArgumentError "abc"[[true, false, true]] diff --git a/test/strings/util.jl b/test/strings/util.jl index 43d88853c4db9..59024e972021b 100644 --- a/test/strings/util.jl +++ b/test/strings/util.jl @@ -41,6 +41,9 @@ @test rpad("αβ", 8, "¹₂³") == "αβ¹₂³¹₂³" @test lpad("αβ", 9, "¹₂³") == "¹₂³¹₂³¹αβ" @test rpad("αβ", 9, "¹₂³") == "αβ¹₂³¹₂³¹" + # Issue #32160 (unsigned underflow in lpad/rpad) + @test lpad("xx", UInt(1), " ") == "xx" + @test rpad("xx", UInt(1), " ") == "xx" end # string manipulation