private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity,
            out string mapName, out SafeMemoryMappedFileHandle.FileStreamSource fileStreamSource)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            mapName = "/" + MemoryMapObjectFilePrefix + Guid.NewGuid().ToString("N");
            fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.ManufacturedSharedMemory;

            // Determine the flags to use when creating the shared memory object
            Interop.libc.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.libc.OpenFlags.O_RDWR :
                Interop.libc.OpenFlags.O_RDONLY;
            flags |= Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.libc.Permissions perms = default(Interop.libc.Permissions);
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.libc.Permissions.S_IRUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.libc.Permissions.S_IWUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.libc.Permissions.S_IXUSR;

            // Create the shared memory object. Then enlarge it to the requested capacity.
            int fd;
            Interop.CheckIo(fd = Interop.libc.shm_open(mapName, flags, (int)perms), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);

            // Wrap the handle in a stream and return it.
            var fs = new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            fs.SetLength(capacity);
            return fs;
        }
Beispiel #2
0
        // Translates the relevant icmpsendecho codes to a IPStatus code.
        private IPStatus GetIPStatus(Interop.IpHlpApi.IcmpV4Type type, Interop.IpHlpApi.IcmpV4Code code)
        {
            switch (type)
            {
                case Interop.IpHlpApi.IcmpV4Type.ICMP4_ECHO_REPLY:
                    return IPStatus.Success;
                case Interop.IpHlpApi.IcmpV4Type.ICMP4_SOURCE_QUENCH:
                    return IPStatus.SourceQuench;
                case Interop.IpHlpApi.IcmpV4Type.ICMP4_PARAM_PROB:
                    return IPStatus.ParameterProblem;
                case Interop.IpHlpApi.IcmpV4Type.ICMP4_TIME_EXCEEDED:
                    return IPStatus.TtlExpired;
                case Interop.IpHlpApi.IcmpV4Type.ICMP4_DST_UNREACH:
                    {
                        switch (code)
                        {
                            case Interop.IpHlpApi.IcmpV4Code.ICMP4_UNREACH_NET:
                                return IPStatus.DestinationNetworkUnreachable;
                            case Interop.IpHlpApi.IcmpV4Code.ICMP4_UNREACH_HOST:
                                return IPStatus.DestinationHostUnreachable;
                            case Interop.IpHlpApi.IcmpV4Code.ICMP4_UNREACH_PROTOCOL:
                                return IPStatus.DestinationProtocolUnreachable;
                            case Interop.IpHlpApi.IcmpV4Code.ICMP4_UNREACH_PORT:
                                return IPStatus.DestinationPortUnreachable;
                            case Interop.IpHlpApi.IcmpV4Code.ICMP4_UNREACH_FRAG_NEEDED:
                                return IPStatus.PacketTooBig;
                            default:
                                return IPStatus.DestinationUnreachable;
                        }
                    }
            }

            return IPStatus.Unknown;
        }
Beispiel #3
0
        public TypeSymbol Parse(Interop.IMetadataImport mdImport, IntPtr signatureBytes, int signatureLength, out bool isIndexer) {
            _mdImport = mdImport;
            _signatureBytes = signatureBytes;
            _signatureLength = signatureLength;
            _signatureIndex = 0;

            isIndexer = false;

            byte signatureMarker = Read();
            byte typeMarker = (byte)(signatureMarker & 0xF);
            switch (typeMarker) {
                case Interop.SIG_FIELD:
                    return ParseField();
                case Interop.SIG_PROPERTY:
                    return ParseProperty(out isIndexer);
                case Interop.SIG_METHOD_DEFAULT:
                case Interop.SIG_METHOD_C:
                case Interop.SIG_METHOD_THISCALL:
                case Interop.SIG_METHOD_VARARG:
                case Interop.SIG_METHOD_STDCALL:
                case Interop.SIG_METHOD_FASTCALL:
                    bool isGeneric = ((signatureMarker & Interop.SIG_GENERIC) != 0);
                    return ParseMethod(isGeneric);
                default:
                    // TODO: Error
                    Debug.Fail("Unexpected signature type");
                    return null;
            }
        }
 protected unsafe void ProcessIpv6Address(Interop.Sys.IpAddressInfo* addressInfo, uint scopeId)
 {
     IPAddress address = IPAddressUtil.GetIPAddressFromNativeInfo(addressInfo);
     address.ScopeId = scopeId;
     AddAddress(address);
     _ipv6ScopeId = scopeId;
 }
Beispiel #5
0
        /// <summary>Opens the specified file with the requested flags and mode.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="flags">The flags with which to open the file.</param>
        /// <param name="mode">The mode for opening the file.</param>
        /// <returns>A SafeFileHandle for the opened file.</returns>
        internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
        {
            Debug.Assert(path != null);

            // If we fail to open the file due to a path not existing, we need to know whether to blame
            // the file itself or its directory.  If we're creating the file, then we blame the directory,
            // otherwise we blame the file.
            bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0;

            // Open the file. 
            SafeFileHandle handle = Interop.CheckIo(
                Interop.Sys.Open(path, flags, mode),
                path, 
                isDirectory: enoentDueToDirectory,
                errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e);

            // Make sure it's not a directory; we do this after opening it once we have a file descriptor 
            // to avoid race conditions.
            Interop.Sys.FileStatus status;
            if (Interop.Sys.FStat(handle, out status) != 0)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), path);
            }
            if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true);
            }

            return handle;
        }
