Skip to content

Commit 6fcff37

Browse files
xgdgscKristofferC
authored and
KristofferC
committed
fix bus error on smaller readonly file in unix (#44354)
Fixes: #28245 Co-authored-by: Jameson Nash <[email protected]> Co-authored-by: Stefan Karpinski <[email protected]> (cherry picked from commit ead627e)
1 parent 2ef3842 commit 6fcff37

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

stdlib/Mmap/src/Mmap.jl

+28-3
Original file line numberDiff line numberDiff line change
@@ -208,18 +208,43 @@ function mmap(io::IO,
208208
mmaplen = (offset - offset_page) + len
209209

210210
file_desc = gethandle(io)
211+
szfile = convert(Csize_t, len + offset)
212+
requestedSizeLarger = false
213+
if !(io isa Mmap.Anonymous)
214+
@static if !Sys.isapple()
215+
requestedSizeLarger = szfile > filesize(io)
216+
end
217+
end
211218
# platform-specific mmapping
212219
@static if Sys.isunix()
213220
prot, flags, iswrite = settings(file_desc, shared)
214-
iswrite && grow && grow!(io, offset, len)
221+
if requestedSizeLarger
222+
if iswrite
223+
if grow
224+
grow!(io, offset, len)
225+
else
226+
throw(ArgumentError("requested size $szfile larger than file size $(filesize(io)), but requested not to grow"))
227+
end
228+
else
229+
throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
230+
end
231+
end
232+
@static if Sys.isapple()
233+
iswrite && grow && grow!(io, offset, len)
234+
end
215235
# mmap the file
216236
ptr = ccall(:jl_mmap, Ptr{Cvoid}, (Ptr{Cvoid}, Csize_t, Cint, Cint, RawFD, Int64),
217237
C_NULL, mmaplen, prot, flags, file_desc, offset_page)
218238
systemerror("memory mapping failed", reinterpret(Int, ptr) == -1)
219239
else
220240
name, readonly, create = settings(io)
221-
szfile = convert(Csize_t, len + offset)
222-
readonly && szfile > filesize(io) && throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
241+
if requestedSizeLarger
242+
if readonly
243+
throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions"))
244+
elseif !grow
245+
throw(ArgumentError("requested size $szfile larger than file size $(filesize(io)), but requested not to grow"))
246+
end
247+
end
223248
handle = create ? ccall(:CreateFileMappingW, stdcall, Ptr{Cvoid}, (OS_HANDLE, Ptr{Cvoid}, DWORD, DWORD, DWORD, Cwstring),
224249
file_desc, C_NULL, readonly ? PAGE_READONLY : PAGE_READWRITE, szfile >> 32, szfile & typemax(UInt32), name) :
225250
ccall(:OpenFileMappingW, stdcall, Ptr{Cvoid}, (DWORD, Cint, Cwstring),

0 commit comments

Comments
 (0)