aboutsummaryrefslogtreecommitdiff
path: root/core/os/stat_windows.odin
blob: 51bd57d5b58c1a094d6ed3edce5861edad94d509 (plain)
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#+private
package os

import "base:runtime"
import "core:time"
import "core:strings"
import win32 "core:sys/windows"

_fstat :: proc(f: ^File, allocator: runtime.Allocator) -> (fi: File_Info, err: Error) {
	if f == nil || (^File_Impl)(f.impl).fd == nil {
		return
	}

	path := _cleanpath_from_handle(f, allocator) or_return

	h := _handle(f)
	switch win32.GetFileType(h) {
	case win32.FILE_TYPE_PIPE, win32.FILE_TYPE_CHAR:
		fi = File_Info {
			fullpath = path,
			name = basename(path),
			type = file_type(h),
		}
		return
	}

	return _file_info_from_get_file_information_by_handle(path, h, allocator)
}

_stat :: proc(name: string, allocator: runtime.Allocator) -> (File_Info, Error) {
	return internal_stat(name, win32.FILE_FLAG_BACKUP_SEMANTICS, allocator)
}

_lstat :: proc(name: string, allocator: runtime.Allocator) -> (File_Info, Error) {
	return internal_stat(name, win32.FILE_FLAG_BACKUP_SEMANTICS|win32.FILE_FLAG_OPEN_REPARSE_POINT, allocator)
}

_same_file :: proc(fi1, fi2: File_Info) -> bool {
	return fi1.fullpath == fi2.fullpath
}

full_path_from_name :: proc(name: string, allocator: runtime.Allocator) -> (path: string, err: Error) {
	name := name
	if name == "" {
		name = "."
	}

	temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })

	p := win32_utf8_to_utf16(name, temp_allocator) or_return

	n := win32.GetFullPathNameW(cstring16(raw_data(p)), 0, nil, nil)
	if n == 0 {
		return "", _get_platform_error()
	}
	buf := make([]u16, n+1, temp_allocator)
	n = win32.GetFullPathNameW(cstring16(raw_data(p)), u32(len(buf)), cstring16(raw_data(buf)), nil)
	if n == 0 {
		return "", _get_platform_error()
	}
	return win32_utf16_to_utf8(buf[:n], allocator)
}

internal_stat :: proc(name: string, create_file_attributes: u32, allocator: runtime.Allocator) -> (fi: File_Info, e: Error) {
	if len(name) == 0 {
		return {}, .Not_Exist
	}
	temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })

	wname := _fix_long_path(name, temp_allocator) or_return
	fa: win32.WIN32_FILE_ATTRIBUTE_DATA
	ok := win32.GetFileAttributesExW(wname, win32.GetFileExInfoStandard, &fa)
	if ok && fa.dwFileAttributes & win32.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
		// Not a symlink
		fi = _file_info_from_win32_file_attribute_data(&fa, name, allocator) or_return
		if fi.type == .Undetermined {
			fi.type = _file_type_from_create_file(wname, create_file_attributes)
		}
		return
	}

	err := 0 if ok else win32.GetLastError()

	if err == win32.ERROR_SHARING_VIOLATION {
		fd: win32.WIN32_FIND_DATAW
		sh := win32.FindFirstFileW(wname, &fd)
		if sh == win32.INVALID_HANDLE_VALUE {
			e = _get_platform_error()
			return
		}
		win32.FindClose(sh)

		fi = _file_info_from_win32_find_data(&fd, name, allocator) or_return
		if fi.type == .Undetermined {
			fi.type = _file_type_from_create_file(wname, create_file_attributes)
		}
		return
	}

	h := win32.CreateFileW(wname, 0, 0, nil, win32.OPEN_EXISTING, create_file_attributes, nil)
	if h == win32.INVALID_HANDLE_VALUE {
		e = _get_platform_error()
		return
	}
	defer win32.CloseHandle(h)
	return _file_info_from_get_file_information_by_handle(name, h, allocator)
}

_cleanpath_strip_prefix :: proc(buf: []u16) -> []u16 {
	buf := buf
	N := 0
	for c, i in buf {
		if c == 0 { break }
		N = i+1
	}
	buf = buf[:N]

	if len(buf) >= 4 {
		if buf[0] == '\\' &&
		   buf[1] == '\\' &&
		   buf[2] == '?'  &&
		   buf[3] == '\\' {
			buf = buf[4:]
		}
	}
	return buf
}

_cleanpath_from_handle :: proc(f: ^File, allocator: runtime.Allocator) -> (string, Error) {
	if f == nil {
		return "", nil
	}
	h := _handle(f)

	n := win32.GetFinalPathNameByHandleW(h, nil, 0, 0)
	if n == 0 {
		return "", _get_platform_error()
	}

	temp_allocator := TEMP_ALLOCATOR_GUARD({ allocator })

	buf := make([]u16, max(n, 260)+1, temp_allocator)
	n = win32.GetFinalPathNameByHandleW(h, cstring16(raw_data(buf)), u32(len(buf)), 0)
	return _cleanpath_from_buf(string16(buf[:n]), allocator)
}