Beispiel #6
0
 public ModuleDescriptionItem(Interop.Core.ModuleDescription @struct)
 {
     Name = @struct.Name;
     ShortName = @struct.ShortName;
     LongName = @struct.LongName;
     Description = @struct.Help;
 }
        private static FileStream CreateSharedBackingObject(Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            Directory.CreateDirectory(s_tempMapsDirectory);
            string path = Path.Combine(s_tempMapsDirectory, Guid.NewGuid().ToString("N"));
            
            FileAccess access =
                (protections & (Interop.libc.MemoryMappedProtections.PROT_READ | Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
                (protections & (Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
                FileAccess.Read;

            // Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
            // Then enlarge it to the requested capacity.
            const int DefaultBufferSize = 0x1000;
            var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
            try
            {
                Interop.CheckIo(Interop.Sys.Unlink(path));
                fs.SetLength(capacity);
            }
            catch
            {
                fs.Dispose();
                throw;
            }
            return fs;
        }
 protected unsafe void ProcessIpv4Address(Interop.Sys.IpAddressInfo* addressInfo, Interop.Sys.IpAddressInfo* netMask)
 {
     IPAddress ipAddress = IPAddressUtil.GetIPAddressFromNativeInfo(addressInfo);
     IPAddress netMaskAddress = IPAddressUtil.GetIPAddressFromNativeInfo(netMask);
     AddAddress(ipAddress);
     _netMasks[ipAddress] = netMaskAddress;
 }
 public bool TryRegister(int fileDescriptor, SocketAsyncEvents current, SocketAsyncEvents events, GCHandle handle, out Interop.Error error)
 {
     if (current == events)
     {
         error = Interop.Error.SUCCESS;
         return true;
     }
     return _backend.TryRegister(fileDescriptor, current, events, handle, out error);
 }
		public static ICorPublishProcess Wrap(Interop.CorPub.ICorPublishProcess objectToWrap)
		{
		    if (objectToWrap != null)
			{
				return new ICorPublishProcess(objectToWrap);
			}

		    return null;
		}
Beispiel #11
0
        /// <summary>Opens the specified file with the requested flags and mode.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="flags">The flags with which to open the file.</param>
        /// <param name="mode">The mode for opening the file.</param>
        /// <returns>A SafeFileHandle for the opened file.</returns>
        internal static SafePipeHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
        {
            // Ideally this would be a constrained execution region, but we don't have access to PrepareConstrainedRegions.
            SafePipeHandle handle = Interop.CheckIo(Interop.Sys.OpenPipe(path, flags, mode));

            Debug.Assert(!handle.IsInvalid);

            return handle;
        }
Beispiel #12
0
 /// <summary>
 /// Copies the address bytes out of the given native info's buffer and constructs a new IPAddress.
 /// </summary>
 /// <param name="addressInfo">A pointer to a native IpAddressInfo structure.</param>
 /// <returns>A new IPAddress created with the information in the native structure.</returns>
 public static unsafe IPAddress GetIPAddressFromNativeInfo(Interop.Sys.IpAddressInfo* addressInfo)
 {
     byte[] ipBytes = new byte[addressInfo->NumAddressBytes];
     fixed (byte* ipArrayPtr = ipBytes)
     {
         Buffer.MemoryCopy(addressInfo->AddressBytes, ipArrayPtr, ipBytes.Length, ipBytes.Length);
     }
     IPAddress ipAddress = new IPAddress(ipBytes);
     return ipAddress;
 }
Beispiel #13
0
 internal static extern int RegCreateKeyEx(
     SafeRegistryHandle hKey,
     String lpSubKey,
     int Reserved,
     String lpClass,
     int dwOptions,
     int samDesired,
     ref Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs,
     out SafeRegistryHandle hkResult,
     out int lpdwDisposition);
Beispiel #14
0
        public static void Import(string filename, out string name, out Interop.Grid grid)
        {
            name = string.Empty;
            grid = null;

            MyObjectBuilder_Definitions loaded = null;
            if (File.Exists(filename))
            {
                using (FileStream stream = File.Open(filename, FileMode.Open))
                {
                    MyObjectBuilderSerializer.DeserializeXML<MyObjectBuilder_Definitions>(stream, out loaded);
                }
            }

            if (loaded != null)
            {
                foreach (MyObjectBuilder_ShipBlueprintDefinition blueprints in loaded.ShipBlueprints)
                {
                    name = blueprints.Id.SubtypeId;

                    grid = new Grid(loaded)
                    {
                        Name = name,
                        Path = filename,
                    };

                    foreach (MyObjectBuilder_CubeGrid cubegrid in blueprints.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in cubegrid.CubeBlocks)
                        {
                            if (block is MyObjectBuilder_TerminalBlock)
                            {
                                MyObjectBuilder_TerminalBlock terminalblock = (MyObjectBuilder_TerminalBlock)block;

                                long entityid = terminalblock.EntityId;
                                string type = GetBlockType(terminalblock.TypeId.ToString());

                                // TODO Use MyTexts.GetString(MyStringId id) to get default blocks names from MyTexts.resx (for localization)
                                string customname = String.IsNullOrEmpty(terminalblock.CustomName) ? type : terminalblock.CustomName;

                                if (block is MyObjectBuilder_MyProgrammableBlock)
                                {
                                    MyObjectBuilder_MyProgrammableBlock prog = (MyObjectBuilder_MyProgrammableBlock)block;
                                    grid.AddBlock(type, new TerminalBlock() { Name = customname, EntityID = entityid, IsProgram = true, Program = prog.Program });
                                }
                                else
                                {
                                    grid.AddBlock(type, new TerminalBlock() { Name = customname, EntityID = entityid, IsProgram = false });
                                }
                            }
                        }
                    }
                }
            }
        }
        private static bool GssInitSecurityContext(
            ref SafeGssContextHandle context,
            SafeGssCredHandle credential,
            bool isNtlm,
            SafeGssNameHandle targetName,
            Interop.NetSecurityNative.GssFlags inFlags,
            byte[] buffer,
            out byte[] outputBuffer,
            out uint outFlags,
            out int isNtlmUsed)
        {
            outputBuffer = null;
            outFlags = 0;

            // EstablishSecurityContext is called multiple times in a session.
            // In each call, we need to pass the context handle from the previous call.
            // For the first call, the context handle will be null.
            if (context == null)
            {
                context = new SafeGssContextHandle();
            }

            Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
            Interop.NetSecurityNative.Status status;

            try
            {
                Interop.NetSecurityNative.Status minorStatus;
                status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
                                                          credential,
                                                          ref context,
                                                          isNtlm,
                                                          targetName,
                                                          (uint)inFlags,
                                                          buffer,
                                                          (buffer == null) ? 0 : buffer.Length,
                                                          ref token,
                                                          out outFlags,
                                                          out isNtlmUsed);

                if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) && (status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
                {
                    throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
                }

                outputBuffer = token.ToByteArray();
            }
            finally
            {
                token.Dispose();
            }

            return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
        }
        /// <summary>
        /// Get the HashAlgorithmName from the given ALG_ID
        /// </summary>
        internal static HashAlgorithmName? GetHashAlgorithmName(Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM hashId)
        {
            CRYPT_OID_INFO oid = Interop.Crypt32.FindAlgIdOidInfo(hashId);
            if (oid.AlgId == -1)
            {
                // The original hash algorithm may not be found and is optional
                return null;
            }

            return new HashAlgorithmName(oid.Name);
        }
Beispiel #17
0
 [System.Security.SecurityCritical]  // auto-generated
 internal static SafeFileHandle UnsafeCreateFile(
     string lpFileName,
     int dwDesiredAccess,
     FileShare dwShareMode,
     ref Interop.mincore.SECURITY_ATTRIBUTES securityAttrs,
     FileMode dwCreationDisposition,
     int dwFlagsAndAttributes,
     IntPtr hTemplateFile)
 {
     return CreateFile(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
 }
Beispiel #18
0
 public void AddBlock(string type, Interop.TerminalBlock block)
 {
     if (!String.IsNullOrEmpty(type))
     {
         if (!_Blocks.ContainsKey(type))
         {
             _Blocks.Add(type, new List<TerminalBlock>());
         }
         _Blocks[type].Add(block);
     }
 }
        internal SystemIPv4InterfaceProperties(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses)
        {
            _index = ipAdapterAddresses.index;
            _routingEnabled = fixedInfo.enableRouting;
            _dhcpEnabled = ((ipAdapterAddresses.flags & Interop.IpHlpApi.AdapterFlags.DhcpEnabled) != 0);
            _haveWins = (ipAdapterAddresses.firstWinsServerAddress != IntPtr.Zero);

            _mtu = ipAdapterAddresses.mtu;

            GetPerAdapterInfo(ipAdapterAddresses.index);
        }
Beispiel #20
0
 public void Send(Interop.Crystal.CrystalPacket packet)
 {
     try
     {
         Utilities.Logger.Debug("Send packet @'" + packet.ID.ToString() + "'@ to server");
         this.Socket.Send(packet.GetBytes);
     }
     catch (Exception e)
     {
         Utilities.Logger.Error("Can't send packet to server : " + e.ToString());
     }
 }
 internal static extern bool CreateProcessWithLogonW(
     string userName,
     string domain,
     IntPtr password,
     LogonFlags logonFlags,
     [MarshalAs(UnmanagedType.LPTStr)] string appName,
     StringBuilder cmdLine,
     int creationFlags,
     IntPtr environmentBlock,
     [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory,
     Interop.Kernel32.STARTUPINFO lpStartupInfo,
     Interop.Kernel32.PROCESS_INFORMATION lpProcessInformation);
        // IPV6 version of the Tcp row.
        internal SystemTcpConnectionInformation(Interop.IpHlpApi.MibTcp6RowOwnerPid row)
        {
            _state = row.state;

            // Port is returned in Big-Endian - most significant bit on left.
            // Unfortunately, its done at the word level and not the DWORD level.
            int localPort = row.localPort1 << 8 | row.localPort2;
            int remotePort = ((_state == TcpState.Listen) ? 0 : row.remotePort1 << 8 | row.remotePort2);

            _localEndPoint = new IPEndPoint(new IPAddress(row.localAddr, row.localScopeId), (int)localPort);
            _remoteEndPoint = new IPEndPoint(new IPAddress(row.remoteAddr, row.remoteScopeId), (int)remotePort);
        }
Beispiel #23
0
 internal SourceRange(Interop.SourceRange native) {
     Native = native;
     var start = new SourceLocation(Interop.clang_getRangeStart(Native));
     var end = new SourceLocation(Interop.clang_getRangeEnd(Native));
     if (end < start) {
         Start = end;
         End = start;
     } else {
         Start = start;
         End = end;
     }
 }
        public AppleCCCryptor(
            Interop.AppleCrypto.PAL_SymmetricAlgorithm algorithm,
            CipherMode cipherMode,
            int blockSizeInBytes,
            byte[] key,
            byte[] iv,
            bool encrypting)
            : base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
        {
            _encrypting = encrypting;

            OpenCryptor(algorithm, cipherMode, key);
        }
 public static void Send(Interop.Crystal.CrystalPacket packet)
 {
     lock (Synchronizers)
     {
         try
         {
             Synchronizers.ToList().ForEach(x => x.Value.Send(packet));
         }
         catch (Exception e)
         {
             Utilities.Logger.Error("Can't send packet to all server : " + e.ToString());
         }
     }
 }
Beispiel #26
0
        protected unsafe void ProcessLinkLayerAddress(Interop.Sys.LinkLayerAddressInfo* llAddr)
        {
            byte[] macAddress = new byte[llAddr->NumAddressBytes];
            fixed (byte* macAddressPtr = macAddress)
            {
                Buffer.MemoryCopy(llAddr->AddressBytes, macAddressPtr, llAddr->NumAddressBytes, llAddr->NumAddressBytes);
            }
            PhysicalAddress physicalAddress = new PhysicalAddress(macAddress);

            _index = llAddr->InterfaceIndex;
            _id = _index.ToString();
            _physicalAddress = physicalAddress;
            _networkInterfaceType = (NetworkInterfaceType)llAddr->HardwareType;
        }
Beispiel #27
0
        private static unsafe IPPacketInformation GetIPPacketInformation(Interop.Sys.MessageHeader* messageHeader, bool isIPv4, bool isIPv6)
        {
            if (!isIPv4 && !isIPv6)
            {
                return default(IPPacketInformation);
            }

            Interop.Sys.IPPacketInformation nativePacketInfo;
            if (!Interop.Sys.TryGetIPPacketInformation(messageHeader, isIPv4, &nativePacketInfo))
            {
                return default(IPPacketInformation);
            }

            return new IPPacketInformation(nativePacketInfo.Address.GetIPAddress(), nativePacketInfo.InterfaceIndex);
        }
Beispiel #28
0
        public static CRYPT_OID_INFO FindAlgIdOidInfo(Interop.BCrypt.ECC_CURVE_ALG_ID_ENUM algId)
        {
            int intAlgId = (int)algId;
            IntPtr fullOidInfo = CryptFindOIDInfo(
                CryptOidInfoKeyType.CRYPT_OID_INFO_ALGID_KEY,
                ref intAlgId,
                OidGroup.HashAlgorithm);

            if (fullOidInfo != IntPtr.Zero)
            {
                return Marshal.PtrToStructure<CRYPT_OID_INFO>(fullOidInfo);
            }

            // Otherwise the lookup failed.
            return new CRYPT_OID_INFO() { AlgId = -1 };
        }
Beispiel #29
0
 public Win32FileSystemObject(string fullPath, Interop.mincore.WIN32_FIND_DATA findData, bool asDirectory)
 {
     _asDirectory = asDirectory;
     _fullPath = fullPath;
     // Copy the information to data
     _data.fileAttributes = (int)findData.dwFileAttributes;
     _data.ftCreationTimeLow = findData.ftCreationTime.dwLowDateTime;
     _data.ftCreationTimeHigh = findData.ftCreationTime.dwHighDateTime;
     _data.ftLastAccessTimeLow = findData.ftLastAccessTime.dwLowDateTime;
     _data.ftLastAccessTimeHigh = findData.ftLastAccessTime.dwHighDateTime;
     _data.ftLastWriteTimeLow = findData.ftLastWriteTime.dwLowDateTime;
     _data.ftLastWriteTimeHigh = findData.ftLastWriteTime.dwHighDateTime;
     _data.fileSizeHigh = findData.nFileSizeHigh;
     _data.fileSizeLow = findData.nFileSizeLow;
     _dataInitialized = 0;
 }
        private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");

            // Determine the flags to use when creating the shared memory object
            Interop.Sys.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.Sys.OpenFlags.O_RDWR :
                Interop.Sys.OpenFlags.O_RDONLY;
            flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.Sys.Permissions.S_IRUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.Sys.Permissions.S_IWUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.Sys.Permissions.S_IXUSR;

            // Create the shared memory object.
            int fd;
            Interop.CheckIo(fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);
            try
            {
                // Unlink the shared memory object immediatley so that it'll go away once all handles 
                // to it are closed (as with opened then unlinked files, it'll remain usable via
                // the open handles even though it's unlinked and can't be opened anew via its name).
                Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));

                // Give it the right capacity.  We do this directly with ftruncate rather
                // than via FileStream.SetLength after the FileStream is created because, on some systems,
                // lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
                // causing it to preemptively throw from SetLength.
                Interop.CheckIo(Interop.libc.ftruncate(fd, capacity));

                // Wrap the file descriptor in a stream and return it.
                return new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            }
            catch
            {
                fileHandle.Dispose();
                throw;
            }
        }
Beispiel #31
0
        private static FileStream?CreateSharedBackingObjectUsingMemory(
            Interop.Sys.MemoryMappedProtections protections, long capacity, HandleInheritability inheritability)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");

            // Determine the flags to use when creating the shared memory object
            Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
                                          Interop.Sys.OpenFlags.O_RDWR :
                                          Interop.Sys.OpenFlags.O_RDONLY;
            flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IRUSR;
            }
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IWUSR;
            }
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
            {
                perms |= Interop.Sys.Permissions.S_IXUSR;
            }

            // Create the shared memory object.
            SafeFileHandle fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);

            if (fd.IsInvalid)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.ENOTSUP)
                {
                    // If ShmOpen is not supported, fall back to file backing object.
                    // Note that the System.Native shim will force this failure on platforms where
                    // the result of native shm_open does not work well with our subsequent call
                    // to mmap.
                    return(null);
                }

                throw Interop.GetExceptionForIoErrno(errorInfo);
            }

            try
            {
                // Unlink the shared memory object immediately so that it'll go away once all handles
                // to it are closed (as with opened then unlinked files, it'll remain usable via
                // the open handles even though it's unlinked and can't be opened anew via its name).
                Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));

                // Give it the right capacity.  We do this directly with ftruncate rather
                // than via FileStream.SetLength after the FileStream is created because, on some systems,
                // lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
                // causing it to preemptively throw from SetLength.
                Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));

                // shm_open sets CLOEXEC implicitly.  If the inheritability requested is Inheritable, remove CLOEXEC.
                if (inheritability == HandleInheritability.Inheritable &&
                    Interop.Sys.Fcntl.SetFD(fd, 0) == -1)
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo());
                }

                // Wrap the file descriptor in a stream and return it.
                return(new FileStream(fd, TranslateProtectionsToFileAccess(protections)));
            }
            catch
            {
                fd.Dispose();
                throw;
            }
        }
