Skip to content

Commit

Permalink
fix bus error on smaller readonly file in unix (#44354)
Browse files Browse the repository at this point in the history
Fixes: #28245
Co-authored-by: Jameson Nash <vtjnash@gmail.com>
Co-authored-by: Stefan Karpinski <stefan@karpinski.org>
  • Loading branch information
3 people committed Aug 21, 2023
1 parent 78d5bfe commit ead627e
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions stdlib/Mmap/src/Mmap.jl
Original file line number Diff line number Diff line change
Expand Up @@ -208,18 +208,43 @@ function mmap(io::IO,
mmaplen = (offset - offset_page) + len

file_desc = gethandle(io)
szfile = convert(Csize_t, len + offset)
requestedSizeLarger = false
if !(io isa Mmap.Anonymous)
@static if !Sys.isapple()
requestedSizeLarger = szfile > filesize(io)
end
end
# platform-specific mmapping
@static if Sys.isunix()
prot, flags, iswrite = settings(file_desc, shared)
iswrite && grow && grow!(io, offset, len)
if requestedSizeLarger
if iswrite
if grow
grow!(io, offset, len)
else
throw(ArgumentError("requested size $szfile larger than file size $(filesize(io)), but requested not to grow"))
end
else
throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
end
end
@static if Sys.isapple()
iswrite && grow && grow!(io, offset, len)
end
# mmap the file
ptr = ccall(:jl_mmap, Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t, Cint, Cint, RawFD, Int64),
C_NULL, mmaplen, prot, flags, file_desc, offset_page)
systemerror("memory mapping failed", reinterpret(Int, ptr) == -1)
else
name, readonly, create = settings(io)
szfile = convert(Csize_t, len + offset)
readonly && szfile > filesize(io) && throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
if requestedSizeLarger
if readonly
throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
elseif !grow
throw(ArgumentError("requested size $szfile larger than file size $(filesize(io)), but requested not to grow"))
end
end
handle = create ? ccall(:CreateFileMappingW, stdcall, Ptr{Cvoid}, (OS_HANDLE, Ptr{Cvoid}, DWORD, DWORD, DWORD, Cwstring),
file_desc, C_NULL, readonly ? PAGE_READONLY : PAGE_READWRITE, szfile >> 32, szfile & typemax(UInt32), name) :
ccall(:OpenFileMappingW, stdcall, Ptr{Cvoid}, (DWORD, Cint, Cwstring),
Expand Down

0 comments on commit ead627e

Please sign in to comment.