-
Notifications
You must be signed in to change notification settings - Fork 130
/
mod.rs
1900 lines (1660 loc) · 74.4 KB
/
mod.rs
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
// Copyright 2016 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use serde;
use bincode;
use crate::ipc;
use libc::intptr_t;
use std::cell::{Cell, RefCell};
use std::cmp::PartialEq;
use std::convert::TryInto;
use std::default::Default;
use std::env;
use std::error::Error as StdError;
use std::ffi::CString;
use std::fmt;
use std::io;
use std::marker::{Send, Sync, PhantomData};
use std::mem;
use std::ops::{Deref, DerefMut, RangeFrom};
use std::ptr;
use std::ptr::null_mut;
use std::slice;
use std::thread;
use std::time::Duration;
use uuid::Uuid;
use winapi::um::winnt::{HANDLE};
use winapi::um::handleapi::{INVALID_HANDLE_VALUE};
use winapi::shared::minwindef::{TRUE, FALSE, LPVOID};
use winapi;
use winapi::um::synchapi::CreateEventA;
mod aliased_cell;
use self::aliased_cell::AliasedCell;
lazy_static! {
static ref CURRENT_PROCESS_ID: winapi::shared::ntdef::ULONG = unsafe { winapi::um::processthreadsapi::GetCurrentProcessId() };
static ref CURRENT_PROCESS_HANDLE: WinHandle = WinHandle::new(unsafe { winapi::um::processthreadsapi::GetCurrentProcess() });
}
// Added to overcome build error where Box<winapi::um::minwinbase::OVERLAPPED> was used and
// struct had a trait of #[derive(Debug)]. Adding NoDebug<> overrode the Debug() trait.
// e.g. - NoDebug<Box<winapi::um::minwinbase::OVERLAPPED>>,
struct NoDebug<T>(T);
impl<T> Deref for NoDebug<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for NoDebug<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T> fmt::Debug for NoDebug<T> {
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
}
lazy_static! {
static ref DEBUG_TRACE_ENABLED: bool = env::var_os("IPC_CHANNEL_WIN_DEBUG_TRACE").is_some();
}
/// Debug macro to better track what's going on in case of errors.
macro_rules! win32_trace {
($($rest:tt)*) => {
if cfg!(feature = "win32-trace") {
if *DEBUG_TRACE_ENABLED { println!($($rest)*); }
}
}
}
/// When we create the pipe, how big of a write buffer do we specify?
///
/// This is reserved in the nonpaged pool. The fragment size is the
/// max we can write to the pipe without fragmentation, and the
/// buffer size is what we tell the pipe it is, so we have room
/// for out of band data etc.
const MAX_FRAGMENT_SIZE: usize = 64 * 1024;
/// Size of the pipe's write buffer, with excess room for the header.
const PIPE_BUFFER_SIZE: usize = MAX_FRAGMENT_SIZE + 4 * 1024;
#[allow(non_snake_case)]
fn GetLastError() -> u32 {
unsafe {
winapi::um::errhandlingapi::GetLastError()
}
}
pub fn channel() -> Result<(OsIpcSender, OsIpcReceiver),WinError> {
let pipe_id = make_pipe_id();
let pipe_name = make_pipe_name(&pipe_id);
let receiver = OsIpcReceiver::new_named(&pipe_name)?;
let sender = OsIpcSender::connect_named(&pipe_name)?;
Ok((sender, receiver))
}
struct MessageHeader {
data_len: u32,
oob_len: u32,
}
impl MessageHeader {
fn total_message_bytes_needed(&self) -> usize {
mem::size_of::<MessageHeader>() + self.data_len as usize + self.oob_len as usize
}
}
struct Message<'data> {
data_len: usize,
oob_len: usize,
bytes: &'data [u8],
}
impl<'data> Message<'data> {
fn from_bytes(bytes: &'data [u8]) -> Option<Message> {
if bytes.len() < mem::size_of::<MessageHeader>() {
return None;
}
unsafe {
let ref header = *(bytes.as_ptr() as *const MessageHeader);
if bytes.len() < header.total_message_bytes_needed() {
return None;
}
Some(Message {
data_len: header.data_len as usize,
oob_len: header.oob_len as usize,
bytes: &bytes[0..header.total_message_bytes_needed()],
})
}
}
fn data(&self) -> &[u8] {
&self.bytes[mem::size_of::<MessageHeader>()..(mem::size_of::<MessageHeader>() + self.data_len)]
}
fn oob_bytes(&self) -> &[u8] {
&self.bytes[(mem::size_of::<MessageHeader>() + self.data_len)..]
}
fn oob_data(&self) -> Option<OutOfBandMessage> {
if self.oob_len > 0 {
let oob = bincode::deserialize::<OutOfBandMessage>(self.oob_bytes())
.expect("Failed to deserialize OOB data");
if oob.target_process_id != *CURRENT_PROCESS_ID {
panic!("Windows IPC channel received handles intended for pid {}, but this is pid {}. \
This likely happened because a receiver was transferred while it had outstanding data \
that contained a channel or shared memory in its pipe. \
This isn't supported in the Windows implementation.",
oob.target_process_id, *CURRENT_PROCESS_ID);
}
Some(oob)
} else {
None
}
}
fn size(&self) -> usize {
mem::size_of::<MessageHeader>() + self.data_len + self.oob_len
}
}
/// If we have any channel handles or shmem segments, then we'll send an
/// OutOfBandMessage after the data message.
///
/// This includes the receiver's process ID, which the receiver checks to
/// make sure that the message was originally sent to it, and was not sitting
/// in another channel's buffer when that channel got transferred to another
/// process. On Windows, we duplicate handles on the sender side to a specific
/// receiver. If the wrong receiver gets it, those handles are not valid.
///
/// TODO(vlad): We could attempt to recover from the above situation by
/// duplicating from the intended target process to ourselves (the receiver).
/// That would only work if the intended process a) still exists; b) can be
/// opened by the receiver with handle dup privileges. Another approach
/// could be to use a separate dedicated process intended purely for handle
/// passing, though that process would need to be global to any processes
/// amongst which you want to share channels or connect one-shot servers to.
/// There may be a system process that we could use for this purpose, but
/// I haven't found one -- and in the system process case, we'd need to ensure
/// that we don't leak the handles (e.g. dup a handle to the system process,
/// and then everything dies -- we don't want those resources to be leaked).
#[derive(Debug)]
struct OutOfBandMessage {
target_process_id: u32,
channel_handles: Vec<intptr_t>,
shmem_handles: Vec<(intptr_t, u64)>, // handle and size
big_data_receiver_handle: Option<(intptr_t, u64)>, // handle and size
}
impl OutOfBandMessage {
fn new(target_id: u32) -> OutOfBandMessage {
OutOfBandMessage {
target_process_id: target_id,
channel_handles: vec![],
shmem_handles: vec![],
big_data_receiver_handle: None,
}
}
fn needs_to_be_sent(&self) -> bool {
!self.channel_handles.is_empty() ||
!self.shmem_handles.is_empty() ||
self.big_data_receiver_handle.is_some()
}
}
impl serde::Serialize for OutOfBandMessage {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer
{
((self.target_process_id,
&self.channel_handles,
&self.shmem_handles,
&self.big_data_receiver_handle)).serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for OutOfBandMessage {
fn deserialize<D>(deserializer: D) -> Result<OutOfBandMessage, D::Error>
where D: serde::Deserializer<'de>
{
let (target_process_id, channel_handles, shmem_handles, big_data_receiver_handle) =
serde::Deserialize::deserialize(deserializer)?;
Ok(OutOfBandMessage {
target_process_id: target_process_id,
channel_handles: channel_handles,
shmem_handles: shmem_handles,
big_data_receiver_handle: big_data_receiver_handle
})
}
}
fn make_pipe_id() -> Uuid {
Uuid::new_v4()
}
fn make_pipe_name(pipe_id: &Uuid) -> CString {
CString::new(format!("\\\\.\\pipe\\rust-ipc-{}", pipe_id.to_string())).unwrap()
}
/// Duplicate a given handle from this process to the target one, passing the
/// given flags to DuplicateHandle.
///
/// Unlike win32 DuplicateHandle, this will preserve INVALID_HANDLE_VALUE (which is
/// also the pseudohandle for the current process).
fn dup_handle_to_process_with_flags(handle: &WinHandle, other_process: &WinHandle, flags: winapi::shared::minwindef::DWORD)
-> Result<WinHandle, WinError>
{
if !handle.is_valid() {
return Ok(WinHandle::invalid());
}
unsafe {
let mut new_handle: HANDLE = INVALID_HANDLE_VALUE;
let ok = winapi::um::handleapi::DuplicateHandle(CURRENT_PROCESS_HANDLE.as_raw(), handle.as_raw(),
other_process.as_raw(), &mut new_handle,
0, FALSE, flags);
if ok == FALSE {
Err(WinError::last("DuplicateHandle"))
} else {
Ok(WinHandle::new(new_handle))
}
}
}
/// Duplicate a handle in the current process.
fn dup_handle(handle: &WinHandle) -> Result<WinHandle,WinError> {
dup_handle_to_process(handle, &WinHandle::new(CURRENT_PROCESS_HANDLE.as_raw()))
}
/// Duplicate a handle to the target process.
fn dup_handle_to_process(handle: &WinHandle, other_process: &WinHandle) -> Result<WinHandle,WinError> {
dup_handle_to_process_with_flags(handle, other_process, winapi::um::winnt::DUPLICATE_SAME_ACCESS)
}
/// Duplicate a handle to the target process, closing the source handle.
fn move_handle_to_process(handle: WinHandle, other_process: &WinHandle) -> Result<WinHandle,WinError> {
let result = dup_handle_to_process_with_flags(&handle, other_process,
winapi::um::winnt::DUPLICATE_CLOSE_SOURCE | winapi::um::winnt::DUPLICATE_SAME_ACCESS);
// Since the handle was moved to another process, the original is no longer valid;
// so we probably shouldn't try to close it explicitly?
mem::forget(handle);
result
}
#[derive(Debug)]
struct WinHandle {
h: HANDLE
}
unsafe impl Send for WinHandle { }
unsafe impl Sync for WinHandle { }
impl Drop for WinHandle {
fn drop(&mut self) {
unsafe {
if self.is_valid() {
let result = winapi::um::handleapi::CloseHandle(self.h);
assert!(thread::panicking() || result != 0);
}
}
}
}
impl Default for WinHandle {
fn default() -> WinHandle {
WinHandle { h: INVALID_HANDLE_VALUE }
}
}
const WINDOWS_APP_MODULE_NAME: &'static str = "api-ms-win-core-handle-l1-1-0";
const COMPARE_OBJECT_HANDLES_FUNCTION_NAME: &'static str = "CompareObjectHandles";
lazy_static! {
static ref WINDOWS_APP_MODULE_NAME_CSTRING: CString = CString::new(WINDOWS_APP_MODULE_NAME).unwrap();
static ref COMPARE_OBJECT_HANDLES_FUNCTION_NAME_CSTRING: CString = CString::new(COMPARE_OBJECT_HANDLES_FUNCTION_NAME).unwrap();
}
#[cfg(feature = "windows-shared-memory-equality")]
impl PartialEq for WinHandle {
fn eq(&self, other: &WinHandle) -> bool {
unsafe {
// Calling LoadLibraryA every time seems to be ok since libraries are refcounted and multiple calls won't produce multiple instances.
let module_handle = winapi::um::libloaderapi::LoadLibraryA(WINDOWS_APP_MODULE_NAME_CSTRING.as_ptr());
if module_handle.is_null() {
panic!("Error loading library {}. {}", WINDOWS_APP_MODULE_NAME, WinError::error_string(GetLastError()));
}
let proc = winapi::um::libloaderapi::GetProcAddress(module_handle, COMPARE_OBJECT_HANDLES_FUNCTION_NAME_CSTRING.as_ptr());
if proc.is_null() {
panic!("Error calling GetProcAddress to use {}. {}", COMPARE_OBJECT_HANDLES_FUNCTION_NAME, WinError::error_string(GetLastError()));
}
let compare_object_handles: unsafe extern "stdcall" fn(HANDLE, HANDLE) -> winapi::shared::minwindef::BOOL = std::mem::transmute(proc);
compare_object_handles(self.h, other.h) != 0
}
}
}
impl WinHandle {
fn new(h: HANDLE) -> WinHandle {
WinHandle { h: h }
}
fn invalid() -> WinHandle {
WinHandle { h: INVALID_HANDLE_VALUE }
}
fn is_valid(&self) -> bool {
self.h != INVALID_HANDLE_VALUE
}
fn as_raw(&self) -> HANDLE {
self.h
}
fn take_raw(&mut self) -> HANDLE {
mem::replace(&mut self.h, INVALID_HANDLE_VALUE)
}
fn take(&mut self) -> WinHandle {
WinHandle::new(self.take_raw())
}
}
/// Helper struct for all data being aliased by the kernel during async reads.
#[derive(Debug)]
struct AsyncData {
/// File handle of the pipe on which the async operation is performed.
handle: WinHandle,
/// Meta-data for this async read operation, filled by the kernel.
///
/// This must be on the heap, in order for its memory location --
/// which is registered in the kernel during an async read --
/// to remain stable even when the enclosing structure is passed around.
ov: NoDebug<Box<Overlapped>>,
/// Buffer for the kernel to store the results of the async read operation.
///
/// The vector provided here needs to have some allocated yet unused space,
/// i.e. `capacity()` needs to be larger than `len()`.
/// If part of the vector is already filled, that is left in place;
/// the new data will only be written to the unused space.
buf: Vec<u8>,
}
#[repr(transparent)]
struct Overlapped(winapi::um::minwinbase::OVERLAPPED);
impl Drop for Overlapped {
fn drop(&mut self) {
unsafe {
if self.0.hEvent != null_mut() && self.0.hEvent != INVALID_HANDLE_VALUE {
let result = winapi::um::handleapi::CloseHandle(self.0.hEvent);
assert!(thread::panicking() || result != 0);
}
}
}
}
impl Overlapped {
fn new(ov: winapi::um::minwinbase::OVERLAPPED) -> Self {
Self(ov)
}
}
impl Deref for Overlapped {
type Target = winapi::um::minwinbase::OVERLAPPED;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Overlapped {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Main object keeping track of a receive handle and its associated state.
///
/// Implements blocking/nonblocking reads of messages from the handle.
#[derive(Debug)]
struct MessageReader {
/// The pipe read handle.
///
/// Note: this is only set while no async read operation
/// is currently in progress with the kernel.
/// When an async read is in progress,
/// it is moved into the `async` sub-structure (see below)
/// along with the other fields used for the async operation,
/// to make sure they all stay in sync,
/// and nothing else can meddle with the the pipe
/// until the operation is completed.
handle: WinHandle,
/// Buffer for outstanding data, that has been received but not yet processed.
///
/// Note: just like `handle` above,
/// this is only set while no async read is in progress.
/// When an async read is in progress,
/// the receive buffer is aliased by the kernel;
/// so we need to temporarily move it into an `AliasedCell`,
/// thus making it inaccessible from safe code --
/// see `async` below.
/// We only move it back once the kernel signals completion of the async read.
read_buf: Vec<u8>,
/// Data used by the kernel during an async read operation.
///
/// Note: Since this field only has a value
/// when an async read operation is in progress
/// (i.e. has been issued to the system, and not completed yet),
/// this also serves as an indicator of the latter.
///
/// WARNING: As the kernel holds mutable aliases of this data
/// while an async read is in progress,
/// it is crucial that it is never accessed in user space
/// from the moment we issue an async read in `start_read()`,
/// until the moment we process the event
/// signalling completion of the async read in `notify_completion()`.
///
/// Since Rust's type system is not aware of the kernel aliases,
/// the compiler cannot guarantee exclusive access the way it normally would,
/// i.e. any access to this value is inherently unsafe!
/// We thus wrap it in an `AliasedCell`,
/// making sure the data is only accessible from code marked `unsafe`;
/// and only move it out when the kernel signals that the async read is done.
r#async: Option<AliasedCell<AsyncData>>,
/// Token identifying the reader/receiver within an `OsIpcReceiverSet`.
///
/// This is returned to callers of `OsIpcReceiverSet.add()` and `OsIpcReceiverSet.select()`.
///
/// `None` if this `MessageReader` is not part of any set.
entry_id: Option<u64>,
}
// We need to explicitly declare this, because of the raw pointer
// contained in the `OVERLAPPED` structure.
//
// Note: the `Send` claim is only really fulfilled
// as long as nothing can ever alias the aforementioned raw pointer.
// As explained in the documentation of the `async` field,
// this is a tricky condition (because of kernel aliasing),
// which we however need to uphold regardless of the `Send` property --
// so claiming `Send` should not introduce any additional issues.
unsafe impl Send for OsIpcReceiver { }
impl Drop for MessageReader {
fn drop(&mut self) {
// Before dropping the `ov` structure and read buffer,
// make sure the kernel won't do any more async updates to them!
self.cancel_io();
}
}
impl MessageReader {
fn new(handle: WinHandle) -> MessageReader {
MessageReader {
handle: handle,
read_buf: Vec::new(),
r#async: None,
entry_id: None,
}
}
fn take(&mut self) -> MessageReader {
// This is currently somewhat inefficient,
// because of the initialisation of things that won't be used.
// Moving the data items of `MessageReader` into an enum will fix this,
// as that way we will be able to just define a data-less `Invalid` case.
mem::replace(self, MessageReader::new(WinHandle::invalid()))
}
/// Request the kernel to cancel a pending async I/O operation on this reader.
///
/// Note that this only schedules the cancel request;
/// but doesn't guarantee that the operation is done
/// (and the buffers are no longer used by the kernel)
/// before this method returns.
///
/// A caller that wants to ensure the operation is really done,
/// will need to wait using `fetch_async_result()`.
/// (Or `fetch_iocp_result()` for readers in a set.)
///
/// The only exception is if the kernel indicates
/// that no operation was actually outstanding at this point.
/// In that case, the `async` data is released immediately;
/// and the caller should not attempt waiting for completion.
fn issue_async_cancel(&mut self) {
unsafe {
let status = winapi::um::ioapiset::CancelIoEx(self.r#async.as_ref().unwrap().alias().handle.as_raw(),
&mut ***self.r#async.as_mut().unwrap().alias_mut().ov.deref_mut());
if status == FALSE {
// A cancel operation is not expected to fail.
// If it does, callers are not prepared for that -- so we have to bail.
//
// Note that we should never ignore a failed cancel,
// since that would affect further operations;
// and the caller definitely must not free the aliased data in that case!
//
// Sometimes `CancelIoEx()` fails with `ERROR_NOT_FOUND` though,
// meaning there is actually no async operation outstanding at this point.
// (Specifically, this is triggered by the `receiver_set_big_data()` test.)
// Not sure why that happens -- but I *think* it should be benign...
//
// In that case, we can safely free the async data right now;
// and the caller should not attempt to wait for completion.
assert!(GetLastError() == winapi::shared::winerror::ERROR_NOT_FOUND);
let async_data = self.r#async.take().unwrap().into_inner();
self.handle = async_data.handle;
self.read_buf = async_data.buf;
}
}
}
fn cancel_io(&mut self) {
if self.r#async.is_some() {
// This doesn't work for readers in a receiver set.
// (`fetch_async_result()` would hang indefinitely.)
// Receiver sets have to handle cancellation specially,
// and make sure they always do that *before* dropping readers.
assert!(self.entry_id.is_none());
self.issue_async_cancel();
// If there is an operation still in flight, wait for it to complete.
//
// This will usually fail with `ERROR_OPERATION_ABORTED`;
// but it could also return success, or some other error,
// if the operation actually completed in the mean time.
// We don't really care either way --
// we just want to be certain there is no operation in flight any more.
if self.r#async.is_some() {
let _ = self.fetch_async_result(BlockingMode::Blocking);
}
}
}
/// Kick off an asynchronous read.
///
/// When an async read is started successfully,
/// the receive buffer is moved out of `read_buf`
/// into the `AliasedCell<>` in `async`,
/// thus making it inaccessible from safe code;
/// it will only be moved back in `notify_completion()`.
/// (See documentation of the `read_buf` and `async` fields.)
fn start_read(&mut self) -> Result<(),WinError> {
// Nothing needs to be done if an async read operation is already in progress.
if self.r#async.is_some() {
return Ok(());
}
win32_trace!("[$ {:?}] start_read", self.handle);
if self.read_buf.len() == self.read_buf.capacity() {
self.read_buf.reserve(PIPE_BUFFER_SIZE);
}
unsafe {
// Temporarily extend the vector to span its entire capacity,
// so we can safely sub-slice it for the actual read.
let buf_len = self.read_buf.len();
let buf_cap = self.read_buf.capacity();
self.read_buf.set_len(buf_cap);
// issue the read to the buffer, at the current length offset
self.r#async = Some(AliasedCell::new(AsyncData {
handle: self.handle.take(),
ov: NoDebug(Box::new({
let mut overlapped: winapi::um::minwinbase::OVERLAPPED = mem::zeroed();
// Create a manually reset event. The documentation for GetOverlappedResultEx
// states you must do this in the remarks section.
overlapped.hEvent = CreateEventA(ptr::null_mut(), TRUE, FALSE, ptr::null_mut());
Overlapped::new(overlapped)
})),
buf: mem::replace(&mut self.read_buf, vec![]),
}));
let ok = {
let async_data = self.r#async.as_mut().unwrap().alias_mut();
let remaining_buf = &mut async_data.buf[buf_len..];
winapi::um::fileapi::ReadFile(async_data.handle.as_raw(),
remaining_buf.as_mut_ptr() as LPVOID,
remaining_buf.len() as u32,
ptr::null_mut(),
&mut ***async_data.ov.deref_mut())
};
// Reset the vector to only expose the already filled part.
//
// This means that the async read
// will actually fill memory beyond the exposed part of the vector.
// While this use of a vector is officially sanctioned for such cases,
// it still feel rather icky to me...
//
// On the other hand, this way we make sure
// the buffer never appears to have more valid data
// than what is actually present,
// which could pose a potential danger in its own right.
// Also, it avoids the need to keep a separate state variable --
// which would bear some risk of getting out of sync.
self.r#async.as_mut().unwrap().alias_mut().buf.set_len(buf_len);
let result = if ok == FALSE {
Err(GetLastError())
} else {
Ok(())
};
match result {
// Normally, for an async operation, a call like
// `ReadFile` would return `FALSE`, and the error code
// would be `ERROR_IO_PENDING`. But in some situations,
// `ReadFile` can complete synchronously (returns `TRUE`).
// Even if it does, a notification that the IO completed
// is still sent to the IO completion port that this
// handle is part of, meaning that we don't have to do any
// special handling for sync-completed operations.
Ok(()) |
Err(winapi::shared::winerror::ERROR_IO_PENDING) => {
Ok(())
},
Err(winapi::shared::winerror::ERROR_BROKEN_PIPE) => {
win32_trace!("[$ {:?}] BROKEN_PIPE straight from ReadFile", self.handle);
let async_data = self.r#async.take().unwrap().into_inner();
self.handle = async_data.handle;
self.read_buf = async_data.buf;
Err(WinError::ChannelClosed)
},
Err(err) => {
let async_data = self.r#async.take().unwrap().into_inner();
self.handle = async_data.handle;
self.read_buf = async_data.buf;
Err(WinError::from_system(err, "ReadFile"))
},
}
}
}
/// Called when we receive an IO Completion Packet for this handle.
///
/// During its course, this method moves `async.buf` back into `read_buf`,
/// thus making it accessible from normal code again;
/// so `get_message()` can extract the received messages from the buffer.
///
/// Invoking this is unsafe, since calling it in error
/// while an async read is actually still in progress in the kernel
/// would have catastrophic effects,
/// as the `async` data is still mutably aliased by the kernel in that case!
/// (See documentation of the `async` field.)
///
/// Also, this method relies on `async` actually having valid data,
/// i.e. nothing should modify its constituent fields
/// between receiving the completion notification from the kernel
/// and invoking this method.
unsafe fn notify_completion(&mut self, io_result: Result<(), WinError>) -> Result<(), WinError> {
win32_trace!("[$ {:?}] notify_completion", self.r#async.as_ref().unwrap().alias().handle);
// Regardless whether the kernel reported success or error,
// it doesn't have an async read operation in flight at this point anymore.
// (And it's safe again to access the `async` data.)
let async_data = self.r#async.take().unwrap().into_inner();
self.handle = async_data.handle;
let ov = async_data.ov;
self.read_buf = async_data.buf;
match io_result {
Ok(()) => {}
Err(WinError::WindowsResult(winapi::shared::winerror::ERROR_BROKEN_PIPE)) => {
// Remote end closed the channel.
return Err(WinError::ChannelClosed);
}
Err(err) => return Err(err),
}
let nbytes = ov.InternalHigh as u32;
let offset = ov.u.s().Offset;
assert!(offset == 0);
let new_size = self.read_buf.len() + nbytes as usize;
win32_trace!("nbytes: {}, offset {}, buf len {}->{}, capacity {}",
nbytes, offset, self.read_buf.len(), new_size, self.read_buf.capacity());
assert!(new_size <= self.read_buf.capacity());
self.read_buf.set_len(new_size);
Ok(())
}
/// Attempt to conclude an already issued async read operation.
///
/// If successful, the result will be ready for picking up by `get_message()`.
///
/// (`get_message()` might still yield nothing though,
/// in case only part of the message was received in this read,
/// and further read operations are necessary to get the rest.)
///
/// In non-blocking mode, this may return with `WinError:NoData`,
/// while the async operation remains in flight.
/// The read buffer remains unavailable in that case,
/// since it's still aliased by the kernel.
/// (And there is nothing new to pick up anyway.)
/// It will only become available again
/// when `fetch_async_result()` returns successfully upon retry.
/// (Or the async read is aborted with `cancel_io()`.)
fn fetch_async_result(&mut self, blocking_mode: BlockingMode) -> Result<(), WinError> {
unsafe {
// Get the overlapped result, blocking if we need to.
let mut nbytes: u32 = 0;
let timeout = match blocking_mode {
BlockingMode::Blocking => winapi::um::winbase::INFINITE,
BlockingMode::Nonblocking => 0,
BlockingMode::Timeout(duration) => duration.as_millis().try_into().unwrap_or(winapi::um::winbase::INFINITE),
};
let ok = winapi::um::ioapiset::GetOverlappedResultEx(self.r#async.as_ref().unwrap().alias().handle.as_raw(),
&mut ***self.r#async.as_mut().unwrap().alias_mut().ov.deref_mut(),
&mut nbytes,
timeout,
FALSE);
winapi::um::synchapi::ResetEvent(self.r#async.as_mut().unwrap().alias_mut().ov.deref_mut().hEvent);
let io_result = if ok == FALSE {
let err = GetLastError();
if blocking_mode != BlockingMode::Blocking && err == winapi::shared::winerror::ERROR_IO_INCOMPLETE {
// Async read hasn't completed yet.
// Inform the caller, while keeping the read in flight.
return Err(WinError::NoData);
}
// Timeout has elapsed, so we must cancel the read operation before proceeding
if err == winapi::shared::winerror::WAIT_TIMEOUT {
self.cancel_io();
return Err(WinError::NoData);
}
// We pass err through to notify_completion so
// that it can handle other errors.
Err(WinError::from_system(err, "GetOverlappedResultEx"))
} else {
Ok(())
};
// Notify that the read completed, which will update the
// read pointers
self.notify_completion(io_result)
}
}
fn get_message(&mut self) -> Result<Option<(Vec<u8>, Vec<OsOpaqueIpcChannel>, Vec<OsIpcSharedMemory>)>,
WinError> {
// Never touch the buffer while it's still mutably aliased by the kernel!
if self.r#async.is_some() {
return Ok(None);
}
let drain_bytes;
let result;
if let Some(message) = Message::from_bytes(&self.read_buf) {
let mut channels: Vec<OsOpaqueIpcChannel> = vec![];
let mut shmems: Vec<OsIpcSharedMemory> = vec![];
let mut big_data = None;
if let Some(oob) = message.oob_data() {
win32_trace!("[$ {:?}] msg with total {} bytes, {} channels, {} shmems, big data handle {:?}",
self.handle, message.data_len, oob.channel_handles.len(), oob.shmem_handles.len(),
oob.big_data_receiver_handle);
for handle in oob.channel_handles {
channels.push(OsOpaqueIpcChannel::new(WinHandle::new(handle as HANDLE)));
}
for (handle, size) in oob.shmem_handles {
shmems.push(OsIpcSharedMemory::from_handle(WinHandle::new(handle as HANDLE),
size as usize,
).unwrap());
}
if oob.big_data_receiver_handle.is_some() {
let (handle, big_data_size) = oob.big_data_receiver_handle.unwrap();
let receiver = OsIpcReceiver::from_handle(WinHandle::new(handle as HANDLE));
big_data = Some(receiver.recv_raw(big_data_size as usize)?);
}
}
let buf_data = big_data.unwrap_or_else(|| message.data().to_vec());
win32_trace!("[$ {:?}] get_message success -> {} bytes, {} channels, {} shmems",
self.handle, buf_data.len(), channels.len(), shmems.len());
drain_bytes = Some(message.size());
result = Some((buf_data, channels, shmems));
} else {
drain_bytes = None;
result = None;
}
if let Some(size) = drain_bytes {
// If the only valid bytes in the buffer are what we just
// consumed, then just set the vector's length to 0. This
// avoids reallocations as in the drain() case, and is
// a significant speedup.
if self.read_buf.len() == size {
self.read_buf.clear();
} else {
self.read_buf.drain(0..size);
}
}
Ok(result)
}
fn add_to_iocp(&mut self, iocp: &WinHandle, entry_id: u64) -> Result<(),WinError> {
unsafe {
assert!(self.entry_id.is_none());
let completion_key = self.handle.as_raw() as winapi::shared::basetsd::ULONG_PTR;
let ret = winapi::um::ioapiset::CreateIoCompletionPort(self.handle.as_raw(),
iocp.as_raw(),
completion_key,
0);
if ret.is_null() {
return Err(WinError::last("CreateIoCompletionPort"));
}
}
self.entry_id = Some(entry_id);
// The readers in the IOCP need to have async reads in flight,
// so they can actually get completion events --
// otherwise, a subsequent `select()` call would just hang indefinitely.
self.start_read()
}
/// Specialized read for out-of-band data ports.
///
/// Here the buffer size is known in advance,
/// and the transfer doesn't have our typical message framing.
///
/// It's only valid to call this as the one and only call after creating a MessageReader.
fn read_raw_sized(mut self, size: usize) -> Result<Vec<u8>,WinError> {
assert!(self.read_buf.len() == 0);
self.read_buf.reserve(size);
while self.read_buf.len() < size {
// Because our handle is asynchronous, we have to do a two-part read --
// first issue the operation, then wait for its completion.
match self.start_read() {
Err(WinError::ChannelClosed) => {
// If the helper channel closes unexpectedly
// (i.e. before supplying the expected amount of data),
// don't report that as a "sender closed" condition on the main channel:
// rather, fail with the actual raw error code.
return Err(WinError::from_system(winapi::shared::winerror::ERROR_BROKEN_PIPE, "ReadFile"));
}
Err(err) => return Err(err),
Ok(()) => {}
};
match self.fetch_async_result(BlockingMode::Blocking) {
Err(WinError::ChannelClosed) => {
return Err(WinError::from_system(winapi::shared::winerror::ERROR_BROKEN_PIPE, "ReadFile"))
}
Err(err) => return Err(err),
Ok(()) => {}
};
}
Ok(mem::replace(&mut self.read_buf, vec![]))
}
/// Get raw handle of the receive port.
///
/// This is only for debug tracing purposes, and must not be used for anything else.
fn get_raw_handle(&self) -> HANDLE {
self.handle.as_raw()
}
}
#[derive(Clone, Copy, Debug)]
enum AtomicMode {
Atomic,
Nonatomic,
}
/// Write data to a handle.
///
/// In `Atomic` mode, this panics if the data can't be written in a single system call.
fn write_buf(handle: &WinHandle, bytes: &[u8], atomic: AtomicMode) -> Result<(),WinError> {
let total = bytes.len();
if total == 0 {
return Ok(());
}
let mut written = 0;
while written < total {
let mut sz: u32 = 0;
let bytes_to_write = &bytes[written..];
unsafe {
if winapi::um::fileapi::WriteFile(handle.as_raw(),
bytes_to_write.as_ptr() as LPVOID,
bytes_to_write.len() as u32,
&mut sz,
ptr::null_mut())
== FALSE
{
return Err(WinError::last("WriteFile"));
}
}
written += sz as usize;
match atomic {
AtomicMode::Atomic => {
if written != total {
panic!("Windows IPC write_buf expected to write full buffer, but only wrote partial (wrote {} out of {} bytes)", written, total);
}
},
AtomicMode::Nonatomic => {
win32_trace!("[c {:?}] ... wrote {} bytes, total {}/{} err {}", handle.as_raw(), sz, written, total, GetLastError());
},
}
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum BlockingMode {
Blocking,
Nonblocking,
Timeout(Duration),
}
#[derive(Debug)]
pub struct OsIpcReceiver {
/// The receive handle and its associated state.
///
/// We can't just deal with raw handles like in the other platform back-ends,
/// since this implementation -- using plain pipes with no native packet handling --
/// requires keeping track of various bits of receiver state,
/// which must not be separated from the handle itself.
///
/// Note: Inner mutability is necessary,