TypeWrapper(Type type) { TypeWrapper baseTypeWrapper = null; if (type.BaseType != null) { baseTypeWrapper = TypeWrapper.Wrap(type.BaseType); } this.type = type; var ctors = type.GetConstructors(); thisPtr = GCHandle.Alloc(this); if (ctors.Length == 0) { constructorValue = JavaScriptValue.CreateFunction(NoConstructorDg, GCHandle.ToIntPtr(thisPtr)); } else if (ctors.Length == 1) { var ctorw = ConstructorWrapper.Wrap(ctors[0]); constructorValue = ctorw.GetJavaScriptValue(); ctorWrapper = ctorw; } else { var os = new OverloadSelector(); foreach (var m in ctors) { os.AppendMethod(m); } constructorValue = os.GetJavaScriptValue(); ctorWrapper = os; } constructorValue.AddRef(); prototypeValue = JavaScriptValue.CreateObject(); prototypeValue.AddRef(); typePtr = GCHandle.Alloc(type); constructorValue.SetIndexedProperty(JavaScriptValue.FromString("_clrtypevalue"), JavaScriptValue.CreateExternalObject(GCHandle.ToIntPtr(typePtr), FreeDg)); // statics ctorStr = type.FullName; constructorValue.SetIndexedProperty(JavaScriptValue.FromString("toString"), JavaScriptValue.CreateFunction(InternalUtil.GetSavedStringDg, GCHandle.ToIntPtr(GCHandle.Alloc(ctorStr)))); AssignMethodProc(constructorValue, type.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static)); AssignFieldProc(constructorValue, type.GetFields(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static)); AssignPropertyProc(constructorValue, type.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static)); // instances prototypeStr = type.FullName + " Instance"; prototypeValue.SetIndexedProperty(JavaScriptValue.FromString("toString"), JavaScriptValue.CreateFunction(InternalUtil.GetSavedStringDg, GCHandle.ToIntPtr(GCHandle.Alloc(prototypeStr)))); AssignMethodProc(prototypeValue, type.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)); AssignFieldProc(prototypeValue, type.GetFields(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)); AssignPropertyProc(prototypeValue, type.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)); constructorValue.SetIndexedProperty(JavaScriptValue.FromString("prototype"), prototypeValue); if (baseTypeWrapper != null) { constructorValue.Prototype = baseTypeWrapper.constructorValue; prototypeValue.Prototype = baseTypeWrapper.prototypeValue; } }
public LuaState() { // Create State L = LuaDLL.luaL_newstate(); // Create LuaInterface library LuaDLL.luaL_openlibs(L); LuaDLL.lua_pushstring(L, "LUAINTERFACE LOADED"); LuaDLL.lua_pushboolean(L, true); LuaDLL.lua_settable(L, (int)LuaIndexes.LUA_REGISTRYINDEX); LuaDLL.lua_newtable(L); LuaDLL.lua_setglobal(L, "luanet"); LuaDLL.lua_pushvalue(L, (int)LuaIndexes.LUA_GLOBALSINDEX); LuaDLL.lua_getglobal(L, "luanet"); LuaDLL.lua_pushstring(L, "getmetatable"); LuaDLL.lua_getglobal(L, "getmetatable"); LuaDLL.lua_settable(L, -3); // Set luanet as global for object translator LuaDLL.lua_replace(L, (int)LuaIndexes.LUA_GLOBALSINDEX); translator = new ObjectTranslator(this, L); LuaDLL.lua_replace(L, (int)LuaIndexes.LUA_GLOBALSINDEX); GCHandle handle = GCHandle.Alloc(translator, GCHandleType.Pinned); IntPtr thisptr = GCHandle.ToIntPtr(handle); LuaDLL.lua_pushlightuserdata(L, thisptr); LuaDLL.lua_setglobal(L, "_translator"); tracebackFunction = new LuaCSFunction(LuaStatic.traceback); // We need to keep this in a managed reference so the delegate doesn't get garbage collected panicCallback = new LuaCSFunction(LuaStatic.panic); LuaDLL.lua_atpanic(L, panicCallback); printFunction = new LuaCSFunction(LuaStatic.print); LuaDLL.lua_pushstdcallcfunction(L, printFunction); LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "print"); loadfileFunction = new LuaCSFunction(LuaStatic.loadfile); LuaDLL.lua_pushstdcallcfunction(L, loadfileFunction); LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "loadfile"); dofileFunction = new LuaCSFunction(LuaStatic.dofile); LuaDLL.lua_pushstdcallcfunction(L, dofileFunction); LuaDLL.lua_setfield(L, LuaIndexes.LUA_GLOBALSINDEX, "dofile"); // Insert our loader FIRST loaderFunction = new LuaCSFunction(LuaStatic.loader); LuaDLL.lua_pushstdcallcfunction(L, loaderFunction); int loaderFunc = LuaDLL.lua_gettop(L); LuaDLL.lua_getfield(L, LuaIndexes.LUA_GLOBALSINDEX, "package"); LuaDLL.lua_getfield(L, -1, "loaders"); int loaderTable = LuaDLL.lua_gettop(L); // Shift table elements right for (int e = LuaDLL.luaL_getn(L, loaderTable) + 1; e > 1; e--) { LuaDLL.lua_rawgeti(L, loaderTable, e - 1); LuaDLL.lua_rawseti(L, loaderTable, e); } LuaDLL.lua_pushvalue(L, loaderFunc); LuaDLL.lua_rawseti(L, loaderTable, 1); LuaDLL.lua_settop(L, 0); DoString(LuaStatic.init_luanet); }
public AudioFrame(IntPtr other) { objPtr = VidyoAudioFrameConstructCopyNative(other); VidyoAudioFrameSetUserDataNative(objPtr, GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak))); }
static void AddTimeout(int priority, uint interval, Func <bool> callback) { var handle = GCHandle.Alloc(callback); g_timeout_add_full(priority, interval, s_pinnedHandler, GCHandle.ToIntPtr(handle), IntPtr.Zero); }
public void SetWaitForExecutionHandler(DataObject controlObject, ControlWaitForExecutionHandler handler, object parameter) { ControlHandlerInfo info = GetControlHandlerInfo(controlObject); info.waitForExecHandler = handler; info.waitForExecHandlerParameter = parameter; if (internalControlWaitForExecutionHandlerRef == null) { internalControlWaitForExecutionHandlerRef = new InternalControlWaitForExecutionHandler(internalControlWaitForExecutionHandler); } IedServer_setWaitForExecutionHandler(self, controlObject.self, internalControlWaitForExecutionHandlerRef, GCHandle.ToIntPtr(info.handle)); }
public static IntPtr CreateMyClass() { var obj = new MyClass(); return(GCHandle.ToIntPtr(GCHandle.Alloc(obj))); }
public bool Apply(ApplyCallback callback, object info = null) { if (callback == null) { throw new ArgumentNullException(nameof(callback)); } BlockLiteral block_handler = new BlockLiteral(); block_handler.SetupBlockUnsafe(applyblock_handler, callback); var gc_handle = info == null ? default(GCHandle) : GCHandle.Alloc(info); try { return(CGPDFArrayApplyBlock(handle, ref block_handler, info == null ? IntPtr.Zero : GCHandle.ToIntPtr(gc_handle))); } finally { block_handler.CleanupBlock(); if (info != null) { gc_handle.Free(); } } }
public AudioUnitStatus AddRenderNotify(RenderDelegate callback) { if (callback == null) { throw new ArgumentException("Callback can not be null"); } AudioUnitStatus error = AudioUnitStatus.OK; if (graphUserCallbacks.Count == 0) { error = (AudioUnitStatus)AUGraphAddRenderNotify(handle, renderCallback, GCHandle.ToIntPtr(gcHandle)); } if (error == AudioUnitStatus.OK) { graphUserCallbacks.Add(callback); } return(error); }
public AudioUnitStatus RemoveRenderNotify(RenderDelegate callback) { if (callback == null) { throw new ArgumentException("Callback can not be null"); } if (!graphUserCallbacks.Contains(callback)) { throw new ArgumentException("Cannot unregister a callback that has not been registered"); } AudioUnitStatus error = AudioUnitStatus.OK; if (graphUserCallbacks.Count == 0) { error = (AudioUnitStatus)AUGraphRemoveRenderNotify(handle, renderCallback, GCHandle.ToIntPtr(gcHandle)); } graphUserCallbacks.Remove(callback); // Remove from list even if there is an error return(error); }
public static long Alloc(object real) { GCHandle handle = GCHandle.Alloc(real); return(GCHandle.ToIntPtr(handle).ToInt64()); }
/// <summary> /// Allocate the object into unmanaged memory and /// returns the IntPtr object. /// </summary> /// <param name="obj">Object to allocate.</param> /// <returns>An IntPtr object representing a GChandle object.</returns> public static IntPtr ToHandlePtr(this object obj) { return(GCHandle.ToIntPtr(GCHandle.Alloc(obj))); }
public IntPtr ToIntPtr() { return(GCHandle.ToIntPtr(_operationHandle)); }
public SafeGCHandle(object target, GCHandleType type) : base(IntPtr.Zero, true) { SetHandle(GCHandle.ToIntPtr(GCHandle.Alloc(target, type))); }
public RemoteCamera(IntPtr other) { objPtr = VidyoRemoteCameraConstructCopyNative(other); VidyoRemoteCameraSetUserDataNative(objPtr, GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak))); }
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) { SafeSslHandle context = null; // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest // mutually supported version and can thus handle any of the set protocols, and we then use // SetProtocolOptions to ensure we only allow the ones requested. using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } // TLS 1.3 uses different ciphersuite restrictions than previous versions. // It has no equivalent to a NoEncryption option. if (policy == EncryptionPolicy.NoEncryption) { if (protocols == SslProtocols.None) { protocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; } else { protocols &= ~SslProtocols.Tls13; if (protocols == SslProtocols.None) { throw new SslException( SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } } } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just // create the handle, it's rooted by the using, no one else has a reference to it, etc. Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet // shutdown (we aren't negotiating for session close to enable later session // restoration). // // If you find yourself wanting to remove this line to enable bidirectional // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html Ssl.SslCtxSetQuietShutdown(innerContext); if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { Crypto.ErrClearError(); throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } bool hasCertificateAndKey = certHandle != null && !certHandle.IsInvalid && certKeyHandle != null && !certKeyHandle.IsInvalid; if (hasCertificateAndKey) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) { Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); } GCHandle alpnHandle = default; try { if (sslAuthenticationOptions.ApplicationProtocols != null) { if (sslAuthenticationOptions.IsServer) { alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols); Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle)); } else { if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) { throw CreateSslException(SR.net_alpn_config_failed); } } } context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } if (!sslAuthenticationOptions.IsServer) { // The IdnMapping converts unicode input into the IDNA punycode sequence. string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost); // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors. if (!Ssl.SslSetTlsExtHostName(context, punyCode)) { Crypto.ErrClearError(); } } if (hasCertificateAndKey) { bool hasCertReference = false; try { certHandle.DangerousAddRef(ref hasCertReference); using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) { using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false)) { if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) { throw CreateSslException(SR.net_ssl_use_cert_failed); } } } } finally { if (hasCertReference) { certHandle.DangerousRelease(); } } } context.AlpnHandle = alpnHandle; } catch { if (alpnHandle.IsAllocated) { alpnHandle.Free(); } throw; } } return(context); }
public static void Initialize(ref IntPtr data, IntPtr rm) { data = GCHandle.ToIntPtr(GCHandle.Alloc(new Measure(rm))); Measure measure = (Measure)data; }
internal ZipArchive(Stream stream, IPlatformOptions options, OpenFlags flags = OpenFlags.RDOnly) { if (options == null) { throw new ArgumentNullException(nameof(options)); } Options = options; Native.zip_error_t errorp; var streamHandle = GCHandle.Alloc(stream, GCHandleType.Normal); IntPtr h = GCHandle.ToIntPtr(streamHandle); IntPtr source = Native.zip_source_function_create(callback, h, out errorp); archive = Native.zip_open_from_source(source, flags, out errorp); if (archive == IntPtr.Zero) { // error; string message = null; var error = (ErrorCode)errorp.zip_err; switch (error) { case ErrorCode.Exists: message = $"The file already exists"; break; case ErrorCode.Incons: message = $"The stream failed consistency checks"; break; case ErrorCode.Memory: message = "libzip returned out of memory error"; break; case ErrorCode.NoEnt: message = $"Stream does not exist and file creation wasn't requested"; break; case ErrorCode.NoZip: message = $"Stream is not a ZIP archive"; break; case ErrorCode.Open: message = $"Stream could not be opened"; break; case ErrorCode.Read: message = $"Error occured while reading the Stream"; break; case ErrorCode.Seek: message = $"Stream does not support seeking"; break; case ErrorCode.OK: break; default: message = $"Unexpected libzip error: {error}"; break; } if (!String.IsNullOrEmpty(message)) { throw new ZipIOException(message, error, Utilities.Errno); } } }
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption) { Debug.Assert(clientCertOption == ClientCertificateOption.Automatic || clientCertOption == ClientCertificateOption.Manual); // Create a client certificate provider if client certs may be used. X509Certificate2Collection clientCertificates = easy._handler._clientCertificates; ClientCertificateProvider certProvider = clientCertOption == ClientCertificateOption.Automatic ? new ClientCertificateProvider(null) : // automatic clientCertificates?.Count > 0 ? new ClientCertificateProvider(clientCertificates) : // manual with certs null; // manual without certs IntPtr userPointer = IntPtr.Zero; if (certProvider != null) { // The client cert provider needs to be passed through to the callback, and thus // we create a GCHandle to keep it rooted. This handle needs to be cleaned up // when the request has completed, and a simple and pay-for-play way to do that // is by cleaning it up in a continuation off of the request. userPointer = GCHandle.ToIntPtr(certProvider._gcHandle); easy.Task.ContinueWith((_, state) => ((IDisposable)state).Dispose(), certProvider, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } // Register the callback with libcurl. We need to register even if there's no user-provided // server callback and even if there are no client certificates, because we support verifying // server certificates against more than those known to OpenSSL. CURLcode answer = easy.SetSslCtxCallback(s_sslCtxCallback, userPointer); switch (answer) { case CURLcode.CURLE_OK: // We successfully registered. If we'll be invoking a user-provided callback to verify the server // certificate as part of that, disable libcurl's verification of the host name. The user's callback // needs to be given the opportunity to examine the cert, and our logic will determine whether // the host name matches and will inform the callback of that. if (easy._handler.ServerCertificateValidationCallback != null) { easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the peer cert's hostname // We don't change the SSL_VERIFYPEER setting, as setting it to 0 will cause // SSL and libcurl to ignore the result of the server callback. } // The allowed SSL protocols will be set in the configuration callback. break; case CURLcode.CURLE_UNKNOWN_OPTION: // Curl 7.38 and prior case CURLcode.CURLE_NOT_BUILT_IN: // Curl 7.39 and later // It's ok if we failed to register the callback if all of the defaults are in play // with relation to handling of certificates. But if that's not the case, failing to // register the callback will result in those options not being factored in, which is // a significant enough error that we need to fail. EventSourceTrace("CURLOPT_SSL_CTX_FUNCTION not supported: {0}", answer, easy: easy); if (certProvider != null || easy._handler.ServerCertificateValidationCallback != null || easy._handler.CheckCertificateRevocationList) { throw new PlatformNotSupportedException( SR.Format(SR.net_http_unix_invalid_certcallback_option, CurlVersionDescription, CurlSslVersionDescription)); } // Since there won't be a callback to configure the allowed SSL protocols, configure them here. SetSslVersion(easy); break; default: ThrowIfCURLEError(answer); break; } }
public void EnableDeveloperMode(string deviceImagePath, string deviceImageSignaturePath) { if (!File.Exists(deviceImagePath) || !File.Exists(deviceImageSignaturePath)) { throw new FileNotFoundException("The specified device image files do not exist."); } iDeviceHandle deviceHandle = null; LockdownClientHandle lockdownHandle = null; LockdownServiceDescriptorHandle serviceDescriptor = null; MobileImageMounterClientHandle mounterHandle = null; AfcClientHandle afcHandle = null; PlistHandle plistHandle = null; FileStream imageStream = null; // Use upload image for iOS 7 and above, otherwise use AFC DiskImageUploadMode mode = int.Parse(((string)Properties["ProductVersion"]).Split('.')[0]) >= 7 ? DiskImageUploadMode.UploadImage : DiskImageUploadMode.AFC; var idevice = LibiMobileDevice.Instance.iDevice; var lockdown = LibiMobileDevice.Instance.Lockdown; var service = LibiMobileDevice.Instance.Service; var mounter = LibiMobileDevice.Instance.MobileImageMounter; var afc = LibiMobileDevice.Instance.Afc; try { // Get device handle if (idevice.idevice_new(out deviceHandle, UDID) != iDeviceError.Success) { throw new Exception("Unable to open device, is it connected?"); } // Get lockdownd handle if (lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "iFakeLocation") != LockdownError.Success) { throw new Exception("Unable to connect to lockdownd."); } // Start image mounter service if (lockdown.lockdownd_start_service(lockdownHandle, "com.apple.mobile.mobile_image_mounter", out serviceDescriptor) != LockdownError.Success) { throw new Exception("Unable to start the mobile image mounter service."); } // Create mounter instance if (mounter.mobile_image_mounter_new(deviceHandle, serviceDescriptor, out mounterHandle) != MobileImageMounterError.Success) { throw new Exception("Unable to create mobile image mounter instance."); } // Close service descriptor serviceDescriptor.Close(); serviceDescriptor = null; // Start the AFC service if (mode == DiskImageUploadMode.AFC) { if (lockdown.lockdownd_start_service(lockdownHandle, "com.apple.afc", out serviceDescriptor) != LockdownError.Success) { throw new Exception("Unable to start AFC service."); } if (afc.afc_client_new(deviceHandle, serviceDescriptor, out afcHandle) != AfcError.Success) { throw new Exception("Unable to connect to AFC service."); } serviceDescriptor.Close(); serviceDescriptor = null; } // Close lockdown handle lockdownHandle.Close(); lockdownHandle = null; // Check if the developer image has already been mounted const string imageType = "Developer"; if (mounter.mobile_image_mounter_lookup_image(mounterHandle, imageType, out plistHandle) == MobileImageMounterError.Success) { var results = PlistReader.ReadPlistDictFromNode(plistHandle, new[] { "ImagePresent", "ImageSignature" }); // Some iOS use ImagePresent to verify presence, while others use ImageSignature instead if ((results.ContainsKey("ImagePresent") && results["ImagePresent"] is bool && (bool)results["ImagePresent"]) || results.ContainsKey("ImageSignature")) { return; } } plistHandle.Close(); plistHandle = null; // Configure paths for upload const string PkgPath = "PublicStaging"; const string PathPrefix = "/private/var/mobile/Media"; var targetName = PkgPath + "/staging.dimage"; var mountName = PathPrefix + "/" + targetName; imageStream = new FileStream(deviceImagePath, FileMode.Open, FileAccess.Read, FileShare.Read); var sig = File.ReadAllBytes(deviceImageSignaturePath); switch (mode) { case DiskImageUploadMode.UploadImage: // Create stream for device image and wrap as a pointer for callback var handle = GCHandle.Alloc(imageStream); // Upload the image and then free unmanaged wrapper mounter.mobile_image_mounter_upload_image(mounterHandle, imageType, (uint)imageStream.Length, sig, (ushort)sig.Length, MounterUploadCallback, GCHandle.ToIntPtr(handle)); handle.Free(); break; case DiskImageUploadMode.AFC: // Create directory for package ReadOnlyCollection <string> strs; if (afc.afc_get_file_info(afcHandle, PkgPath, out strs) != AfcError.Success || afc.afc_make_directory(afcHandle, PkgPath) != AfcError.Success) { throw new Exception("Unable to create directory '" + PkgPath + "' on the device."); } // Create the target file ulong af = 0; if (afc.afc_file_open(afcHandle, targetName, AfcFileMode.FopenWronly, ref af) != AfcError.Success) { throw new Exception("Unable to create file '" + targetName + "'."); } // Read the file in chunks and write via AFC uint amount = 0; byte[] buf = new byte[8192]; do { amount = (uint)imageStream.Read(buf, 0, buf.Length); if (amount > 0) { uint written = 0, total = 0; while (total < amount) { // Write and ensure that it succeeded if (afc.afc_file_write(afcHandle, af, buf, amount, ref written) != AfcError.Success) { afc.afc_file_close(afcHandle, af); throw new Exception("An AFC write error occurred."); } total += written; } if (total != amount) { afc.afc_file_close(afcHandle, af); throw new Exception("The developer image was not written completely."); } } } while (amount > 0); afc.afc_file_close(afcHandle, af); break; } // Mount the image if (mounter.mobile_image_mounter_mount_image(mounterHandle, mountName, sig, (ushort)sig.Length, imageType, out plistHandle) != MobileImageMounterError.Success) { throw new Exception("Unable to mount developer image."); } // Parse the plist result var result = PlistReader.ReadPlistDictFromNode(plistHandle); if (!result.ContainsKey("Status") || result["Status"] as string != "Complete") { throw new Exception("Mount failed with status: " + (result.ContainsKey("Status") ? result["Status"] : "N/A") + " and error: " + (result.ContainsKey("Error") ? result["Error"] : "N/A")); } } finally { if (imageStream != null) { imageStream.Close(); } if (plistHandle != null) { plistHandle.Close(); } if (afcHandle != null) { afcHandle.Close(); } if (mounterHandle != null) { mounterHandle.Close(); } if (serviceDescriptor != null) { serviceDescriptor.Close(); } if (lockdownHandle != null) { lockdownHandle.Close(); } if (deviceHandle != null) { deviceHandle.Close(); } } }
internal static void ForwardWindowEvent(XEvent *xevent) { nint userData; GCHandle gcHandle; XlibWindowProvider windowProvider; Dictionary <nuint, XlibWindow>?windows; XlibWindow? window; bool forwardMessage; var dispatchProvider = XlibDispatchProvider.Instance; if ((xevent->type == ClientMessage) && (xevent->xclient.format == 32) && ((xevent->xclient.message_type == dispatchProvider.GetAtom(_TERRAFX_CREATE_WINDOW)) || (xevent->xclient.message_type == dispatchProvider.GetAtom(_TERRAFX_DISPOSE_WINDOW)))) { // We allow the create and dispose message to be forwarded to the Window instance for xevent->xany.window. // This allows some delayed initialization to occur since most of the fields in Window are lazy. userData = Environment.Is64BitProcess ? (xevent->xclient.data.l[1] << 32) | unchecked ((nint)(uint)xevent->xclient.data.l[0]) : xevent->xclient.data.l[0]; // Unlike the WindowProvider GCHandle, the Window GCHandle is short lived and // we want to free it after we add the relevant entries to the window map. gcHandle = GCHandle.FromIntPtr(userData); { window = (XlibWindow)gcHandle.Target !; windowProvider = window.WindowProvider; windows = windowProvider._windows.Value !; } gcHandle.Free(); if (xevent->xclient.message_type == dispatchProvider.GetAtom(_TERRAFX_CREATE_WINDOW)) { if (windows is null) { windows = new Dictionary <nuint, XlibWindow>(capacity: 4); windowProvider._windows.Value = windows; } windows.Add(xevent->xany.window, window); // We then want to ensure the window provider is registered as a property for fast // subsequent lookups. This proocess also allows everything to be lazily initialized. gcHandle = windowProvider.NativeHandle; userData = GCHandle.ToIntPtr(gcHandle); _ = XChangeProperty( xevent->xany.display, xevent->xany.window, dispatchProvider.GetAtom(_TERRAFX_WINDOWPROVIDER), dispatchProvider.GetAtom(_TERRAFX_NATIVE_INT), 8, PropModeReplace, (byte *)&userData, sizeof(nint) ); } else { Assert(AssertionsEnabled && (xevent->xclient.message_type == dispatchProvider.GetAtom(_TERRAFX_DISPOSE_WINDOW))); _ = RemoveWindow(windows, xevent->xany.display, xevent->xany.window, dispatchProvider); } forwardMessage = true; } else { nuint actualType; int actualFormat; nuint itemCount; nuint bytesRemaining; nint *pUserData; // We don't check the result as there are various cases where this might fail // For example, if the property doesn't exist or has already been deleted _ = XGetWindowProperty( xevent->xany.display, xevent->xany.window, dispatchProvider.GetAtom(_TERRAFX_WINDOWPROVIDER), 0, sizeof(nint) / sizeof(int), False, dispatchProvider.GetAtom(_TERRAFX_NATIVE_INT), &actualType, &actualFormat, &itemCount, &bytesRemaining, (byte **)&pUserData ); if ((actualType == dispatchProvider.GetAtom(_TERRAFX_NATIVE_INT)) && (actualFormat == 8) && (itemCount == SizeOf <nuint>()) && (bytesRemaining == 0)) { userData = pUserData[0]; gcHandle = GCHandle.FromIntPtr(userData); windowProvider = (XlibWindowProvider)gcHandle.Target !; windows = windowProvider._windows.Value !; forwardMessage = windows.TryGetValue(xevent->xany.window, out window); } else { windows = null; window = null; forwardMessage = false; } } if (forwardMessage) { AssertNotNull(windows); AssertNotNull(window); window.ProcessWindowEvent(xevent); if (xevent->type == DestroyNotify) { _ = RemoveWindow(windows, xevent->xany.display, xevent->xany.window, dispatchProvider); } } }
void InitializeConnection() { context = SSLCreateContext(IntPtr.Zero, IsServer ? SslProtocolSide.Server : SslProtocolSide.Client, SslConnectionType.Stream); var result = SSLSetIOFuncs(Handle, readFunc, writeFunc); CheckStatusAndThrow(result); result = SSLSetConnection(Handle, GCHandle.ToIntPtr(handle)); CheckStatusAndThrow(result); if ((EnabledProtocols & SSA.SslProtocols.Tls) != 0) { MinProtocol = SslProtocol.Tls_1_0; } else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0) { MinProtocol = SslProtocol.Tls_1_1; } else { MinProtocol = SslProtocol.Tls_1_2; } if ((EnabledProtocols & SSA.SslProtocols.Tls12) != 0) { MaxProtocol = SslProtocol.Tls_1_2; } else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0) { MaxProtocol = SslProtocol.Tls_1_1; } else { MaxProtocol = SslProtocol.Tls_1_0; } #if APPLE_TLS_DEBUG foreach (var c in GetSupportedCiphers()) { Debug(" {0} SslCipherSuite.{1} {2:x} {3}", IsServer ? "Server" : "Client", c, (int)c, (CipherSuiteCode)c); } #endif if (Settings != null && Settings.EnabledCiphers != null) { SslCipherSuite [] ciphers = new SslCipherSuite [Settings.EnabledCiphers.Length]; for (int i = 0; i < Settings.EnabledCiphers.Length; ++i) { ciphers [i] = (SslCipherSuite)Settings.EnabledCiphers[i]; } SetEnabledCiphers(ciphers); } if (AskForClientCertificate) { SetClientSideAuthenticate(SslAuthenticate.Try); } IPAddress address; if (!IsServer && !string.IsNullOrEmpty(TargetHost) && !IPAddress.TryParse(TargetHost, out address)) { PeerDomainName = ServerName; } }
private void getFieldValue() { string value = ""; int moduleid = (int)ReadDword(); int fielddef = (int)ReadDword(); IntPtr instanceptr = (IntPtr)ReadQword(); object instance = null; GCHandle instanceGCH; instanceGCH = GCHandle.Alloc(null); try { if (instanceptr != IntPtr.Zero) { Marshal.WriteIntPtr((IntPtr)instanceGCH, instanceptr); instance = instanceGCH.Target; } if ((moduleid >= 0) && (moduleid < ModuleList.Count)) { Module m = ModuleList[moduleid]; FieldInfo mb = m.ResolveField(fielddef); if (mb != null) { object o = mb.GetValue(instance); if (o != null) { Type ot = o.GetType(); if ((ot.IsPrimitive) || (Type.GetTypeCode(ot) == TypeCode.String)) { value = o.ToString(); } else { value = o.GetType().Name; GCHandle g = GCHandle.Alloc(o); IntPtr addr = GCHandle.ToIntPtr(g); IntPtr real = Marshal.ReadIntPtr(addr); value = o.GetType().Name + " : " + real.ToString("X8"); g.Free(); System.GC.Collect(); //without this you can see the process memory grow a lot } } else { value = "null"; } } } } catch { } finally { WriteUTF8String(value); if (instanceptr != IntPtr.Zero) { instance = null; try { Marshal.WriteIntPtr((IntPtr)instanceGCH, IntPtr.Zero); instanceGCH.Free(); } catch { } } } }
public void SetCheckHandler(DataObject controlObject, CheckHandler handler, object parameter) { ControlHandlerInfo info = GetControlHandlerInfo(controlObject); info.checkHandler = handler; info.checkHandlerParameter = parameter; if (internalControlPerformCheckHandlerRef == null) { internalControlPerformCheckHandlerRef = new InternalControlPerformCheckHandler(internalCheckHandler); } IedServer_setPerformCheckHandler(self, controlObject.self, internalControlPerformCheckHandlerRef, GCHandle.ToIntPtr(info.handle)); }
private void invokeMethod() { int i; int moduleid = (int)ReadDword(); int methoddef = (int)ReadDword(); GCHandle instancehandle = GCHandle.FromIntPtr((IntPtr)ReadQword()); //it's a gcobject object instance = instancehandle.Target; int paramcount = (int)ReadByte(); object[] parameters = new object[paramcount]; for (i = 0; i < paramcount; i++) { byte[] v; object param = null; byte type = (byte)ReadByte(); switch ((TypeCode)type) { case TypeCode.Boolean: param = ReadByte() != 0; break; case TypeCode.Char: v = new byte[2]; s.Read(v, 0, 2); param = BitConverter.ToChar(v, 0); break; case TypeCode.SByte: param = (sbyte)ReadByte(); break; case TypeCode.Byte: param = ReadByte(); break; case TypeCode.Int16: param = (Int16)ReadWord(); break; case TypeCode.UInt16: param = ReadWord(); break; case TypeCode.Int32: param = (Int32)ReadDword(); break; case TypeCode.UInt32: param = ReadDword(); break; case TypeCode.Int64: param = (Int64)ReadQword(); break; case TypeCode.UInt64: param = ReadQword(); break; case TypeCode.Single: v = new byte[4]; s.Read(v, 0, 4); param = BitConverter.ToSingle(v, 0); break; case TypeCode.Double: v = new byte[8]; s.Read(v, 0, 8); param = BitConverter.ToDouble(v, 0); break; case TypeCode.Decimal: v = new byte[8]; s.Read(v, 0, 8); param = (decimal)BitConverter.ToDouble(v, 0); //convert the double to decimal break; /* * v = new byte[16]; * s.Read(v, 0, 16); * { * int[] bits = new int[4]; * bits[0]=BitConverter.ToInt32(v, 0); * bits[1]=BitConverter.ToInt32(v, 4); * bits[2]=BitConverter.ToInt32(v, 8); * bits[3]=BitConverter.ToInt32(v, 12); * * param = new decimal(bits); * } * */ case TypeCode.DateTime: param = DateTime.FromFileTime((long)ReadQword()); break; case TypeCode.String: param = ReadUTF8String(); break; case TypeCode.Object: default: //handle as a wrapped gc handle { IntPtr val; v = new byte[8]; s.Read(v, 0, 8); if (IntPtr.Size == 4) { val = (IntPtr)BitConverter.ToInt32(v, 0); } else { val = (IntPtr)BitConverter.ToInt64(v, 0); } if (val == IntPtr.Zero) { param = null; } else { GCHandle h = GCHandle.FromIntPtr(val); param = h.Target; } break; } } parameters[i] = param; } if ((moduleid >= 0) && (moduleid < ModuleList.Count)) { byte[] bytes; Module m = ModuleList[moduleid]; MethodBase mb = m.ResolveMethod(methoddef); if (mb != null) { object result = mb.Invoke(instance, parameters); if (result == null) { WriteByte((byte)TypeCode.Empty); } else { Type rtype = result.GetType(); TypeCode tc = Type.GetTypeCode(rtype); WriteByte((byte)tc); switch (tc) { case TypeCode.Boolean: if ((Boolean)result) { WriteByte(1); } else { WriteByte(0); } break; case TypeCode.Char: bytes = BitConverter.GetBytes((Char)result); s.Write(bytes, 0, 2); break; case TypeCode.SByte: case TypeCode.Byte: WriteByte((byte)result); break; case TypeCode.Int16: case TypeCode.UInt16: WriteWord((UInt16)result); break; case TypeCode.Int32: case TypeCode.UInt32: WriteDword((UInt32)result); break; case TypeCode.Int64: case TypeCode.UInt64: WriteQword((UInt64)result); break; case TypeCode.Single: bytes = BitConverter.GetBytes((Single)result); s.Write(bytes, 0, 4); break; case TypeCode.Double: bytes = BitConverter.GetBytes((Double)result); s.Write(bytes, 0, 8); break; case TypeCode.Decimal: Double tempdouble = (Double)(Decimal)result; bytes = BitConverter.GetBytes(tempdouble); s.Write(bytes, 0, 8); break; case TypeCode.DateTime: //conver the time to filetime WriteQword((UInt64)((DateTime)result).ToFileTime()); break; case TypeCode.String: //assuming utf8 string WriteUTF8String((string)result); break; case TypeCode.Object: default: //return a gchandle WriteQword((UInt64)GCHandle.ToIntPtr(GCHandle.Alloc(result))); break; } } } else { WriteByte(255); WriteUTF8String("Invalid method"); } } }
/// <summary>Removes a signal-triggered callback from an object. /// This function removes a callback, previously attached to the emission of a signal, from the object obj. The parameters emission, source and func must match exactly those passed to a previous call to <see cref="Efl.Layout.ISignal.AddSignalCallback"/>. /// /// See <see cref="Efl.Layout.ISignal.AddSignalCallback"/>. /// (Since EFL 1.22)</summary> /// <param name="emission">The signal's "emission" string</param> /// <param name="source">The signal's "source" string</param> /// <param name="func">The callback function to be executed when the signal is emitted.</param> /// <returns><c>true</c> in case of success, <c>false</c> in case of error.</returns> public bool DelSignalCallback(System.String emission, System.String source, EflLayoutSignalCb func) { GCHandle func_handle = GCHandle.Alloc(func); var _ret_var = Efl.Layout.ISignalConcrete.NativeMethods.efl_layout_signal_callback_del_ptr.Value.Delegate(this.NativeHandle,emission, source, GCHandle.ToIntPtr(func_handle), EflLayoutSignalCbWrapper.Cb, Efl.Eo.Globals.free_gchandle); Eina.Error.RaiseIfUnhandledException(); return _ret_var; }
private void ServiceMain(int argc, string[] argv) { GCHandle = GCHandle.Alloc(this); DispatcherHandle = RegisterServiceCtrlHandlerEx(ServiceName, new ServiceHandlerEx(ServiceHandler), GCHandle.ToIntPtr(GCHandle)); if (DispatcherHandle == IntPtr.Zero || DispatcherHandle == new IntPtr(-1)) { Logger.Log(LogLevel.Error, "Invalid handle received from RegisterServiceCtrlHandlerEx"); return; } else { Logger.Log(LogLevel.Debug, "RegisterServiceCtrlHandlerEx returned handle {0}", DispatcherHandle.ToString()); } Logger.SetLogger(new NtEventLogger(), LogLevel.Info); int status = OnControl(() => this.OnStart(argv), ServiceState.StartPending, ServiceState.Running); if (status != 0) { SetServiceStatus(ServiceState.Stopped, win32ExitCode: status); } }
public VTStatus ForEach(Func <CMSampleBuffer, VTStatus> callback, CMTimeRange?range = null) { callbackHandle = GCHandle.Alloc(callback); var foreachResult = VTFrameSiloCallFunctionForEachSampleBuffer(handle, range ?? CMTimeRange.Invalid, GCHandle.ToIntPtr(callbackHandle), static_EachSampleBufferCallback); callbackHandle.Free(); return(foreachResult); }
public LocalMonitor(IntPtr other) { objPtr = VidyoLocalMonitorConstructCopyNative(other); VidyoLocalMonitorSetUserDataNative(objPtr, GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak))); }
public LocalWindowShare(IntPtr other) { objPtr = VidyoLocalWindowShareConstructCopyNative(other); VidyoLocalWindowShareSetUserDataNative(objPtr, GCHandle.ToIntPtr(GCHandle.Alloc(this, GCHandleType.Weak))); }
void AssignPropertyProc(JavaScriptValue setTo, PropertyInfo[] props) { var getpropid = JavaScriptPropertyId.FromString("get"); var setpropid = JavaScriptPropertyId.FromString("set"); foreach (var info in props) { if (info.IsSpecialName) { continue; } var desc = JavaScriptValue.CreateObject(); var id = JavaScriptPropertyId.FromString(info.Name); var proxy = new PropertyProxy(info); desc.SetProperty(getpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertyGetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); desc.SetProperty(setpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertySetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); setTo.DefineProperty(id, desc); propertyWrappers.Add(proxy); } }