Ejemplo n.º 1
0
        internal static void InitializeLoggers()
        {
            lock (LoggerLock)
            {
                if (LogManager.Configuration != null)
                {
                    return;
                }
                var config = new LoggingConfiguration();

                DateTime now = DateTime.Now;

                string activeLogFileName = string.Format("{0}\\Logs\\{1}\\[CoolFish-{2}] {3}.txt", Constants.ApplicationPath.Value,
                                                         now.ToString("MMMM dd yyyy"), Process.GetCurrentProcess().Id,
                                                         now.ToString("T").Replace(':', '.'));


                var file = new FileTarget
                {
                    FileName = activeLogFileName,
                    Layout   =
                        @"[${date:format=MM/dd/yy h\:mm\:ss.ffff tt}] [${level:uppercase=true}] ${message} ${onexception:inner=${newline}${exception:format=tostring}}",
                    CreateDirs       = true,
                    ConcurrentWrites = false
                };


                config.LoggingRules.Add(new LoggingRule("*", LogLevel.FromOrdinal(UserPreferences.Default.LogLevel),
                                                        new AsyncTargetWrapper(file)
                {
                    OverflowAction = AsyncTargetWrapperOverflowAction.Grow
                }));


                var remoteTarget = new RemoteTarget
                {
                    Layout = @"[${level:uppercase=true}] ${message}"
                };


                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error,
                                                        new AsyncTargetWrapper(remoteTarget)
                {
                    OverflowAction = AsyncTargetWrapperOverflowAction.Grow
                }));

                LogManager.Configuration = config;
            }
        }
Ejemplo n.º 2
0
        public void SetUp()
        {
            mockTarget   = Substitute.For <SbTarget>();
            remoteTarget = new RemoteTargetFactory(new RemoteBreakpointFactory())
                           .Create(mockTarget);
            mockAddress      = Substitute.For <SbAddress>();
            mockProcess      = Substitute.For <SbProcess>();
            mockMemoryRegion = Substitute.For <SbMemoryRegionInfo>();
            mockError        = Substitute.For <SbError>();
            mockBreakpoint   = Substitute.For <SbBreakpoint>();
            remoteBreakpoint = new RemoteBreakpointFactory().Create(mockBreakpoint);
            mockFunction     = Substitute.For <SbFunction>();

            mockTarget.GetProcess().Returns(mockProcess);
        }
        public override Task <SetModuleLoadAddressResponse> SetModuleLoadAddress(
            SetModuleLoadAddressRequest request, ServerCallContext context)
        {
            RemoteTarget target    = GrpcLookupUtils.GetTarget(request.Target, _targetStore);
            SbModule     module    = _moduleStore.GetObject(request.Module.Id);
            SbError      error     = target.SetModuleLoadAddress(module, request.SectionsOffset);
            var          grpcError =
                new GrpcSbError {
                Success = error.Success(), Error = error.GetCString()
            };

            return(Task.FromResult(new SetModuleLoadAddressResponse {
                Error = grpcError
            }));
        }
Ejemplo n.º 4
0
        public void SetUp()
        {
            logSpy = new LogSpy();
            logSpy.Attach();

            var noError = new SbErrorStub(true, null);

            mockTarget = Substitute.For <RemoteTarget>();
            mockTarget.SetModuleLoadAddress(Arg.Any <SbModule>(), Arg.Any <long>()).Returns(noError);
            mockModule = Substitute.For <SbModule>();
            mockModule.HasCompileUnits().Returns(false);
            mockModule.FindSection(Arg.Any <string>()).Returns((SbSection)null);
            mockPlatformFileSpec = Substitute.For <SbFileSpec>();
            moduleUtil           = new LldbModuleUtil();
        }
        public override Task <ResolveLoadAddressResponse> ResolveLoadAddress(
            ResolveLoadAddressRequest request, ServerCallContext context)
        {
            RemoteTarget target   = GrpcLookupUtils.GetTarget(request.Target, _targetStore);
            var          response = new ResolveLoadAddressResponse();
            SbAddress    address  = target.ResolveLoadAddress(request.Address);

            if (address != null)
            {
                response.Address = new GrpcSbAddress {
                    Id = _addressStore.AddObject(address),
                };
            }
            return(Task.FromResult(response));
        }
        public override Task <AddModuleResponse> AddModule(AddModuleRequest request,
                                                           ServerCallContext context)
        {
            RemoteTarget target   = GrpcLookupUtils.GetTarget(request.Target, _targetStore);
            var          response = new AddModuleResponse();
            SbModule     module   = target.AddModule(request.Path, request.Triple, request.Uuid);

            if (module != null)
            {
                response.Module = new GrpcSbModule {
                    Id = _moduleStore.AddObject(module)
                };
            }
            return(Task.FromResult(response));
        }
        DebugDisassemblyStream(DebugCodeContext.Factory codeContextFactory,
                               DebugDocumentContext.Factory documentContextFactory,
                               enum_DISASSEMBLY_STREAM_SCOPE scope, IDebugCodeContext2 codeContext,
                               RemoteTarget target)
        {
            _codeContextFactory     = codeContextFactory;
            _documentContextFactory = documentContextFactory;
            _scope  = scope;
            _target = target;

            // Used to cache line entries from the last read call
            _lineEntryCache = new Dictionary <ulong, LineEntryInfo>();

            // Extract the address from {codeContext}.
            _address = codeContext.GetAddress();
        }
