-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
libc.jl
333 lines (269 loc) · 9.88 KB
/
libc.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# This file is a part of Julia. License is MIT: http://julialang.org/license
module Libc
import Base: transcode
export FILE, TmStruct, strftime, strptime, getpid, gethostname, free, malloc, calloc, realloc,
errno, strerror, flush_cstdio, systemsleep, time, transcode
if is_windows()
export GetLastError, FormatMessage
end
include(string(length(Core.ARGS)>=2?Core.ARGS[2]:"","errno_h.jl")) # include($BUILDROOT/base/errno_h.jl)
## RawFD ##
# Wrapper for an OS file descriptor (on both Unix and Windows)
immutable RawFD
fd::Int32
RawFD(fd::Integer) = new(fd)
RawFD(fd::RawFD) = fd
end
Base.cconvert(::Type{Int32}, fd::RawFD) = fd.fd
dup(x::RawFD) = RawFD(ccall((@static is_windows() ? :_dup : :dup), Int32, (Int32,), x.fd))
dup(src::RawFD, target::RawFD) = systemerror("dup", -1 ==
ccall((@static is_windows() ? :_dup2 : :dup2), Int32,
(Int32, Int32), src.fd, target.fd))
# Wrapper for an OS file descriptor (for Windows)
if is_windows()
immutable WindowsRawSocket
handle::Ptr{Void} # On Windows file descriptors are HANDLE's and 64-bit on 64-bit Windows
end
Base.cconvert(::Type{Ptr{Void}}, fd::WindowsRawSocket) = fd.handle
_get_osfhandle(fd::RawFD) = WindowsRawSocket(ccall(:_get_osfhandle,Ptr{Void},(Cint,),fd.fd))
_get_osfhandle(fd::WindowsRawSocket) = fd
else
_get_osfhandle(fd::RawFD) = fd
end
## FILE (not auto-finalized) ##
immutable FILE
ptr::Ptr{Void}
end
modestr(s::IO) = modestr(isreadable(s), iswritable(s))
modestr(r::Bool, w::Bool) = r ? (w ? "r+" : "r") : (w ? "w" : throw(ArgumentError("neither readable nor writable")))
function FILE(fd::RawFD, mode)
FILEp = ccall((@static is_windows() ? :_fdopen : :fdopen), Ptr{Void}, (Cint, Cstring), fd, mode)
systemerror("fdopen", FILEp == C_NULL)
FILE(FILEp)
end
function FILE(s::IO)
f = FILE(dup(RawFD(fd(s))),modestr(s))
seek(f, position(s))
f
end
Base.unsafe_convert(T::Union{Type{Ptr{Void}},Type{Ptr{FILE}}}, f::FILE) = convert(T, f.ptr)
Base.close(f::FILE) = systemerror("fclose", ccall(:fclose, Cint, (Ptr{Void},), f.ptr) != 0)
Base.convert(::Type{FILE}, s::IO) = FILE(s)
function Base.seek(h::FILE, offset::Integer)
systemerror("fseek", ccall(:fseek, Cint, (Ptr{Void}, Clong, Cint),
h.ptr, offset, 0) != 0)
h
end
Base.position(h::FILE) = ccall(:ftell, Clong, (Ptr{Void},), h.ptr)
# flush C stdio output from external libraries
"""
flush_cstdio()
Flushes the C `stdout` and `stderr` streams (which may have been written to by external C code).
"""
flush_cstdio() = ccall(:jl_flush_cstdio, Void, ())
## time-related functions ##
# TODO: check for usleep errors?
if is_unix()
systemsleep(s::Real) = ccall(:usleep, Int32, (UInt32,), round(UInt32, s*1e6))
elseif is_windows()
function systemsleep(s::Real)
ccall(:Sleep, stdcall, Void, (UInt32,), round(UInt32, s * 1e3))
return Int32(0)
end
else
error("systemsleep undefined for this OS")
end
immutable TimeVal
sec::Int64
usec::Int64
end
function TimeVal()
tv = Ref{TimeVal}()
status = ccall(:jl_gettimeofday, Cint, (Ref{TimeVal},), tv)
status != 0 && error("unable to determine current time: ", status)
return tv[]
end
"""
TmStruct([seconds])
Convert a number of seconds since the epoch to broken-down format, with fields `sec`, `min`,
`hour`, `mday`, `month`, `year`, `wday`, `yday`, and `isdst`.
"""
type TmStruct
sec::Int32
min::Int32
hour::Int32
mday::Int32
month::Int32
year::Int32
wday::Int32
yday::Int32
isdst::Int32
# on some platforms the struct is 14 words, even though 9 are specified
_10::Int32
_11::Int32
_12::Int32
_13::Int32
_14::Int32
TmStruct(sec, min, hour, mday, month, year, wday, yday, isdst) =
new(sec, min, hour, mday, month, year, wday, yday, isdst, 0,0,0,0,0)
TmStruct() = new(0,0,0,0,0,0,0,0,0,0,0,0,0,0)
function TmStruct(t::Real)
t = floor(t)
tm = TmStruct()
# TODO: add support for UTC via gmtime_r()
ccall(:localtime_r, Ptr{TmStruct}, (Ptr{Int}, Ptr{TmStruct}), &t, &tm)
return tm
end
end
"""
strftime([format], time)
Convert time, given as a number of seconds since the epoch or a `TmStruct`, to a formatted
string using the given format. Supported formats are the same as those in the standard C
library.
"""
strftime(t) = strftime("%c", t)
strftime(fmt::AbstractString, t::Real) = strftime(fmt, TmStruct(t))
function strftime(fmt::AbstractString, tm::TmStruct)
timestr = Array{UInt8}(128)
n = ccall(:strftime, Int, (Ptr{UInt8}, Int, Cstring, Ptr{TmStruct}),
timestr, length(timestr), fmt, &tm)
if n == 0
return ""
end
return String(timestr[1:n])
end
"""
strptime([format], timestr)
Parse a formatted time string into a `TmStruct` giving the seconds, minute, hour, date, etc.
Supported formats are the same as those in the standard C library. On some platforms,
timezones will not be parsed correctly. If the result of this function will be passed to
`time` to convert it to seconds since the epoch, the `isdst` field should be filled in
manually. Setting it to `-1` will tell the C library to use the current system settings to
determine the timezone.
"""
strptime(timestr::AbstractString) = strptime("%c", timestr)
function strptime(fmt::AbstractString, timestr::AbstractString)
tm = TmStruct()
r = ccall(:strptime, Cstring, (Cstring, Cstring, Ptr{TmStruct}),
timestr, fmt, &tm)
# the following would tell mktime() that this is a local time, and that
# it should try to guess the timezone. not sure if/how this should be
# exposed in the API.
# tm.isdst = -1
if r == C_NULL
# TODO: better error message
throw(ArgumentError("invalid arguments"))
end
@static if is_apple()
# if we didn't explicitly parse the weekday or year day, use mktime
# to fill them in automatically.
if !ismatch(r"([^%]|^)%(a|A|j|w|Ow)", fmt)
ccall(:mktime, Int, (Ptr{TmStruct},), &tm)
end
end
return tm
end
# system date in seconds
"""
time(t::TmStruct)
Converts a `TmStruct` struct to a number of seconds since the epoch.
"""
time(tm::TmStruct) = Float64(ccall(:mktime, Int, (Ptr{TmStruct},), &tm))
time() = ccall(:jl_clock_now, Float64, ())
## process-related functions ##
"""
getpid() -> Int32
Get Julia's process ID.
"""
getpid() = ccall(:jl_getpid, Int32, ())
## network functions ##
"""
gethostname() -> AbstractString
Get the local machine's host name.
"""
function gethostname()
hn = Array{UInt8}(256)
err = @static if is_windows()
ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn))
else
ccall(:gethostname, Int32, (Ptr{UInt8}, UInt), hn, length(hn))
end
systemerror("gethostname", err != 0)
return unsafe_string(pointer(hn))
end
## system error handling ##
"""
errno([code])
Get the value of the C library's `errno`. If an argument is specified, it is used to set the
value of `errno`.
The value of `errno` is only valid immediately after a `ccall` to a C library routine that
sets it. Specifically, you cannot call `errno` at the next prompt in a REPL, because lots of
code is executed between prompts.
"""
errno() = ccall(:jl_errno, Cint, ())
errno(e::Integer) = ccall(:jl_set_errno, Void, (Cint,), e)
"""
strerror(n=errno())
Convert a system call error code to a descriptive string
"""
strerror(e::Integer) = unsafe_string(ccall(:strerror, Cstring, (Int32,), e))
strerror() = strerror(errno())
"""
GetLastError()
Call the Win32 `GetLastError` function [only available on Windows].
"""
function GetLastError end
"""
FormatMessage(n=GetLastError())
Convert a Win32 system call error code to a descriptive string [only available on Windows].
"""
function FormatMessage end
if is_windows()
GetLastError() = ccall(:GetLastError,stdcall,UInt32,())
function FormatMessage(e=GetLastError())
const FORMAT_MESSAGE_ALLOCATE_BUFFER = UInt32(0x100)
const FORMAT_MESSAGE_FROM_SYSTEM = UInt32(0x1000)
const FORMAT_MESSAGE_IGNORE_INSERTS = UInt32(0x200)
const FORMAT_MESSAGE_MAX_WIDTH_MASK = UInt32(0xFF)
lpMsgBuf = Array(Ptr{UInt16})
lpMsgBuf[1] = 0
len = ccall(:FormatMessageW,stdcall,UInt32,(Cint, Ptr{Void}, Cint, Cint, Ptr{Ptr{UInt16}}, Cint, Ptr{Void}),
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
C_NULL, e, 0, lpMsgBuf, 0, C_NULL)
p = lpMsgBuf[1]
len == 0 && return ""
buf = Array{UInt16}(len)
unsafe_copy!(pointer(buf), p, len)
ccall(:LocalFree,stdcall,Ptr{Void},(Ptr{Void},),p)
return transcode(String, buf)
end
end
## Memory related ##
"""
free(addr::Ptr)
Call `free` from the C standard library. Only use this on memory obtained from `malloc`, not
on pointers retrieved from other C libraries. `Ptr` objects obtained from C libraries should
be freed by the free functions defined in that library, to avoid assertion failures if
multiple `libc` libraries exist on the system.
"""
free(p::Ptr) = ccall(:free, Void, (Ptr{Void},), p)
"""
malloc(size::Integer) -> Ptr{Void}
Call `malloc` from the C standard library.
"""
malloc(size::Integer) = ccall(:malloc, Ptr{Void}, (Csize_t,), size)
"""
realloc(addr::Ptr, size::Integer) -> Ptr{Void}
Call `realloc` from the C standard library.
See warning in the documentation for `free` regarding only using this on memory originally
obtained from `malloc`.
"""
realloc(p::Ptr, size::Integer) = ccall(:realloc, Ptr{Void}, (Ptr{Void}, Csize_t), p, size)
"""
calloc(num::Integer, size::Integer) -> Ptr{Void}
Call `calloc` from the C standard library.
"""
calloc(num::Integer, size::Integer) = ccall(:calloc, Ptr{Void}, (Csize_t, Csize_t), num, size)
free(p::Cstring) = free(convert(Ptr{UInt8}, p))
free(p::Cwstring) = free(convert(Ptr{Cwchar_t}, p))
end # module