Skip to content

Commit

Permalink
Fix: panic musn't allocate error message string
Browse files Browse the repository at this point in the history
  • Loading branch information
ysbaddaden committed Jun 19, 2024
1 parent 82b7e69 commit 75360de
Showing 1 changed file with 29 additions and 14 deletions.
43 changes: 29 additions & 14 deletions src/crystal/system/panic.cr
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
module Crystal::System
# Prints a system error message on the standard error then exits.
# Prints a system error message on the standard error then exits with an error
# status.
#
# Prefer `RuntimeError.from_os_error` unless you can't allocate any memory
# (e.g. stop the world).
def self.panic(syscall_name : String, error = nil)
error ||=
{% if flag?(:unix) %}
Errno.value
{% elsif flag?(:win32) %}
WinError.value
{% else %}
{% raise "Unsupported target" %}
{% end %}
Crystal::System.print_error("%s failed with %s (%s)\n",
syscall_name, error.message, error.to_s)
exit 1
end
{% if flag?(:unix) %}
def self.panic(syscall_name : String, error : Errno = Errno.value) : NoReturn
buffer = LibC.strerror(error.value)
message = Bytes.new(buffer, LibC.strlen(buffer))
Crystal::System.print_error("%s failed with ", syscall_name)
Crystal::System.print_error(message)
Crystal::System.print_error(" (%s)\n", error.to_s)
exit 1
end
{% elsif flag?(:win32) %}
def self.panic(syscall_name : String, error : WinError = WinError.value) : NoReturn
buffer = uninitialized UInt16[256]
size = LibC.FormatMessageW(LibC::FORMAT_MESSAGE_FROM_SYSTEM, nil, error.value, 0, buffer, buffer.size, nil)
message = buffer.to_slice[0, size]
Crystal::System.print_error("%s failed with ", syscall_name)
Crystal::System.print_error(message)
Crystal::System.print_error(" (%s)\n", error.to_s)
exit 1
end
{% elsif flag?(:wasm32) %}
def self.panic(syscall_name : String, error : WasiError) : NoReturn
Crystal::System.print_error("%s failed with %s (%s)", syscall_name, error.message, error.to_s)
exit 1
end
{% else %}
{% raise "Unsupported target" %}
{% end %}
end

0 comments on commit 75360de

Please sign in to comment.