Ejemplo n.º 8
0
        public void CreatePendingBreakpoint(IDebugBreakpointRequest2 breakpointRequest,
                                            RemoteTarget target, out IDebugPendingBreakpoint2 pendingBreakpoint)
        {
            taskContext.ThrowIfNotOnMainThread();

            BP_REQUEST_INFO[] requestInfo = new BP_REQUEST_INFO[1];
            breakpointRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION, requestInfo);
            if (requestInfo[0].bpLocation.bpLocationType ==
                (uint)enum_BP_LOCATION_TYPE.BPLT_DATA_STRING)
            {
                pendingBreakpoint = watchpointFactory.Create(Self,
                                                             breakpointRequest, target, debugProgram);
            }
            else
            {
                pendingBreakpoint = pendingBreakpointFactory.Create(
                    Self, debugProgram, breakpointRequest, target);
            }
        }
Ejemplo n.º 9
0
        public void SetUp()
        {
            var taskContext = new JoinableTaskContext();

            mockBreakpointManager = Substitute.For <IBreakpointManager>();
            mockBreakpointRequest = Substitute.For <IDebugBreakpointRequest2>();
            mockProgram           = Substitute.For <IDebugProgram2>();
            mockResolution        = Substitute.For <IDebugBreakpointResolution2>();
            mockResolutionFactory = Substitute.For <DebugWatchpointResolution.Factory>();
            mockResolutionFactory.Create(TEST_ADDRESS_STR, mockProgram).Returns(mockResolution);
            mockTarget = Substitute.For <RemoteTarget>();
            SbError error;

            mockError = Substitute.For <SbError>();
            mockTarget.WatchAddress(TEST_ADDRESS, WATCH_SIZE, false, true, out error).Returns(x =>
            {
                x[4] = mockError;
                return(mockLldbWatchpoint);
            });
            mockMarshal = Substitute.For <Marshal>();
            mockMarshal.GetStringFromIntPtr(Arg.Any <IntPtr>()).Returns(TEST_ADDRESS_STR);
            mockLldbWatchpoint = Substitute.For <SbWatchpoint>();
            requestInfo        = new BP_REQUEST_INFO();
            requestInfo.bpLocation.unionmember4 = (IntPtr)4;
            mockBreakpointRequest.GetRequestInfo(Arg.Any <enum_BPREQI_FIELDS>(),
                                                 Arg.Any <BP_REQUEST_INFO[]>()).Returns(x =>
            {
                enum_BPREQI_FIELDS fields = (enum_BPREQI_FIELDS)x[0];
                BP_REQUEST_INFO[] breakpointRequestInfo = (BP_REQUEST_INFO[])x[1];
                if (breakpointRequestInfo == null || breakpointRequestInfo.Length == 0)
                {
                    return(1);
                }
                return(BuildBreakpointRequestInfo(fields, out breakpointRequestInfo[0]));
            });
            mockLldbWatchpoint.GetId().Returns(EXPECTED_ID);
            SetBreakpointType(enum_BP_LOCATION_TYPE.BPLT_DATA_STRING);

            watchpointFactory = new DebugWatchpoint.Factory(taskContext, mockResolutionFactory,
                                                            new BreakpointErrorEnumFactory(), new BoundBreakpointEnumFactory());
            watchpoint = watchpointFactory.Create(mockBreakpointManager, mockBreakpointRequest,
                                                  mockTarget, mockProgram, mockMarshal);
        }
