From f8fa94cb20672fc517d2621bbe3fce622ae76bce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan=20Talpalaru?= Date: Thu, 22 Nov 2018 14:47:27 +0100 Subject: [PATCH] fix segfault when calling shallow() on an empty string (#9782) [backport] shallow() casts its string argument to a seq and then tries to access its fields. Guess what happens when that string is nil, which seems to be the representation of an empty string (both the default value and an explicitly assigned ""). Segfault encountered when running "ntags -R ." on a large project. The relevant line: https://bitbucket.org/nimcontrib/ntags/src/a1c62c38e539877c105fbe4e08d06b76232f8017/ntags.nim#lines-125 --- lib/system.nim | 2 ++ tests/system/tnilconcats.nim | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/lib/system.nim b/lib/system.nim index a7b22a283..e8b427c55 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -4028,6 +4028,8 @@ proc shallow*(s: var string) {.noSideEffect, inline.} = ## purposes. when not defined(JS) and not defined(nimscript) and not defined(gcDestructors): var s = cast[PGenericSeq](s) + if s == nil: + s = cast[PGenericSeq](newString(0)) # string literals cannot become 'shallow': if (s.reserved and strlitFlag) == 0: s.reserved = s.reserved or seqShallowFlag diff --git a/tests/system/tnilconcats.nim b/tests/system/tnilconcats.nim index 5e4a1b317..c1126405c 100644 --- a/tests/system/tnilconcats.nim +++ b/tests/system/tnilconcats.nim @@ -23,3 +23,10 @@ when true: doAssert s == "fooabc" echo x + + # casting an empty string as sequence with shallow() should not segfault + var s2: string + shallow(s2) + s2 &= "foo" + doAssert s2 == "foo" +