Beispiel #32
0
 public void Show()
 => Interop.Show(Container);
Beispiel #33
0
 internal static byte StopTls(ConnectionHandle ldapHandle) => Interop.ldap_stop_tls(ldapHandle);
Beispiel #34
0
        public static PopupRoot CreateAndAppendNewPopupRoot(Window parentWindow)
        {
            // Generate a unique identifier for the PopupRoot:
            CurrentPopupRootIndentifier++;
            string uniquePopupRootIdentifier = "INTERNAL_Cshtml5_PopupRoot_" + CurrentPopupRootIndentifier.ToString();

            //--------------------------------------
            // Create a DIV for the PopupRoot in the DOM tree:
            //--------------------------------------

            CSHTML5.Interop.ExecuteJavaScriptAsync(
                @"
var popupRoot = document.createElement('div');
popupRoot.setAttribute('id', $0);
popupRoot.style.position = 'absolute';
popupRoot.style.width = '100%';
popupRoot.style.height = '100%';
popupRoot.style.overflowX = 'hidden';
popupRoot.style.overflowY = 'hidden';
popupRoot.style.pointerEvents = 'none';
$1.appendChild(popupRoot);
", uniquePopupRootIdentifier, parentWindow.INTERNAL_RootDomElement);

            //--------------------------------------
            // Get the PopupRoot DIV:
            //--------------------------------------

            object popupRootDiv;

            if (Interop.IsRunningInTheSimulator)
            {
                popupRootDiv = new INTERNAL_HtmlDomElementReference(uniquePopupRootIdentifier, null);
            }
            else
            {
                popupRootDiv = Interop.ExecuteJavaScriptAsync("document.getElementByIdSafe($0)", uniquePopupRootIdentifier);
            }

            //--------------------------------------
            // Create the C# class that points to the PopupRoot DIV:
            //--------------------------------------

            var popupRoot = new PopupRoot(uniquePopupRootIdentifier, parentWindow);

            popupRoot.INTERNAL_OuterDomElement
                  = popupRoot.INTERNAL_InnerDomElement
                  = popupRootDiv;

            //--------------------------------------
            // Listen to clicks anywhere in the popup (this is used to close other popups that are not supposed to stay open):
            //--------------------------------------

#if MIGRATION
            popupRoot.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(INTERNAL_PopupsManager.OnClickOnPopupOrWindow), true);
#else
            popupRoot.AddHandler(UIElement.PointerPressedEvent, new PointerEventHandler(INTERNAL_PopupsManager.OnClickOnPopupOrWindow), true);
#endif

            //--------------------------------------
            // Remember the PopupRoot for later use:
            //--------------------------------------

            PopupRootIdentifierToInstance.Add(uniquePopupRootIdentifier, popupRoot);

            return(popupRoot);
        }
Beispiel #35
0
        /// <summary>
        /// <p>Instructs the object to produce pixels.</p>
        /// </summary>
        /// <typeparam name="T">Type of a pixel. This parameter must exactly match a pixel like using <see cref="Color"/> for a 32bit RGBA color or <see cref="RawVector4"/> for a 64bits for a RGBA 4 floats color.</typeparam>
        /// <param name="output">The destination array. The size of the array must be sizeof(pixel) * Width * Height</param>
        /// <returns><p>If this method succeeds, it returns <strong><see cref="SharpDX.Result.Ok"/></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result"/></strong> error code.</p></returns>
        /// <remarks>
        /// <p><strong>CopyPixels</strong> is one of the two main image processing routines (the other being <strong>Lock</strong>) triggering the actual processing.  It instructs the object to produce pixels according to its algorithm - this may involve decoding a portion of a JPEG stored on disk, copying a block of memory, or even analytically computing a complex gradient.  The algorithm is completely dependent on the object implementing the interface. </p><p> The caller can restrict the operation to a rectangle of interest (ROI) using the prc parameter.  The ROI sub-rectangle must be fully contained in the bounds of the bitmap.  Specifying a <strong><c>null</c></strong> ROI implies that the whole bitmap should be returned.
        /// </p><p> The caller controls the memory management and must provide an output buffer (<em>pbBuffer</em>) for the results of the copy along with the buffer's bounds (<em>cbBufferSize</em>).  The cbStride parameter defines the count of bytes between two vertically adjacent pixels in the output buffer.  The caller must ensure that there is sufficient buffer to complete the call based on the width, height and pixel format of the bitmap and the sub-rectangle provided to the copy method. </p><p> If the caller needs to perform numerous copies of an expensive <strong><see cref="SharpDX.WIC.BitmapSource"/></strong> such as a JPEG, it is recommended to create an in-memory <strong><see cref="SharpDX.WIC.Bitmap"/></strong> first. </p>Codec Developer Remarks<p> The callee must only write to the first (prc-&gt;Width*bitsperpixel+7)/8 bytes of each line of the output buffer (in this case, a line is a consecutive string of <em>cbStride</em> bytes). </p>
        /// </remarks>
        /// <msdn-id>ee690179</msdn-id>
        /// <unmanaged>HRESULT IWICBitmapSource::CopyPixels([In, Optional] const WICRect* prc,[In] unsigned int cbStride,[In] unsigned int cbBufferSize,[In] void* pbBuffer)</unmanaged>
        /// <unmanaged-short>IWICBitmapSource::CopyPixels</unmanaged-short>
        public unsafe void CopyPixels <T>(T[] output) where T : struct
        {
            var size = Size;

            if ((size.Width * size.Height) != output.Length)
            {
                throw new ArgumentException("output.Length must be equal to Width * Height");
            }

            CopyPixels(IntPtr.Zero, Size.Width * Utilities.SizeOf <T>(), (int)output.Length * Utilities.SizeOf <T>(), (IntPtr)Interop.Fixed(output));
        }