Ejemplo n.º 10
0
        internal static RemoteBreakpoint GetBreakpoint(
            ConcurrentDictionary <long, RemoteTarget> targetStore,
            GrpcSbBreakpoint grpcSbBreakpoint)
        {
            RemoteTarget target = null;

            if (!targetStore.TryGetValue(grpcSbBreakpoint.Target.Id, out target))
            {
                ErrorUtils.ThrowError(StatusCode.Internal,
                                      "Could not find target in store: " + grpcSbBreakpoint.Target.Id);
            }
            var breakpoint = target.FindBreakpointById(grpcSbBreakpoint.Id);

            if (breakpoint == null)
            {
                ErrorUtils.ThrowError(StatusCode.Internal,
                                      "Could not find breakpoint in target: " + grpcSbBreakpoint.Id);
            }
            return(breakpoint);
        }
        public override Task <LoadCoreResponse> LoadCore(LoadCoreRequest request,
                                                         ServerCallContext context)
        {
            RemoteTarget target   = GrpcLookupUtils.GetTarget(request.Target, _targetStore);
            SbProcess    process  = target.LoadCore(request.CorePath);
            var          response = new LoadCoreResponse();

            if (process != null)
            {
                if (!_processStore.TryAdd(process.GetUniqueId(), process))
                {
                    ErrorUtils.ThrowError(StatusCode.Internal, "Could not add process to store: " +
                                          process.GetUniqueId());
                }
                response.Process = new GrpcSbProcess {
                    Id = process.GetUniqueId()
                };
            }
            return(Task.FromResult(response));
        }
Ejemplo n.º 12
0
        public ulong GetLoadAddress(RemoteTarget target)
        {
            GetLoadAddressResponse response = null;

            if (connection.InvokeRpc(() =>
            {
                response = client.GetLoadAddress(
                    new GetLoadAddressRequest
                {
                    Section = grpcSbSection,
                    Target = new GrpcSbTarget {
                        Id = target.GetId()
                    }
                });
            }))
            {
                return(response.LoadAddress);
            }
            return(DebuggerConstants.INVALID_ADDRESS);
        }
Ejemplo n.º 13
0
        public ulong GetLoadAddress(RemoteTarget target)
        {
            GetLoadAddressResponse response = null;

            if (connection.InvokeRpc(() =>
            {
                response = client.GetLoadAddress(
                    new GetLoadAddressRequest
                {
                    Address = grpcSbAddress,
                    Target = new GrpcSbTarget {
                        Id = target.GetId()
                    }
                });
            }))
            {
                return(response.LoadAddress);
            }
            return(0);
        }
        public void SetUp()
        {
            taskContext           = new JoinableTaskContext();
            mockBreakpointRequest = Substitute.For <IDebugBreakpointRequest2>();
            mockTarget            = Substitute.For <RemoteTarget>();
            mockProgram           = Substitute.For <IGgpDebugProgram>();
            mockPendingBreakpoint = Substitute.For <IPendingBreakpoint>();
            mockPendingBreakpoint.GetId().Returns(ID);
            mockWatchpoint = Substitute.For <IWatchpoint>();
            mockWatchpoint.GetId().Returns(ID);
            mockPendingBreakpointFactory = Substitute.For <DebugPendingBreakpoint.Factory>();
            mockWatchpointFactory        = Substitute.For <DebugWatchpoint.Factory>();
            var mockDebugEngineHandler = Substitute.For <IDebugEngineHandler>();

            breakpointManager = new LldbBreakpointManager.Factory(taskContext,
                                                                  mockPendingBreakpointFactory, mockWatchpointFactory).Create(mockDebugEngineHandler,
                                                                                                                              mockProgram);

            mockPendingBreakpointFactory.Create(breakpointManager, mockProgram,
                                                mockBreakpointRequest, mockTarget).ReturnsForAnyArgs(mockPendingBreakpoint);
            mockWatchpointFactory.Create(breakpointManager, mockBreakpointRequest, mockTarget,
                                         mockProgram).ReturnsForAnyArgs(mockWatchpoint);
        }
