nim-works / nimskull

An in development statically typed systems programming language; with sustainability at its core. We, the community of users, maintain it.
https://nim-works.github.io/nimskull/index.html
Other
275 stars 39 forks source link

Crash in typeinfo when using the marshal module #1462

Closed DiThi closed 1 week ago

DiThi commented 2 weeks ago

Specification

Using the marshal module the application crashes in some situations.

Example

import std/marshal

type ImageSetting = object
    filename, name: string
    a, b, c: float32

type Settings = object
    last_uri: string
    images: seq[ImageSetting]

var settings: Settings

# it only crashes when last_uri is at least 40 characters long

settings = to[Settings]("""{
  "last_uri": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "images": [
    {
      "name": ""
    }
  ]
}""")

echo settings

This is the smallest I've been able to make an example that crashes before even doing anything with it. If we remove anything, it seems to work until you use the data (with the last echo) when it does crash trying to access a string.

Actual Output

Traceback (most recent call last)
[...]/main.nim(16) main
[...]/nimskull/lib/pure/marshal.nim(339) to
[...]/nimskull/lib/pure/marshal.nim(269) loadAny
[...]/nimskull/lib/pure/marshal.nim(189) loadAny
[...]/nimskull/lib/pure/marshal.nim(174) loadAny
[...]/nimskull/lib/pure/marshal.nim(189) loadAny
[...]/nimskull/lib/pure/marshal.nim(236) loadAny
[...]/nimskull/lib/core/typeinfo.nim(605) setString
SIGSEGV: Illegal storage access. (Attempt to read from nil?)

And if we do something like removing a float or shortening the string:

Traceback (most recent call last)
[...]/src/main.nim(25) main
[...]/nimskull/lib/system/dollars.nim(104) $
[...]/nimskull/lib/system.nim(2848) addQuoted
[...]/nimskull/lib/system/dollars.nim(146) $
[...]/nimskull/lib/system/dollars.nim(116) collectionToString
[...]/nimskull/lib/system.nim(2848) addQuoted
[...]/nimskull/lib/system/dollars.nim(104) $
[...]/nimskull/lib/system.nim(2828) addQuoted
SIGSEGV: Illegal storage access. (Attempt to read from nil?)

Expected Output

(last_uri: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", images: @[(filename: "", name: "", a: 0.0, b: 0.0, c: 0.0)])

Possible Solution

Printing some info in setString suggests that the string "name" is being overwritten with "xxxxxxxxxxxxxxxx", so both the length and the address of the payload become 8680820740569200760.

Additional information

Using Linux x86_64, all default settings.

zerbina commented 2 weeks ago

The problem is with the content of the freshly-allocated sequence not being zeroed, resulting in a segmentation fault when a string is assigned to a location therein.