示例#1
0
        /// <summary>
        /// Gets the process exit code.
        /// </summary>
        /// <remarks>
        /// This method can only be invoked after the process has exited.");
        /// The result is undefined if this instance has been disposed.
        /// </remarks>
        public int GetExitCode()
        {
            Contract.Requires(HasExited);
            using (m_syncSemaphore.AcquireSemaphore())
            {
                if (m_disposed)
                {
                    return(-1);
                }

                int exitCode;
                if (!Native.Processes.ProcessUtilities.GetExitCodeProcess(this.m_processHandle, out exitCode))
                {
                    throw new NativeWin32Exception(Marshal.GetLastWin32Error(), "Unable to get exit code.");
                }

                return(exitCode);
            }
        }
示例#2
0
 /// <nodoc />
 public void UnsafeClear()
 {
     // Order is important here, inverse order could cause deadlock.
     using (_flushMutex.AcquireSemaphore())
         using (_exchangeLock.AcquireWriteLock())
         {
             if (_cache.Count != 0)
             {
                 // Nothing guarantees that some number of updates couldn't have happened in between the last flush
                 // and this reset, because acquisition of the write lock happens after the flush lock. The only way
                 // to deal with this situation is to force a flush before this assignment and after locks have been
                 // acquired. However, this isn't required by our code right now; although it is a simple change.
                 _cache = new ConcurrentBigMap <ShortHash, ContentLocationEntry>();
             }
         }
 }
示例#3
0
        public void Start()
        {
            Contract.Assume(!m_processStarted);

            Encoding        reportEncoding  = Encoding.Unicode;
            SafeFileHandle  childHandle     = null;
            DetouredProcess detouredProcess = m_detouredProcess;

            using (m_reportReaderSemaphore.AcquireSemaphore())
            {
                SafeFileHandle reportHandle;

                try
                {
                    Pipes.CreateInheritablePipe(
                        Pipes.PipeInheritance.InheritWrite,
                        Pipes.PipeFlags.ReadSideAsync,
                        readHandle: out reportHandle,
                        writeHandle: out childHandle);

                    var setup =
                        new FileAccessSetup
                    {
                        ReportPath = "#" + childHandle.DangerousGetHandle().ToInt64(),
                        DllNameX64 = s_binaryPaths.DllNameX64,
                        DllNameX86 = s_binaryPaths.DllNameX86,
                    };

                    bool debugFlagsMatch = true;
                    ArraySegment <byte> manifestBytes = new ArraySegment <byte>();
                    if (m_fileAccessManifest != null)
                    {
                        manifestBytes = m_fileAccessManifest.GetPayloadBytes(setup, FileAccessManifestStream, m_timeoutMins, ref debugFlagsMatch);
                    }

                    if (!debugFlagsMatch)
                    {
                        throw new BuildXLException("Mismatching build type for BuildXL and DetoursServices.dll.");
                    }

                    m_standardInputTcs = TaskSourceSlim.Create <bool>();
                    detouredProcess.Start(
                        s_payloadGuid,
                        manifestBytes,
                        childHandle,
                        s_binaryPaths.DllNameX64,
                        s_binaryPaths.DllNameX86);

                    // At this point, we believe calling 'kill' will result in an eventual callback for job teardown.
                    // This knowledge is significant for ensuring correct cleanup if we did vs. did not start a process;
                    // if started, we expect teardown to happen eventually and clean everything up.
                    m_processStarted = true;

                    ProcessId = detouredProcess.GetProcessId();
                    m_processIdListener?.Invoke(ProcessId);
                }
                finally
                {
                    // release memory
                    m_fileAccessManifest = null;

                    // Note that in the success path, childHandle should already be closed (by Start).
                    if (childHandle != null && !childHandle.IsInvalid)
                    {
                        childHandle.Dispose();
                    }
                }

                var reportFile = AsyncFileFactory.CreateAsyncFile(
                    reportHandle,
                    FileDesiredAccess.GenericRead,
                    ownsHandle: true,
                    kind: FileKind.Pipe);
                StreamDataReceived reportLineReceivedCallback = m_reports == null ? (StreamDataReceived)null : ReportLineReceived;
                m_reportReader = new AsyncPipeReader(reportFile, reportLineReceivedCallback, reportEncoding, m_bufferSize);
                m_reportReader.BeginReadLine();
            }

            // don't wait, we want feeding in of standard input to happen asynchronously
            Analysis.IgnoreResult(FeedStandardInputAsync(detouredProcess, m_standardInputReader, m_standardInputTcs));
        }
