Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Overlapped.cs « Threading « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0a1c2ce727bc4c9f2e6bb2fb1153548e519b82fa (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*
 * This files defines the following types:
 *  - _IOCompletionCallback
 *  - OverlappedData
 *  - Overlapped
 */

/*=============================================================================
**
**
**
** Purpose: Class for converting information to and from the native 
**          overlapped structure used in asynchronous file i/o
**
**
=============================================================================*/

using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;

namespace System.Threading
{
    #region class _IOCompletionCallback

    internal unsafe class _IOCompletionCallback
    {
        private IOCompletionCallback _ioCompletionCallback;
        private ExecutionContext _executionContext;
        private uint _errorCode; // Error code
        private uint _numBytes; // No. of bytes transferred 
        private NativeOverlapped* _pNativeOverlapped;

        internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ExecutionContext executionContext)
        {
            _ioCompletionCallback = ioCompletionCallback;
            _executionContext = executionContext;
        }

        // Context callback: same sig for SendOrPostCallback and ContextCallback
        internal static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context);
        private static void IOCompletionCallback_Context(object state)
        {
            _IOCompletionCallback helper = (_IOCompletionCallback)state;
            Debug.Assert(helper != null, "_IOCompletionCallback cannot be null");
            helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pNativeOverlapped);
        }

        internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pNativeOverlapped)
        {
            do
            {
                OverlappedData overlapped = OverlappedData.GetOverlappedFromNative(pNativeOverlapped);

                if (overlapped._callback is IOCompletionCallback iocb)
                {
                    // We got here because of UnsafePack (or) Pack with EC flow suppressed
                    iocb(errorCode, numBytes, pNativeOverlapped);
                }
                else
                {
                    // We got here because of Pack
                    var helper = (_IOCompletionCallback)overlapped._callback;
                    helper._errorCode = errorCode;
                    helper._numBytes = numBytes;
                    helper._pNativeOverlapped = pNativeOverlapped;
                    ExecutionContext.Run(helper._executionContext, s_ccb, helper);
                }

                //Quickly check the VM again, to see if a packet has arrived.
                //OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
                pNativeOverlapped = null;
            } while (pNativeOverlapped != null);
        }
    }

    #endregion class _IOCompletionCallback

    #region class OverlappedData

    internal unsafe sealed class OverlappedData
    {
        internal IAsyncResult _asyncResult;
        internal object _callback; // IOCompletionCallback or _IOCompletionCallback
        internal Overlapped _overlapped;
        private object _userObject;
        private NativeOverlapped * _pNativeOverlapped;
        private IntPtr _eventHandle;
        private int _offsetLow;
        private int _offsetHigh;
        private GCHandle[] _pinnedData;

        internal ref IAsyncResult AsyncResult => ref _asyncResult;

        internal ref int OffsetLow => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetLow : ref _offsetLow;
        internal ref int OffsetHigh => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->OffsetHigh : ref _offsetHigh;
        internal ref IntPtr EventHandle => ref (_pNativeOverlapped != null) ? ref _pNativeOverlapped->EventHandle : ref _eventHandle;

        internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData)
        {
            if (_pNativeOverlapped != null)
            {
                throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
            }

            if (iocb != null)
            {
                ExecutionContext ec = ExecutionContext.Capture();
                _callback = (ec != null && !ec.IsDefault) ? new _IOCompletionCallback(iocb, ec) : (object)iocb;
            }
            else
            {
                _callback = null;
            }
            _userObject = userData;
            return AllocateNativeOverlapped();
        }

        internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData)
        {
            if (_pNativeOverlapped != null)
            {
                throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
            }
            _userObject = userData;
            _callback = iocb;
            return AllocateNativeOverlapped();
        }

        private unsafe NativeOverlapped* AllocateNativeOverlapped()
        {
            Debug.Assert(_pinnedData == null);

            bool success = false;
            try
            {
                if (_userObject != null)
                {
                    if (_userObject.GetType() == typeof(object[]))
                    {
                        object[] objArray = (object[])_userObject;

                        _pinnedData = new GCHandle[objArray.Length];
                        for (int i = 0; i < objArray.Length; i++)
                        {
                            _pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned);
                        }
                    }
                    else
                    {
                        _pinnedData = new GCHandle[1];
                        _pinnedData[0] = GCHandle.Alloc(_userObject, GCHandleType.Pinned);
                    }
                }

                NativeOverlapped* pNativeOverlapped = (NativeOverlapped*)Interop.MemAlloc((UIntPtr)(sizeof(NativeOverlapped) + sizeof(GCHandle)));
                *(GCHandle*)(pNativeOverlapped + 1) = default(GCHandle);
                _pNativeOverlapped = pNativeOverlapped;

                _pNativeOverlapped->InternalLow = default;
                _pNativeOverlapped->InternalHigh = default;
                _pNativeOverlapped->OffsetLow = _offsetLow;
                _pNativeOverlapped->OffsetHigh = _offsetHigh;
                _pNativeOverlapped->EventHandle = _eventHandle;

                *(GCHandle*)(_pNativeOverlapped + 1) = GCHandle.Alloc(this);

                success = true;
                return _pNativeOverlapped;
            }
            finally
            {
                if (!success)
                    FreeNativeOverlapped();
            }
        }

        internal static unsafe void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr)
        {
            OverlappedData overlappedData = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr);
            overlappedData.FreeNativeOverlapped();
        }

        private void FreeNativeOverlapped()
        {
            if (_pinnedData != null)
            {
                for (int i = 0; i < _pinnedData.Length; i++)
                {
                    if (_pinnedData[i].IsAllocated)
                    {
                        _pinnedData[i].Free();
                    }
                }
                _pinnedData = null;
            }

            if (_pNativeOverlapped != null)
            {
                GCHandle handle = *(GCHandle*)(_pNativeOverlapped + 1);
                if (handle.IsAllocated)
                    handle.Free();

                Interop.MemFree((IntPtr)_pNativeOverlapped);
                _pNativeOverlapped = null;
            }
        }

        internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* pNativeOverlapped)
        {
            GCHandle handle = *(GCHandle*)(pNativeOverlapped + 1);
            return (OverlappedData)handle.Target;
        }
    }

    #endregion class OverlappedData

    #region class Overlapped

    public class Overlapped
    {
        private OverlappedData _overlappedData;

        public Overlapped()
        {
            _overlappedData = new OverlappedData();
            _overlappedData._overlapped = this;
        }

        public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) : this()
        {
            _overlappedData.OffsetLow = offsetLo;
            _overlappedData.OffsetHigh = offsetHi;
            _overlappedData.EventHandle = hEvent;
            _overlappedData.AsyncResult = ar;
        }

        [Obsolete("This constructor is not 64-bit compatible.  Use the constructor that takes an IntPtr for the event handle.  http://go.microsoft.com/fwlink/?linkid=14202")]
        public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar)
        {
        }

        public IAsyncResult AsyncResult
        {
            get { return _overlappedData.AsyncResult; }
            set { _overlappedData.AsyncResult = value; }
        }

        public int OffsetLow
        {
            get { return _overlappedData.OffsetLow; }
            set { _overlappedData.OffsetLow = value; }
        }

        public int OffsetHigh
        {
            get { return _overlappedData.OffsetHigh; }
            set { _overlappedData.OffsetHigh = value; }
        }

        [Obsolete("This property is not 64-bit compatible.  Use EventHandleIntPtr instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        public int EventHandle
        {
            get { return EventHandleIntPtr.ToInt32(); }
            set { EventHandleIntPtr = new IntPtr(value); }
        }

        public IntPtr EventHandleIntPtr
        {
            get { return _overlappedData.EventHandle; }
            set { _overlappedData.EventHandle = value; }
        }

        /*====================================================================
        *  Packs a managed overlapped class into native Overlapped struct.
        *  Roots the iocb and stores it in the ReservedCOR field of native Overlapped 
        *  Pins the native Overlapped struct and returns the pinned index. 
        ====================================================================*/
        [Obsolete("This method is not safe.  Use Pack (iocb, userData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [CLSCompliant(false)]
        public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb)
        {
            return Pack(iocb, null);
        }

        [CLSCompliant(false)]
        public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData)
        {
            return _overlappedData.Pack(iocb, userData);
        }

        [Obsolete("This method is not safe.  Use UnsafePack (iocb, userData) instead.  http://go.microsoft.com/fwlink/?linkid=14202")]
        [CLSCompliant(false)]
        public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
        {
            return UnsafePack(iocb, null);
        }

        [CLSCompliant(false)]
        public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData)
        {
            return _overlappedData.UnsafePack(iocb, userData);
        }

        /*====================================================================
        *  Unpacks an unmanaged native Overlapped struct. 
        *  Unpins the native Overlapped struct
        ====================================================================*/
        [CLSCompliant(false)]
        public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
        {
            if (nativeOverlappedPtr == null)
                throw new ArgumentNullException(nameof(nativeOverlappedPtr));

            return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped;
        }

        [CLSCompliant(false)]
        public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr)
        {
            if (nativeOverlappedPtr == null)
                throw new ArgumentNullException(nameof(nativeOverlappedPtr));

            OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null;
            OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
        }
    }

    #endregion class Overlapped
}