-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
semaphore.cs
427 lines (380 loc) · 15.9 KB
/
semaphore.cs
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
#if MONO
#undef FEATURE_PAL
#endif
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Threading
{
using System.IO;
using System.IO.Ports; // For InternalResources class
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
// CoreSys build problem - we're using mscorlib's implementation assembly instead of one from asmmeta. There's a conflicting NativeMethods type.
using Marshal = System.Runtime.InteropServices.Marshal;
using ComVisibleAttribute = System.Runtime.InteropServices.ComVisibleAttribute;
using System.Threading;
using System.Security;
using System.Security.Permissions;
#if !FEATURE_PAL && !FEATURE_NETCORE
using System.Security.AccessControl;
#endif
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
[HostProtection(Synchronization=true, ExternalThreading=true)]
[ComVisibleAttribute(false)]
public sealed class Semaphore: WaitHandle
{
private const int MAX_PATH = 260;
// creates a nameless semaphore object
// Win32 only takes maximum count of Int32.MaxValue
[SecuritySafeCritical]
#if !FEATURE_NETCORE
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
#endif // !FEATURE_NETCORE
public Semaphore(int initialCount, int maximumCount) : this(initialCount,maximumCount,null){}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
public Semaphore(int initialCount, int maximumCount, string name)
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException("initialCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
}
if (maximumCount < 1)
{
throw new ArgumentOutOfRangeException("maximumCount", SR.GetString(SR.ArgumentOutOfRange_NeedPosNum));
}
if (initialCount > maximumCount)
{
throw new ArgumentException(SR.GetString(SR.Argument_SemaphoreInitialMaximum));
}
if(null != name && MAX_PATH < name.Length)
{
throw new ArgumentException(SR.GetString(SR.Argument_WaitHandleNameTooLong));
}
#if MONO
int errorCode;
var myHandle = new SafeWaitHandle (CreateSemaphore_internal (initialCount, maximumCount, name, out errorCode), true);
#else
SafeWaitHandle myHandle = SafeNativeMethods.CreateSemaphore(null, initialCount, maximumCount, name);
#endif
if (myHandle.IsInvalid)
{
#if !MONO
int errorCode = Marshal.GetLastWin32Error();
#endif
if(null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.GetString(SR.WaitHandleCannotBeOpenedException_InvalidHandle,name));
#if MONO
InternalResources.WinIOError(errorCode, "");
#else
InternalResources.WinIOError();
#endif
}
this.SafeWaitHandle = myHandle;
}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew)
#if !FEATURE_PAL && !FEATURE_NETCORE
: this(initialCount, maximumCount, name, out createdNew, null)
{
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe Semaphore(int initialCount, int maximumCount, string name, out bool createdNew, SemaphoreSecurity semaphoreSecurity)
#endif
{
if (initialCount < 0)
{
throw new ArgumentOutOfRangeException("initialCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
}
if (maximumCount < 1)
{
throw new ArgumentOutOfRangeException("maximumCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
}
if (initialCount > maximumCount)
{
throw new ArgumentException(SR.GetString(SR.Argument_SemaphoreInitialMaximum));
}
if(null != name && MAX_PATH < name.Length)
{
throw new ArgumentException(SR.GetString(SR.Argument_WaitHandleNameTooLong));
}
SafeWaitHandle myHandle;
#if MONO
int errorCode;
myHandle = new SafeWaitHandle (CreateSemaphore_internal (initialCount, maximumCount, name, out errorCode), true);
#else
#if !FEATURE_PAL && !FEATURE_NETCORE
// For ACL's, get the security descriptor from the SemaphoreSecurity.
if (semaphoreSecurity != null) {
NativeMethods.SECURITY_ATTRIBUTES secAttrs = null;
secAttrs = new NativeMethods.SECURITY_ATTRIBUTES();
secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
byte[] sd = semaphoreSecurity.GetSecurityDescriptorBinaryForm();
fixed(byte* pSecDescriptor = sd) {
secAttrs.lpSecurityDescriptor = new SafeLocalMemHandle((IntPtr) pSecDescriptor, false);
myHandle = SafeNativeMethods.CreateSemaphore(secAttrs, initialCount, maximumCount, name);
}
}
else {
#endif
myHandle = SafeNativeMethods.CreateSemaphore(null, initialCount, maximumCount, name);
#if !FEATURE_PAL && !FEATURE_NETCORE
}
#endif
int errorCode = Marshal.GetLastWin32Error();
#endif
if (myHandle.IsInvalid)
{
if(null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.GetString(SR.WaitHandleCannotBeOpenedException_InvalidHandle,name));
#if MONO
InternalResources.WinIOError(errorCode, "");
#else
InternalResources.WinIOError();
#endif
}
createdNew = errorCode != NativeMethods.ERROR_ALREADY_EXISTS;
this.SafeWaitHandle = myHandle;
}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
private Semaphore(SafeWaitHandle handle)
{
this.SafeWaitHandle = handle;
}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
public static Semaphore OpenExisting(string name)
{
#if !FEATURE_PAL && !FEATURE_NETCORE
return OpenExisting(name, SemaphoreRights.Modify | SemaphoreRights.Synchronize);
}
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static Semaphore OpenExisting(string name, SemaphoreRights rights)
{
Semaphore result;
switch (OpenExistingWorker(name, rights, out result))
#else //FEATURE_PAL || FEATURE_NETCORE
Semaphore result;
switch (OpenExistingWorker(name, out result))
#endif //FEATURE_PAL || FEATURE_NETCORE
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(SR.GetString(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
InternalResources.WinIOError(NativeMethods.ERROR_PATH_NOT_FOUND, string.Empty);
return result; //never executes
default:
return result;
}
}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
public static bool TryOpenExisting(string name, out Semaphore result)
{
#if !FEATURE_PAL && !FEATURE_NETCORE
return OpenExistingWorker(name, SemaphoreRights.Modify | SemaphoreRights.Synchronize, out result) == OpenExistingResult.Success;
#else
return OpenExistingWorker(name, out result) == OpenExistingResult.Success;
#endif
}
#if !FEATURE_PAL && !FEATURE_NETCORE
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static bool TryOpenExisting(string name, SemaphoreRights rights, out Semaphore result)
{
return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
}
#endif
// This exists in WaitHandle, but is oddly ifdefed for some reason...
#if MONO
new
#endif
private enum OpenExistingResult
{
Success,
NameNotFound,
PathNotFound,
NameInvalid
}
#if FEATURE_NETCORE
[SecurityCritical]
#else
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
#endif
private static OpenExistingResult OpenExistingWorker(
string name,
#if !FEATURE_PAL && !FEATURE_NETCORE
SemaphoreRights rights,
#endif
out Semaphore result)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if(name.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidNullEmptyArgument, "name"), "name");
}
if(null != name && MAX_PATH < name.Length)
{
throw new ArgumentException(SR.GetString(SR.Argument_WaitHandleNameTooLong));
}
result = null;
#if MOBILE
throw new NotSupportedException ();
#else
#if MONO
int errorCode;
var myHandle = new SafeWaitHandle (OpenSemaphore_internal (name, rights, out errorCode), true);
#else
//Pass false to OpenSemaphore to prevent inheritedHandles
#if FEATURE_PAL || FEATURE_NETCORE
const int SYNCHRONIZE = 0x00100000;
const int SEMAPHORE_MODIFY_STATE = 0x00000002;
SafeWaitHandle myHandle = SafeNativeMethods.OpenSemaphore(SEMAPHORE_MODIFY_STATE | SYNCHRONIZE, false, name);
#else
SafeWaitHandle myHandle = SafeNativeMethods.OpenSemaphore((int) rights, false, name);
#endif
#endif
if (myHandle.IsInvalid)
{
#if !MONO
int errorCode = Marshal.GetLastWin32Error();
#endif
if (NativeMethods.ERROR_FILE_NOT_FOUND == errorCode || NativeMethods.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (NativeMethods.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if (null != name && 0 != name.Length && NativeMethods.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through NativeMethods Errors
#if MONO
InternalResources.WinIOError(errorCode, "");
#else
InternalResources.WinIOError();
#endif
}
result = new Semaphore(myHandle);
return OpenExistingResult.Success;
#endif
}
// increase the count on a semaphore, returns previous count
#if !FEATURE_NETCORE
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[PrePrepareMethod]
#endif
public int Release()
{
return Release(1);
}
// increase the count on a semaphore, returns previous count
#if FEATURE_NETCORE
[SecuritySafeCritical]
#else
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#endif
public int Release(int releaseCount)
{
if (releaseCount < 1)
{
throw new ArgumentOutOfRangeException("releaseCount", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNumRequired));
}
int previousCount;
//If ReleaseSempahore returns false when the specified value would cause
// the semaphore's count to exceed the maximum count set when Semaphore was created
//Non-Zero return
#if MONO
if (!ReleaseSemaphore_internal(SafeWaitHandle.DangerousGetHandle(), releaseCount, out previousCount))
#else
if (!SafeNativeMethods.ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount))
#endif
{
throw new SemaphoreFullException();
}
return previousCount;
}
#if !FEATURE_PAL && !FEATURE_NETCORE
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
public SemaphoreSecurity GetAccessControl() {
return new SemaphoreSecurity(SafeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public void SetAccessControl(SemaphoreSecurity semaphoreSecurity) {
if (semaphoreSecurity == null)
throw new ArgumentNullException("semaphoreSecurity");
semaphoreSecurity.Persist(SafeWaitHandle);
}
#endif
#if MONO
internal unsafe static IntPtr CreateSemaphore_internal (int initialCount, int maximumCount,
string name, out int errorCode)
{
// FIXME Check for embedded nuls in name.
fixed (char *fixed_name = name)
return CreateSemaphore_icall (initialCount, maximumCount,
fixed_name, name?.Length ?? 0, out errorCode);
}
private unsafe static IntPtr OpenSemaphore_internal (string name, SemaphoreRights rights, out int errorCode)
{
// FIXME Check for embedded nuls in name.
fixed (char *fixed_name = name)
return OpenSemaphore_icall (fixed_name, name?.Length ?? 0, rights, out errorCode);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern IntPtr CreateSemaphore_icall (
int initialCount, int maximumCount, char *name, int name_length, out int errorCode);
[MethodImplAttribute (MethodImplOptions.InternalCall)]
private unsafe static extern IntPtr OpenSemaphore_icall (char *name, int name_length,
SemaphoreRights rights, out int errorCode);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool ReleaseSemaphore_internal (
IntPtr handle, int releaseCount, out int previousCount);
#endif
}
}