-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvm_windows_file_system.dart
451 lines (411 loc) · 14.3 KB
/
vm_windows_file_system.dart
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:ffi';
import 'dart:io' as io;
import 'dart:math';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'package:ffi/ffi.dart' as ffi;
import 'package:win32/win32.dart' as win32;
import 'file_system.dart';
import 'internal_constants.dart';
const _hundredsOfNanosecondsPerMicrosecond = 10;
DateTime _fileTimeToDateTime(int t) {
final microseconds = t ~/ _hundredsOfNanosecondsPerMicrosecond;
return DateTime.utc(1601, 1, 1, 0, 0, 0, 0, microseconds);
}
String _formatMessage(int errorCode) {
final buffer = win32.wsalloc(1024);
try {
final result = win32.FormatMessage(
win32.FORMAT_MESSAGE_FROM_SYSTEM | win32.FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
errorCode,
0, // default language
buffer,
1024,
nullptr,
);
if (result == 0) {
return '';
} else {
return buffer.toDartString();
}
} finally {
win32.free(buffer);
}
}
Exception _getError(int errorCode, String message, String path) {
final osError = io.OSError(_formatMessage(errorCode), errorCode);
switch (errorCode) {
case win32.ERROR_ACCESS_DENIED:
case win32.ERROR_CURRENT_DIRECTORY:
case win32.ERROR_WRITE_PROTECT:
case win32.ERROR_BAD_LENGTH:
case win32.ERROR_SHARING_VIOLATION:
case win32.ERROR_LOCK_VIOLATION:
case win32.ERROR_NETWORK_ACCESS_DENIED:
case win32.ERROR_DRIVE_LOCKED:
return io.PathAccessException(path, osError, message);
case win32.ERROR_FILE_EXISTS:
case win32.ERROR_ALREADY_EXISTS:
return io.PathExistsException(path, osError, message);
case win32.ERROR_FILE_NOT_FOUND:
case win32.ERROR_PATH_NOT_FOUND:
case win32.ERROR_INVALID_DRIVE:
case win32.ERROR_INVALID_NAME:
case win32.ERROR_NO_MORE_FILES:
case win32.ERROR_BAD_NETPATH:
case win32.ERROR_BAD_NET_NAME:
case win32.ERROR_BAD_PATHNAME:
return io.PathNotFoundException(path, osError, message);
default:
return io.FileSystemException(message, path, osError);
}
}
/// File system entity data available on Windows.
final class WindowsMetadata implements Metadata {
// TODO(brianquinlan): Reoganize fields when the POSIX `metadata` is
// available.
// TODO(brianquinlan): Document the public fields.
/// Will never have the `FILE_ATTRIBUTE_NORMAL` bit set.
int _attributes;
@override
bool get isDirectory => _attributes & win32.FILE_ATTRIBUTE_DIRECTORY != 0;
@override
bool get isFile => !isDirectory && !isLink;
@override
bool get isLink => _attributes & win32.FILE_ATTRIBUTE_REPARSE_POINT != 0;
@override
final int size;
bool get isReadOnly => _attributes & win32.FILE_ATTRIBUTE_READONLY != 0;
bool get isHidden => _attributes & win32.FILE_ATTRIBUTE_HIDDEN != 0;
bool get isSystem => _attributes & win32.FILE_ATTRIBUTE_SYSTEM != 0;
// TODO(brianquinlan): Refer to
// https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/windows-scripting/5tx15443(v=vs.84)?redirectedfrom=MSDN
bool get needsArchive => _attributes & win32.FILE_ATTRIBUTE_ARCHIVE != 0;
bool get isTemporary => _attributes & win32.FILE_ATTRIBUTE_TEMPORARY != 0;
bool get isOffline => _attributes & win32.FILE_ATTRIBUTE_OFFLINE != 0;
bool get isContentIndexed =>
_attributes & win32.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED == 0;
final int creationTime100Nanos;
final int lastAccessTime100Nanos;
final int lastWriteTime100Nanos;
DateTime get creation => _fileTimeToDateTime(creationTime100Nanos);
DateTime get access => _fileTimeToDateTime(lastAccessTime100Nanos);
DateTime get modification => _fileTimeToDateTime(lastWriteTime100Nanos);
WindowsMetadata._(
this._attributes,
this.size,
this.creationTime100Nanos,
this.lastAccessTime100Nanos,
this.lastWriteTime100Nanos,
);
/// TODO(bquinlan): Document this constructor.
///
/// Make sure to reference:
/// [File Attribute Constants](https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants)
factory WindowsMetadata.fromFileAttributes({
int attributes = 0,
int size = 0,
int creationTime100Nanos = 0,
int lastAccessTime100Nanos = 0,
int lastWriteTime100Nanos = 0,
}) => WindowsMetadata._(
attributes == win32.FILE_ATTRIBUTE_NORMAL ? 0 : attributes,
size,
creationTime100Nanos,
lastAccessTime100Nanos,
lastWriteTime100Nanos,
);
/// TODO(bquinlan): Document this constructor.
factory WindowsMetadata.fromLogicalProperties({
bool isDirectory = false,
bool isLink = false,
int size = 0,
bool isReadOnly = false,
bool isHidden = false,
bool isSystem = false,
bool needsArchive = false,
bool isTemporary = false,
bool isOffline = false,
bool isContentIndexed = false,
int creationTime100Nanos = 0,
int lastAccessTime100Nanos = 0,
int lastWriteTime100Nanos = 0,
}) => WindowsMetadata._(
(isDirectory ? win32.FILE_ATTRIBUTE_DIRECTORY : 0) |
(isLink ? win32.FILE_ATTRIBUTE_REPARSE_POINT : 0) |
(isReadOnly ? win32.FILE_ATTRIBUTE_READONLY : 0) |
(isHidden ? win32.FILE_ATTRIBUTE_HIDDEN : 0) |
(isSystem ? win32.FILE_ATTRIBUTE_SYSTEM : 0) |
(needsArchive ? win32.FILE_ATTRIBUTE_ARCHIVE : 0) |
(isTemporary ? win32.FILE_ATTRIBUTE_TEMPORARY : 0) |
(isOffline ? win32.FILE_ATTRIBUTE_OFFLINE : 0) |
(!isContentIndexed ? win32.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED : 0),
size,
creationTime100Nanos,
lastAccessTime100Nanos,
lastWriteTime100Nanos,
);
@override
bool operator ==(Object other) =>
other is WindowsMetadata &&
_attributes == other._attributes &&
size == other.size &&
creationTime100Nanos == other.creationTime100Nanos &&
lastAccessTime100Nanos == other.lastAccessTime100Nanos &&
lastWriteTime100Nanos == other.lastWriteTime100Nanos;
@override
int get hashCode => Object.hash(
_attributes,
size,
isContentIndexed,
creationTime100Nanos,
lastAccessTime100Nanos,
lastWriteTime100Nanos,
);
}
/// A [FileSystem] implementation for Windows systems.
base class WindowsFileSystem extends FileSystem {
WindowsFileSystem() {
// Calling `GetLastError` for the first time causes the `GetLastError`
// symbol to be loaded, which resets `GetLastError`. So make a harmless
// call before the value is needed.
//
// TODO(brianquinlan): Remove this after it is fixed in the Dart SDK.
win32.GetLastError();
}
@override
void rename(String oldPath, String newPath) => using((arena) {
if (win32.MoveFileEx(
oldPath.toNativeUtf16(allocator: arena),
newPath.toNativeUtf16(allocator: arena),
win32.MOVEFILE_WRITE_THROUGH | win32.MOVEFILE_REPLACE_EXISTING,
) ==
win32.FALSE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'rename failed', oldPath);
}
});
/// Sets metadata for the file system entity.
///
/// TODO(brianquinlan): Document the arguments.
/// Make sure to document that [original] should come from a call to
/// `metadata`. Creating your own `WindowsMetadata` will result in unsupported
/// fields being cleared.
void setMetadata(
String path, {
bool? isReadOnly,
bool? isHidden,
bool? isSystem,
bool? needsArchive,
bool? isTemporary,
bool? isContentIndexed,
bool? isOffline,
WindowsMetadata? original,
}) => using((arena) {
if ((isReadOnly ??
isHidden ??
isSystem ??
needsArchive ??
isTemporary ??
isContentIndexed ??
isOffline) ==
null) {
return;
}
final fileInfo = arena<win32.WIN32_FILE_ATTRIBUTE_DATA>();
final nativePath = path.toNativeUtf16(allocator: arena);
int attributes;
if (original == null) {
if (win32.GetFileAttributesEx(
nativePath,
win32.GetFileExInfoStandard,
fileInfo,
) ==
win32.FALSE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'set metadata failed', path);
}
attributes = fileInfo.ref.dwFileAttributes;
} else {
attributes = original._attributes;
}
if (attributes == win32.FILE_ATTRIBUTE_NORMAL) {
// `FILE_ATTRIBUTE_NORMAL` indicates that no other attributes are set and
// is valid only when used alone.
attributes = 0;
}
int updateBit(int base, int value, bool? bit) => switch (bit) {
null => base,
true => base | value,
false => base & ~value,
};
attributes = updateBit(
attributes,
win32.FILE_ATTRIBUTE_READONLY,
isReadOnly,
);
attributes = updateBit(attributes, win32.FILE_ATTRIBUTE_HIDDEN, isHidden);
attributes = updateBit(attributes, win32.FILE_ATTRIBUTE_SYSTEM, isSystem);
attributes = updateBit(
attributes,
win32.FILE_ATTRIBUTE_ARCHIVE,
needsArchive,
);
attributes = updateBit(
attributes,
win32.FILE_ATTRIBUTE_TEMPORARY,
isTemporary,
);
attributes = updateBit(
attributes,
win32.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
isContentIndexed != null ? !isContentIndexed : null,
);
attributes = updateBit(attributes, win32.FILE_ATTRIBUTE_OFFLINE, isOffline);
if (attributes == 0) {
// `FILE_ATTRIBUTE_NORMAL` indicates that no other attributes are set and
// is valid only when used alone.
attributes = win32.FILE_ATTRIBUTE_NORMAL;
}
if (win32.SetFileAttributes(nativePath, attributes) == win32.FALSE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'set metadata failed', path);
}
});
@override
WindowsMetadata metadata(String path) => using((arena) {
final fileInfo = arena<win32.WIN32_FILE_ATTRIBUTE_DATA>();
if (win32.GetFileAttributesEx(
path.toNativeUtf16(allocator: arena),
win32.GetFileExInfoStandard,
fileInfo,
) ==
win32.FALSE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'metadata failed', path);
}
final info = fileInfo.ref;
final attributes = info.dwFileAttributes;
return WindowsMetadata.fromFileAttributes(
attributes: attributes,
size: info.nFileSizeHigh << 32 | info.nFileSizeLow,
creationTime100Nanos:
info.ftCreationTime.dwHighDateTime << 32 |
info.ftCreationTime.dwLowDateTime,
lastAccessTime100Nanos:
info.ftLastAccessTime.dwHighDateTime << 32 |
info.ftLastAccessTime.dwLowDateTime,
lastWriteTime100Nanos:
info.ftLastWriteTime.dwHighDateTime << 32 |
info.ftLastWriteTime.dwLowDateTime,
);
});
@override
Uint8List readAsBytes(String path) => using((arena) {
// Calling `GetLastError` for the first time causes the `GetLastError`
// symbol to be loaded, which resets `GetLastError`. So make a harmless
// call before the value is needed.
win32.GetLastError();
final f = win32.CreateFile(
path.toNativeUtf16(),
win32.GENERIC_READ | win32.FILE_SHARE_READ,
win32.FILE_SHARE_READ | win32.FILE_SHARE_WRITE,
nullptr,
win32.OPEN_EXISTING,
win32.FILE_ATTRIBUTE_NORMAL,
0,
);
if (f == win32.INVALID_HANDLE_VALUE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'open failed', path);
}
try {
// The result of `GetFileSize` is not defined for non-seeking devices
// such as pipes.
if (win32.GetFileType(f) == win32.FILE_TYPE_DISK) {
final highFileSize = arena<win32.DWORD>();
final lowFileSize = win32.GetFileSize(f, highFileSize);
if (lowFileSize == 0xffffffff) {
// Indicates an error OR that the low order word of the is actually
// that constant.
final errorCode = win32.GetLastError();
if (errorCode != win32.ERROR_SUCCESS) {
return _readUnknownLength(path, f);
}
}
final fileSize = highFileSize.value << 32 | lowFileSize;
if (fileSize == 0) {
return Uint8List(0);
} else {
return _readKnownLength(path, f, fileSize);
}
}
return _readUnknownLength(path, f);
} finally {
win32.CloseHandle(f);
}
});
Uint8List _readUnknownLength(String path, int file) => ffi.using((arena) {
final buffer = arena<Uint8>(blockSize);
final bytesRead = arena<win32.DWORD>();
final builder = BytesBuilder(copy: true);
while (true) {
if (win32.ReadFile(file, buffer, blockSize, bytesRead, nullptr) ==
win32.FALSE) {
final errorCode = win32.GetLastError();
// On Windows, reading from a pipe that is closed by the writer results
// in ERROR_BROKEN_PIPE.
if (errorCode == win32.ERROR_BROKEN_PIPE ||
errorCode == win32.ERROR_SUCCESS) {
return builder.takeBytes();
}
throw _getError(errorCode, 'read failed', path);
}
if (bytesRead.value == 0) {
return builder.takeBytes();
} else {
final typed = buffer.asTypedList(bytesRead.value);
builder.add(typed);
}
}
});
Uint8List _readKnownLength(String path, int file, int length) {
// In the happy path, `buffer` will be returned to the caller as a
// `Uint8List`. If there in an exception, free it and rethrow the exception.
final buffer = ffi.malloc<Uint8>(length);
try {
return ffi.using((arena) {
final bytesRead = arena<win32.DWORD>();
var bufferOffset = 0;
while (bufferOffset < length) {
if (win32.ReadFile(
file,
(buffer + bufferOffset).cast(),
min(length - bufferOffset, maxReadSize),
bytesRead,
nullptr,
) ==
win32.FALSE) {
final errorCode = win32.GetLastError();
throw _getError(errorCode, 'read failed', path);
}
bufferOffset += bytesRead.value;
if (bytesRead.value == 0) {
break;
}
}
return buffer.asTypedList(
bufferOffset,
finalizer: ffi.malloc.nativeFree,
);
});
} on Exception {
ffi.malloc.free(buffer);
rethrow;
}
}
}