Beispiel #36
0
 // Unix specific implementation of the method that extracts the current entry as a fifo file.
 private void ExtractAsFifo(string destinationFileName)
 {
     Debug.Assert(EntryType is TarEntryType.Fifo);
     Interop.CheckIo(Interop.Sys.MkFifo(destinationFileName, (uint)Mode), destinationFileName);
 }
Beispiel #37
0
        private static void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)
        {
            Exception?firstException = null;

            if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)
            {
                DeleteFile(directory.FullName);
                return;
            }

            if (recursive)
            {
                try
                {
                    foreach (string item in Directory.EnumerateFileSystemEntries(directory.FullName))
                    {
                        if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
                        {
                            try
                            {
                                var childDirectory = new DirectoryInfo(item);
                                if (childDirectory.Exists)
                                {
                                    RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);
                                }
                                else
                                {
                                    DeleteFile(item);
                                }
                            }
                            catch (Exception exc)
                            {
                                if (firstException != null)
                                {
                                    firstException = exc;
                                }
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (firstException != null)
                    {
                        firstException = exc;
                    }
                }

                if (firstException != null)
                {
                    throw firstException;
                }
            }

            if (Interop.Sys.RmDir(directory.FullName) < 0)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                switch (errorInfo.Error)
                {
                case Interop.Error.EACCES:
                case Interop.Error.EPERM:
                case Interop.Error.EROFS:
                case Interop.Error.EISDIR:
                    throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName));     // match Win32 exception

                case Interop.Error.ENOENT:
                    if (!throwOnTopLevelDirectoryNotFound)
                    {
                        return;
                    }
                    goto default;

                default:
                    throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);
                }
            }
        }
Beispiel #38
0
        public static Pipeline CreateGraphicsPipeline(Graphics g, PipelineLayout pl, RenderPass rp, string[] shaderNames, bool depthTest, bool depthWrite, bool instancing, Type instanceInfoType, BlendMode blendMode, PrimitiveType primType, PrimitiveRenderMode pmode, PrimitiveCullMode cmode, float lineWidth, Vector2 viewportPos, Vector2 viewportSize)
        {
            if (instancing && instanceInfoType == null)
            {
                throw new NullReferenceException("Instance info type cannot be null");
            }

            var shaderStageCreateInfos = new PipelineShaderStageCreateInfo[shaderNames.Length];

            for (var i = 0; i < shaderNames.Length; i++)
            {
                var shader     = g.Context.Content.Get <ShaderModule>(shaderNames[i]);
                var shaderName = Path.GetFileNameWithoutExtension(shaderNames[i]);
                switch (Path.GetExtension(shaderName))
                {
                case ".vert":
                    shaderStageCreateInfos[i] = new PipelineShaderStageCreateInfo(ShaderStages.Vertex, shader, "main");
                    break;

                case ".frag":
                    shaderStageCreateInfos[i] = new PipelineShaderStageCreateInfo(ShaderStages.Fragment, shader, "main");
                    break;

                default:
                    throw new NotImplementedException($"Unreognized shader type for file \"{shaderNames[i]}\"");
                }
            }

            var fields = typeof(Vertex).GetFields();
            var offset = 0;
            var loci   = 0;
            List <VertexInputAttributeDescription> vertexAttributes = new List <VertexInputAttributeDescription>(fields.Length);

            for (var i = 0; i < fields.Length; i++)
            {
                var ftype = fields[i].FieldType;
                if (ftype == typeof(Vector3) || ftype == typeof(Angle))
                {
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32SFloat, offset));
                    offset += 12;
                    loci++;
                }
                else if (ftype == typeof(Vector2))
                {
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32SFloat, offset));
                    offset += 8;
                    loci++;
                }
                else if (ftype == typeof(Color4))
                {
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32A32SFloat, offset));
                    offset += 16;
                    loci++;
                }
                else if (ftype == typeof(float))
                {
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32SFloat, offset));
                    offset += 4;
                    loci++;
                }
                else if (ftype == typeof(Matrix4))
                {
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32A32SFloat, offset));
                    loci++;
                    offset += 16;
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32A32SFloat, offset));
                    loci++;
                    offset += 16;
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32A32SFloat, offset));
                    loci++;
                    offset += 16;
                    vertexAttributes.Add(new VertexInputAttributeDescription(loci, 0, Format.R32G32B32A32SFloat, offset));
                    loci++;
                    offset += 16;
                }
                else
                {
                    throw new Exception("Field " + fields[i] + " of vertex struct is an illegal type");
                }
            }
            var vertexFieldsLength = fields.Length;

            if (instancing)
            {
                fields = instanceInfoType.GetFields();
                offset = 0;
                for (var i = 0; i < fields.Length; i++)
                {
                    var ftype = fields[i].FieldType;
                    if (ftype == typeof(Vector3) || ftype == typeof(Angle))
                    {
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32SFloat, offset));
                        loci++;
                        offset += 12;
                    }
                    else if (ftype == typeof(Vector2))
                    {
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32SFloat, offset));
                        loci++;
                        offset += 8;
                    }
                    else if (ftype == typeof(Color4))
                    {
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32A32SFloat, offset));
                        loci++;
                        offset += 16;
                    }
                    else if (ftype == typeof(float))
                    {
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32SFloat, offset));
                        loci++;
                        offset += 4;
                    }
                    else if (ftype == typeof(Matrix4))
                    {
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32A32SFloat, offset));
                        loci++;
                        offset += 16;
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32A32SFloat, offset));
                        loci++;
                        offset += 16;
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32A32SFloat, offset));
                        loci++;
                        offset += 16;
                        vertexAttributes.Add(new VertexInputAttributeDescription(loci, 1, Format.R32G32B32A32SFloat, offset));
                        loci++;
                        offset += 16;
                    }
                    else
                    {
                        throw new Exception("Field " + fields[i] + " of instance info struct is an illegal type");
                    }
                }
            }

            var vertexInputStateCreateInfo = new PipelineVertexInputStateCreateInfo(
                (instancing ? new[]
            {
                new VertexInputBindingDescription(0, Interop.SizeOf <Vertex>(), VertexInputRate.Vertex),
                new VertexInputBindingDescription(1, System.Runtime.InteropServices.Marshal.SizeOf(instanceInfoType), VertexInputRate.Instance)
            } :
                 new[]
            {
                new VertexInputBindingDescription(0, Interop.SizeOf <Vertex>(), VertexInputRate.Vertex)
            }),
                vertexAttributes.ToArray()
                );
            var inputAssemblyStateCreateInfo = new PipelineInputAssemblyStateCreateInfo((PrimitiveTopology)primType);
            var viewportStateCreateInfo      = new PipelineViewportStateCreateInfo(
                new Viewport(viewportPos.X + viewportSize.X, viewportPos.Y + viewportSize.Y, -viewportSize.X, -viewportSize.Y),
                new Rect2D((int)viewportPos.X, (int)viewportPos.Y, (int)viewportSize.X, (int)viewportSize.Y));
            var rasterizationStateCreateInfo = new PipelineRasterizationStateCreateInfo
            {
                PolygonMode = (PolygonMode)pmode,
                CullMode    = (CullModes)cmode,
                FrontFace   = FrontFace.Clockwise,
                LineWidth   = lineWidth
            };
            var multisampleStateCreateInfo = new PipelineMultisampleStateCreateInfo
            {
                RasterizationSamples =
                    g.Samples >= 48 ? SampleCounts.Count64 :
                    g.Samples >= 24 ? SampleCounts.Count32 :
                    g.Samples >= 12 ? SampleCounts.Count16 :
                    g.Samples >= 6 ? SampleCounts.Count8 :
                    g.Samples >= 3 ? SampleCounts.Count4 :
                    g.Samples == 2 ? SampleCounts.Count2 :
                    SampleCounts.Count1,
                MinSampleShading = 1.0f
            };
            var depthStencilCreateInfo = new PipelineDepthStencilStateCreateInfo
            {
                DepthTestEnable  = depthTest,
                DepthWriteEnable = depthWrite,
                DepthCompareOp   = CompareOp.LessOrEqual,
                Back             = new StencilOpState
                {
                    FailOp    = StencilOp.Keep,
                    PassOp    = StencilOp.Keep,
                    CompareOp = CompareOp.Always
                },
                Front = new StencilOpState
                {
                    FailOp    = StencilOp.Keep,
                    PassOp    = StencilOp.Keep,
                    CompareOp = CompareOp.Always
                }
            };
            var colorBlendAttachmentState = new PipelineColorBlendAttachmentState
            {
                SrcColorBlendFactor = BlendMode.GetBlendFactor(blendMode.SrcColorFactor),
                DstColorBlendFactor = BlendMode.GetBlendFactor(blendMode.DstColorFactor),
                ColorBlendOp        = BlendMode.GetBlendOp(blendMode.ColorOp),
                SrcAlphaBlendFactor = BlendMode.GetBlendFactor(blendMode.SrcAlphaFactor),
                DstAlphaBlendFactor = BlendMode.GetBlendFactor(blendMode.DstAlphaFactor),
                AlphaBlendOp        = BlendMode.GetBlendOp(blendMode.AlphaOp),
                ColorWriteMask      = BlendMode.GetColorWriteMask(blendMode.Mask),
                BlendEnable         = true
            };
            var colorBlendStateCreateInfo = new PipelineColorBlendStateCreateInfo(
                new[] { colorBlendAttachmentState });

            var pipelineCreateInfo = new GraphicsPipelineCreateInfo(
                pl, rp, 0,
                shaderStageCreateInfos,
                inputAssemblyStateCreateInfo,
                vertexInputStateCreateInfo,
                rasterizationStateCreateInfo,
                viewportState: viewportStateCreateInfo,
                multisampleState: multisampleStateCreateInfo,
                depthStencilState: depthStencilCreateInfo,
                colorBlendState: colorBlendStateCreateInfo//,
                //dynamicState: new PipelineDynamicStateCreateInfo(DynamicState.Viewport)
                );

            return(g.Context.Device.CreateGraphicsPipeline(pipelineCreateInfo));
        }
