-
Notifications
You must be signed in to change notification settings - Fork 54
/
NativeFileWatcherWin.cpp
1492 lines (1291 loc) · 52.5 KB
/
NativeFileWatcherWin.cpp
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Native implementation of Watcher operations.
*/
#include "NativeFileWatcherWin.h"
#include "mozilla/Services.h"
#include "mozilla/UniquePtr.h"
#include "nsClassHashtable.h"
#include "nsComponentManagerUtils.h"
#include "nsDataHashtable.h"
#include "nsIFile.h"
#include "nsIObserverService.h"
#include "nsProxyRelease.h"
#include "nsTArray.h"
#include "mozilla/Logging.h"
#include "mozilla/Scoped.h"
namespace mozilla {
// Enclose everything which is not exported in an anonymous namespace.
namespace {
/**
* An event used to notify the main thread when an error happens.
*/
class WatchedErrorEvent final : public Runnable {
public:
/**
* @param aOnError The passed error callback.
* @param aError The |nsresult| error value.
* @param osError The error returned by GetLastError().
*/
WatchedErrorEvent(
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError,
const nsresult& anError, const DWORD& osError)
: Runnable("WatchedErrorEvent"), mOnError(aOnError), mError(anError) {
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
// Make sure we wrap a valid callback since it's not mandatory to provide
// one when watching a resource.
if (mOnError) {
(void)mOnError->Complete(mError, mOsError);
}
return NS_OK;
}
private:
nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback> mOnError;
nsresult mError;
DWORD mOsError;
};
/**
* An event used to notify the main thread when an operation is successful.
*/
class WatchedSuccessEvent final : public Runnable {
public:
/**
* @param aOnSuccess The passed success callback.
* @param aResourcePath
* The path of the resource for which this event was generated.
*/
WatchedSuccessEvent(const nsMainThreadPtrHandle<
nsINativeFileWatcherSuccessCallback>& aOnSuccess,
const nsAString& aResourcePath)
: Runnable("WatchedSuccessEvent"),
mOnSuccess(aOnSuccess),
mResourcePath(aResourcePath) {
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
// Make sure we wrap a valid callback since it's not mandatory to provide
// one when watching a resource.
if (mOnSuccess) {
(void)mOnSuccess->Complete(mResourcePath);
}
return NS_OK;
}
private:
nsMainThreadPtrHandle<nsINativeFileWatcherSuccessCallback> mOnSuccess;
nsString mResourcePath;
};
/**
* An event used to notify the main thread of a change in a watched
* resource.
*/
class WatchedChangeEvent final : public Runnable {
public:
/**
* @param aOnChange The passed change callback.
* @param aChangedResource The name of the changed resource.
*/
WatchedChangeEvent(
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsAString& aChangedResource)
: Runnable("WatchedChangeEvent"),
mOnChange(aOnChange),
mChangedResource(aChangedResource) {
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
// The second parameter is reserved for future uses: we use 0 as a
// placeholder.
(void)mOnChange->Changed(mChangedResource, 0);
return NS_OK;
}
private:
nsMainThreadPtrHandle<nsINativeFileWatcherCallback> mOnChange;
nsString mChangedResource;
};
static mozilla::LazyLogModule gNativeWatcherPRLog("NativeFileWatcherService");
#define FILEWATCHERLOG(...) \
MOZ_LOG(gNativeWatcherPRLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
// The number of notifications to store within
// WatchedResourceDescriptor:mNotificationBuffer. If the buffer overflows, its
// contents are discarded and a change callback is dispatched with "*" as
// changed path.
const unsigned int WATCHED_RES_MAXIMUM_NOTIFICATIONS = 100;
// The size, in bytes, of the notification buffer used to store the changes
// notifications for each watched resource.
const size_t NOTIFICATION_BUFFER_SIZE =
WATCHED_RES_MAXIMUM_NOTIFICATIONS * sizeof(FILE_NOTIFY_INFORMATION);
/**
* AutoCloseHandle is a RAII wrapper for Windows |HANDLE|s
*/
struct AutoCloseHandleTraits {
typedef HANDLE type;
static type empty() { return INVALID_HANDLE_VALUE; }
static void release(type anHandle) {
if (anHandle != INVALID_HANDLE_VALUE) {
// If CancelIo is called on an |HANDLE| not yet associated to a Completion
// I/O it simply does nothing.
(void)CancelIo(anHandle);
(void)CloseHandle(anHandle);
}
}
};
typedef Scoped<AutoCloseHandleTraits> AutoCloseHandle;
// Define these callback array types to make the code easier to read.
typedef nsTArray<nsMainThreadPtrHandle<nsINativeFileWatcherCallback>>
ChangeCallbackArray;
typedef nsTArray<nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>>
ErrorCallbackArray;
/**
* A structure to keep track of the information related to a
* watched resource.
*/
struct WatchedResourceDescriptor {
// The path on the file system of the watched resource.
nsString mPath;
// A buffer containing the latest notifications received for the resource.
// UniquePtr<FILE_NOTIFY_INFORMATION> cannot be used as the structure
// contains a variable length field (FileName).
UniquePtr<unsigned char> mNotificationBuffer;
// Used to hold information for the asynchronous ReadDirectoryChangesW call
// (does not need to be closed as it is not an |HANDLE|).
OVERLAPPED mOverlappedInfo;
// The OS handle to the watched resource.
AutoCloseHandle mResourceHandle;
WatchedResourceDescriptor(const nsAString& aPath, const HANDLE anHandle)
: mPath(aPath), mResourceHandle(anHandle) {
memset(&mOverlappedInfo, 0, sizeof(OVERLAPPED));
mNotificationBuffer.reset(new unsigned char[NOTIFICATION_BUFFER_SIZE]);
}
};
/**
* A structure used to pass the callbacks to the AddPathRunnableMethod() and
* RemovePathRunnableMethod().
*/
struct PathRunnablesParametersWrapper {
nsString mPath;
nsMainThreadPtrHandle<nsINativeFileWatcherCallback> mChangeCallbackHandle;
nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback> mErrorCallbackHandle;
nsMainThreadPtrHandle<nsINativeFileWatcherSuccessCallback>
mSuccessCallbackHandle;
PathRunnablesParametersWrapper(
const nsAString& aPath,
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError,
const nsMainThreadPtrHandle<nsINativeFileWatcherSuccessCallback>&
aOnSuccess)
: mPath(aPath),
mChangeCallbackHandle(aOnChange),
mErrorCallbackHandle(aOnError),
mSuccessCallbackHandle(aOnSuccess) {}
};
/**
* This runnable is dispatched to the main thread in order to safely
* shutdown the worker thread.
*/
class NativeWatcherIOShutdownTask : public Runnable {
public:
NativeWatcherIOShutdownTask()
: Runnable("NativeWatcherIOShutdownTask"),
mWorkerThread(do_GetCurrentThread()) {
MOZ_ASSERT(!NS_IsMainThread());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(NS_IsMainThread());
mWorkerThread->Shutdown();
return NS_OK;
}
private:
nsCOMPtr<nsIThread> mWorkerThread;
};
/**
* This runnable is dispatched from the main thread to get the notifications of
* the changes in the watched resources by continuously calling the blocking
* function GetQueuedCompletionStatus. This function queries the status of the
* Completion I/O port initialized in the main thread. The watched resources are
* registered to the completion I/O port when calling |addPath|.
*
* Instead of using a loop within the Run() method, the Runnable reschedules
* itself by issuing a NS_DispatchToCurrentThread(this) before exiting. This is
* done to allow the execution of other runnables enqueued within the thread
* task queue.
*/
class NativeFileWatcherIOTask : public Runnable {
public:
explicit NativeFileWatcherIOTask(HANDLE aIOCompletionPort)
: Runnable("NativeFileWatcherIOTask"),
mIOCompletionPort(aIOCompletionPort),
mShuttingDown(false) {}
NS_IMETHOD Run() override;
nsresult AddPathRunnableMethod(
PathRunnablesParametersWrapper* aWrappedParameters);
nsresult RemovePathRunnableMethod(
PathRunnablesParametersWrapper* aWrappedParameters);
nsresult DeactivateRunnableMethod();
private:
// Maintain 2 indexes - one by resource path, one by resource |HANDLE|.
// Since |HANDLE| is basically a typedef to void*, we use nsVoidPtrHashKey to
// compute the hashing key. We need 2 indexes in order to quickly look up the
// changed resource in the Worker Thread.
// The objects are not ref counted and get destroyed by
// mWatchedResourcesByPath on NativeFileWatcherService::Destroy or in
// NativeFileWatcherService::RemovePath.
nsClassHashtable<nsStringHashKey, WatchedResourceDescriptor>
mWatchedResourcesByPath;
nsDataHashtable<nsVoidPtrHashKey, WatchedResourceDescriptor*>
mWatchedResourcesByHandle;
// The same callback can be associated to multiple watches so we need to keep
// them alive as long as there is a watch using them. We create two hashtables
// to map directory names to lists of nsMainThreadPtr<callbacks>.
nsClassHashtable<nsStringHashKey, ChangeCallbackArray> mChangeCallbacksTable;
nsClassHashtable<nsStringHashKey, ErrorCallbackArray> mErrorCallbacksTable;
// We hold a copy of the completion port |HANDLE|, which is owned by the main
// thread.
HANDLE mIOCompletionPort;
// Other methods need to know that a shutdown is in progress.
bool mShuttingDown;
nsresult RunInternal();
nsresult DispatchChangeCallbacks(
WatchedResourceDescriptor* aResourceDescriptor,
const nsAString& aChangedResource);
nsresult ReportChange(
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsAString& aChangedResource);
nsresult DispatchErrorCallbacks(
WatchedResourceDescriptor* aResourceDescriptor, nsresult anError,
DWORD anOSError);
nsresult ReportError(
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError,
nsresult anError, DWORD anOSError);
nsresult ReportSuccess(const nsMainThreadPtrHandle<
nsINativeFileWatcherSuccessCallback>& aOnSuccess,
const nsAString& aResourcePath);
nsresult AddDirectoryToWatchList(
WatchedResourceDescriptor* aDirectoryDescriptor);
void AppendCallbacksToHashtables(
const nsAString& aPath,
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError);
void RemoveCallbacksFromHashtables(
const nsAString& aPath,
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError);
nsresult MakeResourcePath(WatchedResourceDescriptor* changedDescriptor,
const nsAString& resourceName,
nsAString& nativeResourcePath);
};
/**
* The watching thread logic.
*
* @return NS_OK if the watcher loop must be rescheduled, a failure code
* if it must not.
*/
nsresult NativeFileWatcherIOTask::RunInternal() {
// Contains the address of the |OVERLAPPED| structure passed
// to ReadDirectoryChangesW (used to check for |HANDLE| closing).
OVERLAPPED* overlappedStructure;
// The number of bytes transferred by GetQueuedCompletionStatus
// (used to check for |HANDLE| closing).
DWORD transferredBytes = 0;
// Will hold the |HANDLE| to the watched resource returned by
// GetQueuedCompletionStatus which generated the change events.
ULONG_PTR changedResourceHandle = 0;
// Check for changes in the resource status by querying the
// |mIOCompletionPort| (blocking). GetQueuedCompletionStatus is always called
// before the first call to ReadDirectoryChangesW. This isn't a problem, since
// mIOCompletionPort is already a valid |HANDLE| even though it doesn't have
// any associated notification handles (through ReadDirectoryChangesW).
if (!GetQueuedCompletionStatus(mIOCompletionPort, &transferredBytes,
&changedResourceHandle, &overlappedStructure,
INFINITE)) {
// Ok, there was some error.
DWORD errCode = GetLastError();
switch (errCode) {
case ERROR_NOTIFY_ENUM_DIR: {
// There were too many changes and the notification buffer has
// overflowed. We dispatch the special value "*" and reschedule.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - Notification buffer has "
"overflowed");
WatchedResourceDescriptor* changedRes =
mWatchedResourcesByHandle.Get((HANDLE)changedResourceHandle);
nsresult rv =
DispatchChangeCallbacks(changedRes, NS_LITERAL_STRING("*"));
if (NS_FAILED(rv)) {
// We failed to dispatch the error callbacks. Something very
// bad happened to the main thread, so we bail out from the watcher
// thread.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - Failed to dispatch change "
"callbacks (%x).",
rv);
return rv;
}
return NS_OK;
}
case ERROR_ABANDONED_WAIT_0:
case ERROR_INVALID_HANDLE: {
// If we reach this point, mIOCompletionPort was probably closed
// and we need to close this thread. This condition is identified
// by catching the ERROR_INVALID_HANDLE error.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - The completion port was closed "
"(%x).",
errCode);
return NS_ERROR_ABORT;
}
case ERROR_OPERATION_ABORTED: {
// Some path was unwatched! That's not really an error, now it is safe
// to free the memory for the resource and call
// GetQueuedCompletionStatus again.
FILEWATCHERLOG("NativeFileWatcherIOTask::Run - Path unwatched (%x).",
errCode);
WatchedResourceDescriptor* toFree =
mWatchedResourcesByHandle.Get((HANDLE)changedResourceHandle);
if (toFree) {
// Take care of removing the resource and freeing the memory
mWatchedResourcesByHandle.Remove((HANDLE)changedResourceHandle);
// This last call eventually frees the memory
mWatchedResourcesByPath.Remove(toFree->mPath);
}
return NS_OK;
}
default: {
// It should probably never get here, but it's better to be safe.
FILEWATCHERLOG("NativeFileWatcherIOTask::Run - Unknown error (%x).",
errCode);
return NS_ERROR_FAILURE;
}
}
}
// When an |HANDLE| associated to the completion I/O port is gracefully
// closed, GetQueuedCompletionStatus still may return a status update.
// Moreover, this can also be triggered when watching files on a network
// folder and losing the connection. That's an edge case we need to take care
// of for consistency by checking for (!transferredBytes &&
// overlappedStructure). See http://xania.org/200807/iocp
if (!transferredBytes && (overlappedStructure ||
(!overlappedStructure && !changedResourceHandle))) {
// Note: if changedResourceHandle is nullptr as well, the wait on the
// Completion I/O was interrupted by a call to PostQueuedCompletionStatus
// with 0 transferred bytes and nullptr as |OVERLAPPED| and |HANDLE|. This
// is done to allow addPath and removePath to work on this thread.
return NS_OK;
}
// Check to see which resource is changedResourceHandle.
WatchedResourceDescriptor* changedRes =
mWatchedResourcesByHandle.Get((HANDLE)changedResourceHandle);
MOZ_ASSERT(
changedRes,
"Could not find the changed resource in the list of watched ones.");
// Parse the changes and notify the main thread.
const unsigned char* rawNotificationBuffer =
changedRes->mNotificationBuffer.get();
while (true) {
FILE_NOTIFY_INFORMATION* notificationInfo =
(FILE_NOTIFY_INFORMATION*)rawNotificationBuffer;
// FileNameLength is in bytes, but we need FileName length
// in characters, so divide it by sizeof(WCHAR).
nsAutoString resourceName(notificationInfo->FileName,
notificationInfo->FileNameLength / sizeof(WCHAR));
// Handle path normalisation using nsIFile.
nsString resourcePath;
nsresult rv = MakeResourcePath(changedRes, resourceName, resourcePath);
if (NS_SUCCEEDED(rv)) {
rv = DispatchChangeCallbacks(changedRes, resourcePath);
if (NS_FAILED(rv)) {
// Log that we failed to dispatch the change callbacks.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - Failed to dispatch change "
"callbacks (%x).",
rv);
return rv;
}
}
if (!notificationInfo->NextEntryOffset) {
break;
}
rawNotificationBuffer += notificationInfo->NextEntryOffset;
}
// We need to keep watching for further changes.
nsresult rv = AddDirectoryToWatchList(changedRes);
if (NS_FAILED(rv)) {
// We failed to watch the folder.
if (rv == NS_ERROR_ABORT) {
// Log that we also failed to dispatch the error callbacks.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - Failed to watch %s and"
" to dispatch the related error callbacks",
changedRes->mPath.get());
return rv;
}
}
return NS_OK;
}
/**
* Wraps the watcher logic and takes care of rescheduling
* the watcher loop based on the return code of |RunInternal|
* in order to help with code readability.
*
* @return NS_OK or a failure error code from |NS_DispatchToCurrentThread|.
*/
NS_IMETHODIMP
NativeFileWatcherIOTask::Run() {
MOZ_ASSERT(!NS_IsMainThread());
// We return immediately if |mShuttingDown| is true (see below for
// details about the shutdown protocol being followed).
if (mShuttingDown) {
return NS_OK;
}
nsresult rv = RunInternal();
if (NS_FAILED(rv)) {
// A critical error occurred in the watcher loop, don't reschedule.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::Run - Stopping the watcher loop (error %S)",
rv);
// We log the error but return NS_OK instead: we don't want to
// propagate an exception through XPCOM.
return NS_OK;
}
// No error occurred, reschedule.
return NS_DispatchToCurrentThread(this);
}
/**
* Adds the resource to the watched list. This function is enqueued on the
* worker thread by NativeFileWatcherService::AddPath. All the errors are
* reported to the main thread using the error callback function mErrorCallback.
*
* @param pathToWatch
* The path of the resource to watch for changes.
*
* @return NS_ERROR_FILE_NOT_FOUND if the path is invalid or does not exist.
* Returns NS_ERROR_UNEXPECTED if OS |HANDLE|s are unexpectedly closed.
* If the ReadDirectoryChangesW call fails, returns NS_ERROR_FAILURE,
* otherwise NS_OK.
*/
nsresult NativeFileWatcherIOTask::AddPathRunnableMethod(
PathRunnablesParametersWrapper* aWrappedParameters) {
MOZ_ASSERT(!NS_IsMainThread());
UniquePtr<PathRunnablesParametersWrapper> wrappedParameters(
aWrappedParameters);
// We return immediately if |mShuttingDown| is true (see below for
// details about the shutdown protocol being followed).
if (mShuttingDown) {
return NS_OK;
}
if (!wrappedParameters || !wrappedParameters->mChangeCallbackHandle) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - Invalid arguments.");
return NS_ERROR_NULL_POINTER;
}
// Is aPathToWatch already being watched?
WatchedResourceDescriptor* watchedResource =
mWatchedResourcesByPath.Get(wrappedParameters->mPath);
if (watchedResource) {
// Append it to the hash tables.
AppendCallbacksToHashtables(watchedResource->mPath,
wrappedParameters->mChangeCallbackHandle,
wrappedParameters->mErrorCallbackHandle);
return NS_OK;
}
// Retrieve a file handle to associate with the completion port. Makes
// sure to request the appropriate rights (i.e. read files and list
// files contained in a folder). Note: the nullptr security flag prevents
// the |HANDLE| to be passed to child processes.
HANDLE resHandle = CreateFileW(
wrappedParameters->mPath.get(),
FILE_LIST_DIRECTORY, // Access rights
FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, // Share
nullptr, // Security flags
OPEN_EXISTING, // Returns an handle only if the resource exists
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
nullptr); // Template file (only used when creating files)
if (resHandle == INVALID_HANDLE_VALUE) {
DWORD dwError = GetLastError();
nsresult rv;
if (dwError == ERROR_FILE_NOT_FOUND) {
rv = NS_ERROR_FILE_NOT_FOUND;
} else if (dwError == ERROR_ACCESS_DENIED) {
rv = NS_ERROR_FILE_ACCESS_DENIED;
} else {
rv = NS_ERROR_FAILURE;
}
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - CreateFileW failed "
"(error %x) for %S.",
dwError, wrappedParameters->mPath.get());
rv = ReportError(wrappedParameters->mErrorCallbackHandle, rv, dwError);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - "
"Failed to dispatch the error callback (%x).",
rv);
return rv;
}
// Error has already been reported through mErrorCallback.
return NS_OK;
}
// Initialise the resource descriptor.
UniquePtr<WatchedResourceDescriptor> resourceDesc(
new WatchedResourceDescriptor(wrappedParameters->mPath, resHandle));
// Associate the file with the previously opened completion port.
if (!CreateIoCompletionPort(resourceDesc->mResourceHandle, mIOCompletionPort,
(ULONG_PTR)resourceDesc->mResourceHandle.get(),
0)) {
DWORD dwError = GetLastError();
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod"
" - CreateIoCompletionPort failed (error %x) for %S.",
dwError, wrappedParameters->mPath.get());
// This could fail because passed parameters could be invalid |HANDLE|s
// i.e. mIOCompletionPort was unexpectedly closed or failed.
nsresult rv = ReportError(wrappedParameters->mErrorCallbackHandle,
NS_ERROR_UNEXPECTED, dwError);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - "
"Failed to dispatch the error callback (%x).",
rv);
return rv;
}
// Error has already been reported through mErrorCallback.
return NS_OK;
}
// Append the callbacks to the hash tables. We do this now since
// AddDirectoryToWatchList could use the error callback, but we
// need to make sure to remove them if AddDirectoryToWatchList fails.
AppendCallbacksToHashtables(wrappedParameters->mPath,
wrappedParameters->mChangeCallbackHandle,
wrappedParameters->mErrorCallbackHandle);
// We finally watch the resource for changes.
nsresult rv = AddDirectoryToWatchList(resourceDesc.get());
if (NS_SUCCEEDED(rv)) {
// Add the resource pointer to both indexes.
WatchedResourceDescriptor* resource = resourceDesc.release();
mWatchedResourcesByPath.Put(wrappedParameters->mPath, resource);
mWatchedResourcesByHandle.Put(resHandle, resource);
// Dispatch the success callback.
nsresult rv = ReportSuccess(wrappedParameters->mSuccessCallbackHandle,
wrappedParameters->mPath);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - "
"Failed to dispatch the success callback (%x).",
rv);
return rv;
}
return NS_OK;
}
// We failed to watch the folder. Remove the callbacks
// from the hash tables.
RemoveCallbacksFromHashtables(wrappedParameters->mPath,
wrappedParameters->mChangeCallbackHandle,
wrappedParameters->mErrorCallbackHandle);
if (rv != NS_ERROR_ABORT) {
// Just don't add the descriptor to the watch list.
return NS_OK;
}
// We failed to dispatch the error callbacks as well.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::AddPathRunnableMethod - Failed to watch %s and"
" to dispatch the related error callbacks",
resourceDesc->mPath.get());
return rv;
}
/**
* Removes the path from the list of watched resources. Silently ignores the
* request if the path was not being watched.
*
* Remove Protocol:
*
* 1. Find the resource to unwatch through the provided path.
* 2. Remove the error and change callbacks from the list of callbacks
* associated with the resource.
* 3. Remove the error and change callbacks from the callback hash maps.
* 4. If there are no more change callbacks for the resource, close
* its file |HANDLE|. We do not free the buffer memory just yet, it's
* still needed for the next call to GetQueuedCompletionStatus. That
* memory will be freed in NativeFileWatcherIOTask::Run.
*
* @param aWrappedParameters
* The structure containing the resource path, the error and change
* callback handles.
*/
nsresult NativeFileWatcherIOTask::RemovePathRunnableMethod(
PathRunnablesParametersWrapper* aWrappedParameters) {
MOZ_ASSERT(!NS_IsMainThread());
UniquePtr<PathRunnablesParametersWrapper> wrappedParameters(
aWrappedParameters);
// We return immediately if |mShuttingDown| is true (see below for
// details about the shutdown protocol being followed).
if (mShuttingDown) {
return NS_OK;
}
if (!wrappedParameters || !wrappedParameters->mChangeCallbackHandle) {
return NS_ERROR_NULL_POINTER;
}
WatchedResourceDescriptor* toRemove =
mWatchedResourcesByPath.Get(wrappedParameters->mPath);
if (!toRemove) {
// We are trying to remove a path which wasn't being watched. Silently
// ignore and dispatch the success callback.
nsresult rv = ReportSuccess(wrappedParameters->mSuccessCallbackHandle,
wrappedParameters->mPath);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::RemovePathRunnableMethod - "
"Failed to dispatch the success callback (%x).",
rv);
return rv;
}
return NS_OK;
}
ChangeCallbackArray* changeCallbackArray =
mChangeCallbacksTable.Get(toRemove->mPath);
// This should always be valid.
MOZ_ASSERT(changeCallbackArray);
bool removed = changeCallbackArray->RemoveElement(
wrappedParameters->mChangeCallbackHandle);
if (!removed) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::RemovePathRunnableMethod - Unable to remove "
"the change "
"callback from the change callback hash map for %S.",
wrappedParameters->mPath.get());
MOZ_CRASH();
}
ErrorCallbackArray* errorCallbackArray =
mErrorCallbacksTable.Get(toRemove->mPath);
MOZ_ASSERT(errorCallbackArray);
removed = errorCallbackArray->RemoveElement(
wrappedParameters->mErrorCallbackHandle);
if (!removed) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::RemovePathRunnableMethod - Unable to remove "
"the error "
"callback from the error callback hash map for %S.",
wrappedParameters->mPath.get());
MOZ_CRASH();
}
// If there are still callbacks left, keep the descriptor.
// We don't check for error callbacks since there's no point in keeping
// the descriptor if there are no change callbacks but some error callbacks.
if (changeCallbackArray->Length()) {
// Dispatch the success callback.
nsresult rv = ReportSuccess(wrappedParameters->mSuccessCallbackHandle,
wrappedParameters->mPath);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::RemovePathRunnableMethod - "
"Failed to dispatch the success callback (%x).",
rv);
return rv;
}
return NS_OK;
}
// In this runnable, we just cancel callbacks (see above) and I/O (see below).
// Resources are freed by the worker thread when GetQueuedCompletionStatus
// detects that a resource was removed from the watch list.
// Since when closing |HANDLE|s relative to watched resources
// GetQueuedCompletionStatus is notified one last time, it would end
// up referring to deallocated memory if we were to free the memory here.
// This happens because the worker IO is scheduled to watch the resources
// again once we complete executing this function.
// Enforce CloseHandle/CancelIO by disposing the AutoCloseHandle. We don't
// remove the entry from mWatchedResourceBy* since the completion port might
// still be using the notification buffer. Entry remove is performed when
// handling ERROR_OPERATION_ABORTED in NativeFileWatcherIOTask::Run.
toRemove->mResourceHandle.dispose();
// Dispatch the success callback.
nsresult rv = ReportSuccess(wrappedParameters->mSuccessCallbackHandle,
wrappedParameters->mPath);
if (NS_FAILED(rv)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::RemovePathRunnableMethod - "
"Failed to dispatch the success callback (%x).",
rv);
return rv;
}
return NS_OK;
}
/**
* Removes all the watched resources from the watch list and stops the
* watcher thread. Frees all the used resources.
*/
nsresult NativeFileWatcherIOTask::DeactivateRunnableMethod() {
MOZ_ASSERT(!NS_IsMainThread());
// Remind users to manually remove the watches before quitting.
MOZ_ASSERT(!mWatchedResourcesByHandle.Count(),
"Clients of the nsINativeFileWatcher must remove "
"watches manually before quitting.");
// Log any pending watch.
for (auto it = mWatchedResourcesByHandle.Iter(); !it.Done(); it.Next()) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::DeactivateRunnableMethod - "
"%S is still being watched.",
it.UserData()->mPath.get());
}
// We return immediately if |mShuttingDown| is true (see below for
// details about the shutdown protocol being followed).
if (mShuttingDown) {
// If this happens, we are in a strange situation.
FILEWATCHERLOG(
"NativeFileWatcherIOTask::DeactivateRunnableMethod - We are already "
"shutting down.");
MOZ_CRASH();
return NS_OK;
}
// Deactivate all the non-shutdown methods of this object.
mShuttingDown = true;
// Remove all the elements from the index. Memory will be freed by
// calling Clear() on mWatchedResourcesByPath.
mWatchedResourcesByHandle.Clear();
// Clear frees the memory associated with each element and clears the table.
// Since we are using Scoped |HANDLE|s, they get automatically closed as well.
mWatchedResourcesByPath.Clear();
// Now that all the descriptors are closed, release the callback hahstables.
mChangeCallbacksTable.Clear();
mErrorCallbacksTable.Clear();
// Close the IO completion port, eventually making
// the watcher thread exit from the watching loop.
if (mIOCompletionPort) {
if (!CloseHandle(mIOCompletionPort)) {
FILEWATCHERLOG(
"NativeFileWatcherIOTask::DeactivateRunnableMethod - "
"Failed to close the IO completion port HANDLE.");
}
}
// Now we just need to reschedule a final call to Shutdown() back to the main
// thread.
RefPtr<NativeWatcherIOShutdownTask> shutdownRunnable =
new NativeWatcherIOShutdownTask();
return NS_DispatchToMainThread(shutdownRunnable);
}
/**
* Helper function to dispatch a change notification to all the registered
* callbacks.
* @param aResourceDescriptor
* The resource descriptor.
* @param aChangedResource
* The path of the changed resource.
* @return NS_OK if all the callbacks are dispatched correctly, a |nsresult|
* error code otherwise.
*/
nsresult NativeFileWatcherIOTask::DispatchChangeCallbacks(
WatchedResourceDescriptor* aResourceDescriptor,
const nsAString& aChangedResource) {
MOZ_ASSERT(aResourceDescriptor);
// Retrieve the change callbacks array.
ChangeCallbackArray* changeCallbackArray =
mChangeCallbacksTable.Get(aResourceDescriptor->mPath);
// This should always be valid.
MOZ_ASSERT(changeCallbackArray);
for (size_t i = 0; i < changeCallbackArray->Length(); i++) {
nsresult rv = ReportChange((*changeCallbackArray)[i], aChangedResource);
if (NS_FAILED(rv)) {
return rv;
}
}
return NS_OK;
}
/**
* Helper function to post a change runnable to the main thread.
*
* @param aOnChange
* The change callback handle.
* @param aChangedResource
* The resource name to dispatch thorough the change callback.
*
* @return NS_OK if the callback is dispatched correctly.
*/
nsresult NativeFileWatcherIOTask::ReportChange(
const nsMainThreadPtrHandle<nsINativeFileWatcherCallback>& aOnChange,
const nsAString& aChangedResource) {
RefPtr<WatchedChangeEvent> changeRunnable =
new WatchedChangeEvent(aOnChange, aChangedResource);
return NS_DispatchToMainThread(changeRunnable);
}
/**
* Helper function to dispatch a error notification to all the registered
* callbacks.
* @param aResourceDescriptor
* The resource descriptor.
* @param anError
* The error to dispatch thorough the error callback.
* @param anOSError
* An OS specific error code to send with the callback.
* @return NS_OK if all the callbacks are dispatched correctly, a |nsresult|
* error code otherwise.
*/
nsresult NativeFileWatcherIOTask::DispatchErrorCallbacks(
WatchedResourceDescriptor* aResourceDescriptor, nsresult anError,
DWORD anOSError) {
MOZ_ASSERT(aResourceDescriptor);
// Retrieve the error callbacks array.
ErrorCallbackArray* errorCallbackArray =
mErrorCallbacksTable.Get(aResourceDescriptor->mPath);
// This must be valid.
MOZ_ASSERT(errorCallbackArray);
for (size_t i = 0; i < errorCallbackArray->Length(); i++) {
nsresult rv = ReportError((*errorCallbackArray)[i], anError, anOSError);
if (NS_FAILED(rv)) {
return rv;
}
}
return NS_OK;
}
/**
* Helper function to post an error runnable to the main thread.
*
* @param aOnError
* The error callback handle.
* @param anError
* The error to dispatch thorough the error callback.
* @param anOSError
* An OS specific error code to send with the callback.
*
* @return NS_OK if the callback is dispatched correctly.
*/
nsresult NativeFileWatcherIOTask::ReportError(
const nsMainThreadPtrHandle<nsINativeFileWatcherErrorCallback>& aOnError,
nsresult anError, DWORD anOSError) {
RefPtr<WatchedErrorEvent> errorRunnable =
new WatchedErrorEvent(aOnError, anError, anOSError);