_cleanpath_from_handle_u16 :: proc(f: ^File) -> ([]u16, Error) {
	if f  == nil {
		return nil, nil
	}
	h := _handle(f)

	n := win32.GetFinalPathNameByHandleW(h, nil, 0, 0)
	if n == 0 {
		return nil, _get_platform_error()
	}

	temp_allocator := TEMP_ALLOCATOR_GUARD({})

	buf := make([]u16, max(n, 260)+1, temp_allocator)
	n = win32.GetFinalPathNameByHandleW(h, cstring16(raw_data(buf)), u32(len(buf)), 0)
	return _cleanpath_strip_prefix(buf[:n]), nil
}

_cleanpath_from_buf :: proc(buf: string16, allocator: runtime.Allocator) -> (string, runtime.Allocator_Error) {
	buf := transmute([]u16)buf
	buf = _cleanpath_strip_prefix(buf)
	return win32_utf16_to_utf8(buf, allocator)
}

basename :: proc(name: string) -> (base: string) {
	name := name
	if len(name) > 3 && name[:3] == `\\?` {
		name = name[3:]
	}

	if len(name) == 2 && name[1] == ':' {
		return "."
	} else if len(name) > 2 && name[1] == ':' {
		name = name[2:]
	}
	i := len(name)-1

	for ; i > 0 && (name[i] == '/' || name[i] == '\\'); i -= 1 {
		name = name[:i]
	}
	for i -= 1; i >= 0; i -= 1 {
		if name[i] == '/' || name[i] == '\\' {
			name = name[i+1:]
			break
		}
	}
	return name
}

file_type :: proc(h: win32.HANDLE) -> File_Type {
	switch win32.GetFileType(h) {
	case win32.FILE_TYPE_PIPE: return .Named_Pipe
	case win32.FILE_TYPE_CHAR: return .Character_Device
	case win32.FILE_TYPE_DISK: return .Regular
	}
	return .Undetermined
}

_file_type_from_create_file :: proc(wname: win32.wstring, create_file_attributes: u32) -> File_Type {
	h := win32.CreateFileW(wname, 0, 0, nil, win32.OPEN_EXISTING, create_file_attributes, nil)
	if h == win32.INVALID_HANDLE_VALUE {
		return .Undetermined
	}
	defer win32.CloseHandle(h)
	return file_type(h)
}

_file_type_mode_from_file_attributes :: proc(file_attributes: win32.DWORD, h: win32.HANDLE, ReparseTag: win32.DWORD) -> (type: File_Type, mode: Permissions) {
	if file_attributes & win32.FILE_ATTRIBUTE_READONLY != 0 {
		mode += Permissions_Write_All
	} else {
		mode += Permissions_Read_Write_All
	}

	is_sym := false
	if file_attributes & win32.FILE_ATTRIBUTE_REPARSE_POINT == 0 {
		is_sym = false
	} else {
		is_sym = ReparseTag == win32.IO_REPARSE_TAG_SYMLINK || ReparseTag == win32.IO_REPARSE_TAG_MOUNT_POINT
	}

	if is_sym {
		type = .Symlink
	} else if file_attributes & win32.FILE_ATTRIBUTE_DIRECTORY != 0 {
		type = .Directory
		mode += Permissions_Execute_All
	} else if h != nil {
		type = file_type(h)
	}
	return
}

// a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC)
time_as_filetime :: #force_inline proc(t: time.Time) -> (ft: win32.LARGE_INTEGER) {
	win := u64(t._nsec / 100) + 116444736000000000
	return win32.LARGE_INTEGER(win)
}

filetime_as_time_li :: #force_inline proc(ft: win32.LARGE_INTEGER) -> (t: time.Time) {
	return {_nsec=(i64(ft) - 116444736000000000) * 100}
}

filetime_as_time_ft :: #force_inline proc(ft: win32.FILETIME) -> (t: time.Time) {
	return filetime_as_time_li(win32.LARGE_INTEGER(ft.dwLowDateTime) + win32.LARGE_INTEGER(ft.dwHighDateTime) << 32)
}

filetime_as_time :: proc{filetime_as_time_ft, filetime_as_time_li}