Beispiel #39
0
        internal Exports(Module module)
        {
            Interop.wasm_exporttype_vec_t exports;
            Interop.wasm_module_exports(module.Handle, out exports);

            try
            {
                var all       = new List <Export>((int)exports.size);
                var functions = new List <FunctionExport>();
                var globals   = new List <GlobalExport>();
                var tables    = new List <TableExport>();
                var memories  = new List <MemoryExport>();

                for (int i = 0; i < (int)exports.size; ++i)
                {
                    unsafe
                    {
                        var exportType = exports.data[i];
                        var externType = Interop.wasm_exporttype_type(exportType);

                        switch (Interop.wasm_externtype_kind(externType))
                        {
                        case Interop.wasm_externkind_t.WASM_EXTERN_FUNC:
                            var function = new FunctionExport(exportType, externType);
                            functions.Add(function);
                            all.Add(function);
                            break;

                        case Interop.wasm_externkind_t.WASM_EXTERN_GLOBAL:
                            var global = new GlobalExport(exportType, externType);
                            globals.Add(global);
                            all.Add(global);
                            break;

                        case Interop.wasm_externkind_t.WASM_EXTERN_TABLE:
                            var table = new TableExport(exportType, externType);
                            tables.Add(table);
                            all.Add(table);
                            break;

                        case Interop.wasm_externkind_t.WASM_EXTERN_MEMORY:
                            var memory = new MemoryExport(exportType, externType);
                            memories.Add(memory);
                            all.Add(memory);
                            break;

                        default:
                            throw new NotSupportedException("Unsupported export extern type.");
                        }
                    }
                }

                Functions = functions;
                Globals   = globals;
                Tables    = tables;
                Memories  = memories;
                All       = all;
            }
            finally
            {
                Interop.wasm_exporttype_vec_delete(ref exports);
            }
        }
Beispiel #40
0
 void ad_AdClosed(object sender, AdDuplex.InterstitialAdLoadedEventArgs e)
 {
     Interop.InterstitialClose();
 }
 private int InternalBind(NetworkCredential tempCredential, SEC_WINNT_AUTH_IDENTITY_EX cred, BindMethod method)
 => tempCredential == null && AuthType == AuthType.External ? Interop.ldap_bind_s(_ldapHandle, null, null, method) : Interop.ldap_bind_s(_ldapHandle, null, cred, method);
Beispiel #42
0
 public unsafe bool CheckFeatureSupport <T>(Feature feature, ref T featureSupport) where T : struct
 {
     return(CheckFeatureSupport(feature, new IntPtr(Unsafe.AsPointer(ref featureSupport)), Interop.SizeOf <T>()).Success);
 }
Beispiel #43
0
 public IntPtr GetProcAddress(string command)
 {
     return(getProcAddrDel(instance, Interop.GetUTF8(command)));
 }
Beispiel #44
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private unsafe void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != Device.Null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.Description;

            PhysicalDeviceProperties physicalDeviceProperties;

            NativePhysicalDevice.GetProperties(out physicalDeviceProperties);
            ConstantBufferDataPlacementAlignment = (int)physicalDeviceProperties.Limits.MinUniformBufferOffsetAlignment;
            TimestampFrequency = (long)(1.0e9 / physicalDeviceProperties.Limits.TimestampPeriod); // Resolution in nanoseconds

            RequestedProfile = graphicsProfiles.Last();

            var queueProperties = NativePhysicalDevice.QueueFamilyProperties;

            //IsProfilingSupported = queueProperties[0].TimestampValidBits > 0;

            // Command lists are thread-safe and execute deferred
            IsDeferred = true;

            // TODO VULKAN
            // Create Vulkan device based on profile
            uint queuePriorities = 0;
            var  queueCreateInfo = new DeviceQueueCreateInfo
            {
                StructureType    = StructureType.DeviceQueueCreateInfo,
                QueueFamilyIndex = 0,
                QueueCount       = 1,
                QueuePriorities  = new IntPtr(&queuePriorities)
            };

            var enabledFeature = new PhysicalDeviceFeatures
            {
                FillModeNonSolid   = true,
                ShaderClipDistance = true,
                ShaderCullDistance = true,
                SamplerAnisotropy  = true,
                DepthClamp         = true,
            };

            var extensionProperties     = NativePhysicalDevice.GetDeviceExtensionProperties();
            var availableExtensionNames = new List <string>();
            var desiredExtensionNames   = new List <string>();

            for (int index = 0; index < extensionProperties.Length; index++)
            {
                var namePointer = new IntPtr(Interop.Fixed(ref extensionProperties[index].ExtensionName));
                var name        = Marshal.PtrToStringAnsi(namePointer);
                availableExtensionNames.Add(name);
            }

            desiredExtensionNames.Add("VK_KHR_swapchain");
            if (!availableExtensionNames.Contains("VK_KHR_swapchain"))
            {
                throw new InvalidOperationException();
            }

            if (availableExtensionNames.Contains("VK_EXT_debug_marker") && IsDebugMode)
            {
                desiredExtensionNames.Add("VK_EXT_debug_marker");
                IsProfilingSupported = true;
            }

            var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray();

            try
            {
                var deviceCreateInfo = new DeviceCreateInfo
                {
                    StructureType         = StructureType.DeviceCreateInfo,
                    QueueCreateInfoCount  = 1,
                    QueueCreateInfos      = new IntPtr(&queueCreateInfo),
                    EnabledExtensionCount = (uint)enabledExtensionNames.Length,
                    EnabledExtensionNames = enabledExtensionNames.Length > 0 ? new IntPtr(Interop.Fixed(enabledExtensionNames)) : IntPtr.Zero,
                    EnabledFeatures       = new IntPtr(&enabledFeature)
                };

                nativeDevice = NativePhysicalDevice.CreateDevice(ref deviceCreateInfo);
            }
            finally
            {
                foreach (var enabledExtensionName in enabledExtensionNames)
                {
                    Marshal.FreeHGlobal(enabledExtensionName);
                }
            }

            NativeCommandQueue = nativeDevice.GetQueue(0, 0);

            //// Prepare copy command list (start it closed, so that every new use start with a Reset)
            var commandPoolCreateInfo = new CommandPoolCreateInfo
            {
                StructureType    = StructureType.CommandPoolCreateInfo,
                QueueFamilyIndex = 0, //device.NativeCommandQueue.FamilyIndex
                Flags            = CommandPoolCreateFlags.ResetCommandBuffer
            };

            NativeCopyCommandPool = NativeDevice.CreateCommandPool(ref commandPoolCreateInfo);

            var commandBufferAllocationInfo = new CommandBufferAllocateInfo
            {
                StructureType      = StructureType.CommandBufferAllocateInfo,
                Level              = CommandBufferLevel.Primary,
                CommandPool        = NativeCopyCommandPool,
                CommandBufferCount = 1
            };
            CommandBuffer nativeCommandBuffer;

            NativeDevice.AllocateCommandBuffers(ref commandBufferAllocationInfo, &nativeCommandBuffer);
            NativeCopyCommandBuffer = nativeCommandBuffer;

            DescriptorPools = new HeapPool(this);

            nativeResourceCollector       = new NativeResourceCollector(this);
            graphicsResourceLinkCollector = new GraphicsResourceLinkCollector(this);

            EmptyTexelBufferInt   = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_UInt);
            EmptyTexelBufferFloat = Buffer.Typed.New(this, 1, PixelFormat.R32G32B32A32_Float);
            EmptyTexture          = Texture.New2D(this, 1, 1, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.ShaderResource);
        }
