1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <string.h>
15af245d11STodd Fiala #include <stdint.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
27af245d11STodd Fiala #include "lldb/Core/Error.h"
28af245d11STodd Fiala #include "lldb/Core/Module.h"
296edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
30af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
31af245d11STodd Fiala #include "lldb/Core/State.h"
321e209fccSTamas Berghammer #include "lldb/Host/common/NativeBreakpoint.h"
330cbf0b13STamas Berghammer #include "lldb/Host/common/NativeRegisterContext.h"
34af245d11STodd Fiala #include "lldb/Host/Host.h"
3539de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
365b981ab9SPavel Labath #include "lldb/Target/Platform.h"
3790aff47cSZachary Turner #include "lldb/Target/Process.h"
38af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
395b981ab9SPavel Labath #include "lldb/Target/Target.h"
40c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
41af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
42f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
43af245d11STodd Fiala 
441e209fccSTamas Berghammer #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
45af245d11STodd Fiala #include "NativeThreadLinux.h"
46af245d11STodd Fiala #include "ProcFileReader.h"
471e209fccSTamas Berghammer #include "Procfs.h"
48cacde7dfSTodd Fiala 
49d858487eSTamas Berghammer // System includes - They have to be included after framework includes because they define some
50d858487eSTamas Berghammer // macros which collide with variable names in other modules
51d858487eSTamas Berghammer #include <linux/unistd.h>
52d858487eSTamas Berghammer #include <sys/socket.h>
538b335671SVince Harron 
54df7c6995SPavel Labath #include <sys/syscall.h>
55d858487eSTamas Berghammer #include <sys/types.h>
56d858487eSTamas Berghammer #include <sys/user.h>
57d858487eSTamas Berghammer #include <sys/wait.h>
58d858487eSTamas Berghammer 
598b335671SVince Harron #include "lldb/Host/linux/Personality.h"
608b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
61df7c6995SPavel Labath #include "lldb/Host/linux/Uio.h"
628b335671SVince Harron #include "lldb/Host/android/Android.h"
63af245d11STodd Fiala 
640bce1b67STodd Fiala #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
65af245d11STodd Fiala 
66af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
67af245d11STodd Fiala #ifndef TRAP_HWBKPT
68af245d11STodd Fiala   #define TRAP_HWBKPT 4
69af245d11STodd Fiala #endif
70af245d11STodd Fiala 
717cb18bf5STamas Berghammer using namespace lldb;
727cb18bf5STamas Berghammer using namespace lldb_private;
73db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
747cb18bf5STamas Berghammer using namespace llvm;
757cb18bf5STamas Berghammer 
76af245d11STodd Fiala // Private bits we only need internally.
77df7c6995SPavel Labath 
78df7c6995SPavel Labath static bool ProcessVmReadvSupported()
79df7c6995SPavel Labath {
80df7c6995SPavel Labath     static bool is_supported;
81df7c6995SPavel Labath     static std::once_flag flag;
82df7c6995SPavel Labath 
83df7c6995SPavel Labath     std::call_once(flag, [] {
84df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
85df7c6995SPavel Labath 
86df7c6995SPavel Labath         uint32_t source = 0x47424742;
87df7c6995SPavel Labath         uint32_t dest = 0;
88df7c6995SPavel Labath 
89df7c6995SPavel Labath         struct iovec local, remote;
90df7c6995SPavel Labath         remote.iov_base = &source;
91df7c6995SPavel Labath         local.iov_base = &dest;
92df7c6995SPavel Labath         remote.iov_len = local.iov_len = sizeof source;
93df7c6995SPavel Labath 
94df7c6995SPavel Labath         // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
95df7c6995SPavel Labath         ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
96df7c6995SPavel Labath         is_supported = (res == sizeof(source) && source == dest);
97df7c6995SPavel Labath         if (log)
98df7c6995SPavel Labath         {
99df7c6995SPavel Labath             if (is_supported)
100df7c6995SPavel Labath                 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
101df7c6995SPavel Labath                         __FUNCTION__);
102df7c6995SPavel Labath             else
103df7c6995SPavel Labath                 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
104df7c6995SPavel Labath                         __FUNCTION__, strerror(errno));
105df7c6995SPavel Labath         }
106df7c6995SPavel Labath     });
107df7c6995SPavel Labath 
108df7c6995SPavel Labath     return is_supported;
109df7c6995SPavel Labath }
110df7c6995SPavel Labath 
111af245d11STodd Fiala namespace
112af245d11STodd Fiala {
113af245d11STodd Fiala     Error
114af245d11STodd Fiala     ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
115af245d11STodd Fiala     {
116af245d11STodd Fiala         // Grab process info for the running process.
117af245d11STodd Fiala         ProcessInstanceInfo process_info;
118af245d11STodd Fiala         if (!platform.GetProcessInfo (pid, process_info))
119db264a6dSTamas Berghammer             return Error("failed to get process info");
120af245d11STodd Fiala 
121af245d11STodd Fiala         // Resolve the executable module.
122af245d11STodd Fiala         ModuleSP exe_module_sp;
123e56f6dceSChaoren Lin         ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
124af245d11STodd Fiala         FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
125af245d11STodd Fiala         Error error = platform.ResolveExecutable(
12654539338SOleksiy Vyalov             exe_module_spec,
127af245d11STodd Fiala             exe_module_sp,
128af245d11STodd Fiala             executable_search_paths.GetSize () ? &executable_search_paths : NULL);
129af245d11STodd Fiala 
130af245d11STodd Fiala         if (!error.Success ())
131af245d11STodd Fiala             return error;
132af245d11STodd Fiala 
133af245d11STodd Fiala         // Check if we've got our architecture from the exe_module.
134af245d11STodd Fiala         arch = exe_module_sp->GetArchitecture ();
135af245d11STodd Fiala         if (arch.IsValid ())
136af245d11STodd Fiala             return Error();
137af245d11STodd Fiala         else
138af245d11STodd Fiala             return Error("failed to retrieve a valid architecture from the exe module");
139af245d11STodd Fiala     }
140af245d11STodd Fiala 
141af245d11STodd Fiala     void
142db264a6dSTamas Berghammer     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
143af245d11STodd Fiala     {
144af245d11STodd Fiala         uint8_t *ptr = (uint8_t *)bytes;
145af245d11STodd Fiala         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
146af245d11STodd Fiala         for(uint32_t i=0; i<loop_count; i++)
147af245d11STodd Fiala         {
148af245d11STodd Fiala             s.Printf ("[%x]", *ptr);
149af245d11STodd Fiala             ptr++;
150af245d11STodd Fiala         }
151af245d11STodd Fiala     }
152af245d11STodd Fiala 
153af245d11STodd Fiala     void
154af245d11STodd Fiala     PtraceDisplayBytes(int &req, void *data, size_t data_size)
155af245d11STodd Fiala     {
156af245d11STodd Fiala         StreamString buf;
157af245d11STodd Fiala         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
158af245d11STodd Fiala                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
159af245d11STodd Fiala 
160af245d11STodd Fiala         if (verbose_log)
161af245d11STodd Fiala         {
162af245d11STodd Fiala             switch(req)
163af245d11STodd Fiala             {
164af245d11STodd Fiala             case PTRACE_POKETEXT:
165af245d11STodd Fiala             {
166af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
167af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
168af245d11STodd Fiala                 break;
169af245d11STodd Fiala             }
170af245d11STodd Fiala             case PTRACE_POKEDATA:
171af245d11STodd Fiala             {
172af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
173af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
174af245d11STodd Fiala                 break;
175af245d11STodd Fiala             }
176af245d11STodd Fiala             case PTRACE_POKEUSER:
177af245d11STodd Fiala             {
178af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
179af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
180af245d11STodd Fiala                 break;
181af245d11STodd Fiala             }
182af245d11STodd Fiala             case PTRACE_SETREGS:
183af245d11STodd Fiala             {
184af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
185af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
186af245d11STodd Fiala                 break;
187af245d11STodd Fiala             }
188af245d11STodd Fiala             case PTRACE_SETFPREGS:
189af245d11STodd Fiala             {
190af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
191af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
192af245d11STodd Fiala                 break;
193af245d11STodd Fiala             }
194af245d11STodd Fiala             case PTRACE_SETSIGINFO:
195af245d11STodd Fiala             {
196af245d11STodd Fiala                 DisplayBytes(buf, data, sizeof(siginfo_t));
197af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
198af245d11STodd Fiala                 break;
199af245d11STodd Fiala             }
200af245d11STodd Fiala             case PTRACE_SETREGSET:
201af245d11STodd Fiala             {
202af245d11STodd Fiala                 // Extract iov_base from data, which is a pointer to the struct IOVEC
203af245d11STodd Fiala                 DisplayBytes(buf, *(void **)data, data_size);
204af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
205af245d11STodd Fiala                 break;
206af245d11STodd Fiala             }
207af245d11STodd Fiala             default:
208af245d11STodd Fiala             {
209af245d11STodd Fiala             }
210af245d11STodd Fiala             }
211af245d11STodd Fiala         }
212af245d11STodd Fiala     }
213af245d11STodd Fiala 
21419cbe96aSPavel Labath     static constexpr unsigned k_ptrace_word_size = sizeof(void*);
21519cbe96aSPavel Labath     static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
2161107b5a5SPavel Labath } // end of anonymous namespace
2171107b5a5SPavel Labath 
218bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
219bd7cbc5aSPavel Labath // descriptor.
220bd7cbc5aSPavel Labath static Error
221bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
222bd7cbc5aSPavel Labath {
223bd7cbc5aSPavel Labath     Error error;
224bd7cbc5aSPavel Labath 
225bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
226bd7cbc5aSPavel Labath     if (status == -1)
227bd7cbc5aSPavel Labath     {
228bd7cbc5aSPavel Labath         error.SetErrorToErrno();
229bd7cbc5aSPavel Labath         return error;
230bd7cbc5aSPavel Labath     }
231bd7cbc5aSPavel Labath 
232bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
233bd7cbc5aSPavel Labath     {
234bd7cbc5aSPavel Labath         error.SetErrorToErrno();
235bd7cbc5aSPavel Labath         return error;
236bd7cbc5aSPavel Labath     }
237bd7cbc5aSPavel Labath 
238bd7cbc5aSPavel Labath     return error;
239bd7cbc5aSPavel Labath }
240bd7cbc5aSPavel Labath 
241bd7cbc5aSPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
242af245d11STodd Fiala                                        char const **argv,
243af245d11STodd Fiala                                        char const **envp,
244d3173f34SChaoren Lin                                        const FileSpec &stdin_file_spec,
245d3173f34SChaoren Lin                                        const FileSpec &stdout_file_spec,
246d3173f34SChaoren Lin                                        const FileSpec &stderr_file_spec,
247d3173f34SChaoren Lin                                        const FileSpec &working_dir,
248db264a6dSTamas Berghammer                                        const ProcessLaunchInfo &launch_info)
249bd7cbc5aSPavel Labath     : m_module(module),
250af245d11STodd Fiala       m_argv(argv),
251af245d11STodd Fiala       m_envp(envp),
252d3173f34SChaoren Lin       m_stdin_file_spec(stdin_file_spec),
253d3173f34SChaoren Lin       m_stdout_file_spec(stdout_file_spec),
254d3173f34SChaoren Lin       m_stderr_file_spec(stderr_file_spec),
2550bce1b67STodd Fiala       m_working_dir(working_dir),
2560bce1b67STodd Fiala       m_launch_info(launch_info)
2570bce1b67STodd Fiala {
2580bce1b67STodd Fiala }
259af245d11STodd Fiala 
260af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
261af245d11STodd Fiala { }
262af245d11STodd Fiala 
263af245d11STodd Fiala // -----------------------------------------------------------------------------
264af245d11STodd Fiala // Public Static Methods
265af245d11STodd Fiala // -----------------------------------------------------------------------------
266af245d11STodd Fiala 
267db264a6dSTamas Berghammer Error
268d5b310f2SPavel Labath NativeProcessProtocol::Launch (
269db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
270db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
27119cbe96aSPavel Labath     MainLoop &mainloop,
272af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
273af245d11STodd Fiala {
274af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
275af245d11STodd Fiala 
276d5b310f2SPavel Labath     lldb::ModuleSP exe_module_sp;
277d5b310f2SPavel Labath     PlatformSP platform_sp (Platform::GetHostPlatform ());
278d5b310f2SPavel Labath     Error error = platform_sp->ResolveExecutable(
279d5b310f2SPavel Labath             ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
280d5b310f2SPavel Labath             exe_module_sp,
281d5b310f2SPavel Labath             nullptr);
282d5b310f2SPavel Labath 
283d5b310f2SPavel Labath     if (! error.Success())
284d5b310f2SPavel Labath         return error;
285af245d11STodd Fiala 
286af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
287d3173f34SChaoren Lin     FileSpec working_dir{launch_info.GetWorkingDirectory()};
288d3173f34SChaoren Lin     if (working_dir &&
289d3173f34SChaoren Lin             (!working_dir.ResolvePath() ||
290d3173f34SChaoren Lin              working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
291af245d11STodd Fiala     {
292d3173f34SChaoren Lin         error.SetErrorStringWithFormat ("No such file or directory: %s",
293d3173f34SChaoren Lin                 working_dir.GetCString());
294af245d11STodd Fiala         return error;
295af245d11STodd Fiala     }
296af245d11STodd Fiala 
297db264a6dSTamas Berghammer     const FileAction *file_action;
298af245d11STodd Fiala 
299d3173f34SChaoren Lin     // Default of empty will mean to use existing open file descriptors.
300d3173f34SChaoren Lin     FileSpec stdin_file_spec{};
301d3173f34SChaoren Lin     FileSpec stdout_file_spec{};
302d3173f34SChaoren Lin     FileSpec stderr_file_spec{};
303af245d11STodd Fiala 
304af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
30575f47c3aSTodd Fiala     if (file_action)
306d3173f34SChaoren Lin         stdin_file_spec = file_action->GetFileSpec();
307af245d11STodd Fiala 
308af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
30975f47c3aSTodd Fiala     if (file_action)
310d3173f34SChaoren Lin         stdout_file_spec = file_action->GetFileSpec();
311af245d11STodd Fiala 
312af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
31375f47c3aSTodd Fiala     if (file_action)
314d3173f34SChaoren Lin         stderr_file_spec = file_action->GetFileSpec();
31575f47c3aSTodd Fiala 
31675f47c3aSTodd Fiala     if (log)
31775f47c3aSTodd Fiala     {
318d3173f34SChaoren Lin         if (stdin_file_spec)
319d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
320d3173f34SChaoren Lin                     __FUNCTION__, stdin_file_spec.GetCString());
32175f47c3aSTodd Fiala         else
32275f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
32375f47c3aSTodd Fiala 
324d3173f34SChaoren Lin         if (stdout_file_spec)
325d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
326d3173f34SChaoren Lin                     __FUNCTION__, stdout_file_spec.GetCString());
32775f47c3aSTodd Fiala         else
32875f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
32975f47c3aSTodd Fiala 
330d3173f34SChaoren Lin         if (stderr_file_spec)
331d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
332d3173f34SChaoren Lin                     __FUNCTION__, stderr_file_spec.GetCString());
33375f47c3aSTodd Fiala         else
33475f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
33575f47c3aSTodd Fiala     }
336af245d11STodd Fiala 
337af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
338af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
339af245d11STodd Fiala 
340af245d11STodd Fiala     if (log)
341af245d11STodd Fiala     {
342af245d11STodd Fiala         int i = 0;
343af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
344af245d11STodd Fiala         {
345af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
346af245d11STodd Fiala             ++i;
347af245d11STodd Fiala         }
348af245d11STodd Fiala     }
349af245d11STodd Fiala 
350af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
351af245d11STodd Fiala     {
352af245d11STodd Fiala         native_process_sp.reset ();
353af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
354af245d11STodd Fiala         return error;
355af245d11STodd Fiala     }
356af245d11STodd Fiala 
357cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
35819cbe96aSPavel Labath             mainloop,
359d5b310f2SPavel Labath             exe_module_sp.get(),
360af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
361af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
362d3173f34SChaoren Lin             stdin_file_spec,
363d3173f34SChaoren Lin             stdout_file_spec,
364d3173f34SChaoren Lin             stderr_file_spec,
365af245d11STodd Fiala             working_dir,
3660bce1b67STodd Fiala             launch_info,
367af245d11STodd Fiala             error);
368af245d11STodd Fiala 
369af245d11STodd Fiala     if (error.Fail ())
370af245d11STodd Fiala     {
371af245d11STodd Fiala         native_process_sp.reset ();
372af245d11STodd Fiala         if (log)
373af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
374af245d11STodd Fiala         return error;
375af245d11STodd Fiala     }
376af245d11STodd Fiala 
377af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
378af245d11STodd Fiala 
379af245d11STodd Fiala     return error;
380af245d11STodd Fiala }
381af245d11STodd Fiala 
382db264a6dSTamas Berghammer Error
383d5b310f2SPavel Labath NativeProcessProtocol::Attach (
384af245d11STodd Fiala     lldb::pid_t pid,
385db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
38619cbe96aSPavel Labath     MainLoop &mainloop,
387af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
388af245d11STodd Fiala {
389af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
390af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
391af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
392af245d11STodd Fiala 
393af245d11STodd Fiala     // Grab the current platform architecture.  This should be Linux,
394af245d11STodd Fiala     // since this code is only intended to run on a Linux host.
395615eb7e6SGreg Clayton     PlatformSP platform_sp (Platform::GetHostPlatform ());
396af245d11STodd Fiala     if (!platform_sp)
397af245d11STodd Fiala         return Error("failed to get a valid default platform");
398af245d11STodd Fiala 
399af245d11STodd Fiala     // Retrieve the architecture for the running process.
400af245d11STodd Fiala     ArchSpec process_arch;
401af245d11STodd Fiala     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
402af245d11STodd Fiala     if (!error.Success ())
403af245d11STodd Fiala         return error;
404af245d11STodd Fiala 
4051339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
406af245d11STodd Fiala 
4071339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
408af245d11STodd Fiala     {
409af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
410af245d11STodd Fiala         return error;
411af245d11STodd Fiala     }
412af245d11STodd Fiala 
41319cbe96aSPavel Labath     native_process_linux_sp->AttachToInferior (mainloop, pid, error);
414af245d11STodd Fiala     if (!error.Success ())
415af245d11STodd Fiala         return error;
416af245d11STodd Fiala 
4171339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
418af245d11STodd Fiala     return error;
419af245d11STodd Fiala }
420af245d11STodd Fiala 
421af245d11STodd Fiala // -----------------------------------------------------------------------------
422af245d11STodd Fiala // Public Instance Methods
423af245d11STodd Fiala // -----------------------------------------------------------------------------
424af245d11STodd Fiala 
425af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
426af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
427af245d11STodd Fiala     m_arch (),
428af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
429af245d11STodd Fiala     m_mem_region_cache (),
4300e1d729bSPavel Labath     m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
431af245d11STodd Fiala {
432af245d11STodd Fiala }
433af245d11STodd Fiala 
434af245d11STodd Fiala void
435af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
43619cbe96aSPavel Labath     MainLoop &mainloop,
437af245d11STodd Fiala     Module *module,
438af245d11STodd Fiala     const char *argv[],
439af245d11STodd Fiala     const char *envp[],
440d3173f34SChaoren Lin     const FileSpec &stdin_file_spec,
441d3173f34SChaoren Lin     const FileSpec &stdout_file_spec,
442d3173f34SChaoren Lin     const FileSpec &stderr_file_spec,
443d3173f34SChaoren Lin     const FileSpec &working_dir,
444db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
445db264a6dSTamas Berghammer     Error &error)
446af245d11STodd Fiala {
44719cbe96aSPavel Labath     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
44819cbe96aSPavel Labath             [this] (MainLoopBase &) { SigchldHandler(); }, error);
44919cbe96aSPavel Labath     if (! m_sigchld_handle)
45019cbe96aSPavel Labath         return;
45119cbe96aSPavel Labath 
452af245d11STodd Fiala     if (module)
453af245d11STodd Fiala         m_arch = module->GetArchitecture ();
454af245d11STodd Fiala 
455af245d11STodd Fiala     SetState (eStateLaunching);
456af245d11STodd Fiala 
457af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
458d3173f34SChaoren Lin         new LaunchArgs(module, argv, envp,
459d3173f34SChaoren Lin                        stdin_file_spec,
460d3173f34SChaoren Lin                        stdout_file_spec,
461d3173f34SChaoren Lin                        stderr_file_spec,
462d3173f34SChaoren Lin                        working_dir,
463d3173f34SChaoren Lin                        launch_info));
464af245d11STodd Fiala 
46519cbe96aSPavel Labath     Launch(args.get(), error);
466af245d11STodd Fiala }
467af245d11STodd Fiala 
468af245d11STodd Fiala void
46919cbe96aSPavel Labath NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
470af245d11STodd Fiala {
471af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
472af245d11STodd Fiala     if (log)
473af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
474af245d11STodd Fiala 
47519cbe96aSPavel Labath     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
47619cbe96aSPavel Labath             [this] (MainLoopBase &) { SigchldHandler(); }, error);
47719cbe96aSPavel Labath     if (! m_sigchld_handle)
47819cbe96aSPavel Labath         return;
47919cbe96aSPavel Labath 
480af245d11STodd Fiala     // We can use the Host for everything except the ResolveExecutable portion.
481615eb7e6SGreg Clayton     PlatformSP platform_sp = Platform::GetHostPlatform ();
482af245d11STodd Fiala     if (!platform_sp)
483af245d11STodd Fiala     {
484af245d11STodd Fiala         if (log)
485af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
486af245d11STodd Fiala         error.SetErrorString ("no default platform available");
48750d60be3SShawn Best         return;
488af245d11STodd Fiala     }
489af245d11STodd Fiala 
490af245d11STodd Fiala     // Gather info about the process.
491af245d11STodd Fiala     ProcessInstanceInfo process_info;
49250d60be3SShawn Best     if (!platform_sp->GetProcessInfo (pid, process_info))
49350d60be3SShawn Best     {
49450d60be3SShawn Best         if (log)
49550d60be3SShawn Best             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
49650d60be3SShawn Best         error.SetErrorString ("failed to get process info");
49750d60be3SShawn Best         return;
49850d60be3SShawn Best     }
499af245d11STodd Fiala 
500af245d11STodd Fiala     // Resolve the executable module
501af245d11STodd Fiala     ModuleSP exe_module_sp;
502af245d11STodd Fiala     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
503e56f6dceSChaoren Lin     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
5046edef204SOleksiy Vyalov     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
505af245d11STodd Fiala                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
506af245d11STodd Fiala     if (!error.Success())
507af245d11STodd Fiala         return;
508af245d11STodd Fiala 
509af245d11STodd Fiala     // Set the architecture to the exe architecture.
510af245d11STodd Fiala     m_arch = exe_module_sp->GetArchitecture();
511af245d11STodd Fiala     if (log)
512af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
513af245d11STodd Fiala 
514af245d11STodd Fiala     m_pid = pid;
515af245d11STodd Fiala     SetState(eStateAttaching);
516af245d11STodd Fiala 
51719cbe96aSPavel Labath     Attach(pid, error);
518af245d11STodd Fiala }
519af245d11STodd Fiala 
520bd7cbc5aSPavel Labath ::pid_t
521bd7cbc5aSPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
522af245d11STodd Fiala {
5230bce1b67STodd Fiala     assert (args && "null args");
524af245d11STodd Fiala 
525af245d11STodd Fiala     const char **argv = args->m_argv;
526af245d11STodd Fiala     const char **envp = args->m_envp;
527d3173f34SChaoren Lin     const FileSpec working_dir = args->m_working_dir;
528af245d11STodd Fiala 
529af245d11STodd Fiala     lldb_utility::PseudoTerminal terminal;
530af245d11STodd Fiala     const size_t err_len = 1024;
531af245d11STodd Fiala     char err_str[err_len];
532af245d11STodd Fiala     lldb::pid_t pid;
533af245d11STodd Fiala 
534af245d11STodd Fiala     // Propagate the environment if one is not supplied.
535af245d11STodd Fiala     if (envp == NULL || envp[0] == NULL)
536af245d11STodd Fiala         envp = const_cast<const char **>(environ);
537af245d11STodd Fiala 
538af245d11STodd Fiala     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
539af245d11STodd Fiala     {
540bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
541bd7cbc5aSPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
542bd7cbc5aSPavel Labath         return -1;
543af245d11STodd Fiala     }
544af245d11STodd Fiala 
545af245d11STodd Fiala     // Recognized child exit status codes.
546af245d11STodd Fiala     enum {
547af245d11STodd Fiala         ePtraceFailed = 1,
548af245d11STodd Fiala         eDupStdinFailed,
549af245d11STodd Fiala         eDupStdoutFailed,
550af245d11STodd Fiala         eDupStderrFailed,
551af245d11STodd Fiala         eChdirFailed,
552af245d11STodd Fiala         eExecFailed,
55378856474SPavel Labath         eSetGidFailed,
55478856474SPavel Labath         eSetSigMaskFailed
555af245d11STodd Fiala     };
556af245d11STodd Fiala 
557af245d11STodd Fiala     // Child process.
558af245d11STodd Fiala     if (pid == 0)
559af245d11STodd Fiala     {
560d2c4c9b1SPavel Labath         // First, make sure we disable all logging. If we are logging to stdout, our logs can be
561d2c4c9b1SPavel Labath         // mistaken for inferior output.
562d2c4c9b1SPavel Labath         Log::DisableAllLogChannels(nullptr);
56375f47c3aSTodd Fiala         // FIXME consider opening a pipe between parent/child and have this forked child
564d2c4c9b1SPavel Labath         // send log info to parent re: launch status.
565af245d11STodd Fiala 
56675f47c3aSTodd Fiala         // Start tracing this child that is about to exec.
5674a9babb2SPavel Labath         error = PtraceWrapper(PTRACE_TRACEME, 0);
568bd7cbc5aSPavel Labath         if (error.Fail())
569af245d11STodd Fiala             exit(ePtraceFailed);
570af245d11STodd Fiala 
571493c3a12SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
572493c3a12SPavel Labath         // This closes original fd from which they were copied (and avoids
573493c3a12SPavel Labath         // leaking descriptors to the debugged process.
574493c3a12SPavel Labath         terminal.CloseSlaveFileDescriptor();
575493c3a12SPavel Labath 
576af245d11STodd Fiala         // Do not inherit setgid powers.
577af245d11STodd Fiala         if (setgid(getgid()) != 0)
578af245d11STodd Fiala             exit(eSetGidFailed);
579af245d11STodd Fiala 
580af245d11STodd Fiala         // Attempt to have our own process group.
581af245d11STodd Fiala         if (setpgid(0, 0) != 0)
582af245d11STodd Fiala         {
58375f47c3aSTodd Fiala             // FIXME log that this failed. This is common.
584af245d11STodd Fiala             // Don't allow this to prevent an inferior exec.
585af245d11STodd Fiala         }
586af245d11STodd Fiala 
587af245d11STodd Fiala         // Dup file descriptors if needed.
588d3173f34SChaoren Lin         if (args->m_stdin_file_spec)
589d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
590af245d11STodd Fiala                 exit(eDupStdinFailed);
591af245d11STodd Fiala 
592d3173f34SChaoren Lin         if (args->m_stdout_file_spec)
593d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
594af245d11STodd Fiala                 exit(eDupStdoutFailed);
595af245d11STodd Fiala 
596d3173f34SChaoren Lin         if (args->m_stderr_file_spec)
597d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
598af245d11STodd Fiala                 exit(eDupStderrFailed);
599af245d11STodd Fiala 
6009cf4f2c2SChaoren Lin         // Close everything besides stdin, stdout, and stderr that has no file
6019cf4f2c2SChaoren Lin         // action to avoid leaking
6029cf4f2c2SChaoren Lin         for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
6039cf4f2c2SChaoren Lin             if (!args->m_launch_info.GetFileActionForFD(fd))
6049cf4f2c2SChaoren Lin                 close(fd);
6059cf4f2c2SChaoren Lin 
606af245d11STodd Fiala         // Change working directory
607d3173f34SChaoren Lin         if (working_dir && 0 != ::chdir(working_dir.GetCString()))
608af245d11STodd Fiala               exit(eChdirFailed);
609af245d11STodd Fiala 
6100bce1b67STodd Fiala         // Disable ASLR if requested.
6110bce1b67STodd Fiala         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
6120bce1b67STodd Fiala         {
6130bce1b67STodd Fiala             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
6140bce1b67STodd Fiala             if (old_personality == -1)
6150bce1b67STodd Fiala             {
61675f47c3aSTodd Fiala                 // Can't retrieve Linux personality.  Cannot disable ASLR.
6170bce1b67STodd Fiala             }
6180bce1b67STodd Fiala             else
6190bce1b67STodd Fiala             {
6200bce1b67STodd Fiala                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
6210bce1b67STodd Fiala                 if (new_personality == -1)
6220bce1b67STodd Fiala                 {
62375f47c3aSTodd Fiala                     // Disabling ASLR failed.
6240bce1b67STodd Fiala                 }
6250bce1b67STodd Fiala                 else
6260bce1b67STodd Fiala                 {
62775f47c3aSTodd Fiala                     // Disabling ASLR succeeded.
6280bce1b67STodd Fiala                 }
6290bce1b67STodd Fiala             }
6300bce1b67STodd Fiala         }
6310bce1b67STodd Fiala 
63278856474SPavel Labath         // Clear the signal mask to prevent the child from being affected by
63378856474SPavel Labath         // any masking done by the parent.
63478856474SPavel Labath         sigset_t set;
63578856474SPavel Labath         if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
63678856474SPavel Labath             exit(eSetSigMaskFailed);
63778856474SPavel Labath 
63875f47c3aSTodd Fiala         // Execute.  We should never return...
639af245d11STodd Fiala         execve(argv[0],
640af245d11STodd Fiala                const_cast<char *const *>(argv),
641af245d11STodd Fiala                const_cast<char *const *>(envp));
64275f47c3aSTodd Fiala 
64375f47c3aSTodd Fiala         // ...unless exec fails.  In which case we definitely need to end the child here.
644af245d11STodd Fiala         exit(eExecFailed);
645af245d11STodd Fiala     }
646af245d11STodd Fiala 
64775f47c3aSTodd Fiala     //
64875f47c3aSTodd Fiala     // This is the parent code here.
64975f47c3aSTodd Fiala     //
65075f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
65175f47c3aSTodd Fiala 
652af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
653af245d11STodd Fiala     ::pid_t wpid;
654af245d11STodd Fiala     int status;
655af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
656af245d11STodd Fiala     {
657bd7cbc5aSPavel Labath         error.SetErrorToErrno();
658af245d11STodd Fiala         if (log)
659bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
660bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
661af245d11STodd Fiala 
662af245d11STodd Fiala         // Mark the inferior as invalid.
663af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
664bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
665af245d11STodd Fiala 
666bd7cbc5aSPavel Labath         return -1;
667af245d11STodd Fiala     }
668af245d11STodd Fiala     else if (WIFEXITED(status))
669af245d11STodd Fiala     {
670af245d11STodd Fiala         // open, dup or execve likely failed for some reason.
671bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
672af245d11STodd Fiala         switch (WEXITSTATUS(status))
673af245d11STodd Fiala         {
674af245d11STodd Fiala             case ePtraceFailed:
675bd7cbc5aSPavel Labath                 error.SetErrorString("Child ptrace failed.");
676af245d11STodd Fiala                 break;
677af245d11STodd Fiala             case eDupStdinFailed:
678bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdin failed.");
679af245d11STodd Fiala                 break;
680af245d11STodd Fiala             case eDupStdoutFailed:
681bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdout failed.");
682af245d11STodd Fiala                 break;
683af245d11STodd Fiala             case eDupStderrFailed:
684bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stderr failed.");
685af245d11STodd Fiala                 break;
686af245d11STodd Fiala             case eChdirFailed:
687bd7cbc5aSPavel Labath                 error.SetErrorString("Child failed to set working directory.");
688af245d11STodd Fiala                 break;
689af245d11STodd Fiala             case eExecFailed:
690bd7cbc5aSPavel Labath                 error.SetErrorString("Child exec failed.");
691af245d11STodd Fiala                 break;
692af245d11STodd Fiala             case eSetGidFailed:
693bd7cbc5aSPavel Labath                 error.SetErrorString("Child setgid failed.");
694af245d11STodd Fiala                 break;
69578856474SPavel Labath             case eSetSigMaskFailed:
69678856474SPavel Labath                 error.SetErrorString("Child failed to set signal mask.");
69778856474SPavel Labath                 break;
698af245d11STodd Fiala             default:
699bd7cbc5aSPavel Labath                 error.SetErrorString("Child returned unknown exit status.");
700af245d11STodd Fiala                 break;
701af245d11STodd Fiala         }
702af245d11STodd Fiala 
703af245d11STodd Fiala         if (log)
704af245d11STodd Fiala         {
705af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
706af245d11STodd Fiala                     __FUNCTION__,
707af245d11STodd Fiala                     WEXITSTATUS(status));
708af245d11STodd Fiala         }
709af245d11STodd Fiala 
710af245d11STodd Fiala         // Mark the inferior as invalid.
711af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
712bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
713af245d11STodd Fiala 
714bd7cbc5aSPavel Labath         return -1;
715af245d11STodd Fiala     }
716af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
717af245d11STodd Fiala            "Could not sync with inferior process.");
718af245d11STodd Fiala 
719af245d11STodd Fiala     if (log)
720af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
721af245d11STodd Fiala 
722bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
723bd7cbc5aSPavel Labath     if (error.Fail())
724af245d11STodd Fiala     {
725af245d11STodd Fiala         if (log)
726af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
727bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
728af245d11STodd Fiala 
729af245d11STodd Fiala         // Mark the inferior as invalid.
730af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
731bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
732af245d11STodd Fiala 
733bd7cbc5aSPavel Labath         return -1;
734af245d11STodd Fiala     }
735af245d11STodd Fiala 
736af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
737af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
738bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
739bd7cbc5aSPavel Labath     m_pid = pid;
740af245d11STodd Fiala 
741af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
742af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
743af245d11STodd Fiala     // descriptor to read from).
744bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
745bd7cbc5aSPavel Labath     if (error.Fail())
746af245d11STodd Fiala     {
747af245d11STodd Fiala         if (log)
748af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
749bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
750af245d11STodd Fiala 
751af245d11STodd Fiala         // Mark the inferior as invalid.
752af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
753bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
754af245d11STodd Fiala 
755bd7cbc5aSPavel Labath         return -1;
756af245d11STodd Fiala     }
757af245d11STodd Fiala 
758af245d11STodd Fiala     if (log)
759af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
760af245d11STodd Fiala 
761f9077782SPavel Labath     NativeThreadLinuxSP thread_sp = AddThread(pid);
762af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
763f9077782SPavel Labath     thread_sp->SetStoppedBySignal(SIGSTOP);
764f9077782SPavel Labath     ThreadWasCreated(*thread_sp);
765af245d11STodd Fiala 
766af245d11STodd Fiala     // Let our process instance know the thread has stopped.
767bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
768bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
769af245d11STodd Fiala 
770af245d11STodd Fiala     if (log)
771af245d11STodd Fiala     {
772bd7cbc5aSPavel Labath         if (error.Success ())
773af245d11STodd Fiala         {
774af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
775af245d11STodd Fiala         }
776af245d11STodd Fiala         else
777af245d11STodd Fiala         {
778af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
779bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
780bd7cbc5aSPavel Labath             return -1;
781af245d11STodd Fiala         }
782af245d11STodd Fiala     }
783bd7cbc5aSPavel Labath     return pid;
784af245d11STodd Fiala }
785af245d11STodd Fiala 
786bd7cbc5aSPavel Labath ::pid_t
787bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
788af245d11STodd Fiala {
789af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
790af245d11STodd Fiala 
791af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
792af245d11STodd Fiala     Host::TidMap tids_to_attach;
793af245d11STodd Fiala     if (pid <= 1)
794af245d11STodd Fiala     {
795bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
796bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
797bd7cbc5aSPavel Labath         return -1;
798af245d11STodd Fiala     }
799af245d11STodd Fiala 
800af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
801af245d11STodd Fiala     {
802af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
803af245d11STodd Fiala              it != tids_to_attach.end();)
804af245d11STodd Fiala         {
805af245d11STodd Fiala             if (it->second == false)
806af245d11STodd Fiala             {
807af245d11STodd Fiala                 lldb::tid_t tid = it->first;
808af245d11STodd Fiala 
809af245d11STodd Fiala                 // Attach to the requested process.
810af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
8114a9babb2SPavel Labath                 error = PtraceWrapper(PTRACE_ATTACH, tid);
812bd7cbc5aSPavel Labath                 if (error.Fail())
813af245d11STodd Fiala                 {
814af245d11STodd Fiala                     // No such thread. The thread may have exited.
815af245d11STodd Fiala                     // More error handling may be needed.
816bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
817af245d11STodd Fiala                     {
818af245d11STodd Fiala                         it = tids_to_attach.erase(it);
819af245d11STodd Fiala                         continue;
820af245d11STodd Fiala                     }
821af245d11STodd Fiala                     else
822bd7cbc5aSPavel Labath                         return -1;
823af245d11STodd Fiala                 }
824af245d11STodd Fiala 
825af245d11STodd Fiala                 int status;
826af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
827af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
828af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
829af245d11STodd Fiala                 {
830af245d11STodd Fiala                     // No such thread. The thread may have exited.
831af245d11STodd Fiala                     // More error handling may be needed.
832af245d11STodd Fiala                     if (errno == ESRCH)
833af245d11STodd Fiala                     {
834af245d11STodd Fiala                         it = tids_to_attach.erase(it);
835af245d11STodd Fiala                         continue;
836af245d11STodd Fiala                     }
837af245d11STodd Fiala                     else
838af245d11STodd Fiala                     {
839bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
840bd7cbc5aSPavel Labath                         return -1;
841af245d11STodd Fiala                     }
842af245d11STodd Fiala                 }
843af245d11STodd Fiala 
844bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
845bd7cbc5aSPavel Labath                 if (error.Fail())
846bd7cbc5aSPavel Labath                     return -1;
847af245d11STodd Fiala 
848af245d11STodd Fiala                 if (log)
849af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
850af245d11STodd Fiala 
851af245d11STodd Fiala                 it->second = true;
852af245d11STodd Fiala 
853af245d11STodd Fiala                 // Create the thread, mark it as stopped.
854f9077782SPavel Labath                 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
855af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
856fa03ad2eSChaoren Lin 
857fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
858f9077782SPavel Labath                 thread_sp->SetStoppedBySignal(SIGSTOP);
859f9077782SPavel Labath                 ThreadWasCreated(*thread_sp);
860bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
861af245d11STodd Fiala             }
862af245d11STodd Fiala 
863af245d11STodd Fiala             // move the loop forward
864af245d11STodd Fiala             ++it;
865af245d11STodd Fiala         }
866af245d11STodd Fiala     }
867af245d11STodd Fiala 
868af245d11STodd Fiala     if (tids_to_attach.size() > 0)
869af245d11STodd Fiala     {
870bd7cbc5aSPavel Labath         m_pid = pid;
871af245d11STodd Fiala         // Let our process instance know the thread has stopped.
872bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
873af245d11STodd Fiala     }
874af245d11STodd Fiala     else
875af245d11STodd Fiala     {
876bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
877bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
878bd7cbc5aSPavel Labath         return -1;
879af245d11STodd Fiala     }
880af245d11STodd Fiala 
881bd7cbc5aSPavel Labath     return pid;
882af245d11STodd Fiala }
883af245d11STodd Fiala 
88497ccc294SChaoren Lin Error
885af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
886af245d11STodd Fiala {
887af245d11STodd Fiala     long ptrace_opts = 0;
888af245d11STodd Fiala 
889af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
890af245d11STodd Fiala     // limbo until it is destroyed.
891af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
892af245d11STodd Fiala 
893af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
894af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
895af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
896af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
897af245d11STodd Fiala 
898af245d11STodd Fiala     // Have the tracer notify us before execve returns
899af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
900af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
901af245d11STodd Fiala 
9024a9babb2SPavel Labath     return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
903af245d11STodd Fiala }
904af245d11STodd Fiala 
905af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
906af245d11STodd Fiala {
907af245d11STodd Fiala     if (WIFEXITED (status))
908af245d11STodd Fiala         return ExitType::eExitTypeExit;
909af245d11STodd Fiala     else if (WIFSIGNALED (status))
910af245d11STodd Fiala         return ExitType::eExitTypeSignal;
911af245d11STodd Fiala     else if (WIFSTOPPED (status))
912af245d11STodd Fiala         return ExitType::eExitTypeStop;
913af245d11STodd Fiala     else
914af245d11STodd Fiala     {
915af245d11STodd Fiala         // We don't know what this is.
916af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
917af245d11STodd Fiala     }
918af245d11STodd Fiala }
919af245d11STodd Fiala 
920af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
921af245d11STodd Fiala {
922af245d11STodd Fiala     if (WIFEXITED (status))
923af245d11STodd Fiala         return WEXITSTATUS (status);
924af245d11STodd Fiala     else if (WIFSIGNALED (status))
925af245d11STodd Fiala         return WTERMSIG (status);
926af245d11STodd Fiala     else if (WIFSTOPPED (status))
927af245d11STodd Fiala         return WSTOPSIG (status);
928af245d11STodd Fiala     else
929af245d11STodd Fiala     {
930af245d11STodd Fiala         // We don't know what this is.
931af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
932af245d11STodd Fiala     }
933af245d11STodd Fiala }
934af245d11STodd Fiala 
9351107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
9361107b5a5SPavel Labath void
9371107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
938af245d11STodd Fiala                                     bool exited,
939af245d11STodd Fiala                                     int signal,
940af245d11STodd Fiala                                     int status)
941af245d11STodd Fiala {
942af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
943af245d11STodd Fiala 
944af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
9451107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
946af245d11STodd Fiala 
947af245d11STodd Fiala     // Handle when the thread exits.
948af245d11STodd Fiala     if (exited)
949af245d11STodd Fiala     {
950af245d11STodd Fiala         if (log)
95186fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
952af245d11STodd Fiala 
953af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
9541107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
955af245d11STodd Fiala 
956af245d11STodd Fiala         if (is_main_thread)
957af245d11STodd Fiala         {
958af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
959af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
960af245d11STodd Fiala             // for the main thread.
9611107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
962af245d11STodd Fiala             if (!already_notified)
963af245d11STodd Fiala             {
964af245d11STodd Fiala                 if (log)
9651107b5a5SPavel Labath                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ()));
966af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
9671107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
968af245d11STodd Fiala 
969af245d11STodd Fiala                 // Notify delegate that our process has exited.
9701107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
971af245d11STodd Fiala             }
972af245d11STodd Fiala             else
973af245d11STodd Fiala             {
974af245d11STodd Fiala                 if (log)
975af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
976af245d11STodd Fiala             }
977af245d11STodd Fiala         }
978af245d11STodd Fiala         else
979af245d11STodd Fiala         {
980af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
981af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
982af245d11STodd Fiala             // and we would have done an all-stop then.
983af245d11STodd Fiala             if (log)
984af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
985af245d11STodd Fiala         }
9861107b5a5SPavel Labath         return;
987af245d11STodd Fiala     }
988af245d11STodd Fiala 
989af245d11STodd Fiala     siginfo_t info;
990b9cc0c75SPavel Labath     const auto info_err = GetSignalInfo(pid, &info);
991b9cc0c75SPavel Labath     auto thread_sp = GetThreadByID(pid);
992b9cc0c75SPavel Labath 
993b9cc0c75SPavel Labath     if (! thread_sp)
994b9cc0c75SPavel Labath     {
995b9cc0c75SPavel Labath         // Normally, the only situation when we cannot find the thread is if we have just
996b9cc0c75SPavel Labath         // received a new thread notification. This is indicated by GetSignalInfo() returning
997b9cc0c75SPavel Labath         // si_code == SI_USER and si_pid == 0
998b9cc0c75SPavel Labath         if (log)
999b9cc0c75SPavel Labath             log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
1000b9cc0c75SPavel Labath 
1001b9cc0c75SPavel Labath         if (info_err.Fail())
1002b9cc0c75SPavel Labath         {
1003b9cc0c75SPavel Labath             if (log)
1004b9cc0c75SPavel Labath                 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
1005b9cc0c75SPavel Labath             return;
1006b9cc0c75SPavel Labath         }
1007b9cc0c75SPavel Labath 
1008b9cc0c75SPavel Labath         if (log && (info.si_code != SI_USER || info.si_pid != 0))
1009b9cc0c75SPavel Labath             log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") unexpected signal info (si_code: %d, si_pid: %d). Treating as a new thread notification anyway.", __FUNCTION__, pid, info.si_code, info.si_pid);
1010b9cc0c75SPavel Labath 
1011b9cc0c75SPavel Labath         auto thread_sp = AddThread(pid);
1012b9cc0c75SPavel Labath         // Resume the newly created thread.
1013b9cc0c75SPavel Labath         ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1014b9cc0c75SPavel Labath         ThreadWasCreated(*thread_sp);
1015b9cc0c75SPavel Labath         return;
1016b9cc0c75SPavel Labath     }
1017b9cc0c75SPavel Labath 
1018b9cc0c75SPavel Labath     // Get details on the signal raised.
1019b9cc0c75SPavel Labath     if (info_err.Success())
1020fa03ad2eSChaoren Lin     {
1021fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
1022fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
1023b9cc0c75SPavel Labath             MonitorSIGTRAP(info, *thread_sp);
1024fa03ad2eSChaoren Lin         else
1025b9cc0c75SPavel Labath             MonitorSignal(info, *thread_sp, exited);
1026fa03ad2eSChaoren Lin     }
1027fa03ad2eSChaoren Lin     else
1028af245d11STodd Fiala     {
1029b9cc0c75SPavel Labath         if (info_err.GetError() == EINVAL)
1030af245d11STodd Fiala         {
1031fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
103239036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
103339036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
103439036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
103539036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
103639036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
103739036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
103839036ac3SPavel Labath             // correctly for all signals.
1039fa03ad2eSChaoren Lin             if (log)
104039036ac3SPavel Labath                 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
1041b9cc0c75SPavel Labath             ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1042a9882ceeSTodd Fiala         }
1043a9882ceeSTodd Fiala         else
1044a9882ceeSTodd Fiala         {
1045af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
1046af245d11STodd Fiala 
1047af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
1048af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
1049af245d11STodd Fiala             // with it anymore.
1050af245d11STodd Fiala 
1051af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
10521107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
1053af245d11STodd Fiala 
1054af245d11STodd Fiala             if (log)
1055af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
1056b9cc0c75SPavel Labath                              __FUNCTION__, info_err.AsCString(), pid, signal, status, info_err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
1057af245d11STodd Fiala 
1058af245d11STodd Fiala             if (is_main_thread)
1059af245d11STodd Fiala             {
1060af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
1061af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
10621107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
10631107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1064af245d11STodd Fiala             }
1065af245d11STodd Fiala             else
1066af245d11STodd Fiala             {
1067af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
1068af245d11STodd Fiala                 if (log)
10691107b5a5SPavel Labath                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid);
1070af245d11STodd Fiala             }
1071af245d11STodd Fiala         }
1072af245d11STodd Fiala     }
1073af245d11STodd Fiala }
1074af245d11STodd Fiala 
1075af245d11STodd Fiala void
1076426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
1077426bdf88SPavel Labath {
1078426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1079426bdf88SPavel Labath 
1080f9077782SPavel Labath     NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
1081426bdf88SPavel Labath 
1082426bdf88SPavel Labath     if (new_thread_sp)
1083426bdf88SPavel Labath     {
1084426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
1085426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
1086426bdf88SPavel Labath         return;
1087426bdf88SPavel Labath     }
1088426bdf88SPavel Labath 
1089426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
1090426bdf88SPavel Labath     int status = -1;
1091426bdf88SPavel Labath     ::pid_t wait_pid;
1092426bdf88SPavel Labath     do
1093426bdf88SPavel Labath     {
1094426bdf88SPavel Labath         if (log)
1095426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1096426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
1097426bdf88SPavel Labath     }
1098426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
1099426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
1100426bdf88SPavel Labath     // some checks just in case.
1101426bdf88SPavel Labath     if (wait_pid != tid) {
1102426bdf88SPavel Labath         if (log)
1103426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1104426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
1105426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1106426bdf88SPavel Labath         return;
1107426bdf88SPavel Labath     }
1108426bdf88SPavel Labath     if (WIFEXITED(status))
1109426bdf88SPavel Labath     {
1110426bdf88SPavel Labath         if (log)
1111426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1112426bdf88SPavel Labath         // Also a very improbable event.
1113426bdf88SPavel Labath         return;
1114426bdf88SPavel Labath     }
1115426bdf88SPavel Labath 
1116426bdf88SPavel Labath     siginfo_t info;
1117426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
1118426bdf88SPavel Labath     if (error.Fail())
1119426bdf88SPavel Labath     {
1120426bdf88SPavel Labath         if (log)
1121426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1122426bdf88SPavel Labath         return;
1123426bdf88SPavel Labath     }
1124426bdf88SPavel Labath 
1125426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1126426bdf88SPavel Labath     {
1127426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
1128426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
1129426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
1130426bdf88SPavel Labath         // created properly.
1131426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid);
1132426bdf88SPavel Labath     }
1133426bdf88SPavel Labath 
1134426bdf88SPavel Labath     if (log)
1135426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1136426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
1137426bdf88SPavel Labath 
1138f9077782SPavel Labath     new_thread_sp = AddThread(tid);
1139b9cc0c75SPavel Labath     ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1140f9077782SPavel Labath     ThreadWasCreated(*new_thread_sp);
1141426bdf88SPavel Labath }
1142426bdf88SPavel Labath 
1143426bdf88SPavel Labath void
1144b9cc0c75SPavel Labath NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
1145af245d11STodd Fiala {
1146af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1147b9cc0c75SPavel Labath     const bool is_main_thread = (thread.GetID() == GetID ());
1148af245d11STodd Fiala 
1149b9cc0c75SPavel Labath     assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
1150af245d11STodd Fiala 
1151b9cc0c75SPavel Labath     switch (info.si_code)
1152af245d11STodd Fiala     {
1153af245d11STodd Fiala     // TODO: these two cases are required if we want to support tracing of the inferiors' children.  We'd need this to debug a monitor.
1154af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1155af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1156af245d11STodd Fiala 
1157af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1158af245d11STodd Fiala     {
11595fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
1160426bdf88SPavel Labath         // creation.
1161426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
1162426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
1163426bdf88SPavel Labath         // here.
1164af245d11STodd Fiala 
1165af245d11STodd Fiala         unsigned long event_message = 0;
1166b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &event_message).Fail())
1167fa03ad2eSChaoren Lin         {
1168426bdf88SPavel Labath             if (log)
1169b9cc0c75SPavel Labath                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, thread.GetID());
1170426bdf88SPavel Labath         } else
1171426bdf88SPavel Labath             WaitForNewThread(event_message);
1172af245d11STodd Fiala 
1173b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1174af245d11STodd Fiala         break;
1175af245d11STodd Fiala     }
1176af245d11STodd Fiala 
1177af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1178a9882ceeSTodd Fiala     {
1179f9077782SPavel Labath         NativeThreadLinuxSP main_thread_sp;
1180af245d11STodd Fiala         if (log)
1181b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
1182a9882ceeSTodd Fiala 
11831dbc6c9cSPavel Labath         // Exec clears any pending notifications.
11840e1d729bSPavel Labath         m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1185fa03ad2eSChaoren Lin 
1186*57a77118SPavel Labath         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.
1187a9882ceeSTodd Fiala         if (log)
1188a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1189a9882ceeSTodd Fiala 
1190a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
1191a9882ceeSTodd Fiala         {
1192a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1193a9882ceeSTodd Fiala             if (is_main_thread)
1194a9882ceeSTodd Fiala             {
1195f9077782SPavel Labath                 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
1196a9882ceeSTodd Fiala                 if (log)
1197a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1198a9882ceeSTodd Fiala             }
1199a9882ceeSTodd Fiala             else
1200a9882ceeSTodd Fiala             {
1201a9882ceeSTodd Fiala                 if (log)
1202a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1203a9882ceeSTodd Fiala             }
1204a9882ceeSTodd Fiala         }
1205a9882ceeSTodd Fiala 
1206a9882ceeSTodd Fiala         m_threads.clear ();
1207a9882ceeSTodd Fiala 
1208a9882ceeSTodd Fiala         if (main_thread_sp)
1209a9882ceeSTodd Fiala         {
1210a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
1211a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
1212f9077782SPavel Labath             main_thread_sp->SetStoppedByExec();
1213a9882ceeSTodd Fiala         }
1214a9882ceeSTodd Fiala         else
1215a9882ceeSTodd Fiala         {
1216a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1217a9882ceeSTodd Fiala             if (log)
1218a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1219a9882ceeSTodd Fiala         }
1220a9882ceeSTodd Fiala 
1221fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
1222f9077782SPavel Labath         ThreadWasCreated(*main_thread_sp);
1223fa03ad2eSChaoren Lin 
1224a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
1225a9882ceeSTodd Fiala         NotifyDidExec ();
1226a9882ceeSTodd Fiala 
1227a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
1228a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1229fa03ad2eSChaoren Lin 
1230fa03ad2eSChaoren Lin         // Let the process know we're stopped.
1231b9cc0c75SPavel Labath         StopRunningThreads(main_thread_sp->GetID());
1232a9882ceeSTodd Fiala 
1233af245d11STodd Fiala         break;
1234a9882ceeSTodd Fiala     }
1235af245d11STodd Fiala 
1236af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1237af245d11STodd Fiala     {
1238af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
12396e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
12406e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
12416e35163cSPavel Labath         // here.
1242fa03ad2eSChaoren Lin 
1243af245d11STodd Fiala         unsigned long data = 0;
1244b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &data).Fail())
1245af245d11STodd Fiala             data = -1;
1246af245d11STodd Fiala 
1247af245d11STodd Fiala         if (log)
1248af245d11STodd Fiala         {
1249af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1250af245d11STodd Fiala                          __FUNCTION__,
1251af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1252b9cc0c75SPavel Labath                          thread.GetID(),
1253af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
1254af245d11STodd Fiala         }
1255af245d11STodd Fiala 
1256af245d11STodd Fiala         if (is_main_thread)
1257af245d11STodd Fiala         {
1258af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
125975f47c3aSTodd Fiala         }
126075f47c3aSTodd Fiala 
126186852d36SPavel Labath         StateType state = thread.GetState();
126286852d36SPavel Labath         if (! StateIsRunningState(state))
126386852d36SPavel Labath         {
126486852d36SPavel Labath             // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
126586852d36SPavel Labath             // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
126686852d36SPavel Labath             // we should not be receiving any ptrace events while the inferior is stopped. This
126786852d36SPavel Labath             // makes sure that the inferior is resumed and exits normally.
126886852d36SPavel Labath             state = eStateRunning;
126986852d36SPavel Labath         }
127086852d36SPavel Labath         ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
1271af245d11STodd Fiala 
1272af245d11STodd Fiala         break;
1273af245d11STodd Fiala     }
1274af245d11STodd Fiala 
1275af245d11STodd Fiala     case 0:
1276c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
1277c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
127886fd8e45SChaoren Lin     {
1279c16f5dcaSChaoren Lin         // If a watchpoint was hit, report it
1280c16f5dcaSChaoren Lin         uint32_t wp_index;
12811fa5c4b9STamas Berghammer         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
1282c16f5dcaSChaoren Lin         if (error.Fail() && log)
1283c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() "
1284c16f5dcaSChaoren Lin                         "received error while checking for watchpoint hits, "
1285c16f5dcaSChaoren Lin                         "pid = %" PRIu64 " error = %s",
1286b9cc0c75SPavel Labath                         __FUNCTION__, thread.GetID(), error.AsCString());
1287c16f5dcaSChaoren Lin         if (wp_index != LLDB_INVALID_INDEX32)
12885830aa75STamas Berghammer         {
1289b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
1290c16f5dcaSChaoren Lin             break;
1291c16f5dcaSChaoren Lin         }
1292b9cc0c75SPavel Labath 
1293be379e15STamas Berghammer         // Otherwise, report step over
1294be379e15STamas Berghammer         MonitorTrace(thread);
1295af245d11STodd Fiala         break;
1296b9cc0c75SPavel Labath     }
1297af245d11STodd Fiala 
1298af245d11STodd Fiala     case SI_KERNEL:
129935799963SMohit K. Bhakkad #if defined __mips__
130035799963SMohit K. Bhakkad         // For mips there is no special signal for watchpoint
130135799963SMohit K. Bhakkad         // So we check for watchpoint in kernel trap
130235799963SMohit K. Bhakkad     {
130335799963SMohit K. Bhakkad         // If a watchpoint was hit, report it
130435799963SMohit K. Bhakkad         uint32_t wp_index;
1305b9cc0c75SPavel Labath         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
130635799963SMohit K. Bhakkad         if (error.Fail() && log)
130735799963SMohit K. Bhakkad             log->Printf("NativeProcessLinux::%s() "
130835799963SMohit K. Bhakkad                         "received error while checking for watchpoint hits, "
130935799963SMohit K. Bhakkad                         "pid = %" PRIu64 " error = %s",
131016ad0321SMohit K. Bhakkad                         __FUNCTION__, thread.GetID(), error.AsCString());
131135799963SMohit K. Bhakkad         if (wp_index != LLDB_INVALID_INDEX32)
131235799963SMohit K. Bhakkad         {
1313b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
131435799963SMohit K. Bhakkad             break;
131535799963SMohit K. Bhakkad         }
131635799963SMohit K. Bhakkad     }
131735799963SMohit K. Bhakkad         // NO BREAK
131835799963SMohit K. Bhakkad #endif
1319af245d11STodd Fiala     case TRAP_BRKPT:
1320b9cc0c75SPavel Labath         MonitorBreakpoint(thread);
1321af245d11STodd Fiala         break;
1322af245d11STodd Fiala 
1323af245d11STodd Fiala     case SIGTRAP:
1324af245d11STodd Fiala     case (SIGTRAP | 0x80):
1325af245d11STodd Fiala         if (log)
1326b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
1327fa03ad2eSChaoren Lin 
1328af245d11STodd Fiala         // Ignore these signals until we know more about them.
1329b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1330af245d11STodd Fiala         break;
1331af245d11STodd Fiala 
1332af245d11STodd Fiala     default:
1333af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
1334af245d11STodd Fiala         if (log)
13356e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1336b9cc0c75SPavel Labath                     __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1337af245d11STodd Fiala         break;
1338af245d11STodd Fiala 
1339af245d11STodd Fiala     }
1340af245d11STodd Fiala }
1341af245d11STodd Fiala 
1342af245d11STodd Fiala void
1343b9cc0c75SPavel Labath NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
1344c16f5dcaSChaoren Lin {
1345c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1346c16f5dcaSChaoren Lin     if (log)
1347c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1348b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1349c16f5dcaSChaoren Lin 
13500e1d729bSPavel Labath     // This thread is currently stopped.
1351b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
1352c16f5dcaSChaoren Lin 
1353b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1354c16f5dcaSChaoren Lin }
1355c16f5dcaSChaoren Lin 
1356c16f5dcaSChaoren Lin void
1357b9cc0c75SPavel Labath NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
1358c16f5dcaSChaoren Lin {
1359c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1360c16f5dcaSChaoren Lin     if (log)
1361c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1362b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1363c16f5dcaSChaoren Lin 
1364c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
1365b9cc0c75SPavel Labath     thread.SetStoppedByBreakpoint();
1366b9cc0c75SPavel Labath     Error error = FixupBreakpointPCAsNeeded(thread);
1367c16f5dcaSChaoren Lin     if (error.Fail())
1368c16f5dcaSChaoren Lin         if (log)
1369c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1370b9cc0c75SPavel Labath                     __FUNCTION__, thread.GetID(), error.AsCString());
1371d8c338d4STamas Berghammer 
1372b9cc0c75SPavel Labath     if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1373b9cc0c75SPavel Labath         thread.SetStoppedByTrace();
1374c16f5dcaSChaoren Lin 
1375b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1376c16f5dcaSChaoren Lin }
1377c16f5dcaSChaoren Lin 
1378c16f5dcaSChaoren Lin void
1379f9077782SPavel Labath NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
1380c16f5dcaSChaoren Lin {
1381c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1382c16f5dcaSChaoren Lin     if (log)
1383c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1384c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
1385f9077782SPavel Labath                     __FUNCTION__, thread.GetID(), wp_index);
1386c16f5dcaSChaoren Lin 
1387c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
1388c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
1389f9077782SPavel Labath     thread.SetStoppedByWatchpoint(wp_index);
1390c16f5dcaSChaoren Lin 
1391c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
1392f9077782SPavel Labath     StopRunningThreads(thread.GetID());
1393c16f5dcaSChaoren Lin }
1394c16f5dcaSChaoren Lin 
1395c16f5dcaSChaoren Lin void
1396b9cc0c75SPavel Labath NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
1397af245d11STodd Fiala {
1398b9cc0c75SPavel Labath     const int signo = info.si_signo;
1399b9cc0c75SPavel Labath     const bool is_from_llgs = info.si_pid == getpid ();
1400af245d11STodd Fiala 
1401af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1402af245d11STodd Fiala 
1403af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1404af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1405af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1406af245d11STodd Fiala     //
1407af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
1408af245d11STodd Fiala     // "crash".
1409af245d11STodd Fiala     //
1410af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
1411af245d11STodd Fiala 
1412af245d11STodd Fiala     // Handle the signal.
1413b9cc0c75SPavel Labath     if (info.si_code == SI_TKILL || info.si_code == SI_USER)
1414af245d11STodd Fiala     {
1415af245d11STodd Fiala         if (log)
1416af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1417af245d11STodd Fiala                             __FUNCTION__,
141898d0a4b3SChaoren Lin                             Host::GetSignalAsCString(signo),
1419af245d11STodd Fiala                             signo,
1420b9cc0c75SPavel Labath                             (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1421b9cc0c75SPavel Labath                             info.si_pid,
1422511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
1423b9cc0c75SPavel Labath                             thread.GetID());
1424af245d11STodd Fiala     }
142558a2f669STodd Fiala 
142658a2f669STodd Fiala     // Check for thread stop notification.
1427b9cc0c75SPavel Labath     if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
1428af245d11STodd Fiala     {
1429af245d11STodd Fiala         // This is a tgkill()-based stop.
1430fa03ad2eSChaoren Lin         if (log)
1431fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1432fa03ad2eSChaoren Lin                          __FUNCTION__,
1433fa03ad2eSChaoren Lin                          GetID (),
1434b9cc0c75SPavel Labath                          thread.GetID());
1435fa03ad2eSChaoren Lin 
1436aab58633SChaoren Lin         // Check that we're not already marked with a stop reason.
1437aab58633SChaoren Lin         // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1438aab58633SChaoren Lin         // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1439aab58633SChaoren Lin         // and that, without an intervening resume, we received another stop.  It is more likely
1440aab58633SChaoren Lin         // that we are missing the marking of a run state somewhere if we find that the thread was
1441aab58633SChaoren Lin         // marked as stopped.
1442b9cc0c75SPavel Labath         const StateType thread_state = thread.GetState();
1443aab58633SChaoren Lin         if (!StateIsStoppedState (thread_state, false))
1444aab58633SChaoren Lin         {
1445ed89c7feSPavel Labath             // An inferior thread has stopped because of a SIGSTOP we have sent it.
1446ed89c7feSPavel Labath             // Generally, these are not important stops and we don't want to report them as
1447ed89c7feSPavel Labath             // they are just used to stop other threads when one thread (the one with the
1448ed89c7feSPavel Labath             // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1449ed89c7feSPavel Labath             // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1450ed89c7feSPavel Labath             // leave the signal intact if this is the thread that was chosen as the
1451ed89c7feSPavel Labath             // triggering thread.
14520e1d729bSPavel Labath             if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
14530e1d729bSPavel Labath             {
1454b9cc0c75SPavel Labath                 if (m_pending_notification_tid == thread.GetID())
1455b9cc0c75SPavel Labath                     thread.SetStoppedBySignal(SIGSTOP, &info);
1456ed89c7feSPavel Labath                 else
1457b9cc0c75SPavel Labath                     thread.SetStoppedWithNoReason();
1458ed89c7feSPavel Labath 
1459b9cc0c75SPavel Labath                 SetCurrentThreadID (thread.GetID ());
14600e1d729bSPavel Labath                 SignalIfAllThreadsStopped();
14610e1d729bSPavel Labath             }
14620e1d729bSPavel Labath             else
14630e1d729bSPavel Labath             {
14640e1d729bSPavel Labath                 // We can end up here if stop was initiated by LLGS but by this time a
14650e1d729bSPavel Labath                 // thread stop has occurred - maybe initiated by another event.
1466b9cc0c75SPavel Labath                 Error error = ResumeThread(thread, thread.GetState(), 0);
14670e1d729bSPavel Labath                 if (error.Fail() && log)
14680e1d729bSPavel Labath                 {
14690e1d729bSPavel Labath                     log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
1470b9cc0c75SPavel Labath                             __FUNCTION__, thread.GetID(), error.AsCString());
14710e1d729bSPavel Labath                 }
14720e1d729bSPavel Labath             }
1473aab58633SChaoren Lin         }
1474aab58633SChaoren Lin         else
1475aab58633SChaoren Lin         {
1476aab58633SChaoren Lin             if (log)
1477aab58633SChaoren Lin             {
1478aab58633SChaoren Lin                 // Retrieve the signal name if the thread was stopped by a signal.
1479aab58633SChaoren Lin                 int stop_signo = 0;
1480b9cc0c75SPavel Labath                 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
148198d0a4b3SChaoren Lin                 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1482aab58633SChaoren Lin                 if (!signal_name)
1483aab58633SChaoren Lin                     signal_name = "<no-signal-name>";
1484aab58633SChaoren Lin 
1485aab58633SChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is",
1486aab58633SChaoren Lin                              __FUNCTION__,
1487aab58633SChaoren Lin                              GetID (),
1488b9cc0c75SPavel Labath                              thread.GetID(),
1489aab58633SChaoren Lin                              StateAsCString (thread_state),
1490aab58633SChaoren Lin                              stop_signo,
1491aab58633SChaoren Lin                              signal_name);
1492aab58633SChaoren Lin             }
14930e1d729bSPavel Labath             SignalIfAllThreadsStopped();
1494af245d11STodd Fiala         }
1495af245d11STodd Fiala 
149658a2f669STodd Fiala         // Done handling.
1497af245d11STodd Fiala         return;
1498af245d11STodd Fiala     }
1499af245d11STodd Fiala 
1500af245d11STodd Fiala     if (log)
150198d0a4b3SChaoren Lin         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
1502af245d11STodd Fiala 
150386fd8e45SChaoren Lin     // This thread is stopped.
1504b9cc0c75SPavel Labath     thread.SetStoppedBySignal(signo, &info);
150586fd8e45SChaoren Lin 
150686fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
1507b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1508511e5cdcSTodd Fiala }
1509af245d11STodd Fiala 
1510e7708688STamas Berghammer namespace {
1511e7708688STamas Berghammer 
1512e7708688STamas Berghammer struct EmulatorBaton
1513e7708688STamas Berghammer {
1514e7708688STamas Berghammer     NativeProcessLinux* m_process;
1515e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
15166648fcc3SPavel Labath 
15176648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
15186648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
1519e7708688STamas Berghammer 
1520e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
1521e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
1522e7708688STamas Berghammer };
1523e7708688STamas Berghammer 
1524e7708688STamas Berghammer } // anonymous namespace
1525e7708688STamas Berghammer 
1526e7708688STamas Berghammer static size_t
1527e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
1528e7708688STamas Berghammer                     void *baton,
1529e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
1530e7708688STamas Berghammer                     lldb::addr_t addr,
1531e7708688STamas Berghammer                     void *dst,
1532e7708688STamas Berghammer                     size_t length)
1533e7708688STamas Berghammer {
1534e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1535e7708688STamas Berghammer 
15363eb4b458SChaoren Lin     size_t bytes_read;
1537e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1538e7708688STamas Berghammer     return bytes_read;
1539e7708688STamas Berghammer }
1540e7708688STamas Berghammer 
1541e7708688STamas Berghammer static bool
1542e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
1543e7708688STamas Berghammer                       void *baton,
1544e7708688STamas Berghammer                       const RegisterInfo *reg_info,
1545e7708688STamas Berghammer                       RegisterValue &reg_value)
1546e7708688STamas Berghammer {
1547e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1548e7708688STamas Berghammer 
15496648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
15506648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
15516648fcc3SPavel Labath     {
15526648fcc3SPavel Labath         reg_value = it->second;
15536648fcc3SPavel Labath         return true;
15546648fcc3SPavel Labath     }
15556648fcc3SPavel Labath 
1556e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
1557e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
1558e7708688STamas Berghammer     // register context based on the dwarf register numbers.
1559e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1560e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1561e7708688STamas Berghammer 
1562e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
15636648fcc3SPavel Labath     if (error.Success())
15646648fcc3SPavel Labath         return true;
1565cdc22a88SMohit K. Bhakkad 
15666648fcc3SPavel Labath     return false;
1567e7708688STamas Berghammer }
1568e7708688STamas Berghammer 
1569e7708688STamas Berghammer static bool
1570e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
1571e7708688STamas Berghammer                        void *baton,
1572e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
1573e7708688STamas Berghammer                        const RegisterInfo *reg_info,
1574e7708688STamas Berghammer                        const RegisterValue &reg_value)
1575e7708688STamas Berghammer {
1576e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
15776648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
1578e7708688STamas Berghammer     return true;
1579e7708688STamas Berghammer }
1580e7708688STamas Berghammer 
1581e7708688STamas Berghammer static size_t
1582e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
1583e7708688STamas Berghammer                      void *baton,
1584e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
1585e7708688STamas Berghammer                      lldb::addr_t addr,
1586e7708688STamas Berghammer                      const void *dst,
1587e7708688STamas Berghammer                      size_t length)
1588e7708688STamas Berghammer {
1589e7708688STamas Berghammer     return length;
1590e7708688STamas Berghammer }
1591e7708688STamas Berghammer 
1592e7708688STamas Berghammer static lldb::addr_t
1593e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
1594e7708688STamas Berghammer {
1595e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1596e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1597e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1598e7708688STamas Berghammer }
1599e7708688STamas Berghammer 
1600e7708688STamas Berghammer Error
1601b9cc0c75SPavel Labath NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
1602e7708688STamas Berghammer {
1603e7708688STamas Berghammer     Error error;
1604b9cc0c75SPavel Labath     NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1605e7708688STamas Berghammer 
1606e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
1607e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1608e7708688STamas Berghammer 
1609e7708688STamas Berghammer     if (emulator_ap == nullptr)
1610e7708688STamas Berghammer         return Error("Instruction emulator not found!");
1611e7708688STamas Berghammer 
1612e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
1613e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
1614e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1615e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1616e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1617e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1618e7708688STamas Berghammer 
1619e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
1620e7708688STamas Berghammer         return Error("Read instruction failed!");
1621e7708688STamas Berghammer 
16226648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
16236648fcc3SPavel Labath 
16246648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
16256648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
16266648fcc3SPavel Labath 
16276648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
16286648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
16296648fcc3SPavel Labath 
1630e7708688STamas Berghammer     lldb::addr_t next_pc;
1631e7708688STamas Berghammer     lldb::addr_t next_flags;
16326648fcc3SPavel Labath     if (emulation_result)
1633e7708688STamas Berghammer     {
16346648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
16356648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
16366648fcc3SPavel Labath 
16376648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
16386648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
1639e7708688STamas Berghammer         else
1640e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
1641e7708688STamas Berghammer     }
16426648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
1643e7708688STamas Berghammer     {
1644e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
1645e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
1646e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
1647e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
1648e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1649e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
1650e7708688STamas Berghammer     }
1651e7708688STamas Berghammer     else
1652e7708688STamas Berghammer     {
1653e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
1654e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
1655e7708688STamas Berghammer         // modifying the PC but we don't  know how.
1656e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
1657e7708688STamas Berghammer     }
1658e7708688STamas Berghammer 
1659e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
1660e7708688STamas Berghammer     {
1661e7708688STamas Berghammer         if (next_flags & 0x20)
1662e7708688STamas Berghammer         {
1663e7708688STamas Berghammer             // Thumb mode
1664e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
1665e7708688STamas Berghammer         }
1666e7708688STamas Berghammer         else
1667e7708688STamas Berghammer         {
1668e7708688STamas Berghammer             // Arm mode
1669e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
1670e7708688STamas Berghammer         }
1671e7708688STamas Berghammer     }
1672cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
1673c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips64el
1674c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips
1675c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mipsel)
1676cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
1677e7708688STamas Berghammer     else
1678e7708688STamas Berghammer     {
1679e7708688STamas Berghammer         // No size hint is given for the next breakpoint
1680e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
1681e7708688STamas Berghammer     }
1682e7708688STamas Berghammer 
1683e7708688STamas Berghammer     if (error.Fail())
1684e7708688STamas Berghammer         return error;
1685e7708688STamas Berghammer 
1686b9cc0c75SPavel Labath     m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1687e7708688STamas Berghammer 
1688e7708688STamas Berghammer     return Error();
1689e7708688STamas Berghammer }
1690e7708688STamas Berghammer 
1691e7708688STamas Berghammer bool
1692e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
1693e7708688STamas Berghammer {
1694cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
1695c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1696c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
1697cdc22a88SMohit K. Bhakkad         return false;
1698cdc22a88SMohit K. Bhakkad     return true;
1699e7708688STamas Berghammer }
1700e7708688STamas Berghammer 
1701af245d11STodd Fiala Error
1702af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1703af245d11STodd Fiala {
1704af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1705af245d11STodd Fiala     if (log)
1706af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1707af245d11STodd Fiala 
1708e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
1709af245d11STodd Fiala 
1710e7708688STamas Berghammer     if (software_single_step)
1711e7708688STamas Berghammer     {
1712e7708688STamas Berghammer         for (auto thread_sp : m_threads)
1713e7708688STamas Berghammer         {
1714e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
1715e7708688STamas Berghammer 
1716e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1717e7708688STamas Berghammer             if (action == nullptr)
1718e7708688STamas Berghammer                 continue;
1719e7708688STamas Berghammer 
1720e7708688STamas Berghammer             if (action->state == eStateStepping)
1721e7708688STamas Berghammer             {
1722b9cc0c75SPavel Labath                 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
1723e7708688STamas Berghammer                 if (error.Fail())
1724e7708688STamas Berghammer                     return error;
1725e7708688STamas Berghammer             }
1726e7708688STamas Berghammer         }
1727e7708688STamas Berghammer     }
1728e7708688STamas Berghammer 
1729af245d11STodd Fiala     for (auto thread_sp : m_threads)
1730af245d11STodd Fiala     {
1731af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
1732af245d11STodd Fiala 
1733af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
17346a196ce6SChaoren Lin 
17356a196ce6SChaoren Lin         if (action == nullptr)
17366a196ce6SChaoren Lin         {
17376a196ce6SChaoren Lin             if (log)
17386a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
17396a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
17406a196ce6SChaoren Lin             continue;
17416a196ce6SChaoren Lin         }
1742af245d11STodd Fiala 
1743af245d11STodd Fiala         if (log)
1744af245d11STodd Fiala         {
1745af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1746af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1747af245d11STodd Fiala         }
1748af245d11STodd Fiala 
1749af245d11STodd Fiala         switch (action->state)
1750af245d11STodd Fiala         {
1751af245d11STodd Fiala         case eStateRunning:
17520e1d729bSPavel Labath         case eStateStepping:
1753fa03ad2eSChaoren Lin         {
1754af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
1755fa03ad2eSChaoren Lin             const int signo = action->signal;
1756b9cc0c75SPavel Labath             ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
1757af245d11STodd Fiala             break;
1758ae29d395SChaoren Lin         }
1759af245d11STodd Fiala 
1760af245d11STodd Fiala         case eStateSuspended:
1761af245d11STodd Fiala         case eStateStopped:
1762108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
1763af245d11STodd Fiala 
1764af245d11STodd Fiala         default:
1765af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1766af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1767af245d11STodd Fiala         }
1768af245d11STodd Fiala     }
1769af245d11STodd Fiala 
17705830aa75STamas Berghammer     return Error();
1771af245d11STodd Fiala }
1772af245d11STodd Fiala 
1773af245d11STodd Fiala Error
1774af245d11STodd Fiala NativeProcessLinux::Halt ()
1775af245d11STodd Fiala {
1776af245d11STodd Fiala     Error error;
1777af245d11STodd Fiala 
1778af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
1779af245d11STodd Fiala         error.SetErrorToErrno ();
1780af245d11STodd Fiala 
1781af245d11STodd Fiala     return error;
1782af245d11STodd Fiala }
1783af245d11STodd Fiala 
1784af245d11STodd Fiala Error
1785af245d11STodd Fiala NativeProcessLinux::Detach ()
1786af245d11STodd Fiala {
1787af245d11STodd Fiala     Error error;
1788af245d11STodd Fiala 
1789af245d11STodd Fiala     // Stop monitoring the inferior.
179019cbe96aSPavel Labath     m_sigchld_handle.reset();
1791af245d11STodd Fiala 
17927a9495bcSPavel Labath     // Tell ptrace to detach from the process.
17937a9495bcSPavel Labath     if (GetID () == LLDB_INVALID_PROCESS_ID)
17947a9495bcSPavel Labath         return error;
17957a9495bcSPavel Labath 
17967a9495bcSPavel Labath     for (auto thread_sp : m_threads)
17977a9495bcSPavel Labath     {
17987a9495bcSPavel Labath         Error e = Detach(thread_sp->GetID());
17997a9495bcSPavel Labath         if (e.Fail())
18007a9495bcSPavel Labath             error = e; // Save the error, but still attempt to detach from other threads.
18017a9495bcSPavel Labath     }
18027a9495bcSPavel Labath 
1803af245d11STodd Fiala     return error;
1804af245d11STodd Fiala }
1805af245d11STodd Fiala 
1806af245d11STodd Fiala Error
1807af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
1808af245d11STodd Fiala {
1809af245d11STodd Fiala     Error error;
1810af245d11STodd Fiala 
1811af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1812af245d11STodd Fiala     if (log)
1813af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
181498d0a4b3SChaoren Lin                 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1815af245d11STodd Fiala 
1816af245d11STodd Fiala     if (kill(GetID(), signo))
1817af245d11STodd Fiala         error.SetErrorToErrno();
1818af245d11STodd Fiala 
1819af245d11STodd Fiala     return error;
1820af245d11STodd Fiala }
1821af245d11STodd Fiala 
1822af245d11STodd Fiala Error
1823e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
1824e9547b80SChaoren Lin {
1825e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
1826e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
1827e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1828e9547b80SChaoren Lin 
1829e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
1830e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
1831e9547b80SChaoren Lin 
1832e9547b80SChaoren Lin     if (log)
1833e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1834e9547b80SChaoren Lin 
1835e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
1836e9547b80SChaoren Lin     {
1837e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
1838e9547b80SChaoren Lin         if (!thread_sp)
1839e9547b80SChaoren Lin             continue;
1840e9547b80SChaoren Lin 
1841e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
1842e9547b80SChaoren Lin         // target of the interrupt.
1843e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
1844e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
1845e9547b80SChaoren Lin             thread_state == eStateStepping)
1846e9547b80SChaoren Lin         {
1847e9547b80SChaoren Lin             running_thread_sp = thread_sp;
1848e9547b80SChaoren Lin             break;
1849e9547b80SChaoren Lin         }
1850e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1851e9547b80SChaoren Lin         {
1852e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
1853e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
1854e9547b80SChaoren Lin         }
1855e9547b80SChaoren Lin     }
1856e9547b80SChaoren Lin 
1857e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
1858e9547b80SChaoren Lin     {
18595830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
1860e9547b80SChaoren Lin         if (log)
1861e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
18625830aa75STamas Berghammer 
1863e9547b80SChaoren Lin         return error;
1864e9547b80SChaoren Lin     }
1865e9547b80SChaoren Lin 
1866e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1867e9547b80SChaoren Lin 
1868e9547b80SChaoren Lin     if (log)
1869e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1870e9547b80SChaoren Lin                      __FUNCTION__,
1871e9547b80SChaoren Lin                      GetID (),
1872e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
1873e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
1874e9547b80SChaoren Lin 
1875ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
187645f5cb31SPavel Labath 
18775830aa75STamas Berghammer     return Error();
1878e9547b80SChaoren Lin }
1879e9547b80SChaoren Lin 
1880e9547b80SChaoren Lin Error
1881af245d11STodd Fiala NativeProcessLinux::Kill ()
1882af245d11STodd Fiala {
1883af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1884af245d11STodd Fiala     if (log)
1885af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1886af245d11STodd Fiala 
1887af245d11STodd Fiala     Error error;
1888af245d11STodd Fiala 
1889af245d11STodd Fiala     switch (m_state)
1890af245d11STodd Fiala     {
1891af245d11STodd Fiala         case StateType::eStateInvalid:
1892af245d11STodd Fiala         case StateType::eStateExited:
1893af245d11STodd Fiala         case StateType::eStateCrashed:
1894af245d11STodd Fiala         case StateType::eStateDetached:
1895af245d11STodd Fiala         case StateType::eStateUnloaded:
1896af245d11STodd Fiala             // Nothing to do - the process is already dead.
1897af245d11STodd Fiala             if (log)
1898af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1899af245d11STodd Fiala             return error;
1900af245d11STodd Fiala 
1901af245d11STodd Fiala         case StateType::eStateConnected:
1902af245d11STodd Fiala         case StateType::eStateAttaching:
1903af245d11STodd Fiala         case StateType::eStateLaunching:
1904af245d11STodd Fiala         case StateType::eStateStopped:
1905af245d11STodd Fiala         case StateType::eStateRunning:
1906af245d11STodd Fiala         case StateType::eStateStepping:
1907af245d11STodd Fiala         case StateType::eStateSuspended:
1908af245d11STodd Fiala             // We can try to kill a process in these states.
1909af245d11STodd Fiala             break;
1910af245d11STodd Fiala     }
1911af245d11STodd Fiala 
1912af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
1913af245d11STodd Fiala     {
1914af245d11STodd Fiala         error.SetErrorToErrno ();
1915af245d11STodd Fiala         return error;
1916af245d11STodd Fiala     }
1917af245d11STodd Fiala 
1918af245d11STodd Fiala     return error;
1919af245d11STodd Fiala }
1920af245d11STodd Fiala 
1921af245d11STodd Fiala static Error
1922af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1923af245d11STodd Fiala {
1924af245d11STodd Fiala     memory_region_info.Clear();
1925af245d11STodd Fiala 
1926af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
1927af245d11STodd Fiala 
1928af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
1929af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
1930af245d11STodd Fiala 
1931af245d11STodd Fiala     // Parse out the starting address
1932af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1933af245d11STodd Fiala 
1934af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
1935af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1936af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1937af245d11STodd Fiala 
1938af245d11STodd Fiala     // Parse out the ending address
1939af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1940af245d11STodd Fiala 
1941af245d11STodd Fiala     // Parse out the space after the address.
1942af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1943af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1944af245d11STodd Fiala 
1945af245d11STodd Fiala     // Save the range.
1946af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
1947af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
1948af245d11STodd Fiala 
1949af245d11STodd Fiala     // Parse out each permission entry.
1950af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
1951af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1952af245d11STodd Fiala 
1953af245d11STodd Fiala     // Handle read permission.
1954af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
1955af245d11STodd Fiala     if (read_perm_char == 'r')
1956af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1957af245d11STodd Fiala     else
1958af245d11STodd Fiala     {
1959af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1960af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1961af245d11STodd Fiala     }
1962af245d11STodd Fiala 
1963af245d11STodd Fiala     // Handle write permission.
1964af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
1965af245d11STodd Fiala     if (write_perm_char == 'w')
1966af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1967af245d11STodd Fiala     else
1968af245d11STodd Fiala     {
1969af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1970af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1971af245d11STodd Fiala     }
1972af245d11STodd Fiala 
1973af245d11STodd Fiala     // Handle execute permission.
1974af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
1975af245d11STodd Fiala     if (exec_perm_char == 'x')
1976af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1977af245d11STodd Fiala     else
1978af245d11STodd Fiala     {
1979af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1980af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1981af245d11STodd Fiala     }
1982af245d11STodd Fiala 
1983af245d11STodd Fiala     return Error ();
1984af245d11STodd Fiala }
1985af245d11STodd Fiala 
1986af245d11STodd Fiala Error
1987af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1988af245d11STodd Fiala {
1989af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
1990af245d11STodd Fiala     // with no perms if it is not mapped.
1991af245d11STodd Fiala 
1992af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
1993af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
1994af245d11STodd Fiala     // FIXME assert if we find differently.
1995af245d11STodd Fiala 
1996af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1997af245d11STodd Fiala     Error error;
1998af245d11STodd Fiala 
1999af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2000af245d11STodd Fiala     {
2001af245d11STodd Fiala         // We're done.
2002af245d11STodd Fiala         error.SetErrorString ("unsupported");
2003af245d11STodd Fiala         return error;
2004af245d11STodd Fiala     }
2005af245d11STodd Fiala 
2006af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
2007af245d11STodd Fiala     // if memory region handling is supported.
2008af245d11STodd Fiala     if (m_mem_region_cache.empty ())
2009af245d11STodd Fiala     {
2010af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2011af245d11STodd Fiala              [&] (const std::string &line) -> bool
2012af245d11STodd Fiala              {
2013af245d11STodd Fiala                  MemoryRegionInfo info;
2014af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2015af245d11STodd Fiala                  if (parse_error.Success ())
2016af245d11STodd Fiala                  {
2017af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
2018af245d11STodd Fiala                      return true;
2019af245d11STodd Fiala                  }
2020af245d11STodd Fiala                  else
2021af245d11STodd Fiala                  {
2022af245d11STodd Fiala                      if (log)
2023af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2024af245d11STodd Fiala                      return false;
2025af245d11STodd Fiala                  }
2026af245d11STodd Fiala              });
2027af245d11STodd Fiala 
2028af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
2029af245d11STodd Fiala         if (error.Fail ())
2030af245d11STodd Fiala         {
2031af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2032af245d11STodd Fiala             return error;
2033af245d11STodd Fiala         }
2034af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
2035af245d11STodd Fiala         {
2036af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2037af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
2038af245d11STodd Fiala             if (log)
2039af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2040af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2041af245d11STodd Fiala             error.SetErrorString ("not supported");
2042af245d11STodd Fiala             return error;
2043af245d11STodd Fiala         }
2044af245d11STodd Fiala 
2045af245d11STodd Fiala         if (log)
2046af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2047af245d11STodd Fiala 
2048af245d11STodd Fiala         // We support memory retrieval, remember that.
2049af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
2050af245d11STodd Fiala     }
2051af245d11STodd Fiala     else
2052af245d11STodd Fiala     {
2053af245d11STodd Fiala         if (log)
2054af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2055af245d11STodd Fiala     }
2056af245d11STodd Fiala 
2057af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
2058af245d11STodd Fiala 
2059af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2060af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
2061af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2062af245d11STodd Fiala     {
2063af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
2064af245d11STodd Fiala 
2065af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2066af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2067af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2068af245d11STodd Fiala 
2069af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
2070af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2071af245d11STodd Fiala         {
2072af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
2073af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2074af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2075af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2076af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2077af245d11STodd Fiala 
2078af245d11STodd Fiala             return error;
2079af245d11STodd Fiala         }
2080af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
2081af245d11STodd Fiala         {
2082af245d11STodd Fiala             // The target address is within the memory region we're processing here.
2083af245d11STodd Fiala             range_info = proc_entry_info;
2084af245d11STodd Fiala             return error;
2085af245d11STodd Fiala         }
2086af245d11STodd Fiala 
2087af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
2088af245d11STodd Fiala     }
2089af245d11STodd Fiala 
209009839c33STamas Berghammer     // If we made it here, we didn't find an entry that contained the given address. Return the
209109839c33STamas Berghammer     // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
209209839c33STamas Berghammer     // size.
209309839c33STamas Berghammer     range_info.GetRange ().SetRangeBase (load_addr);
209409839c33STamas Berghammer     switch (m_arch.GetAddressByteSize())
209509839c33STamas Berghammer     {
209609839c33STamas Berghammer         case 4:
209709839c33STamas Berghammer             range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
209809839c33STamas Berghammer             break;
209909839c33STamas Berghammer         case 8:
210009839c33STamas Berghammer             range_info.GetRange ().SetByteSize (0ull - load_addr);
210109839c33STamas Berghammer             break;
210209839c33STamas Berghammer         default:
210309839c33STamas Berghammer             assert(false && "Unrecognized data byte size");
210409839c33STamas Berghammer             break;
210509839c33STamas Berghammer     }
210609839c33STamas Berghammer     range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
210709839c33STamas Berghammer     range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
210809839c33STamas Berghammer     range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2109af245d11STodd Fiala     return error;
2110af245d11STodd Fiala }
2111af245d11STodd Fiala 
2112af245d11STodd Fiala void
2113af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2114af245d11STodd Fiala {
2115af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2116af245d11STodd Fiala     if (log)
2117af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2118af245d11STodd Fiala 
2119af245d11STodd Fiala         if (log)
2120af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2121af245d11STodd Fiala         m_mem_region_cache.clear ();
2122af245d11STodd Fiala }
2123af245d11STodd Fiala 
2124af245d11STodd Fiala Error
21253eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2126af245d11STodd Fiala {
2127af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
2128af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2129af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
2130af245d11STodd Fiala #if 1
2131af245d11STodd Fiala     return Error ("not implemented yet");
2132af245d11STodd Fiala #else
2133af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
2134af245d11STodd Fiala 
2135af245d11STodd Fiala     unsigned prot = 0;
2136af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
2137af245d11STodd Fiala         prot |= eMmapProtRead;
2138af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
2139af245d11STodd Fiala         prot |= eMmapProtWrite;
2140af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
2141af245d11STodd Fiala         prot |= eMmapProtExec;
2142af245d11STodd Fiala 
2143af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
2144af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
2145af245d11STodd Fiala     // refactored out).
2146af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
2147af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2148af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
2149af245d11STodd Fiala         return Error ();
2150af245d11STodd Fiala     } else {
2151af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
2152af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2153af245d11STodd Fiala     }
2154af245d11STodd Fiala #endif
2155af245d11STodd Fiala }
2156af245d11STodd Fiala 
2157af245d11STodd Fiala Error
2158af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2159af245d11STodd Fiala {
2160af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
2161af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
2162af245d11STodd Fiala     return Error ("not implemented");
2163af245d11STodd Fiala }
2164af245d11STodd Fiala 
2165af245d11STodd Fiala lldb::addr_t
2166af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
2167af245d11STodd Fiala {
2168af245d11STodd Fiala #if 1
2169af245d11STodd Fiala     // punt on this for now
2170af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2171af245d11STodd Fiala #else
2172af245d11STodd Fiala     // Return the image info address for the exe module
2173af245d11STodd Fiala #if 1
2174af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2175af245d11STodd Fiala 
2176af245d11STodd Fiala     ModuleSP module_sp;
2177af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
2178af245d11STodd Fiala     if (error.Fail ())
2179af245d11STodd Fiala     {
2180af245d11STodd Fiala          if (log)
2181af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2182af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
2183af245d11STodd Fiala     }
2184af245d11STodd Fiala 
2185af245d11STodd Fiala     if (module_sp == nullptr)
2186af245d11STodd Fiala     {
2187af245d11STodd Fiala          if (log)
2188af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2189af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2190af245d11STodd Fiala     }
2191af245d11STodd Fiala 
2192af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2193af245d11STodd Fiala     if (object_file_sp == nullptr)
2194af245d11STodd Fiala     {
2195af245d11STodd Fiala          if (log)
2196af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2197af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2198af245d11STodd Fiala     }
2199af245d11STodd Fiala 
2200af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
2201af245d11STodd Fiala #else
2202af245d11STodd Fiala     Target *target = &GetTarget();
2203af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2204af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
2205af245d11STodd Fiala 
2206af245d11STodd Fiala     if (addr.IsValid())
2207af245d11STodd Fiala         return addr.GetLoadAddress(target);
2208af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2209af245d11STodd Fiala #endif
2210af245d11STodd Fiala #endif // punt on this for now
2211af245d11STodd Fiala }
2212af245d11STodd Fiala 
2213af245d11STodd Fiala size_t
2214af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
2215af245d11STodd Fiala {
2216af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
2217af245d11STodd Fiala     // with respect to thread state and they keep the thread list
2218af245d11STodd Fiala     // populated properly. All this method needs to do is return the
2219af245d11STodd Fiala     // thread count.
2220af245d11STodd Fiala     return m_threads.size ();
2221af245d11STodd Fiala }
2222af245d11STodd Fiala 
2223af245d11STodd Fiala bool
2224af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2225af245d11STodd Fiala {
2226af245d11STodd Fiala     arch = m_arch;
2227af245d11STodd Fiala     return true;
2228af245d11STodd Fiala }
2229af245d11STodd Fiala 
2230af245d11STodd Fiala Error
2231b9cc0c75SPavel Labath NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
2232af245d11STodd Fiala {
2233af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
2234af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
2235af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
2236bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2237af245d11STodd Fiala 
2238af245d11STodd Fiala     switch (m_arch.GetMachine ())
2239af245d11STodd Fiala     {
2240af245d11STodd Fiala         case llvm::Triple::x86:
2241af245d11STodd Fiala         case llvm::Triple::x86_64:
2242af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2243af245d11STodd Fiala             return Error ();
2244af245d11STodd Fiala 
2245bb00d0b6SUlrich Weigand         case llvm::Triple::systemz:
2246bb00d0b6SUlrich Weigand             actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2247bb00d0b6SUlrich Weigand             return Error ();
2248bb00d0b6SUlrich Weigand 
2249ff7fd900STamas Berghammer         case llvm::Triple::arm:
2250ff7fd900STamas Berghammer         case llvm::Triple::aarch64:
2251e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
2252e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
2253ce815e45SSagar Thakur         case llvm::Triple::mips:
2254ce815e45SSagar Thakur         case llvm::Triple::mipsel:
2255ff7fd900STamas Berghammer             // On these architectures the PC don't get updated for breakpoint hits
2256c60c9452SJaydeep Patil             actual_opcode_size = 0;
2257e8659b5dSMohit K. Bhakkad             return Error ();
2258e8659b5dSMohit K. Bhakkad 
2259af245d11STodd Fiala         default:
2260af245d11STodd Fiala             assert(false && "CPU type not supported!");
2261af245d11STodd Fiala             return Error ("CPU type not supported");
2262af245d11STodd Fiala     }
2263af245d11STodd Fiala }
2264af245d11STodd Fiala 
2265af245d11STodd Fiala Error
2266af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2267af245d11STodd Fiala {
2268af245d11STodd Fiala     if (hardware)
2269af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
2270af245d11STodd Fiala     else
2271af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
2272af245d11STodd Fiala }
2273af245d11STodd Fiala 
2274af245d11STodd Fiala Error
227563c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
227663c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
227763c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
2278af245d11STodd Fiala {
227963c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
228063c8be95STamas Berghammer     // architecture.  Need MIPS support here.
22812afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2282be379e15STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2283be379e15STamas Berghammer     // linux kernel does otherwise.
2284be379e15STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
2285af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
22863df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
22872c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
2288bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2289be379e15STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
2290af245d11STodd Fiala 
2291af245d11STodd Fiala     switch (m_arch.GetMachine ())
2292af245d11STodd Fiala     {
22932afc5966STodd Fiala     case llvm::Triple::aarch64:
22942afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
22952afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
22962afc5966STodd Fiala         return Error ();
22972afc5966STodd Fiala 
229863c8be95STamas Berghammer     case llvm::Triple::arm:
229963c8be95STamas Berghammer         switch (trap_opcode_size_hint)
230063c8be95STamas Berghammer         {
230163c8be95STamas Berghammer         case 2:
230263c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
230363c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
230463c8be95STamas Berghammer             return Error ();
230563c8be95STamas Berghammer         case 4:
230663c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
230763c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
230863c8be95STamas Berghammer             return Error ();
230963c8be95STamas Berghammer         default:
231063c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
231163c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
231263c8be95STamas Berghammer         }
231363c8be95STamas Berghammer 
2314af245d11STodd Fiala     case llvm::Triple::x86:
2315af245d11STodd Fiala     case llvm::Triple::x86_64:
2316af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
2317af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
2318af245d11STodd Fiala         return Error ();
2319af245d11STodd Fiala 
2320ce815e45SSagar Thakur     case llvm::Triple::mips:
23213df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
23223df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
23233df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
23243df471c3SMohit K. Bhakkad         return Error ();
23253df471c3SMohit K. Bhakkad 
2326ce815e45SSagar Thakur     case llvm::Triple::mipsel:
23272c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
23282c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
23292c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
23302c2acf96SMohit K. Bhakkad         return Error ();
23312c2acf96SMohit K. Bhakkad 
2332bb00d0b6SUlrich Weigand     case llvm::Triple::systemz:
2333bb00d0b6SUlrich Weigand         trap_opcode_bytes = g_s390x_opcode;
2334bb00d0b6SUlrich Weigand         actual_opcode_size = sizeof(g_s390x_opcode);
2335bb00d0b6SUlrich Weigand         return Error ();
2336bb00d0b6SUlrich Weigand 
2337af245d11STodd Fiala     default:
2338af245d11STodd Fiala         assert(false && "CPU type not supported!");
2339af245d11STodd Fiala         return Error ("CPU type not supported");
2340af245d11STodd Fiala     }
2341af245d11STodd Fiala }
2342af245d11STodd Fiala 
2343af245d11STodd Fiala #if 0
2344af245d11STodd Fiala ProcessMessage::CrashReason
2345af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2346af245d11STodd Fiala {
2347af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2348af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
2349af245d11STodd Fiala 
2350af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2351af245d11STodd Fiala 
2352af245d11STodd Fiala     switch (info->si_code)
2353af245d11STodd Fiala     {
2354af245d11STodd Fiala     default:
2355af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
2356af245d11STodd Fiala         break;
2357af245d11STodd Fiala     case SI_KERNEL:
2358af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
2359af245d11STodd Fiala         // (this is poorly documented in sigaction)
2360af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
2361af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2362af245d11STodd Fiala         break;
2363af245d11STodd Fiala     case SEGV_MAPERR:
2364af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2365af245d11STodd Fiala         break;
2366af245d11STodd Fiala     case SEGV_ACCERR:
2367af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2368af245d11STodd Fiala         break;
2369af245d11STodd Fiala     }
2370af245d11STodd Fiala 
2371af245d11STodd Fiala     return reason;
2372af245d11STodd Fiala }
2373af245d11STodd Fiala #endif
2374af245d11STodd Fiala 
2375af245d11STodd Fiala 
2376af245d11STodd Fiala #if 0
2377af245d11STodd Fiala ProcessMessage::CrashReason
2378af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2379af245d11STodd Fiala {
2380af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2381af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2382af245d11STodd Fiala 
2383af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2384af245d11STodd Fiala 
2385af245d11STodd Fiala     switch (info->si_code)
2386af245d11STodd Fiala     {
2387af245d11STodd Fiala     default:
2388af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2389af245d11STodd Fiala         break;
2390af245d11STodd Fiala     case ILL_ILLOPC:
2391af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2392af245d11STodd Fiala         break;
2393af245d11STodd Fiala     case ILL_ILLOPN:
2394af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
2395af245d11STodd Fiala         break;
2396af245d11STodd Fiala     case ILL_ILLADR:
2397af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
2398af245d11STodd Fiala         break;
2399af245d11STodd Fiala     case ILL_ILLTRP:
2400af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
2401af245d11STodd Fiala         break;
2402af245d11STodd Fiala     case ILL_PRVOPC:
2403af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
2404af245d11STodd Fiala         break;
2405af245d11STodd Fiala     case ILL_PRVREG:
2406af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
2407af245d11STodd Fiala         break;
2408af245d11STodd Fiala     case ILL_COPROC:
2409af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
2410af245d11STodd Fiala         break;
2411af245d11STodd Fiala     case ILL_BADSTK:
2412af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
2413af245d11STodd Fiala         break;
2414af245d11STodd Fiala     }
2415af245d11STodd Fiala 
2416af245d11STodd Fiala     return reason;
2417af245d11STodd Fiala }
2418af245d11STodd Fiala #endif
2419af245d11STodd Fiala 
2420af245d11STodd Fiala #if 0
2421af245d11STodd Fiala ProcessMessage::CrashReason
2422af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2423af245d11STodd Fiala {
2424af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2425af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
2426af245d11STodd Fiala 
2427af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2428af245d11STodd Fiala 
2429af245d11STodd Fiala     switch (info->si_code)
2430af245d11STodd Fiala     {
2431af245d11STodd Fiala     default:
2432af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
2433af245d11STodd Fiala         break;
2434af245d11STodd Fiala     case FPE_INTDIV:
2435af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
2436af245d11STodd Fiala         break;
2437af245d11STodd Fiala     case FPE_INTOVF:
2438af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
2439af245d11STodd Fiala         break;
2440af245d11STodd Fiala     case FPE_FLTDIV:
2441af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
2442af245d11STodd Fiala         break;
2443af245d11STodd Fiala     case FPE_FLTOVF:
2444af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
2445af245d11STodd Fiala         break;
2446af245d11STodd Fiala     case FPE_FLTUND:
2447af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
2448af245d11STodd Fiala         break;
2449af245d11STodd Fiala     case FPE_FLTRES:
2450af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
2451af245d11STodd Fiala         break;
2452af245d11STodd Fiala     case FPE_FLTINV:
2453af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
2454af245d11STodd Fiala         break;
2455af245d11STodd Fiala     case FPE_FLTSUB:
2456af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
2457af245d11STodd Fiala         break;
2458af245d11STodd Fiala     }
2459af245d11STodd Fiala 
2460af245d11STodd Fiala     return reason;
2461af245d11STodd Fiala }
2462af245d11STodd Fiala #endif
2463af245d11STodd Fiala 
2464af245d11STodd Fiala #if 0
2465af245d11STodd Fiala ProcessMessage::CrashReason
2466af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2467af245d11STodd Fiala {
2468af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2469af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
2470af245d11STodd Fiala 
2471af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2472af245d11STodd Fiala 
2473af245d11STodd Fiala     switch (info->si_code)
2474af245d11STodd Fiala     {
2475af245d11STodd Fiala     default:
2476af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
2477af245d11STodd Fiala         break;
2478af245d11STodd Fiala     case BUS_ADRALN:
2479af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
2480af245d11STodd Fiala         break;
2481af245d11STodd Fiala     case BUS_ADRERR:
2482af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
2483af245d11STodd Fiala         break;
2484af245d11STodd Fiala     case BUS_OBJERR:
2485af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
2486af245d11STodd Fiala         break;
2487af245d11STodd Fiala     }
2488af245d11STodd Fiala 
2489af245d11STodd Fiala     return reason;
2490af245d11STodd Fiala }
2491af245d11STodd Fiala #endif
2492af245d11STodd Fiala 
2493af245d11STodd Fiala Error
249426438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2495af245d11STodd Fiala {
2496df7c6995SPavel Labath     if (ProcessVmReadvSupported()) {
2497df7c6995SPavel Labath         // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2498df7c6995SPavel Labath         // this syscall if it is supported.
2499df7c6995SPavel Labath 
2500df7c6995SPavel Labath         const ::pid_t pid = GetID();
2501df7c6995SPavel Labath 
2502df7c6995SPavel Labath         struct iovec local_iov, remote_iov;
2503df7c6995SPavel Labath         local_iov.iov_base = buf;
2504df7c6995SPavel Labath         local_iov.iov_len = size;
2505df7c6995SPavel Labath         remote_iov.iov_base = reinterpret_cast<void *>(addr);
2506df7c6995SPavel Labath         remote_iov.iov_len = size;
2507df7c6995SPavel Labath 
2508df7c6995SPavel Labath         bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2509df7c6995SPavel Labath         const bool success = bytes_read == size;
2510df7c6995SPavel Labath 
2511df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2512df7c6995SPavel Labath         if (log)
2513df7c6995SPavel Labath             log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2514df7c6995SPavel Labath                     __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2515df7c6995SPavel Labath 
2516df7c6995SPavel Labath         if (success)
2517df7c6995SPavel Labath             return Error();
2518df7c6995SPavel Labath         // else
2519df7c6995SPavel Labath         //     the call failed for some reason, let's retry the read using ptrace api.
2520df7c6995SPavel Labath     }
2521df7c6995SPavel Labath 
252219cbe96aSPavel Labath     unsigned char *dst = static_cast<unsigned char*>(buf);
252319cbe96aSPavel Labath     size_t remainder;
252419cbe96aSPavel Labath     long data;
252519cbe96aSPavel Labath 
252619cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
252719cbe96aSPavel Labath     if (log)
252819cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
252919cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
253019cbe96aSPavel Labath         log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
253119cbe96aSPavel Labath 
253219cbe96aSPavel Labath     for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
253319cbe96aSPavel Labath     {
253419cbe96aSPavel Labath         Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
253519cbe96aSPavel Labath         if (error.Fail())
253619cbe96aSPavel Labath         {
253719cbe96aSPavel Labath             if (log)
253819cbe96aSPavel Labath                 ProcessPOSIXLog::DecNestLevel();
253919cbe96aSPavel Labath             return error;
254019cbe96aSPavel Labath         }
254119cbe96aSPavel Labath 
254219cbe96aSPavel Labath         remainder = size - bytes_read;
254319cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
254419cbe96aSPavel Labath 
254519cbe96aSPavel Labath         // Copy the data into our buffer
2546f6ef187bSMohit K. Bhakkad         memcpy(dst, &data, remainder);
254719cbe96aSPavel Labath 
254819cbe96aSPavel Labath         if (log && ProcessPOSIXLog::AtTopNestLevel() &&
254919cbe96aSPavel Labath                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
255019cbe96aSPavel Labath                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
255119cbe96aSPavel Labath                                 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
255219cbe96aSPavel Labath         {
255319cbe96aSPavel Labath             uintptr_t print_dst = 0;
255419cbe96aSPavel Labath             // Format bytes from data by moving into print_dst for log output
255519cbe96aSPavel Labath             for (unsigned i = 0; i < remainder; ++i)
255619cbe96aSPavel Labath                 print_dst |= (((data >> i*8) & 0xFF) << i*8);
255779203995SPavel Labath             log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
255879203995SPavel Labath                     __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
255919cbe96aSPavel Labath         }
256019cbe96aSPavel Labath         addr += k_ptrace_word_size;
256119cbe96aSPavel Labath         dst += k_ptrace_word_size;
256219cbe96aSPavel Labath     }
256319cbe96aSPavel Labath 
256419cbe96aSPavel Labath     if (log)
256519cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
256619cbe96aSPavel Labath     return Error();
2567af245d11STodd Fiala }
2568af245d11STodd Fiala 
2569af245d11STodd Fiala Error
25703eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
25713eb4b458SChaoren Lin {
25723eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
25733eb4b458SChaoren Lin     if (error.Fail()) return error;
25743eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
25753eb4b458SChaoren Lin }
25763eb4b458SChaoren Lin 
25773eb4b458SChaoren Lin Error
25783eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
2579af245d11STodd Fiala {
258019cbe96aSPavel Labath     const unsigned char *src = static_cast<const unsigned char*>(buf);
258119cbe96aSPavel Labath     size_t remainder;
258219cbe96aSPavel Labath     Error error;
258319cbe96aSPavel Labath 
258419cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
258519cbe96aSPavel Labath     if (log)
258619cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
258719cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
258879203995SPavel Labath         log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
258919cbe96aSPavel Labath 
259019cbe96aSPavel Labath     for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
259119cbe96aSPavel Labath     {
259219cbe96aSPavel Labath         remainder = size - bytes_written;
259319cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
259419cbe96aSPavel Labath 
259519cbe96aSPavel Labath         if (remainder == k_ptrace_word_size)
259619cbe96aSPavel Labath         {
259719cbe96aSPavel Labath             unsigned long data = 0;
2598f6ef187bSMohit K. Bhakkad             memcpy(&data, src, k_ptrace_word_size);
259919cbe96aSPavel Labath 
260019cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
260119cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
260219cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
260319cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
260419cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
260519cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, data);
260619cbe96aSPavel Labath 
260719cbe96aSPavel Labath             error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
260819cbe96aSPavel Labath             if (error.Fail())
260919cbe96aSPavel Labath             {
261019cbe96aSPavel Labath                 if (log)
261119cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
261219cbe96aSPavel Labath                 return error;
261319cbe96aSPavel Labath             }
261419cbe96aSPavel Labath         }
261519cbe96aSPavel Labath         else
261619cbe96aSPavel Labath         {
261719cbe96aSPavel Labath             unsigned char buff[8];
261819cbe96aSPavel Labath             size_t bytes_read;
261919cbe96aSPavel Labath             error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
262019cbe96aSPavel Labath             if (error.Fail())
262119cbe96aSPavel Labath             {
262219cbe96aSPavel Labath                 if (log)
262319cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
262419cbe96aSPavel Labath                 return error;
262519cbe96aSPavel Labath             }
262619cbe96aSPavel Labath 
262719cbe96aSPavel Labath             memcpy(buff, src, remainder);
262819cbe96aSPavel Labath 
262919cbe96aSPavel Labath             size_t bytes_written_rec;
263019cbe96aSPavel Labath             error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
263119cbe96aSPavel Labath             if (error.Fail())
263219cbe96aSPavel Labath             {
263319cbe96aSPavel Labath                 if (log)
263419cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
263519cbe96aSPavel Labath                 return error;
263619cbe96aSPavel Labath             }
263719cbe96aSPavel Labath 
263819cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
263919cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
264019cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
264119cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
264219cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
264319cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
264419cbe96aSPavel Labath         }
264519cbe96aSPavel Labath 
264619cbe96aSPavel Labath         addr += k_ptrace_word_size;
264719cbe96aSPavel Labath         src += k_ptrace_word_size;
264819cbe96aSPavel Labath     }
264919cbe96aSPavel Labath     if (log)
265019cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
265119cbe96aSPavel Labath     return error;
2652af245d11STodd Fiala }
2653af245d11STodd Fiala 
265497ccc294SChaoren Lin Error
265597ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
2656af245d11STodd Fiala {
265719cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2658af245d11STodd Fiala }
2659af245d11STodd Fiala 
266097ccc294SChaoren Lin Error
2661af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2662af245d11STodd Fiala {
266319cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2664af245d11STodd Fiala }
2665af245d11STodd Fiala 
2666db264a6dSTamas Berghammer Error
2667af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
2668af245d11STodd Fiala {
266997ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
267097ccc294SChaoren Lin         return Error();
267197ccc294SChaoren Lin 
267219cbe96aSPavel Labath     return PtraceWrapper(PTRACE_DETACH, tid);
2673af245d11STodd Fiala }
2674af245d11STodd Fiala 
2675af245d11STodd Fiala bool
2676d3173f34SChaoren Lin NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
2677af245d11STodd Fiala {
2678d3173f34SChaoren Lin     int target_fd = open(file_spec.GetCString(), flags, 0666);
2679af245d11STodd Fiala 
2680af245d11STodd Fiala     if (target_fd == -1)
2681af245d11STodd Fiala         return false;
2682af245d11STodd Fiala 
2683493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
2684493c3a12SPavel Labath         return false;
2685493c3a12SPavel Labath 
2686493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
2687af245d11STodd Fiala }
2688af245d11STodd Fiala 
2689af245d11STodd Fiala bool
2690af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2691af245d11STodd Fiala {
2692af245d11STodd Fiala     for (auto thread_sp : m_threads)
2693af245d11STodd Fiala     {
2694af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2695af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
2696af245d11STodd Fiala         {
2697af245d11STodd Fiala             // We have this thread.
2698af245d11STodd Fiala             return true;
2699af245d11STodd Fiala         }
2700af245d11STodd Fiala     }
2701af245d11STodd Fiala 
2702af245d11STodd Fiala     // We don't have this thread.
2703af245d11STodd Fiala     return false;
2704af245d11STodd Fiala }
2705af245d11STodd Fiala 
2706af245d11STodd Fiala bool
2707af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2708af245d11STodd Fiala {
27091dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
27101dbc6c9cSPavel Labath 
27111dbc6c9cSPavel Labath     if (log)
27121dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
27131dbc6c9cSPavel Labath 
27141dbc6c9cSPavel Labath     bool found = false;
27151dbc6c9cSPavel Labath 
2716af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2717af245d11STodd Fiala     {
2718af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
2719af245d11STodd Fiala         {
2720af245d11STodd Fiala             m_threads.erase (it);
27211dbc6c9cSPavel Labath             found = true;
27221dbc6c9cSPavel Labath             break;
2723af245d11STodd Fiala         }
2724af245d11STodd Fiala     }
2725af245d11STodd Fiala 
27269eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
27271dbc6c9cSPavel Labath 
27281dbc6c9cSPavel Labath     return found;
2729af245d11STodd Fiala }
2730af245d11STodd Fiala 
2731f9077782SPavel Labath NativeThreadLinuxSP
2732af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2733af245d11STodd Fiala {
2734af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2735af245d11STodd Fiala 
2736af245d11STodd Fiala     if (log)
2737af245d11STodd Fiala     {
2738af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2739af245d11STodd Fiala                 __FUNCTION__,
2740af245d11STodd Fiala                 GetID (),
2741af245d11STodd Fiala                 thread_id);
2742af245d11STodd Fiala     }
2743af245d11STodd Fiala 
2744af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2745af245d11STodd Fiala 
2746af245d11STodd Fiala     // If this is the first thread, save it as the current thread
2747af245d11STodd Fiala     if (m_threads.empty ())
2748af245d11STodd Fiala         SetCurrentThreadID (thread_id);
2749af245d11STodd Fiala 
2750f9077782SPavel Labath     auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2751af245d11STodd Fiala     m_threads.push_back (thread_sp);
2752af245d11STodd Fiala     return thread_sp;
2753af245d11STodd Fiala }
2754af245d11STodd Fiala 
2755af245d11STodd Fiala Error
2756b9cc0c75SPavel Labath NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
2757af245d11STodd Fiala {
275875f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2759af245d11STodd Fiala 
2760af245d11STodd Fiala     Error error;
2761af245d11STodd Fiala 
2762af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
2763b9cc0c75SPavel Labath     NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2764af245d11STodd Fiala     if (!context_sp)
2765af245d11STodd Fiala     {
2766af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2767af245d11STodd Fiala         if (log)
2768af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2769af245d11STodd Fiala         return error;
2770af245d11STodd Fiala     }
2771af245d11STodd Fiala 
2772af245d11STodd Fiala     uint32_t breakpoint_size = 0;
2773b9cc0c75SPavel Labath     error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2774af245d11STodd Fiala     if (error.Fail ())
2775af245d11STodd Fiala     {
2776af245d11STodd Fiala         if (log)
2777af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2778af245d11STodd Fiala         return error;
2779af245d11STodd Fiala     }
2780af245d11STodd Fiala     else
2781af245d11STodd Fiala     {
2782af245d11STodd Fiala         if (log)
2783af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2784af245d11STodd Fiala     }
2785af245d11STodd Fiala 
2786af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
2787c60c9452SJaydeep Patil     const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
2788af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
27893eb4b458SChaoren Lin     if (breakpoint_size > 0)
2790af245d11STodd Fiala     {
2791af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
27923eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
27933eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
2794af245d11STodd Fiala     }
2795af245d11STodd Fiala 
2796af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
2797af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
2798af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2799af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
2800af245d11STodd Fiala     {
2801af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
2802af245d11STodd Fiala         if (log)
2803af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2804af245d11STodd Fiala         return Error ();
2805af245d11STodd Fiala     }
2806af245d11STodd Fiala 
2807af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
2808af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
2809af245d11STodd Fiala     {
2810af245d11STodd Fiala         if (log)
2811af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2812af245d11STodd Fiala         return Error ();
2813af245d11STodd Fiala     }
2814af245d11STodd Fiala 
2815af245d11STodd Fiala     //
2816af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
2817af245d11STodd Fiala     //
2818af245d11STodd Fiala 
2819af245d11STodd Fiala     // Sanity check.
2820af245d11STodd Fiala     if (breakpoint_size == 0)
2821af245d11STodd Fiala     {
2822af245d11STodd Fiala         // Nothing to do!  How did we get here?
2823af245d11STodd Fiala         if (log)
2824af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", it is software, but the size is zero, nothing to do (unexpected)", __FUNCTION__, GetID (), breakpoint_addr);
2825af245d11STodd Fiala         return Error ();
2826af245d11STodd Fiala     }
2827af245d11STodd Fiala 
2828af245d11STodd Fiala     // Change the program counter.
2829af245d11STodd Fiala     if (log)
2830b9cc0c75SPavel Labath         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr, breakpoint_addr);
2831af245d11STodd Fiala 
2832af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
2833af245d11STodd Fiala     if (error.Fail ())
2834af245d11STodd Fiala     {
2835af245d11STodd Fiala         if (log)
2836b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
2837af245d11STodd Fiala         return error;
2838af245d11STodd Fiala     }
2839af245d11STodd Fiala 
2840af245d11STodd Fiala     return error;
2841af245d11STodd Fiala }
2842fa03ad2eSChaoren Lin 
28437cb18bf5STamas Berghammer Error
28447cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
28457cb18bf5STamas Berghammer {
28467cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
28477cb18bf5STamas Berghammer 
2848162fb8e8SPavel Labath     bool found = false;
28497cb18bf5STamas Berghammer     file_spec.Clear();
2850162fb8e8SPavel Labath     ProcFileReader::ProcessLineByLine(GetID(), "maps",
2851162fb8e8SPavel Labath         [&] (const std::string &line)
2852162fb8e8SPavel Labath         {
2853162fb8e8SPavel Labath             SmallVector<StringRef, 16> columns;
2854162fb8e8SPavel Labath             StringRef(line).split(columns, " ", -1, false);
2855162fb8e8SPavel Labath             if (columns.size() < 6)
2856162fb8e8SPavel Labath                 return true; // continue searching
2857162fb8e8SPavel Labath 
2858162fb8e8SPavel Labath             FileSpec this_file_spec(columns[5].str().c_str(), false);
2859162fb8e8SPavel Labath             if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2860162fb8e8SPavel Labath                 return true; // continue searching
2861162fb8e8SPavel Labath 
2862162fb8e8SPavel Labath             file_spec = this_file_spec;
2863162fb8e8SPavel Labath             found = true;
2864162fb8e8SPavel Labath             return false; // we are done
2865162fb8e8SPavel Labath         });
2866162fb8e8SPavel Labath 
2867162fb8e8SPavel Labath     if (! found)
28687cb18bf5STamas Berghammer         return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
28697cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
2870162fb8e8SPavel Labath 
2871162fb8e8SPavel Labath     return Error();
28727cb18bf5STamas Berghammer }
2873c076559aSPavel Labath 
28745eb721edSPavel Labath Error
2875783bfc8cSTamas Berghammer NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2876783bfc8cSTamas Berghammer {
2877783bfc8cSTamas Berghammer     load_addr = LLDB_INVALID_ADDRESS;
2878783bfc8cSTamas Berghammer     Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2879783bfc8cSTamas Berghammer         [&] (const std::string &line) -> bool
2880783bfc8cSTamas Berghammer         {
2881783bfc8cSTamas Berghammer             StringRef maps_row(line);
2882783bfc8cSTamas Berghammer 
2883783bfc8cSTamas Berghammer             SmallVector<StringRef, 16> maps_columns;
2884783bfc8cSTamas Berghammer             maps_row.split(maps_columns, StringRef(" "), -1, false);
2885783bfc8cSTamas Berghammer 
2886783bfc8cSTamas Berghammer             if (maps_columns.size() < 6)
2887783bfc8cSTamas Berghammer             {
2888783bfc8cSTamas Berghammer                 // Return true to continue reading the proc file
2889783bfc8cSTamas Berghammer                 return true;
2890783bfc8cSTamas Berghammer             }
2891783bfc8cSTamas Berghammer 
2892783bfc8cSTamas Berghammer             if (maps_columns[5] == file_name)
2893783bfc8cSTamas Berghammer             {
2894783bfc8cSTamas Berghammer                 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2895783bfc8cSTamas Berghammer                 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2896783bfc8cSTamas Berghammer 
2897783bfc8cSTamas Berghammer                 // Return false to stop reading the proc file further
2898783bfc8cSTamas Berghammer                 return false;
2899783bfc8cSTamas Berghammer             }
2900783bfc8cSTamas Berghammer 
2901783bfc8cSTamas Berghammer             // Return true to continue reading the proc file
2902783bfc8cSTamas Berghammer             return true;
2903783bfc8cSTamas Berghammer         });
2904783bfc8cSTamas Berghammer     return error;
2905783bfc8cSTamas Berghammer }
2906783bfc8cSTamas Berghammer 
2907f9077782SPavel Labath NativeThreadLinuxSP
2908f9077782SPavel Labath NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2909f9077782SPavel Labath {
2910f9077782SPavel Labath     return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2911f9077782SPavel Labath }
2912f9077782SPavel Labath 
2913783bfc8cSTamas Berghammer Error
2914b9cc0c75SPavel Labath NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
2915c076559aSPavel Labath {
29165eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
29175eb721edSPavel Labath 
29181dbc6c9cSPavel Labath     if (log)
29190e1d729bSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
2920b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
2921c076559aSPavel Labath 
2922c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
2923108c325dSPavel Labath     // stop notification that is currently waiting for
29240e1d729bSPavel Labath     // all threads to stop.  This is potentially a buggy situation since
2925c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
2926c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
2927c076559aSPavel Labath     // out the pending stop notification.
29280e1d729bSPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
2929c076559aSPavel Labath     {
2930b9cc0c75SPavel Labath         log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2931c076559aSPavel Labath     }
2932c076559aSPavel Labath 
2933c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
2934c076559aSPavel Labath     // to reflect it is running after this completes.
29350e1d729bSPavel Labath     switch (state)
2936c076559aSPavel Labath     {
29370e1d729bSPavel Labath     case eStateRunning:
29380e1d729bSPavel Labath     {
2939605b51b8SPavel Labath         const auto resume_result = thread.Resume(signo);
29400e1d729bSPavel Labath         if (resume_result.Success())
29410e1d729bSPavel Labath             SetState(eStateRunning, true);
29420e1d729bSPavel Labath         return resume_result;
2943c076559aSPavel Labath     }
29440e1d729bSPavel Labath     case eStateStepping:
29450e1d729bSPavel Labath     {
2946605b51b8SPavel Labath         const auto step_result = thread.SingleStep(signo);
29470e1d729bSPavel Labath         if (step_result.Success())
29480e1d729bSPavel Labath             SetState(eStateRunning, true);
29490e1d729bSPavel Labath         return step_result;
29500e1d729bSPavel Labath     }
29510e1d729bSPavel Labath     default:
29520e1d729bSPavel Labath         if (log)
29530e1d729bSPavel Labath             log->Printf("NativeProcessLinux::%s Unhandled state %s.",
29540e1d729bSPavel Labath                     __FUNCTION__, StateAsCString(state));
29550e1d729bSPavel Labath         llvm_unreachable("Unhandled state for resume");
29560e1d729bSPavel Labath     }
2957c076559aSPavel Labath }
2958c076559aSPavel Labath 
2959c076559aSPavel Labath //===----------------------------------------------------------------------===//
2960c076559aSPavel Labath 
2961c076559aSPavel Labath void
2962337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
2963c076559aSPavel Labath {
29645eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2965c076559aSPavel Labath 
29665eb721edSPavel Labath     if (log)
2967c076559aSPavel Labath     {
29685eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
2969c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
2970c076559aSPavel Labath     }
2971c076559aSPavel Labath 
29720e1d729bSPavel Labath     m_pending_notification_tid = triggering_tid;
29730e1d729bSPavel Labath 
29740e1d729bSPavel Labath     // Request a stop for all the thread stops that need to be stopped
29750e1d729bSPavel Labath     // and are not already known to be stopped.
29760e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
29770e1d729bSPavel Labath     {
29780e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
29790e1d729bSPavel Labath             static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
29800e1d729bSPavel Labath     }
29810e1d729bSPavel Labath 
29820e1d729bSPavel Labath     SignalIfAllThreadsStopped();
2983c076559aSPavel Labath 
29845eb721edSPavel Labath     if (log)
2985c076559aSPavel Labath     {
29865eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2987c076559aSPavel Labath     }
2988c076559aSPavel Labath }
2989c076559aSPavel Labath 
2990c076559aSPavel Labath void
29919eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
2992c076559aSPavel Labath {
29930e1d729bSPavel Labath     if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
29940e1d729bSPavel Labath         return; // No pending notification. Nothing to do.
29950e1d729bSPavel Labath 
29960e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
2997c076559aSPavel Labath     {
29980e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
29990e1d729bSPavel Labath             return; // Some threads are still running. Don't signal yet.
30000e1d729bSPavel Labath     }
30010e1d729bSPavel Labath 
30020e1d729bSPavel Labath     // We have a pending notification and all threads have stopped.
30039eb1ecb9SPavel Labath     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
30049eb1ecb9SPavel Labath 
30059eb1ecb9SPavel Labath     // Clear any temporary breakpoints we used to implement software single stepping.
30069eb1ecb9SPavel Labath     for (const auto &thread_info: m_threads_stepping_with_breakpoint)
30079eb1ecb9SPavel Labath     {
30089eb1ecb9SPavel Labath         Error error = RemoveBreakpoint (thread_info.second);
30099eb1ecb9SPavel Labath         if (error.Fail())
30109eb1ecb9SPavel Labath             if (log)
30119eb1ecb9SPavel Labath                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
30129eb1ecb9SPavel Labath                         __FUNCTION__, thread_info.first, error.AsCString());
30139eb1ecb9SPavel Labath     }
30149eb1ecb9SPavel Labath     m_threads_stepping_with_breakpoint.clear();
30159eb1ecb9SPavel Labath 
30169eb1ecb9SPavel Labath     // Notify the delegate about the stop
30170e1d729bSPavel Labath     SetCurrentThreadID(m_pending_notification_tid);
3018ed89c7feSPavel Labath     SetState(StateType::eStateStopped, true);
30190e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
3020c076559aSPavel Labath }
3021c076559aSPavel Labath 
3022c076559aSPavel Labath void
3023f9077782SPavel Labath NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
3024c076559aSPavel Labath {
30251dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
30261dbc6c9cSPavel Labath 
30271dbc6c9cSPavel Labath     if (log)
3028f9077782SPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
30291dbc6c9cSPavel Labath 
3030f9077782SPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
3031c076559aSPavel Labath     {
3032c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
3033c076559aSPavel Labath         // notification.
3034f9077782SPavel Labath         thread.RequestStop();
3035c076559aSPavel Labath     }
3036c076559aSPavel Labath }
3037068f8a7eSTamas Berghammer 
303819cbe96aSPavel Labath void
303919cbe96aSPavel Labath NativeProcessLinux::SigchldHandler()
3040068f8a7eSTamas Berghammer {
304119cbe96aSPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
304219cbe96aSPavel Labath     // Process all pending waitpid notifications.
304319cbe96aSPavel Labath     while (true)
304419cbe96aSPavel Labath     {
304519cbe96aSPavel Labath         int status = -1;
304619cbe96aSPavel Labath         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
304719cbe96aSPavel Labath 
304819cbe96aSPavel Labath         if (wait_pid == 0)
304919cbe96aSPavel Labath             break; // We are done.
305019cbe96aSPavel Labath 
305119cbe96aSPavel Labath         if (wait_pid == -1)
305219cbe96aSPavel Labath         {
305319cbe96aSPavel Labath             if (errno == EINTR)
305419cbe96aSPavel Labath                 continue;
305519cbe96aSPavel Labath 
305619cbe96aSPavel Labath             Error error(errno, eErrorTypePOSIX);
305719cbe96aSPavel Labath             if (log)
305819cbe96aSPavel Labath                 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
305919cbe96aSPavel Labath                         __FUNCTION__, error.AsCString());
306019cbe96aSPavel Labath             break;
306119cbe96aSPavel Labath         }
306219cbe96aSPavel Labath 
306319cbe96aSPavel Labath         bool exited = false;
306419cbe96aSPavel Labath         int signal = 0;
306519cbe96aSPavel Labath         int exit_status = 0;
306619cbe96aSPavel Labath         const char *status_cstr = nullptr;
306719cbe96aSPavel Labath         if (WIFSTOPPED(status))
306819cbe96aSPavel Labath         {
306919cbe96aSPavel Labath             signal = WSTOPSIG(status);
307019cbe96aSPavel Labath             status_cstr = "STOPPED";
307119cbe96aSPavel Labath         }
307219cbe96aSPavel Labath         else if (WIFEXITED(status))
307319cbe96aSPavel Labath         {
307419cbe96aSPavel Labath             exit_status = WEXITSTATUS(status);
307519cbe96aSPavel Labath             status_cstr = "EXITED";
307619cbe96aSPavel Labath             exited = true;
307719cbe96aSPavel Labath         }
307819cbe96aSPavel Labath         else if (WIFSIGNALED(status))
307919cbe96aSPavel Labath         {
308019cbe96aSPavel Labath             signal = WTERMSIG(status);
308119cbe96aSPavel Labath             status_cstr = "SIGNALED";
308219cbe96aSPavel Labath             if (wait_pid == static_cast< ::pid_t>(GetID())) {
308319cbe96aSPavel Labath                 exited = true;
308419cbe96aSPavel Labath                 exit_status = -1;
308519cbe96aSPavel Labath             }
308619cbe96aSPavel Labath         }
308719cbe96aSPavel Labath         else
308819cbe96aSPavel Labath             status_cstr = "(\?\?\?)";
308919cbe96aSPavel Labath 
309019cbe96aSPavel Labath         if (log)
309119cbe96aSPavel Labath             log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
309219cbe96aSPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
309319cbe96aSPavel Labath                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
309419cbe96aSPavel Labath 
309519cbe96aSPavel Labath         MonitorCallback (wait_pid, exited, signal, exit_status);
309619cbe96aSPavel Labath     }
3097068f8a7eSTamas Berghammer }
3098068f8a7eSTamas Berghammer 
3099068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
3100068f8a7eSTamas Berghammer // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
31014a9babb2SPavel Labath Error
31024a9babb2SPavel Labath NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
3103068f8a7eSTamas Berghammer {
31044a9babb2SPavel Labath     Error error;
31054a9babb2SPavel Labath     long int ret;
3106068f8a7eSTamas Berghammer 
3107068f8a7eSTamas Berghammer     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3108068f8a7eSTamas Berghammer 
3109068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3110068f8a7eSTamas Berghammer 
3111068f8a7eSTamas Berghammer     errno = 0;
3112068f8a7eSTamas Berghammer     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
31134a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3114068f8a7eSTamas Berghammer     else
31154a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3116068f8a7eSTamas Berghammer 
31174a9babb2SPavel Labath     if (ret == -1)
3118068f8a7eSTamas Berghammer         error.SetErrorToErrno();
3119068f8a7eSTamas Berghammer 
31204a9babb2SPavel Labath     if (result)
31214a9babb2SPavel Labath         *result = ret;
31224a9babb2SPavel Labath 
3123068f8a7eSTamas Berghammer     if (log)
31244a9babb2SPavel Labath         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
3125068f8a7eSTamas Berghammer 
3126068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3127068f8a7eSTamas Berghammer 
3128068f8a7eSTamas Berghammer     if (log && error.GetError() != 0)
3129068f8a7eSTamas Berghammer     {
3130068f8a7eSTamas Berghammer         const char* str;
3131068f8a7eSTamas Berghammer         switch (error.GetError())
3132068f8a7eSTamas Berghammer         {
3133068f8a7eSTamas Berghammer         case ESRCH:  str = "ESRCH"; break;
3134068f8a7eSTamas Berghammer         case EINVAL: str = "EINVAL"; break;
3135068f8a7eSTamas Berghammer         case EBUSY:  str = "EBUSY"; break;
3136068f8a7eSTamas Berghammer         case EPERM:  str = "EPERM"; break;
3137068f8a7eSTamas Berghammer         default:     str = error.AsCString();
3138068f8a7eSTamas Berghammer         }
3139068f8a7eSTamas Berghammer         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3140068f8a7eSTamas Berghammer     }
3141068f8a7eSTamas Berghammer 
31424a9babb2SPavel Labath     return error;
3143068f8a7eSTamas Berghammer }
3144