_file_info_from_win32_file_attribute_data :: proc(d: ^win32.WIN32_FILE_ATTRIBUTE_DATA, name: string, allocator: runtime.Allocator) -> (fi: File_Info, e: Error) {
	fi.size = i64(d.nFileSizeHigh)<<32 + i64(d.nFileSizeLow)
	type, mode := _file_type_mode_from_file_attributes(d.dwFileAttributes, nil, 0)
	fi.type = type
	fi.mode |= mode
	fi.creation_time     = filetime_as_time(d.ftCreationTime)
	fi.modification_time = filetime_as_time(d.ftLastWriteTime)
	fi.access_time       = filetime_as_time(d.ftLastAccessTime)
	fi.fullpath, e = full_path_from_name(name, allocator)
	fi.name = basename(fi.fullpath)
	return
}

_file_info_from_win32_find_data :: proc(d: ^win32.WIN32_FIND_DATAW, name: string, allocator: runtime.Allocator) -> (fi: File_Info, e: Error) {
	fi.size = i64(d.nFileSizeHigh)<<32 + i64(d.nFileSizeLow)
	type, mode := _file_type_mode_from_file_attributes(d.dwFileAttributes, nil, 0)
	fi.type = type
	fi.mode |= mode
	fi.creation_time     = filetime_as_time(d.ftCreationTime)
	fi.modification_time = filetime_as_time(d.ftLastWriteTime)
	fi.access_time       = filetime_as_time(d.ftLastAccessTime)
	fi.fullpath, e = full_path_from_name(name, allocator)
	fi.name = basename(fi.fullpath)
	return
}

_file_info_from_get_file_information_by_handle :: proc(path: string, h: win32.HANDLE, allocator: runtime.Allocator) -> (File_Info, Error) {
	d: win32.BY_HANDLE_FILE_INFORMATION
	if !win32.GetFileInformationByHandle(h, &d) {
		return {}, _get_platform_error()

	}

	ti: win32.FILE_ATTRIBUTE_TAG_INFO
	if !win32.GetFileInformationByHandleEx(h, .FileAttributeTagInfo, &ti, size_of(ti)) {
		err := _get_platform_error()
		if perr, ok := is_platform_error(err); ok && perr != i32(win32.ERROR_INVALID_PARAMETER) {
			return {}, err
		}
		// Indicate this is a symlink on FAT file systems
		ti.ReparseTag = 0
	}
	fi: File_Info
	fi.fullpath = path
	fi.name = basename(path)
	fi.inode = u128(u64(d.nFileIndexHigh)<<32 + u64(d.nFileIndexLow))
	fi.size  = i64(d.nFileSizeHigh)<<32  + i64(d.nFileSizeLow)
	type, mode := _file_type_mode_from_file_attributes(d.dwFileAttributes, h, 0)
	fi.type = type
	fi.mode |= mode
	fi.creation_time     = filetime_as_time(d.ftCreationTime)
	fi.modification_time = filetime_as_time(d.ftLastWriteTime)
	fi.access_time       = filetime_as_time(d.ftLastAccessTime)
	return fi, nil
}

reserved_names := [?]string{
	"CON", "PRN", "AUX", "NUL",
	"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
	"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
}

_is_reserved_name :: proc(path: string) -> bool {
	if len(path) == 0 {
		return false
	}
	for reserved in reserved_names {
		if strings.equal_fold(path, reserved) {
			return true
		}
	}
	return false
}

_volume_name_len :: proc(path: string) -> (length: int) {
	if len(path) < 2 {
		return 0
	}

	if path[1] == ':' {
		switch path[0] {
		case 'a'..='z', 'A'..='Z':
			return 2
		}
	}

	/*
		See: URL: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
		Further allowed paths can be of the form of:
		- \\server\share or \\server\share\more\path
		- \\?\C:\...
		- \\.\PhysicalDriveX
	*/
	// Any remaining kind of path has to start with two slashes.
	if !_is_path_separator(path[0]) || !_is_path_separator(path[1]) {
		return 0
	}

	// Device path. The volume name is the whole string
	if len(path) >= 5 && path[2] == '.' && _is_path_separator(path[3]) {
		return len(path)
	}

	// We're a UNC share `\\host\share`, file namespace `\\?\C:` or UNC in file namespace `\\?\\host\share`
	prefix := 2

	// File namespace.
	if len(path) >= 5 && path[2] == '?' && _is_path_separator(path[3]) {
		if _is_path_separator(path[4]) {
			// `\\?\\` UNC path in file namespace
			prefix = 5
		}

		if len(path) >= 6 && path[5] == ':' {
			switch path[4] {
			case 'a'..='z', 'A'..='Z':
				return 6
			case:
				return 0
			}
		}
	}

	// UNC path, minimum version of the volume is `\\h\s` for host, share.
	// Can also contain an IP address in the host position.
	slash_count := 0
	for i in prefix..<len(path) {
		// Host needs to be at least 1 character
		if _is_path_separator(path[i]) && i > 0 {
			slash_count += 1

			if slash_count == 2 {
				return i
			}
		}
	}

	return len(path)
}