Beispiel #45
0
        public unsafe GraphicsAdapterFactoryInstance(bool enableValidation)
        {
            var applicationInfo = new ApplicationInfo
            {
                StructureType = StructureType.ApplicationInfo,
                ApiVersion    = new SharpVulkan.Version(1, 0, 0),
                EngineName    = Marshal.StringToHGlobalAnsi("Xenko"),
                //EngineVersion = new SharpVulkan.Version()
            };

            var desiredLayerNames = new[]
            {
                //"VK_LAYER_LUNARG_standard_validation",
                "VK_LAYER_GOOGLE_threading",
                "VK_LAYER_LUNARG_parameter_validation",
                "VK_LAYER_LUNARG_device_limits",
                "VK_LAYER_LUNARG_object_tracker",
                "VK_LAYER_LUNARG_image",
                "VK_LAYER_LUNARG_core_validation",
                "VK_LAYER_LUNARG_swapchain",
                "VK_LAYER_GOOGLE_unique_objects",
                //"VK_LAYER_LUNARG_api_dump",
                //"VK_LAYER_LUNARG_vktrace"
            };

            IntPtr[] enabledLayerNames = new IntPtr[0];

            if (enableValidation)
            {
                var layers = Vulkan.InstanceLayerProperties;
                var availableLayerNames = new HashSet <string>();

                for (int index = 0; index < layers.Length; index++)
                {
                    var properties  = layers[index];
                    var namePointer = new IntPtr(Interop.Fixed(ref properties.LayerName));
                    var name        = Marshal.PtrToStringAnsi(namePointer);

                    availableLayerNames.Add(name);
                }

                enabledLayerNames = desiredLayerNames
                                    .Where(x => availableLayerNames.Contains(x))
                                    .Select(Marshal.StringToHGlobalAnsi).ToArray();
            }

            var extensionProperties     = Vulkan.GetInstanceExtensionProperties();
            var availableExtensionNames = new List <string>();
            var desiredExtensionNames   = new List <string>();

            for (int index = 0; index < extensionProperties.Length; index++)
            {
                var namePointer = new IntPtr(Interop.Fixed(ref extensionProperties[index].ExtensionName));
                var name        = Marshal.PtrToStringAnsi(namePointer);
                availableExtensionNames.Add(name);
            }

            desiredExtensionNames.Add("VK_KHR_surface");
            if (!availableExtensionNames.Contains("VK_KHR_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_surface is not available");
            }

#if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP
            desiredExtensionNames.Add("VK_KHR_win32_surface");
            if (!availableExtensionNames.Contains("VK_KHR_win32_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_win32_surface is not available");
            }
#elif SILICONSTUDIO_PLATFORM_ANDROID
            desiredExtensionNames.Add("VK_KHR_android_surface");
            if (!availableExtensionNames.Contains("VK_KHR_android_surface"))
            {
                throw new InvalidOperationException("Required extension VK_KHR_android_surface is not available");
            }
#elif SILICONSTUDIO_PLATFORM_LINUX
            if (availableExtensionNames.Contains("VK_KHR_xlib_surface"))
            {
                desiredExtensionNames.Add("VK_KHR_xlib_surface");
                HasXlibSurfaceSupport = true;
            }
            else if (availableExtensionNames.Contains("VK_KHR_xcb_surface"))
            {
                desiredExtensionNames.Add("VK_KHR_xcb_surface");
            }
            else
            {
                throw new InvalidOperationException("None of the supported surface extensions VK_KHR_xcb_surface or VK_KHR_xlib_surface is available");
            }
#endif
            bool enableDebugReport = enableValidation && availableExtensionNames.Contains("VK_EXT_debug_report");
            if (enableDebugReport)
            {
                desiredExtensionNames.Add("VK_EXT_debug_report");
            }

            var enabledExtensionNames = desiredExtensionNames.Select(Marshal.StringToHGlobalAnsi).ToArray();

            var createDebugReportCallbackName = Marshal.StringToHGlobalAnsi("vkCreateDebugReportCallbackEXT");

            try
            {
                fixed(void *enabledExtensionNamesPointer = &enabledExtensionNames[0])
                {
                    var insatanceCreateInfo = new InstanceCreateInfo
                    {
                        StructureType         = StructureType.InstanceCreateInfo,
                        ApplicationInfo       = new IntPtr(&applicationInfo),
                        EnabledLayerCount     = enabledLayerNames != null ? (uint)enabledLayerNames.Length : 0,
                        EnabledLayerNames     = enabledLayerNames?.Length > 0 ? new IntPtr(Interop.Fixed(enabledLayerNames)) : IntPtr.Zero,
                        EnabledExtensionCount = (uint)enabledExtensionNames.Length,
                        EnabledExtensionNames = new IntPtr(enabledExtensionNamesPointer)
                    };

                    NativeInstance = Vulkan.CreateInstance(ref insatanceCreateInfo);
                }

                if (enableDebugReport)
                {
                    var createDebugReportCallback = (CreateDebugReportCallbackDelegate)Marshal.GetDelegateForFunctionPointer(NativeInstance.GetProcAddress((byte *)createDebugReportCallbackName), typeof(CreateDebugReportCallbackDelegate));

                    debugReport = DebugReport;
                    var createInfo = new DebugReportCallbackCreateInfo
                    {
                        StructureType = StructureType.DebugReportCallbackCreateInfo,
                        Flags         = (uint)(DebugReportFlags.Error | DebugReportFlags.Warning /* | DebugReportFlags.PerformanceWarning | DebugReportFlags.Information | DebugReportFlags.Debug*/),
                        Callback      = Marshal.GetFunctionPointerForDelegate(debugReport)
                    };
                    createDebugReportCallback(NativeInstance, ref createInfo, null, out debugReportCallback);
                }

                if (availableExtensionNames.Contains("VK_EXT_debug_marker"))
                {
                    var beginDebugMarkerName = System.Text.Encoding.ASCII.GetBytes("vkCmdDebugMarkerBeginEXT");

                    var ptr = NativeInstance.GetProcAddress((byte *)Interop.Fixed(beginDebugMarkerName));
                    if (ptr != IntPtr.Zero)
                    {
                        BeginDebugMarker = (BeginDebugMarkerDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(BeginDebugMarkerDelegate));
                    }

                    var endDebugMarkerName = System.Text.Encoding.ASCII.GetBytes("vkCmdDebugMarkerEndEXT");
                    ptr = NativeInstance.GetProcAddress((byte *)Interop.Fixed(endDebugMarkerName));
                    if (ptr != IntPtr.Zero)
                    {
                        EndDebugMarker = (EndDebugMarkerDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(EndDebugMarkerDelegate));
                    }
                }
            }
            finally
            {
                foreach (var enabledExtensionName in enabledExtensionNames)
                {
                    Marshal.FreeHGlobal(enabledExtensionName);
                }

                foreach (var enabledLayerName in enabledLayerNames)
                {
                    Marshal.FreeHGlobal(enabledLayerName);
                }

                Marshal.FreeHGlobal(applicationInfo.EngineName);
                Marshal.FreeHGlobal(createDebugReportCallbackName);
            }
        }
Beispiel #46
0
 public void Hide()
 => Interop.Hide(Container);
Beispiel #47
0
 // Unix specific implementation of the method that extracts the current entry as a character device.
 private void ExtractAsCharacterDevice(string destinationFileName)
 {
     Debug.Assert(EntryType is TarEntryType.CharacterDevice);
     Interop.CheckIo(Interop.Sys.CreateCharacterDevice(destinationFileName, (uint)Mode, (uint)_header._devMajor, (uint)_header._devMinor), destinationFileName);
 }
Beispiel #48
0
 public void Fetch()
 {
     featuresField = Interop.WVR_GetSupportedFeatures();
 }