示例#4
0
        public void Start()
        {
            Contract.Assume(!m_processStarted);

            Encoding        reportEncoding  = Encoding.Unicode;
            SafeFileHandle  childHandle     = null;
            DetouredProcess detouredProcess = m_detouredProcess;

            bool useNonDefaultPipeReader = PipeReaderFactory.GetKind() != PipeReaderFactory.Kind.Default;

            using (m_reportReaderSemaphore.AcquireSemaphore())
            {
                NamedPipeServerStream pipeStream   = null;
                SafeFileHandle        reportHandle = null;

                try
                {
                    if (useNonDefaultPipeReader)
                    {
                        pipeStream = Pipes.CreateNamedPipeServerStream(
                            PipeDirection.In,
                            PipeOptions.Asynchronous,
                            PipeOptions.None,
                            out childHandle);
                    }
                    else
                    {
                        Pipes.CreateInheritablePipe(
                            Pipes.PipeInheritance.InheritWrite,
                            Pipes.PipeFlags.ReadSideAsync,
                            readHandle: out reportHandle,
                            writeHandle: out childHandle);
                    }

                    var setup = new FileAccessSetup
                    {
                        ReportPath = "#" + childHandle.DangerousGetHandle().ToInt64(),
                        DllNameX64 = s_binaryPaths.DllNameX64,
                        DllNameX86 = s_binaryPaths.DllNameX86,
                    };

                    bool debugFlagsMatch = true;
                    ArraySegment <byte> manifestBytes = new ArraySegment <byte>();
                    if (m_fileAccessManifest != null)
                    {
                        manifestBytes = m_fileAccessManifest.GetPayloadBytes(m_loggingContext, setup, FileAccessManifestStream, m_timeoutMins, ref debugFlagsMatch);
                    }

                    if (!debugFlagsMatch)
                    {
                        throw new BuildXLException("Mismatching build type for BuildXL and DetoursServices.dll.");
                    }

                    m_standardInputTcs = TaskSourceSlim.Create <bool>();
                    detouredProcess.Start(
                        s_payloadGuid,
                        manifestBytes,
                        childHandle,
                        s_binaryPaths.DllNameX64,
                        s_binaryPaths.DllNameX86);

                    // At this point, we believe calling 'kill' will result in an eventual callback for job teardown.
                    // This knowledge is significant for ensuring correct cleanup if we did vs. did not start a process;
                    // if started, we expect teardown to happen eventually and clean everything up.
                    m_processStarted = true;

                    ProcessId = detouredProcess.GetProcessId();
                }
                catch (AccessViolationException)
                {
                    int ramPercent = 0, availableRamMb = 0, availablePageFileMb = 0, totalPageFileMb = 0;

                    MEMORYSTATUSEX memoryStatusEx = new MEMORYSTATUSEX();
                    if (GlobalMemoryStatusEx(memoryStatusEx))
                    {
                        ramPercent          = (int)memoryStatusEx.dwMemoryLoad;
                        availableRamMb      = new FileSize(memoryStatusEx.ullAvailPhys).MB;
                        availablePageFileMb = new FileSize(memoryStatusEx.ullAvailPageFile).MB;
                        totalPageFileMb     = new FileSize(memoryStatusEx.ullTotalPageFile).MB;
                    }

                    string memUsage = $"RamPercent: {ramPercent}, AvailableRamMb: {availableRamMb}, AvailablePageFileMb: {availablePageFileMb}, TotalPageFileMb: {totalPageFileMb}";
                    Native.Tracing.Logger.Log.DetouredProcessAccessViolationException(m_loggingContext, (m_reports?.PipDescription ?? "") + " - " + memUsage);
                    throw;
                }
                finally
                {
                    // release memory
                    m_fileAccessManifest = null;

                    // Note that in the success path, childHandle should already be closed (by Start).
                    if (childHandle != null && !childHandle.IsInvalid)
                    {
                        childHandle.Dispose();
                    }
                }

                StreamDataReceived reportLineReceivedCallback = m_reports == null ? null : ReportLineReceived;

                if (useNonDefaultPipeReader)
                {
                    m_reportReader = PipeReaderFactory.CreateNonDefaultPipeReader(
                        pipeStream,
                        message => reportLineReceivedCallback(message),
                        reportEncoding,
                        m_bufferSize);
                }
                else
                {
                    var reportFile = AsyncFileFactory.CreateAsyncFile(
                        reportHandle,
                        FileDesiredAccess.GenericRead,
                        ownsHandle: true,
                        kind: FileKind.Pipe);
                    m_reportReader = new AsyncPipeReader(
                        reportFile,
                        reportLineReceivedCallback,
                        reportEncoding,
                        m_bufferSize,
                        numOfRetriesOnCancel: m_numRetriesPipeReadOnCancel,
                        debugPipeReporter: new AsyncPipeReader.DebugReporter(errorMsg => DebugPipeConnection($"ReportReader: {errorMsg}")));
                }

                m_reportReader.BeginReadLine();
            }

            // don't wait, we want feeding in of standard input to happen asynchronously
            Analysis.IgnoreResult(FeedStandardInputAsync(detouredProcess, m_standardInputReader, m_standardInputTcs));
        }