Ejemplo n.º 15
0
 public LldbAttachedProgram(IBreakpointManager breakpointManager, IEventManager eventManager,
                            ILLDBShell lldbShell, IModuleFileLoader moduleFileLoader,
                            IDebugEngineHandler debugEngineHandler,
                            ITaskExecutor taskExecutor, IGgpDebugProgram debugProgram,
                            SbDebugger debugger, RemoteTarget target, SbProcess process,
                            IExceptionManager exceptionManager,
                            IDebugModuleCache debugModuleCache,
                            ILldbListenerSubscriber listenerSubscriber, uint remotePid)
 {
     _debugProgram       = debugProgram;
     _breakpointManager  = breakpointManager;
     _eventManager       = eventManager;
     _lldbShell          = lldbShell;
     _moduleFileLoader   = moduleFileLoader;
     _debugEngineHandler = debugEngineHandler;
     _taskExecutor       = taskExecutor;
     _debugger           = debugger;
     _target             = target;
     _process            = process;
     _exceptionManager   = exceptionManager;
     _debugModuleCache   = debugModuleCache;
     _listenerSubscriber = listenerSubscriber;
     RemotePid           = remotePid;
 }
Ejemplo n.º 16
0
 public virtual IBinaryLoader Create(RemoteTarget lldbTarget)
 {
     return(new BinaryLoader(moduleUtil, moduleFileFinder, lldbTarget));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates a SIP request.
        /// </summary>
        /// <param name="method">The SIP method (invite etc.)</param>
        /// <param name="content">The SIP body contents.</param>
        /// <param name="contentType">The type of the SIP body.</param>
        /// <returns>Message.</returns>
        public virtual Message CreateRequest(string method, string content = "", string contentType = "")
        {
            Server = false;
            if (RemoteParty == null)
            {
                Debug.Assert(false, String.Format("No remoteParty for UAC\n"));
            }
            if (LocalParty == null)
            {
                LocalParty = new Address("\"Anonymous\" <sip:[email protected]>");
            }
            //TODO: Use Remote Party instead of Remote Target?
            SIPURI uri;

            if (RemoteTarget != null)
            {
                uri = new SIPURI(RemoteTarget.ToString());
            }
            else
            {
                uri = new SIPURI(RemoteParty.ToString());
            }

            if (method == "REGISTER")
            {
                //TODO: Is this right ?
                //uri.User = "";
            }
            if ((method != "ACK") && (method != "CANCEL"))
            {
                LocalSeq = ++LocalSeq;
            }
            //TODO: Use Remote Party instead of Remote Target?
            Header to;

            if (RemoteTarget != null)
            {
                to = new Header(RemoteTarget.ToString(), "To");
            }
            else
            {
                to = new Header(RemoteParty.ToString(), "To");
            }

            Header from = new Header(LocalParty.ToString(), "From");

            from.Attributes["tag"] = LocalTag;
            Header cSeq        = new Header(LocalSeq + " " + method, "CSeq");
            Header callId      = new Header(CallID, "Call-ID");
            Header maxForwards = new Header(MaxForwards.ToString(), "Max-Forwards");
            Header via         = Stack.CreateVia();
            Dictionary <string, object> branchParams = new Dictionary <string, object>
            {
                { "To", to.Value },
                { "From", @from.Value },
                { "CallId", callId.Value },
                { "CSeq", cSeq.Number }
            };

            via.Attributes["branch"] = Transaction.CreateBranch(branchParams, false);
            if (LocalTarget == null)
            {
                LocalTarget      = Stack.Uri.Dup();
                LocalTarget.User = LocalParty.Uri.User;
            }
            Header contact = new Header(LocalTarget.ToString(), "Contact");

            Header[]      headerList = { to, from, cSeq, callId, maxForwards, via, contact };
            List <Header> headers    = headerList.ToList();

            // Check this TODO
            //
            if (RouteSet.Count != 0)
            {
                headers.AddRange(RouteSet);
            }

            //app adds other headers such as Supported, Require and Proxy-Require
            if (!string.IsNullOrEmpty(contentType))
            {
                headers.Add(new Header(contentType, "Content-Type"));
            }
            Dictionary <string, List <Header> > headerDict = new Dictionary <string, List <Header> >();

            foreach (Header h in headers)
            {
                if (headerDict.ContainsKey(h.Name))
                {
                    headerDict[h.Name].Add(h);
                }
                else
                {
                    List <Header> temp = new List <Header> {
                        h
                    };
                    headerDict.Add(h.Name, temp);
                }
            }
            Request = Message.CreateRequest(method, uri, headerDict, content);
            return(Request);
        }
Ejemplo n.º 18
0
        public static void RegisterRemote()
        {
            //if (EnviromentProvider.IsProduction)
            //{
            //    try
            //    {
            //        var exceptioneerTarget = new ExceptioneerTarget();
            //        LogManager.Configuration.AddTarget("Exceptioneer", exceptioneerTarget);
            //        LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, exceptioneerTarget));
            //    }
            //    catch (Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}

            try
            {
                var remoteTarget = new RemoteTarget();
                LogManager.Configuration.AddTarget("RemoteTarget", remoteTarget);
                LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, remoteTarget));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            LogManager.ConfigurationReloaded += (sender, args) => RegisterRemote();
        }