Beispiel #49
0
        private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
        {
            Exception firstException = null;

            if (recursive)
            {
                try
                {
                    foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
                    {
                        if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
                        {
                            try
                            {
                                if (DirectoryExists(item))
                                {
                                    RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
                                }
                                else
                                {
                                    DeleteFile(item);
                                }
                            }
                            catch (Exception exc)
                            {
                                if (firstException != null)
                                {
                                    firstException = exc;
                                }
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (firstException != null)
                    {
                        firstException = exc;
                    }
                }

                if (firstException != null)
                {
                    throw firstException;
                }
            }

            while (Interop.libc.rmdir(fullPath) < 0)
            {
                int errno = Marshal.GetLastWin32Error();
                switch (errno)
                {
                case Interop.Errors.EINTR:     // interrupted; try again
                    continue;

                case Interop.Errors.EACCES:
                case Interop.Errors.EPERM:
                case Interop.Errors.EROFS:
                case Interop.Errors.EISDIR:
                    throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath));     // match Win32 exception

                case Interop.Errors.ENOENT:
                    if (!throwOnTopLevelDirectoryNotFound)
                    {
                        return;
                    }
                    goto default;

                default:
                    throw Interop.GetExceptionForIoErrno(errno, fullPath, isDirectory: true);
                }
            }
        }
Beispiel #50
0
 internal static void FreeValue(IntPtr referral) => Interop.ldap_value_free(referral);
Beispiel #51
0
        /// <summary>
        /// <p>Instructs the object to produce pixels.</p>
        /// </summary>
        /// <typeparam name="T">Type of a pixel. This parameter must exactly match a pixel like using <see cref="Color"/> for a 32bit RGBA color or <see cref="RawVector4"/> for a 64bits for a RGBA 4 floats color.</typeparam>
        /// <param name="rectangle"><dd>  <p>The rectangle to copy. A <strong><c>null</c></strong> value specifies the entire bitmap.</p> </dd></param>
        /// <param name="output">The destination array. The size of the array must be sizeof(pixel) * rectangle.Width * rectangle.Height</param>
        /// <returns><p>If this method succeeds, it returns <strong><see cref="SharpDX.Result.Ok" /></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result" /></strong> error code.</p></returns>
        /// <exception cref="System.ArgumentException">output.Length must be equal to Width * Height</exception>
        /// <msdn-id>ee690179</msdn-id>
        ///   <unmanaged>HRESULT IWICBitmapSource::CopyPixels([In, Optional] const WICRect* prc,[In] unsigned int cbStride,[In] unsigned int cbBufferSize,[In] void* pbBuffer)</unmanaged>
        ///   <unmanaged-short>IWICBitmapSource::CopyPixels</unmanaged-short>
        /// <remarks><p><strong>CopyPixels</strong> is one of the two main image processing routines (the other being <strong>Lock</strong>) triggering the actual processing.  It instructs the object to produce pixels according to its algorithm - this may involve decoding a portion of a JPEG stored on disk, copying a block of memory, or even analytically computing a complex gradient.  The algorithm is completely dependent on the object implementing the interface. </p><p> The caller can restrict the operation to a rectangle of interest (ROI) using the prc parameter.  The ROI sub-rectangle must be fully contained in the bounds of the bitmap.  Specifying a <strong><c>null</c></strong> ROI implies that the whole bitmap should be returned.
        ///   </p><p> The caller controls the memory management and must provide an output buffer (<em>pbBuffer</em>) for the results of the copy along with the buffer's bounds (<em>cbBufferSize</em>).  The cbStride parameter defines the count of bytes between two vertically adjacent pixels in the output buffer.  The caller must ensure that there is sufficient buffer to complete the call based on the width, height and pixel format of the bitmap and the sub-rectangle provided to the copy method. </p><p> If the caller needs to perform numerous copies of an expensive <strong><see cref="SharpDX.WIC.BitmapSource" /></strong> such as a JPEG, it is recommended to create an in-memory <strong><see cref="SharpDX.WIC.Bitmap" /></strong> first. </p>Codec Developer Remarks<p> The callee must only write to the first (prc-&gt;Width*bitsperpixel+7)/8 bytes of each line of the output buffer (in this case, a line is a consecutive string of <em>cbStride</em> bytes). </p></remarks>
        public unsafe void CopyPixels <T>(RawBox rectangle, T[] output) where T : struct
        {
            if ((rectangle.Width * rectangle.Height) != output.Length)
            {
                throw new ArgumentException("output.Length must be equal to Width * Height");
            }

            CopyPixels(new IntPtr(&rectangle), rectangle.Width * Utilities.SizeOf <T>(), (int)output.Length * Utilities.SizeOf <T>(), (IntPtr)Interop.Fixed(output));
        }
Beispiel #52
0
        /// <summary>
        /// Used by the CreateOrOpen factory method groups.
        /// </summary>
        private static SafeMemoryMappedFileHandle CreateOrOpenCore(
            string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access,
            MemoryMappedFileOptions options, long capacity)
        {
            /// Try to open the file if it exists -- this requires a bit more work. Loop until we can
            /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail
            /// if the file exists and we have non-null security attributes, in which case we need to
            /// use OpenFileMapping.  But, there exists a race condition because the memory mapped file
            /// may have closed between the two calls -- hence the loop.
            ///
            /// The retry/timeout logic increases the wait time each pass through the loop and times
            /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened,
            /// throw an InvalidOperationException.

            Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");

            SafeMemoryMappedFileHandle handle = null;

            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability);

            int waitRetries = 14;   //((2^13)-1)*10ms == approximately 1.4mins
            int waitSleep   = 0;

            // keep looping until we've exhausted retries or break as soon we get valid handle
            while (waitRetries > 0)
            {
                // try to create
                handle = Interop.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs,
                                                   GetPageAccess(access) | (int)options, capacity, mapName);

                if (!handle.IsInvalid)
                {
                    break;
                }
                else
                {
                    handle.Dispose();
                    int createErrorCode = Marshal.GetLastWin32Error();
                    if (createErrorCode != Interop.Errors.ERROR_ACCESS_DENIED)
                    {
                        throw Win32Marshal.GetExceptionForWin32Error(createErrorCode);
                    }
                }

                // try to open
                handle = Interop.OpenFileMapping(GetFileMapAccess(access), (inheritability &
                                                                            HandleInheritability.Inheritable) != 0, mapName);

                // valid handle
                if (!handle.IsInvalid)
                {
                    break;
                }
                // didn't get valid handle; have to retry
                else
                {
                    handle.Dispose();
                    int openErrorCode = Marshal.GetLastWin32Error();
                    if (openErrorCode != Interop.Errors.ERROR_FILE_NOT_FOUND)
                    {
                        throw Win32Marshal.GetExceptionForWin32Error(openErrorCode);
                    }

                    // increase wait time
                    --waitRetries;
                    if (waitSleep == 0)
                    {
                        waitSleep = 10;
                    }
                    else
                    {
                        Thread.Sleep(waitSleep);
                        waitSleep *= 2;
                    }
                }
            }

            // finished retrying but couldn't create or open
            if (handle == null || handle.IsInvalid)
            {
                throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping);
            }

            return(handle);
        }
Beispiel #53
0
            internal void Start()
            {
                // Make sure _fullPath doesn't contain a link or alias
                // since the OS will give back the actual, non link'd or alias'd paths
                _fullDirectory = Interop.Sys.RealPath(_fullDirectory);
                if (_fullDirectory == null)
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
                }

                Debug.Assert(string.IsNullOrEmpty(_fullDirectory) == false, "Watch directory is null or empty");

                // Normalize the _fullDirectory path to have a trailing slash
                if (_fullDirectory[_fullDirectory.Length - 1] != '/')
                {
                    _fullDirectory += "/";
                }

                // Get the path to watch and verify we created the CFStringRef
                SafeCreateHandle path = Interop.CoreFoundation.CFStringCreateWithCString(_fullDirectory);

                if (path.IsInvalid)
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
                }

                // Take the CFStringRef and put it into an array to pass to the EventStream
                SafeCreateHandle arrPaths = Interop.CoreFoundation.CFArrayCreate(new CFStringRef[1] {
                    path.DangerousGetHandle()
                }, 1);

                if (arrPaths.IsInvalid)
                {
                    path.Dispose();
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
                }

                // Create the callback for the EventStream if it wasn't previously created for this instance.
                if (_callback == null)
                {
                    _callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback);
                }

                // Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O
                Interop.Sys.Sync();

                // Create the event stream for the path and tell the stream to watch for file system events.
                _eventStream = Interop.EventStream.FSEventStreamCreate(
                    _callback,
                    arrPaths,
                    Interop.EventStream.kFSEventStreamEventIdSinceNow,
                    0.0f,
                    EventStreamFlags);
                if (_eventStream.IsInvalid)
                {
                    arrPaths.Dispose();
                    path.Dispose();
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
                }

                // Create and start our watcher thread then wait for the thread to initialize and start
                // the RunLoop. We wait for that to prevent this function from returning before the RunLoop
                // has a chance to start so that any callers won't race with the background thread's initialization
                // and calling Stop, which would attempt to stop a RunLoop that hasn't started yet.
                var runLoopStarted = new ManualResetEventSlim();

                new Thread(WatchForFileSystemEventsThreadStart)
                {
                    IsBackground = true
                }.Start(runLoopStarted);
                runLoopStarted.Wait();
            }
Beispiel #54
0
        public static void CreateDirectory(string fullPath)
        {
            // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.

            int length = fullPath.Length;

            // We need to trim the trailing slash or the code will try to create 2 directories of the same name.
            if (length >= 2 && Path.EndsInDirectorySeparator(fullPath))
            {
                length--;
            }

            // For paths that are only // or ///
            if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
            }

            // We can save a bunch of work if the directory we want to create already exists.
            if (DirectoryExists(fullPath))
            {
                return;
            }

            // Attempt to figure out which directories don't exist, and only create the ones we need.
            bool           somepathexists = false;
            Stack <string> stackDir       = new Stack <string>();
            int            lengthRoot     = PathInternal.GetRootLength(fullPath);

            if (length > lengthRoot)
            {
                int i = length - 1;
                while (i >= lengthRoot && !somepathexists)
                {
                    string dir = fullPath.Substring(0, i + 1);
                    if (!DirectoryExists(dir)) // Create only the ones missing
                    {
                        stackDir.Push(dir);
                    }
                    else
                    {
                        somepathexists = true;
                    }

                    while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
                    {
                        i--;
                    }
                    i--;
                }
            }

            int count = stackDir.Count;

            if (count == 0 && !somepathexists)
            {
                string?root = Path.GetPathRoot(fullPath);
                if (!DirectoryExists(root))
                {
                    throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
                }
                return;
            }

            // Create all the directories
            int result = 0;

            Interop.ErrorInfo firstError  = default(Interop.ErrorInfo);
            string            errorString = fullPath;

            while (stackDir.Count > 0)
            {
                string name = stackDir.Pop();

                // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
                // We do the same.
                result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
                if (result < 0 && firstError.Error == 0)
                {
                    Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();

                    // While we tried to avoid creating directories that don't
                    // exist above, there are a few cases that can fail, e.g.
                    // a race condition where another process or thread creates
                    // the directory first, or there's a file at the location.
                    if (errorInfo.Error != Interop.Error.EEXIST)
                    {
                        firstError = errorInfo;
                    }
                    else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
                    {
                        // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
                        firstError  = errorInfo;
                        errorString = name;
                    }
                }
            }

            // Only throw an exception if creating the exact directory we wanted failed to work correctly.
            if (result < 0 && firstError.Error != 0)
            {
                throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
            }
        }
Beispiel #55
0
 internal static void FreeAttributes(IntPtr berelement) => Interop.ldap_value_free_len(berelement);
Beispiel #56
0
 static Sys()
 {
     Interop.mono_pal_init();
 }
Beispiel #57
0
    public void UpdatePoses(WVR_PoseOriginModel origin, bool isSimulator)
    {
        Log.gpl.d(LOG_TAG, "UpdatePoses");

#if UNITY_EDITOR
        if (Application.isEditor)
        {
            if (isSimulator)
            {
                WaveVR_Utils.WVR_GetSyncPose_S((int)origin, poses, poses.Length);
            }
        }
        else
#endif
        {
            bool _focusCapturedBySystem = Interop.WVR_IsInputFocusCapturedBySystem();
            if (this.FocusCapturedBySystem != _focusCapturedBySystem)
            {
                this.FocusCapturedBySystem = _focusCapturedBySystem;
                WaveVR_Utils.Event.Send(WaveVR_Utils.Event.SYSTEMFOCUS_CHANGED, this.FocusCapturedBySystem);
            }
            Interop.WVR_GetSyncPose(origin, poses, (uint)poses.Length);
        }

        for (uint i = 0; i < DeviceTypes.Length; i++)
        {
            bool _hasType = false;

            for (uint j = 0; j < poses.Length; j++)
            {
                WVR_DevicePosePair_t _pose = poses[j];

                if (_pose.type == DeviceTypes [i])
                {
                    _hasType          = true;
                    deviceIndexMap[i] = j;

                    if (connected [i] != _pose.pose.IsValidPose)
                    {
                        connected [i] = _pose.pose.IsValidPose;
                        Log.i(LOG_TAG, "device " + DeviceTypes [i] + " is " + (connected [i] ? "connected" : "disconnected"));
                        WaveVR_Utils.Event.Send(WaveVR_Utils.Event.DEVICE_CONNECTED, DeviceTypes [i], connected[i]);
                    }

                    if (connected [i])
                    {
                        rtPoses[j].update(_pose.pose.PoseMatrix);
                    }

                    break;
                }
            }

            // no such type
            if (!_hasType)
            {
                if (connected [i] == true)
                {
                    connected [i] = false;
                    Log.i(LOG_TAG, "device " + DeviceTypes [i] + " is disconnected.");
                    WaveVR_Utils.Event.Send(WaveVR_Utils.Event.DEVICE_CONNECTED, DeviceTypes [i], connected[i]);
                }
            }
        }

        for (int i = 0; i < poses.Length; i++)
        {
            WVR_DeviceType _type      = poses [i].type;
            bool           _connected = false;
#if UNITY_EDITOR
            if (isSimulator)
            {
                _connected = WaveVR_Utils.WVR_IsDeviceConnected_S((int)_type);
            }
            else
#endif
            {
                _connected = Interop.WVR_IsDeviceConnected(_type);
            }

            bool _posevalid = poses [i].pose.IsValidPose;

            Log.gpl.d(LOG_TAG, "Device " + _type + " is " + (_connected ? "connected" : "disconnected")
                      + ", pose is " + (_posevalid ? "valid" : "invalid")
                      + ", pos: {" + rtPoses [i].pos.x + ", " + rtPoses [i].pos.y + ", " + rtPoses [i].pos.z + "}"
                      + ", rot: {" + rtPoses [i].rot.x + ", " + rtPoses [i].rot.y + ", " + rtPoses [i].rot.z + ", " + rtPoses [i].rot.w + "}");
        }

        try
        {
            WaveVR_Utils.Event.Send(WaveVR_Utils.Event.NEW_POSES, poses, rtPoses);
        }
        catch (Exception ex)
        {
            Log.e(LOG_TAG, "Send NEW_POSES Event Exception : " + ex);
        }
        Log.gpl.d(LOG_TAG, "after new poses");
        try
        {
            WaveVR_Utils.Event.Send(WaveVR_Utils.Event.AFTER_NEW_POSES);
        }
        catch (Exception ex)
        {
            Log.e(LOG_TAG, "Send AFTER_NEW_POSES Event Exception : " + ex);
        }
    }
Beispiel #58
0
    private WaveVR()
    {
        Debug.Log("WaveVR()+");
#if UNITY_EDITOR
        if (Application.isEditor)
        {
            Debug.Log("WaveVR()+   in editor");
            try
            {
                string ipaddr = "";
                //WaveVR_Utils.SIM_ConnectType type = WaveVR_Utils.SIM_ConnectType.SIM_ConnectType_USB;
                System.IntPtr ptrIPaddr = Marshal.StringToHGlobalAnsi(ipaddr);
                WaveVR_Utils.WVR_SetPrintCallback_S(WaveVR_Utils.PrintLog);
                WaveVR_Utils.SIM_InitError error = WaveVR_Utils.WVR_Init_S(0, ptrIPaddr);
                Debug.Log("WVR_Init_S = " + error);

                if (error != 0)
                {
                    WaveVR_Utils.WVR_Quit_S();
                    Debug.Log("WVR_Quit");
                    Debug.Log("WaveVR()-");
                    return;
                }
                isSimulatorOn = true;
            }
            catch (Exception e)
            {
                Debug.Log("WVR_Init_S failed " + e);
                return;
            }
        }
        else
#endif
        {
            Log.d(LOG_TAG, "WaveVR()+");

            WVR_InitError error = Interop.WVR_Init(WVR_AppType.WVR_AppType_VRContent);
            if (error != WVR_InitError.WVR_InitError_None)
            {
                ReportError(error);
                Interop.WVR_Quit();
                Debug.Log("WVR_Quit");
                return;
            }
            WaveVR_Utils.notifyActivityUnityStarted();
        }

        for (int i = 0; i < 3; i++)
        {
            poses[i]          = new WVR_DevicePosePair_t();
            connected[i]      = false; // force update connection status to all listener.
            deviceIndexMap[i] = 0;     // use hmd's id as default.
        }

        hmd             = new Device(WVR_DeviceType.WVR_DeviceType_HMD);
        controllerLeft  = new Device(WVR_DeviceType.WVR_DeviceType_Controller_Left);
        controllerRight = new Device(WVR_DeviceType.WVR_DeviceType_Controller_Right);

#if UNITY_EDITOR
        if (Application.isEditor)
        {
            Debug.Log("WaveVR()-");
        }
        else
#endif
        {
            Log.d(LOG_TAG, "WaveVR()-");
        }
    }
Beispiel #59
0
        public unsafe T CheckFeatureSupport <T>(Feature feature) where T : struct
        {
            T featureSupport = default;

            CheckFeatureSupport(feature, new IntPtr(Unsafe.AsPointer(ref featureSupport)), Interop.SizeOf <T>());
            return(featureSupport);
        }
Beispiel #60
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Bitmap"/> class from an array of pixel data.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <param name="pixelDatas">The pixel data.</param>
        /// <param name="stride">Stride of a row of pixels (number of bytes per row). By default the stride is == 0, and calculated by taking the sizeof(T) * width.</param>
        /// <msdn-id>ee690291</msdn-id>
        /// <unmanaged>HRESULT IWICImagingFactory::CreateBitmapFromMemory([In] unsigned int uiWidth,[In] unsigned int uiHeight,[In] const GUID&amp; pixelFormat,[In] unsigned int cbStride,[In] unsigned int cbBufferSize,[In] void* pbBuffer,[Out, Fast] IWICBitmap** ppIBitmap)</unmanaged>
        /// <unmanaged-short>IWICImagingFactory::CreateBitmapFromMemory</unmanaged-short>
        public unsafe static Bitmap New <T>(ImagingFactory factory, int width, int height, System.Guid pixelFormat, T[] pixelDatas, int stride = 0) where T : struct
        {
            if (stride == 0)
            {
                stride = width * Utilities.SizeOf <T>();
            }

            return(new Bitmap(factory, width, height, pixelFormat, new DataRectangle((IntPtr)Interop.Fixed(pixelDatas), stride)));
        }