Пример #1
0
        public void CanDeleteWithOtherOpenHardlinks()
        {
            string hardlink1 = Path.Combine(TemporaryDirectory, "hardlink1");

            File.WriteAllText(hardlink1, "asdf");

            string hardlink2 = Path.Combine(TemporaryDirectory, "hardlink2");

            XAssert.IsTrue(CreateHardLinkIfSupported(hardlink2, hardlink1));

            // Open a handle to hardlink2 without FileShare Delete mode
            using (new FileStream(hardlink2, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BuildXLException exception = null;
                try
                {
                    FileUtilities.DeleteFile(hardlink1);
                }
                catch (BuildXLException ex)
                {
                    exception = ex;
                }
                // Successfully delete file
                XAssert.IsTrue(exception == null);
                XAssert.IsFalse(File.Exists(hardlink1));
            }
        }
Пример #2
0
        /// <summary>
        /// Creates an instances of this class.
        /// </summary>
        public SandboxedProcessOutput(
            long length,
            string value,
            string fileName,
            Encoding encoding,
            ISandboxedProcessFileStorage fileStorage,
            SandboxedProcessFile file,
            BuildXLException exception)
        {
            Contract.Requires((fileName == null && length >= 0) || (fileName != null && length >= NoLength) || exception != null);
            Contract.Requires(exception != null ^ (value != null ^ fileName != null));
            Contract.Requires(value == null || length == value.Length);
            Contract.Requires(exception != null || encoding != null);
            Contract.Requires(exception != null || fileName != null || fileStorage != null);
            Contract.Requires(encoding != null);

            m_length      = length;
            m_value       = value;
            m_fileName    = fileName;
            m_encoding    = encoding;
            m_fileStorage = fileStorage;
            m_file        = file;
            m_saveTask    = m_fileName != null ? Unit.VoidTask : null;
            m_exception   = exception;
        }
        /// <summary>
        /// Creates an instances of this class.
        /// </summary>
        public SandboxedProcessOutput(
            long length,
            string value,
            string fileName,
            Encoding encoding,
            ISandboxedProcessFileStorage fileStorage,
            SandboxedProcessFile file,
            BuildXLException exception)
        {
            requires((fileName == null && length >= 0) || (fileName != null && length >= NoLength) || exception != null);
            requires(exception != null ^ (value != null ^ fileName != null));
            requires(value == null || length == value.Length);
            requires(exception != null || encoding != null);
            requires(exception != null || fileName != null || fileStorage != null);
            requires(encoding != null);

            m_length      = length;
            m_value       = value;
            m_fileName    = fileName;
            m_encoding    = encoding;
            m_fileStorage = fileStorage;
            m_file        = file;
            m_saveTask    = m_fileName != null ? Unit.VoidTask : null;
            m_exception   = exception;

            void requires(bool condition)
            {
                if (!condition)
                {
                    throw Contract.AssertFailure($"length: {length}; value: '{value}'; filename: {fileName}; encoding: {encoding}; exception: {exception?.ToString()}");
                }
            }
        }
        /// <summary>
        /// Deserializes an instance of <see cref="SandboxedProcessOutput"/>.
        /// </summary>
        public static SandboxedProcessOutput Deserialize(BuildXLReader reader)
        {
            long     length   = reader.ReadInt64();
            string   value    = reader.ReadNullableString();
            string   fileName = reader.ReadNullableString();
            Encoding encoding = reader.ReadEncoding();
            SandboxedProcessStandardFiles standardFiles = reader.ReadNullable(r => SandboxedProcessStandardFiles.Deserialize(r));
            ISandboxedProcessFileStorage  fileStorage   = null;

            if (standardFiles != null)
            {
                fileStorage = new StandardFileStorage(standardFiles);
            }
            SandboxedProcessFile file      = (SandboxedProcessFile)reader.ReadUInt32Compact();
            BuildXLException     exception = reader.ReadNullable(r => new BuildXLException(r.ReadNullableString(), (ExceptionRootCause)r.ReadUInt32Compact()));

            return(new SandboxedProcessOutput(
                       length,
                       value,
                       fileName,
                       encoding,
                       fileStorage,
                       file,
                       exception));
        }
Пример #5
0
        /// <summary>
        /// Re-creates an instance from a saved file.
        /// </summary>
        public static SandboxedProcessOutput FromFile(string fileName, string encodingName, SandboxedProcessFile file)
        {
            Contract.Requires(fileName != null);
            Contract.Requires(encodingName != null);

            BuildXLException exception = null;
            Encoding         encoding;

#if DISABLE_FEATURE_EXTENDED_ENCODING
            // Console encoding is forced to UTF-8 in CoreFx see: https://github.com/dotnet/corefx/issues/10054
            // Trying to parse anything else or in the Windows case 'Codepage - 437', fails. We default to UTF-8 which
            // is the standard console encoding on any Unix based system anyway.
            encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
#else
            try
            {
                try
                {
                    encoding = Encoding.GetEncoding(encodingName);
                }
                catch (ArgumentException ex)
                {
                    throw new BuildXLException("Unsupported encoding name", ex);
                }
            }
            catch (BuildXLException ex)
            {
                fileName  = null;
                encoding  = null;
                exception = ex;
            }
#endif

            return(new SandboxedProcessOutput(NoLength, null, fileName, encoding, null, file, exception));
        }
Пример #6
0
        public void ErrorCodeWithNestedNativeNtException()
        {
            var ex = new BuildXLException(
                "Outer",
                new BuildXLException("Less outer", new NativeNtException(new NtStatus((uint)NtStatusCode.StatusPipeBroken), "Inner")));

            XAssert.AreEqual(unchecked ((int)NtStatusCode.StatusPipeBroken), ex.LogEventErrorCode);
            string message = ex.LogEventMessage;

            XAssert.IsTrue(message.Contains("Less outer"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("Inner"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("Outer"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("StatusPipeBroken"), "Missing substring in {0}", message);
        }
Пример #7
0
        public void Constructor()
        {
            const string Message = "Hello";

            var ex = new BuildXLException(Message);

            XAssert.AreEqual(Message, ex.Message);

            var inner = new ArgumentException();

            ex = new BuildXLException(Message, inner);
            XAssert.AreEqual(Message, ex.Message);
            Assert.Equal(inner, ex.InnerException);
        }
Пример #8
0
        public void ErrorCodeWithNestedNativeWin32Exception()
        {
            const int ErrorAccessDenied = 5;
            var       ex = new BuildXLException(
                "Outer",
                new BuildXLException("Less outer", new NativeWin32Exception(ErrorAccessDenied, "Inner")));

            XAssert.AreEqual(ErrorAccessDenied, ex.LogEventErrorCode);
            string message = ex.LogEventMessage;

            XAssert.IsTrue(message.Contains("Less outer"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("Inner"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("Outer"), "Missing substring in {0}", message);
            XAssert.IsTrue(message.Contains("Access is denied"), "Missing substring in {0}", message);
        }
Пример #9
0
        public async Task FromException()
        {
            var toThrow = new BuildXLException("Got exception?");

            try
            {
                await TaskUtilities.FromException <int>(toThrow);
            }
            catch (BuildXLException ex)
            {
                XAssert.AreSame(toThrow, ex);
                return;
            }

            XAssert.Fail("Expected an exception");
        }
Пример #10
0
 private void HandleRecoverableIOException(Action action)
 {
     try
     {
         ExceptionUtilities.HandleRecoverableIOException(
             action,
             ex => { throw new BuildXLException("Writing file failed", ex); });
     }
     catch (BuildXLException ex)
     {
         m_exception = ex;
         ReleaseTextWriter();
         ReleaseStringBuilder();
         m_fileName = null;
         m_length   = SandboxedProcessOutput.NoLength;
         IsFrozen   = true;
     }
 }
Пример #11
0
        public void MoveTempDeletionCanReplaceRunningExecutable()
        {
            // Make a copy of DummyWaiter.exe to use as the test subject for deleting a running executable.
            // Keep the copy in the same directory as the original since it will need runtime dlls
            string dummyWaiterLocation = DummyWaiter.GetDummyWaiterExeLocation();
            string exeCopy             = dummyWaiterLocation + ".copy.exe";

            File.Copy(dummyWaiterLocation, exeCopy);

            using (var waiter = DummyWaiter.RunAndWait(exeCopy))
            {
                BuildXLException caughtException = null;
                try
                {
                    FileUtilities.DeleteFile(exeCopy);
                }
                catch (BuildXLException ex)
                {
                    caughtException = ex;
                }

                XAssert.IsNotNull(caughtException, "Expected deletion without a tempCleaner to fail");
                XAssert.IsTrue(File.Exists(exeCopy));

                caughtException = null;


                try
                {
                    FileUtilities.DeleteFile(exeCopy, tempDirectoryCleaner: MoveDeleteCleaner);
                }
                catch (BuildXLException ex)
                {
                    caughtException = ex;
                }

                XAssert.IsNull(caughtException, "Expected deletion with a MoveDeleteCleaner to succeed");
                XAssert.IsFalse(File.Exists(exeCopy));
            }
        }
Пример #12
0
        /// <summary>
        /// Attempts to create a process memory dump at the requested location. Any file already existing at that location will be overwritten
        /// </summary>
        public static bool TryDumpProcess(Process process, string dumpPath, out Exception dumpCreationException, bool compress = false)
        {
            if (OperatingSystemHelper.IsUnixOS)
            {
                dumpCreationException = new PlatformNotSupportedException();
                return(false);
            }

            string processName = "Exited";

            try
            {
                processName = process.ProcessName;
                bool dumpResult = TryDumpProcess(process.Handle, process.Id, dumpPath, out dumpCreationException, compress);
                if (!dumpResult)
                {
                    Contract.Assume(dumpCreationException != null, "Exception was null on failure.");
                }

                return(dumpResult);
            }
            catch (Win32Exception ex)
            {
                dumpCreationException = new BuildXLException("Failed to get process handle to create a process dump for: " + processName, ex);
                return(false);
            }
            catch (InvalidOperationException ex)
            {
                dumpCreationException = new BuildXLException("Failed to get process handle to create a process dump for: " + processName, ex);
                return(false);
            }
            catch (NotSupportedException ex)
            {
                dumpCreationException = new BuildXLException("Failed to get process handle to create a process dump for: " + processName, ex);
                return(false);
            }
        }
Пример #13
0
 private static Optional <CompositeGraphFingerprint> LogAndReturnFailure(BuildXLException ex)
 {
     Tracing.Logger.Log.FailedToComputeGraphFingerprint(Events.StaticContext, ex.LogEventMessage);
     return(Optional <CompositeGraphFingerprint> .Invalid);
 }
Пример #14
0
        private Possible <ISourceFile> HandleIoError(AbsolutePath pathToParse, AbsolutePath moduleOrConfigPathPromptingParse, BuildXLException failureException)
        {
            var specPathString = pathToParse.ToString(Context.PathTable);
            var location       = new Location()
            {
                File = moduleOrConfigPathPromptingParse.ToString(Context.PathTable)
            };

            if (failureException.InnerException is IOException)
            {
                if (m_fileSystem.Exists(AbsolutePath.Create(Context.PathTable, specPathString)))
                {
                    Logger.ReportFailReadFileContent(
                        Context.LoggingContext,
                        location,
                        specPathString,
                        "File not found.");

                    return(new CannotReadSpecFailure(specPathString, CannotReadSpecFailure.CannotReadSpecReason.SpecDoesNotExist));
                }
            }

            if (failureException.InnerException is UnauthorizedAccessException)
            {
                if (Directory.Exists(specPathString))
                {
                    Logger.ReportFailReadFileContent(
                        Context.LoggingContext,
                        location,
                        specPathString,
                        "Expected a file path, parser can not parse a directory.");

                    return(new CannotReadSpecFailure(specPathString, CannotReadSpecFailure.CannotReadSpecReason.PathIsADirectory));
                }
            }

            Logger.ReportFailReadFileContent(
                Context.LoggingContext,
                location,
                specPathString,
                "Unexpected error: " + failureException);

            return(new CannotReadSpecFailure(specPathString, CannotReadSpecFailure.CannotReadSpecReason.IoException));
        }
Пример #15
0
 private static Optional <CompositeGraphFingerprint> LogAndReturnFailure(LoggingContext loggingContext, BuildXLException ex)
 {
     Tracing.Logger.Log.FailedToComputeGraphFingerprint(loggingContext, ex.LogEventMessage);
     return(Optional <CompositeGraphFingerprint> .Empty);
 }
Пример #16
0
 /// <param name="path">The path that could not be deleted</param>
 /// <param name="exception">The cause of the failure</param>
 public DeletionFailure(string path, BuildXLException exception) : base(exception)
 {
     Path = path;
 }