Ejemplo n.º 19
0
        public bool ApplyPlaceholderProperties(SbModule destModule,
                                               PlaceholderModuleProperties properties, RemoteTarget lldbTarget)
        {
            long      slide         = properties.Slide;
            SbAddress headerAddress = destModule.GetObjectFileHeaderAddress();

            if (headerAddress != null)
            {
                // For libraries this will generally equal 0, for executables it will equal
                // |placeholderBaseLoadAddress|.
                ulong fileBaseAddress = headerAddress.GetFileAddress();
                slide -= (long)fileBaseAddress;
            }

            SbError error = lldbTarget.SetModuleLoadAddress(destModule, slide);

            if (error.Fail())
            {
                Trace.WriteLine(
                    $"Failed to set load address on destination module: {error.GetCString()}.");
                return(false);
            }

            if (!destModule.SetPlatformFileSpec(properties.PlatformFileSpec))
            {
                Trace.WriteLine("Failed to set file spec on the destination module.");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 20
0
 public bool DeleteTarget(RemoteTarget target)
 {
     // Not needed as the external process shutdown will take care of cleanup.
     return(true);
 }
Ejemplo n.º 21
0
 public SbProcessStub(RemoteTarget target, string coreFileName)
 {
     this.target       = target;
     this.coreFileName = coreFileName;
     signalStub        = new SbUnixSignalsStub();
 }
Ejemplo n.º 22
0
            public ILldbAttachedProgram Create(
                IDebugProcess2 debugProcess, Guid programId, IDebugEngine2 debugEngine,
                IDebugEventCallback2 callback, SbDebugger debugger, RemoteTarget target,
                LldbListenerSubscriber listenerSubscriber, SbProcess process,
                SbCommandInterpreter commandInterpreter, bool isCoreAttach,
                IExceptionManager exceptionManager, IModuleSearchLogHolder moduleSearchLogHolder,
                uint remotePid)
            {
                // Required due to an issue triggered by the proxy used to wrap debugProgramFactory.
                // TODO: Remove assertion once the issue with Castle.DynamicProxy is
                // fixed.
                _taskContext.ThrowIfNotOnMainThread();

                var debugEngineHandler = _debugEngineHandlerFactory.Create(debugEngine, callback);

                var binaryLoader     = _binaryLoaderFactory.Create(target);
                var symbolLoader     = _symbolLoaderFactory.Create(commandInterpreter);
                var moduleFileLoader = _moduleFileLoaderFactory.Create(symbolLoader, binaryLoader,
                                                                       moduleSearchLogHolder);

                var debugModuleCache = _debugModuleCacheFactory.Create(
                    (lldbModule, loadOrder, ggpProgram) => _debugModuleFactory.Create(
                        moduleFileLoader, moduleSearchLogHolder, lldbModule, loadOrder,
                        debugEngineHandler, ggpProgram));
                var ad7FrameInfoCreator = new AD7FrameInfoCreator(debugModuleCache);

                var stackFrameCreator = new StackFramesProvider.StackFrameCreator(
                    (frame, thread, program) => _debugStackFrameCreator(
                        ad7FrameInfoCreator, frame, thread, debugEngineHandler, program));
                var threadCreator = new DebugProgram.ThreadCreator(
                    (thread, program) => _debugThreadCreatorDelegate(
                        ad7FrameInfoCreator, stackFrameCreator, thread, program));
                var debugProgram = _debugProgramFactory.Create(
                    debugEngineHandler, threadCreator, debugProcess, programId, process, target,
                    debugModuleCache, isCoreAttach);

                _taskExecutor.StartAsyncTasks(
                    ex => debugEngineHandler.Abort(debugProgram, ExitInfo.Error(ex)));

                var breakpointManager =
                    _breakpointManagerFactory.Create(debugEngineHandler, debugProgram);
                var eventManager =
                    _eventManagerFactory.Create(debugEngineHandler, breakpointManager, debugProgram,
                                                process, listenerSubscriber);

                // TODO: Listen for module load/unload events from LLDB
                binaryLoader.LldbModuleReplaced += (o, args) =>
                {
                    debugModuleCache.GetOrCreate(args.AddedModule, debugProgram);
                    debugModuleCache.Remove(args.RemovedModule);
                };
                debugModuleCache.ModuleAdded += (o, args) =>
                                                debugEngineHandler.OnModuleLoad(args.Module, debugProgram);
                debugModuleCache.ModuleRemoved += (o, args) =>
                                                  debugEngineHandler.OnModuleUnload(args.Module, debugProgram);

                return(new LldbAttachedProgram(breakpointManager, eventManager, _lldbShell,
                                               moduleFileLoader, debugEngineHandler, _taskExecutor,
                                               debugProgram, debugger, target, process,
                                               exceptionManager, debugModuleCache,
                                               listenerSubscriber, remotePid));
            }
Ejemplo n.º 23
0
        SbProcess LoadCore(RemoteTarget lldbTarget, IAction loadCoreAction)
        {
            var moduleFileLoadRecorder = _moduleFileLoadRecorderFactory.Create(loadCoreAction);

            moduleFileLoadRecorder.RecordBeforeLoad(Array.Empty <SbModule>());

            bool isFullDump = _coreFilePath.EndsWith(".core");

            if (isFullDump)
            {
                string combinedPath = _taskContext.Factory.Run(async() =>
                {
                    await _taskContext.Factory.SwitchToMainThreadAsync();
                    _symbolSettingsProvider.GetStorePaths(out string paths, out string cache);
                    return(SymbolUtils.GetCombinedLookupPaths(paths, cache));
                });

                _moduleFileFinder.SetSearchPaths(combinedPath);

                TextWriter     searchLog = new StringWriter();
                DumpReadResult dump      = _dumpModulesProvider.GetModules(_coreFilePath);

                DumpModule[] executableModules =
                    dump.Modules.Where(module => module.IsExecutable).ToArray();
                DumpModule[] nonExecutableModules =
                    dump.Modules.Where(module => !module.IsExecutable).ToArray();

                // We should not pre-load non executable modules if there wasn't any successfully
                // loaded executable modules. Otherwise lldb will not upgrade image list during the
                // attachment to the core dump and will try to resolve the executable on the
                // developer machine. See (internal)
                if (executableModules.Any() &&
                    executableModules.All(module =>
                                          TryPreloadModule(lldbTarget, searchLog, module)))
                {
                    foreach (DumpModule module in nonExecutableModules)
                    {
                        TryPreloadModule(lldbTarget, searchLog, module);
                    }
                }

                if (dump.Warning == DumpReadWarning.None && !executableModules.Any())
                {
                    dump.Warning = DumpReadWarning.ExecutableBuildIdMissing;
                }
                if (dump.Warning != DumpReadWarning.None)
                {
                    var shouldAttach = _taskContext.Factory.Run(
                        async() => await _warningDialog.ShouldAttachToIncosistentCoreFileAsync(
                            dump.Warning));
                    if (!shouldAttach)
                    {
                        throw new CoreAttachStoppedException();
                    }
                }
            }

            SbProcess lldbDebuggerProcess = lldbTarget.LoadCore(_coreFilePath);

            if (lldbDebuggerProcess == null)
            {
                throw new AttachException(VSConstants.E_ABORT,
                                          ErrorStrings.FailedToLoadCore(_coreFilePath));
            }

            RecordModules(lldbTarget, moduleFileLoadRecorder);
            return(lldbDebuggerProcess);
        }
Ejemplo n.º 24
0
        public async Task <ILldbAttachedProgram> LaunchAsync(
            ICancelable task, IDebugProcess2 process, Guid programId, uint?attachPid,
            DebuggerOptions.DebuggerOptions debuggerOptions, HashSet <string> libPaths,
            GrpcConnection grpcConnection, int localDebuggerPort, string targetIpAddress,
            int targetPort, IDebugEventCallback2 callback)
        {
            var       launchSucceeded = false;
            Stopwatch launchTimer     = Stopwatch.StartNew();


            // This should be the first request to the DebuggerGrpcServer.  Providing a retry wait
            // time allows us to connect to a DebuggerGrpcServer that is slow to start. Note that
            // we postpone sourcing .lldbinit until we are done with our initialization so that
            // the users can override our defaults.
            var lldbDebugger =
                _lldbDebuggerFactory.Create(grpcConnection, false, TimeSpan.FromSeconds(10));

            if (lldbDebugger == null)
            {
                throw new AttachException(VSConstants.E_ABORT, ErrorStrings.FailedToCreateDebugger);
            }

            if (debuggerOptions[DebuggerOption.CLIENT_LOGGING] == DebuggerOptionState.ENABLED)
            {
                lldbDebugger.EnableLog("lldb", new List <string> {
                    "default", "module"
                });

                // TODO: Disable 'dwarf' logs until we can determine why this
                // causes LLDB to hang.
                // lldbDebugger.EnableLog("dwarf", new List<string> { "default" });
            }

            if (_fastExpressionEvaluation)
            {
                lldbDebugger.EnableFastExpressionEvaluation();
            }

            lldbDebugger.SetDefaultLLDBSettings();

            // Apply .lldbinit after we set our settings so that the user can override our
            // defaults with a custom .lldbinit.
            LoadLocalLldbInit(lldbDebugger);

            // Add exec search paths, so that LLDB can find the executable and any dependent
            // libraries.  If LLDB is able to find the files locally, it won't try to download
            // them from the remote server, saving valuable time on attach.
            foreach (string path in libPaths)
            {
                lldbDebugger.SetLibrarySearchPath(path);
            }

            lldbDebugger.SetAsync(true);

            SbPlatform lldbPlatform;

            switch (_launchOption)
            {
            case LaunchOption.AttachToGame:
            // Fall through.
            case LaunchOption.LaunchGame:
                lldbPlatform = CreateRemotePlatform(grpcConnection, lldbDebugger);
                if (lldbPlatform == null)
                {
                    throw new AttachException(VSConstants.E_FAIL,
                                              ErrorStrings.FailedToCreateLldbPlatform);
                }
                task.ThrowIfCancellationRequested();
                Trace.WriteLine("Attempting to connect debugger");
                task.Progress.Report("Connecting to debugger");

                string connectRemoteUrl      = $"{_lldbConnectUrl}:{localDebuggerPort}";
                string connectRemoteArgument =
                    CreateConnectRemoteArgument(connectRemoteUrl, targetIpAddress, targetPort);

                SbPlatformConnectOptions lldbConnectOptions =
                    _lldbPlatformConnectOptionsFactory.Create(connectRemoteArgument);

                IAction debugerWaitAction =
                    _actionRecorder.CreateToolAction(ActionType.DebugWaitDebugger);

                bool TryConnectRemote()
                {
                    if (lldbPlatform.ConnectRemote(lldbConnectOptions).Success())
                    {
                        return(true);
                    }

                    VerifyGameIsReady(debugerWaitAction);
                    return(false);
                }

                try
                {
                    debugerWaitAction.Record(() => RetryWithTimeout(
                                                 task, TryConnectRemote, _launchRetryDelay,
                                                 _launchTimeout, launchTimer));
                }
                catch (TimeoutException e)
                {
                    throw new AttachException(
                              VSConstants.E_ABORT,
                              ErrorStrings.FailedToConnectDebugger(lldbConnectOptions.GetUrl()), e);
                }
                Trace.WriteLine("LLDB successfully connected");
                break;

            case LaunchOption.AttachToCore:
                lldbPlatform = _lldbPlatformFactory.Create(_localLldbPlatformName, grpcConnection);
                if (lldbPlatform == null)
                {
                    throw new AttachException(VSConstants.E_FAIL,
                                              ErrorStrings.FailedToCreateLldbPlatform);
                }
                break;

            default:
                throw new AttachException(VSConstants.E_ABORT, ErrorStrings.InvalidLaunchOption(
                                              _launchOption.ToString()));
            }

            lldbDebugger.SetSelectedPlatform(lldbPlatform);

            task.ThrowIfCancellationRequested();
            task.Progress.Report("Debugger is attaching (this can take a while)");

            RemoteTarget lldbTarget = null;

            if (_launchOption == LaunchOption.LaunchGame &&
                !string.IsNullOrEmpty(_executableFullPath))
            {
                var createExecutableTargetAction =
                    _actionRecorder.CreateToolAction(ActionType.DebugCreateExecutableTarget);
                createExecutableTargetAction.Record(
                    () => lldbTarget = CreateTarget(lldbDebugger, _executableFullPath));
            }
            else
            {
                lldbTarget = CreateTarget(lldbDebugger, "");
            }

            var lldbListener = CreateListener(grpcConnection);

            // This is required to catch breakpoint change events.
            lldbTarget.AddListener(lldbListener, EventType.STATE_CHANGED);
            var listenerSubscriber = new LldbListenerSubscriber(lldbListener);
            var eventHandler       = new EventHandler <FileUpdateReceivedEventArgs>(
                (s, e) => ListenerSubscriberOnFileUpdateReceived(task, e));

            listenerSubscriber.FileUpdateReceived += eventHandler;
            listenerSubscriber.Start();

            try
            {
                if (_launchOption == LaunchOption.AttachToCore)
                {
                    var       loadCoreAction      = _actionRecorder.CreateToolAction(ActionType.DebugLoadCore);
                    SbProcess lldbDebuggerProcess = null;
                    loadCoreAction.Record(() =>
                                          lldbDebuggerProcess = LoadCore(lldbTarget, loadCoreAction));

                    await _taskContext.Factory.SwitchToMainThreadAsync();

                    return(_attachedProgramFactory.Create(
                               process, programId, _debugEngine, callback, lldbDebugger, lldbTarget,
                               listenerSubscriber, lldbDebuggerProcess,
                               lldbDebugger.GetCommandInterpreter(), true, new NullExceptionManager(),
                               _moduleSearchLogHolder, remotePid: 0));
                }

                // Get process ID.
                uint processId = 0;
                switch (_launchOption)
                {
                case LaunchOption.AttachToGame:
                    if (!attachPid.HasValue)
                    {
                        throw new AttachException(VSConstants.E_ABORT,
                                                  ErrorStrings.FailedToRetrieveProcessId);
                    }

                    processId = attachPid.Value;
                    break;

                case LaunchOption.LaunchGame:
                    // Since we have no way of knowing when the remote process actually
                    // starts, try a few times to get the pid.

                    IAction debugWaitAction =
                        _actionRecorder.CreateToolAction(ActionType.DebugWaitProcess);

                    bool TryGetRemoteProcessId()
                    {
                        if (GetRemoteProcessId(_executableFileName, lldbPlatform, out processId))
                        {
                            return(true);
                        }

                        VerifyGameIsReady(debugWaitAction);
                        return(false);
                    }

                    try
                    {
                        debugWaitAction.Record(() => RetryWithTimeout(
                                                   task, TryGetRemoteProcessId, _launchRetryDelay,
                                                   _launchTimeout, launchTimer));
                    }
                    catch (TimeoutException e)
                    {
                        throw new AttachException(VSConstants.E_ABORT,
                                                  ErrorStrings.FailedToRetrieveProcessId, e);
                    }

                    break;
                }

                Trace.WriteLine("Attaching to pid " + processId);
                var debugAttachAction = _actionRecorder.CreateToolAction(ActionType.DebugAttach);

                SbProcess debuggerProcess = null;
                debugAttachAction.Record(() => {
                    var moduleFileLoadRecorder =
                        _moduleFileLoadRecorderFactory.Create(debugAttachAction);
                    moduleFileLoadRecorder.RecordBeforeLoad(Array.Empty <SbModule>());

                    debuggerProcess = lldbTarget.AttachToProcessWithID(lldbListener, processId,
                                                                       out SbError lldbError);
                    if (lldbError.Fail())
                    {
                        throw new AttachException(
                            VSConstants.E_ABORT,
                            GetLldbAttachErrorDetails(lldbError, lldbPlatform, processId));
                    }

                    RecordModules(lldbTarget, moduleFileLoadRecorder);
                });

                var exceptionManager = _exceptionManagerFactory.Create(debuggerProcess);

                await _taskContext.Factory.SwitchToMainThreadAsync();

                ILldbAttachedProgram attachedProgram = _attachedProgramFactory.Create(
                    process, programId, _debugEngine, callback, lldbDebugger, lldbTarget,
                    listenerSubscriber, debuggerProcess, lldbDebugger.GetCommandInterpreter(),
                    false, exceptionManager, _moduleSearchLogHolder, processId);
                launchSucceeded = true;
                return(attachedProgram);
            }
            finally
            {
                // clean up the SBListener subscriber
                listenerSubscriber.FileUpdateReceived -= eventHandler;
                // stop the SBListener subscriber completely if the game failed to launch
                if (!launchSucceeded)
                {
                    listenerSubscriber.Stop();
                }
            }
        }
Ejemplo n.º 25
0
 public bool DeleteTarget(RemoteTarget target)
 => targets.Remove(target);