-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix: panic musn't allocate error message string
- Loading branch information
1 parent
82b7e69
commit 75360de
Showing
1 changed file
with
29 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |