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"
286edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
29af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
30af245d11STodd Fiala #include "lldb/Core/State.h"
31af245d11STodd Fiala #include "lldb/Host/Host.h"
3239de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
332a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
342a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
352a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3690aff47cSZachary Turner #include "lldb/Target/Process.h"
37af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
385b981ab9SPavel Labath #include "lldb/Target/Target.h"
39c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
40af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
41f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
42af245d11STodd Fiala 
431e209fccSTamas Berghammer #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
44af245d11STodd Fiala #include "NativeThreadLinux.h"
45af245d11STodd Fiala #include "ProcFileReader.h"
461e209fccSTamas Berghammer #include "Procfs.h"
47cacde7dfSTodd Fiala 
48d858487eSTamas Berghammer // System includes - They have to be included after framework includes because they define some
49d858487eSTamas Berghammer // macros which collide with variable names in other modules
50d858487eSTamas Berghammer #include <linux/unistd.h>
51d858487eSTamas Berghammer #include <sys/socket.h>
528b335671SVince Harron 
53df7c6995SPavel Labath #include <sys/syscall.h>
54d858487eSTamas Berghammer #include <sys/types.h>
55d858487eSTamas Berghammer #include <sys/user.h>
56d858487eSTamas Berghammer #include <sys/wait.h>
57d858487eSTamas Berghammer 
588b335671SVince Harron #include "lldb/Host/linux/Personality.h"
598b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
60df7c6995SPavel Labath #include "lldb/Host/linux/Uio.h"
618b335671SVince Harron #include "lldb/Host/android/Android.h"
62af245d11STodd Fiala 
630bce1b67STodd Fiala #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
64af245d11STodd Fiala 
65af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
66af245d11STodd Fiala #ifndef TRAP_HWBKPT
67af245d11STodd Fiala   #define TRAP_HWBKPT 4
68af245d11STodd Fiala #endif
69af245d11STodd Fiala 
707cb18bf5STamas Berghammer using namespace lldb;
717cb18bf5STamas Berghammer using namespace lldb_private;
72db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
737cb18bf5STamas Berghammer using namespace llvm;
747cb18bf5STamas Berghammer 
75af245d11STodd Fiala // Private bits we only need internally.
76df7c6995SPavel Labath 
77df7c6995SPavel Labath static bool ProcessVmReadvSupported()
78df7c6995SPavel Labath {
79df7c6995SPavel Labath     static bool is_supported;
80df7c6995SPavel Labath     static std::once_flag flag;
81df7c6995SPavel Labath 
82df7c6995SPavel Labath     std::call_once(flag, [] {
83df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
84df7c6995SPavel Labath 
85df7c6995SPavel Labath         uint32_t source = 0x47424742;
86df7c6995SPavel Labath         uint32_t dest = 0;
87df7c6995SPavel Labath 
88df7c6995SPavel Labath         struct iovec local, remote;
89df7c6995SPavel Labath         remote.iov_base = &source;
90df7c6995SPavel Labath         local.iov_base = &dest;
91df7c6995SPavel Labath         remote.iov_len = local.iov_len = sizeof source;
92df7c6995SPavel Labath 
93df7c6995SPavel Labath         // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
94df7c6995SPavel Labath         ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95df7c6995SPavel Labath         is_supported = (res == sizeof(source) && source == dest);
96df7c6995SPavel Labath         if (log)
97df7c6995SPavel Labath         {
98df7c6995SPavel Labath             if (is_supported)
99df7c6995SPavel Labath                 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
100df7c6995SPavel Labath                         __FUNCTION__);
101df7c6995SPavel Labath             else
102df7c6995SPavel Labath                 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
103df7c6995SPavel Labath                         __FUNCTION__, strerror(errno));
104df7c6995SPavel Labath         }
105df7c6995SPavel Labath     });
106df7c6995SPavel Labath 
107df7c6995SPavel Labath     return is_supported;
108df7c6995SPavel Labath }
109df7c6995SPavel Labath 
110af245d11STodd Fiala namespace
111af245d11STodd Fiala {
112af245d11STodd Fiala Error
1132a86b555SPavel Labath ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch)
114af245d11STodd Fiala {
115af245d11STodd Fiala     // Grab process info for the running process.
116af245d11STodd Fiala     ProcessInstanceInfo process_info;
1172a86b555SPavel Labath     if (!Host::GetProcessInfo(pid, process_info))
118db264a6dSTamas Berghammer         return Error("failed to get process info");
119af245d11STodd Fiala 
120af245d11STodd Fiala     // Resolve the executable module.
1212a86b555SPavel Labath     ModuleSpecList module_specs;
1222a86b555SPavel Labath     if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs))
1232a86b555SPavel Labath         return Error("failed to get module specifications");
1242a86b555SPavel Labath     assert(module_specs.GetSize() == 1);
125af245d11STodd Fiala 
1262a86b555SPavel Labath     arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
127af245d11STodd Fiala     if (arch.IsValid())
128af245d11STodd Fiala         return Error();
129af245d11STodd Fiala     else
130af245d11STodd Fiala         return Error("failed to retrieve a valid architecture from the exe module");
131af245d11STodd Fiala }
132af245d11STodd Fiala 
1330c4f01d4SPavel Labath // Used to notify the parent about which part of the launch sequence failed.
1340c4f01d4SPavel Labath enum LaunchCallSpecifier
1350c4f01d4SPavel Labath {
1360c4f01d4SPavel Labath     ePtraceFailed,
1370c4f01d4SPavel Labath     eDupStdinFailed,
1380c4f01d4SPavel Labath     eDupStdoutFailed,
1390c4f01d4SPavel Labath     eDupStderrFailed,
1400c4f01d4SPavel Labath     eChdirFailed,
1410c4f01d4SPavel Labath     eExecFailed,
1420c4f01d4SPavel Labath     eSetGidFailed,
1430c4f01d4SPavel Labath     eSetSigMaskFailed,
1440c4f01d4SPavel Labath     eLaunchCallMax = eSetSigMaskFailed
1450c4f01d4SPavel Labath };
1460c4f01d4SPavel Labath 
1470c4f01d4SPavel Labath static uint8_t LLVM_ATTRIBUTE_NORETURN
1480c4f01d4SPavel Labath ExitChildAbnormally(LaunchCallSpecifier spec)
1490c4f01d4SPavel Labath {
1500c4f01d4SPavel Labath     static_assert(eLaunchCallMax < 0x8, "Have more launch calls than we are able to represent");
1510c4f01d4SPavel Labath     // This may truncate the topmost bits of the errno because the exit code is only 8 bits wide.
1520c4f01d4SPavel Labath     // However, it should still give us a pretty good indication of what went wrong. (And the
1530c4f01d4SPavel Labath     // most common errors have small numbers anyway).
1540c4f01d4SPavel Labath     _exit(unsigned(spec) | (errno << 3));
1550c4f01d4SPavel Labath }
1560c4f01d4SPavel Labath 
1570c4f01d4SPavel Labath // The second member is the errno (or its 5 lowermost bits anyway).
1580c4f01d4SPavel Labath inline std::pair<LaunchCallSpecifier, uint8_t>
1590c4f01d4SPavel Labath DecodeChildExitCode(int exit_code)
1600c4f01d4SPavel Labath {
1610c4f01d4SPavel Labath     return std::make_pair(LaunchCallSpecifier(exit_code & 0x7), exit_code >> 3);
1620c4f01d4SPavel Labath }
1630c4f01d4SPavel Labath 
164af245d11STodd Fiala     void
165db264a6dSTamas Berghammer     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
166af245d11STodd Fiala     {
167af245d11STodd Fiala         uint8_t *ptr = (uint8_t *)bytes;
168af245d11STodd Fiala         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
169af245d11STodd Fiala         for(uint32_t i=0; i<loop_count; i++)
170af245d11STodd Fiala         {
171af245d11STodd Fiala             s.Printf ("[%x]", *ptr);
172af245d11STodd Fiala             ptr++;
173af245d11STodd Fiala         }
174af245d11STodd Fiala     }
175af245d11STodd Fiala 
176af245d11STodd Fiala     void
177af245d11STodd Fiala     PtraceDisplayBytes(int &req, void *data, size_t data_size)
178af245d11STodd Fiala     {
179af245d11STodd Fiala         StreamString buf;
180af245d11STodd Fiala         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
181af245d11STodd Fiala                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
182af245d11STodd Fiala 
183af245d11STodd Fiala         if (verbose_log)
184af245d11STodd Fiala         {
185af245d11STodd Fiala             switch(req)
186af245d11STodd Fiala             {
187af245d11STodd Fiala             case PTRACE_POKETEXT:
188af245d11STodd Fiala             {
189af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
190af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
191af245d11STodd Fiala                 break;
192af245d11STodd Fiala             }
193af245d11STodd Fiala             case PTRACE_POKEDATA:
194af245d11STodd Fiala             {
195af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
196af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
197af245d11STodd Fiala                 break;
198af245d11STodd Fiala             }
199af245d11STodd Fiala             case PTRACE_POKEUSER:
200af245d11STodd Fiala             {
201af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
202af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
203af245d11STodd Fiala                 break;
204af245d11STodd Fiala             }
205af245d11STodd Fiala             case PTRACE_SETREGS:
206af245d11STodd Fiala             {
207af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
208af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
209af245d11STodd Fiala                 break;
210af245d11STodd Fiala             }
211af245d11STodd Fiala             case PTRACE_SETFPREGS:
212af245d11STodd Fiala             {
213af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
214af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
215af245d11STodd Fiala                 break;
216af245d11STodd Fiala             }
217af245d11STodd Fiala             case PTRACE_SETSIGINFO:
218af245d11STodd Fiala             {
219af245d11STodd Fiala                 DisplayBytes(buf, data, sizeof(siginfo_t));
220af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
221af245d11STodd Fiala                 break;
222af245d11STodd Fiala             }
223af245d11STodd Fiala             case PTRACE_SETREGSET:
224af245d11STodd Fiala             {
225af245d11STodd Fiala                 // Extract iov_base from data, which is a pointer to the struct IOVEC
226af245d11STodd Fiala                 DisplayBytes(buf, *(void **)data, data_size);
227af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
228af245d11STodd Fiala                 break;
229af245d11STodd Fiala             }
230af245d11STodd Fiala             default:
231af245d11STodd Fiala             {
232af245d11STodd Fiala             }
233af245d11STodd Fiala             }
234af245d11STodd Fiala         }
235af245d11STodd Fiala     }
236af245d11STodd Fiala 
23719cbe96aSPavel Labath     static constexpr unsigned k_ptrace_word_size = sizeof(void*);
23819cbe96aSPavel Labath     static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
2391107b5a5SPavel Labath } // end of anonymous namespace
2401107b5a5SPavel Labath 
241bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
242bd7cbc5aSPavel Labath // descriptor.
243bd7cbc5aSPavel Labath static Error
244bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
245bd7cbc5aSPavel Labath {
246bd7cbc5aSPavel Labath     Error error;
247bd7cbc5aSPavel Labath 
248bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
249bd7cbc5aSPavel Labath     if (status == -1)
250bd7cbc5aSPavel Labath     {
251bd7cbc5aSPavel Labath         error.SetErrorToErrno();
252bd7cbc5aSPavel Labath         return error;
253bd7cbc5aSPavel Labath     }
254bd7cbc5aSPavel Labath 
255bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
256bd7cbc5aSPavel Labath     {
257bd7cbc5aSPavel Labath         error.SetErrorToErrno();
258bd7cbc5aSPavel Labath         return error;
259bd7cbc5aSPavel Labath     }
260bd7cbc5aSPavel Labath 
261bd7cbc5aSPavel Labath     return error;
262bd7cbc5aSPavel Labath }
263bd7cbc5aSPavel Labath 
2642a86b555SPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(char const **argv, char const **envp, const FileSpec &stdin_file_spec,
2652a86b555SPavel Labath                                            const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec,
2662a86b555SPavel Labath                                            const FileSpec &working_dir, const ProcessLaunchInfo &launch_info)
2672a86b555SPavel Labath     : m_argv(argv),
268af245d11STodd Fiala       m_envp(envp),
269d3173f34SChaoren Lin       m_stdin_file_spec(stdin_file_spec),
270d3173f34SChaoren Lin       m_stdout_file_spec(stdout_file_spec),
271d3173f34SChaoren Lin       m_stderr_file_spec(stderr_file_spec),
2720bce1b67STodd Fiala       m_working_dir(working_dir),
2730bce1b67STodd Fiala       m_launch_info(launch_info)
2740bce1b67STodd Fiala {
2750bce1b67STodd Fiala }
276af245d11STodd Fiala 
277af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
278af245d11STodd Fiala { }
279af245d11STodd Fiala 
280af245d11STodd Fiala // -----------------------------------------------------------------------------
281af245d11STodd Fiala // Public Static Methods
282af245d11STodd Fiala // -----------------------------------------------------------------------------
283af245d11STodd Fiala 
284db264a6dSTamas Berghammer Error
285d5b310f2SPavel Labath NativeProcessProtocol::Launch (
286db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
287db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
28819cbe96aSPavel Labath     MainLoop &mainloop,
289af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
290af245d11STodd Fiala {
291af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
292af245d11STodd Fiala 
2932a86b555SPavel Labath     Error error;
294af245d11STodd Fiala 
295af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
296d3173f34SChaoren Lin     FileSpec working_dir{launch_info.GetWorkingDirectory()};
297d3173f34SChaoren Lin     if (working_dir &&
298d3173f34SChaoren Lin             (!working_dir.ResolvePath() ||
299d3173f34SChaoren Lin              working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
300af245d11STodd Fiala     {
301d3173f34SChaoren Lin         error.SetErrorStringWithFormat ("No such file or directory: %s",
302d3173f34SChaoren Lin                 working_dir.GetCString());
303af245d11STodd Fiala         return error;
304af245d11STodd Fiala     }
305af245d11STodd Fiala 
306db264a6dSTamas Berghammer     const FileAction *file_action;
307af245d11STodd Fiala 
308d3173f34SChaoren Lin     // Default of empty will mean to use existing open file descriptors.
309d3173f34SChaoren Lin     FileSpec stdin_file_spec{};
310d3173f34SChaoren Lin     FileSpec stdout_file_spec{};
311d3173f34SChaoren Lin     FileSpec stderr_file_spec{};
312af245d11STodd Fiala 
313af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
31475f47c3aSTodd Fiala     if (file_action)
315d3173f34SChaoren Lin         stdin_file_spec = file_action->GetFileSpec();
316af245d11STodd Fiala 
317af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
31875f47c3aSTodd Fiala     if (file_action)
319d3173f34SChaoren Lin         stdout_file_spec = file_action->GetFileSpec();
320af245d11STodd Fiala 
321af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
32275f47c3aSTodd Fiala     if (file_action)
323d3173f34SChaoren Lin         stderr_file_spec = file_action->GetFileSpec();
32475f47c3aSTodd Fiala 
32575f47c3aSTodd Fiala     if (log)
32675f47c3aSTodd Fiala     {
327d3173f34SChaoren Lin         if (stdin_file_spec)
328d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
329d3173f34SChaoren Lin                     __FUNCTION__, stdin_file_spec.GetCString());
33075f47c3aSTodd Fiala         else
33175f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
33275f47c3aSTodd Fiala 
333d3173f34SChaoren Lin         if (stdout_file_spec)
334d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
335d3173f34SChaoren Lin                     __FUNCTION__, stdout_file_spec.GetCString());
33675f47c3aSTodd Fiala         else
33775f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
33875f47c3aSTodd Fiala 
339d3173f34SChaoren Lin         if (stderr_file_spec)
340d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
341d3173f34SChaoren Lin                     __FUNCTION__, stderr_file_spec.GetCString());
34275f47c3aSTodd Fiala         else
34375f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
34475f47c3aSTodd Fiala     }
345af245d11STodd Fiala 
346af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
347af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
348af245d11STodd Fiala 
349af245d11STodd Fiala     if (log)
350af245d11STodd Fiala     {
351af245d11STodd Fiala         int i = 0;
352af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
353af245d11STodd Fiala         {
354af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
355af245d11STodd Fiala             ++i;
356af245d11STodd Fiala         }
357af245d11STodd Fiala     }
358af245d11STodd Fiala 
359af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
360af245d11STodd Fiala     {
361af245d11STodd Fiala         native_process_sp.reset ();
362af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
363af245d11STodd Fiala         return error;
364af245d11STodd Fiala     }
365af245d11STodd Fiala 
366cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
36719cbe96aSPavel Labath             mainloop,
368af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
369af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
370d3173f34SChaoren Lin             stdin_file_spec,
371d3173f34SChaoren Lin             stdout_file_spec,
372d3173f34SChaoren Lin             stderr_file_spec,
373af245d11STodd Fiala             working_dir,
3740bce1b67STodd Fiala             launch_info,
375af245d11STodd Fiala             error);
376af245d11STodd Fiala 
377af245d11STodd Fiala     if (error.Fail ())
378af245d11STodd Fiala     {
379af245d11STodd Fiala         native_process_sp.reset ();
380af245d11STodd Fiala         if (log)
381af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
382af245d11STodd Fiala         return error;
383af245d11STodd Fiala     }
384af245d11STodd Fiala 
385af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
386af245d11STodd Fiala 
387af245d11STodd Fiala     return error;
388af245d11STodd Fiala }
389af245d11STodd Fiala 
390db264a6dSTamas Berghammer Error
391d5b310f2SPavel Labath NativeProcessProtocol::Attach (
392af245d11STodd Fiala     lldb::pid_t pid,
393db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
39419cbe96aSPavel Labath     MainLoop &mainloop,
395af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
396af245d11STodd Fiala {
397af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
398af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
399af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
400af245d11STodd Fiala 
401af245d11STodd Fiala     // Retrieve the architecture for the running process.
402af245d11STodd Fiala     ArchSpec process_arch;
4032a86b555SPavel Labath     Error error = ResolveProcessArchitecture(pid, process_arch);
404af245d11STodd Fiala     if (!error.Success ())
405af245d11STodd Fiala         return error;
406af245d11STodd Fiala 
4071339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
408af245d11STodd Fiala 
4091339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
410af245d11STodd Fiala     {
411af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
412af245d11STodd Fiala         return error;
413af245d11STodd Fiala     }
414af245d11STodd Fiala 
41519cbe96aSPavel Labath     native_process_linux_sp->AttachToInferior (mainloop, pid, error);
416af245d11STodd Fiala     if (!error.Success ())
417af245d11STodd Fiala         return error;
418af245d11STodd Fiala 
4191339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
420af245d11STodd Fiala     return error;
421af245d11STodd Fiala }
422af245d11STodd Fiala 
423af245d11STodd Fiala // -----------------------------------------------------------------------------
424af245d11STodd Fiala // Public Instance Methods
425af245d11STodd Fiala // -----------------------------------------------------------------------------
426af245d11STodd Fiala 
427af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
428af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
429af245d11STodd Fiala     m_arch (),
430af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
431af245d11STodd Fiala     m_mem_region_cache (),
4320e1d729bSPavel Labath     m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
433af245d11STodd Fiala {
434af245d11STodd Fiala }
435af245d11STodd Fiala 
436af245d11STodd Fiala void
437af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
43819cbe96aSPavel Labath     MainLoop &mainloop,
439af245d11STodd Fiala     const char *argv[],
440af245d11STodd Fiala     const char *envp[],
441d3173f34SChaoren Lin     const FileSpec &stdin_file_spec,
442d3173f34SChaoren Lin     const FileSpec &stdout_file_spec,
443d3173f34SChaoren Lin     const FileSpec &stderr_file_spec,
444d3173f34SChaoren Lin     const FileSpec &working_dir,
445db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
446db264a6dSTamas Berghammer     Error &error)
447af245d11STodd Fiala {
44819cbe96aSPavel Labath     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
44919cbe96aSPavel Labath             [this] (MainLoopBase &) { SigchldHandler(); }, error);
45019cbe96aSPavel Labath     if (! m_sigchld_handle)
45119cbe96aSPavel Labath         return;
45219cbe96aSPavel Labath 
453af245d11STodd Fiala     SetState (eStateLaunching);
454af245d11STodd Fiala 
455af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
4562a86b555SPavel Labath         new LaunchArgs(argv, envp, stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir, launch_info));
457af245d11STodd Fiala 
45819cbe96aSPavel Labath     Launch(args.get(), error);
459af245d11STodd Fiala }
460af245d11STodd Fiala 
461af245d11STodd Fiala void
46219cbe96aSPavel Labath NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
463af245d11STodd Fiala {
464af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
465af245d11STodd Fiala     if (log)
466af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
467af245d11STodd Fiala 
46819cbe96aSPavel Labath     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
46919cbe96aSPavel Labath             [this] (MainLoopBase &) { SigchldHandler(); }, error);
47019cbe96aSPavel Labath     if (! m_sigchld_handle)
47119cbe96aSPavel Labath         return;
47219cbe96aSPavel Labath 
4732a86b555SPavel Labath     error = ResolveProcessArchitecture(pid, m_arch);
474af245d11STodd Fiala     if (!error.Success())
475af245d11STodd Fiala         return;
476af245d11STodd Fiala 
477af245d11STodd Fiala     // Set the architecture to the exe architecture.
478af245d11STodd Fiala     if (log)
479af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
480af245d11STodd Fiala 
481af245d11STodd Fiala     m_pid = pid;
482af245d11STodd Fiala     SetState(eStateAttaching);
483af245d11STodd Fiala 
48419cbe96aSPavel Labath     Attach(pid, error);
485af245d11STodd Fiala }
486af245d11STodd Fiala 
4870c4f01d4SPavel Labath void
4880c4f01d4SPavel Labath NativeProcessLinux::ChildFunc(const LaunchArgs &args)
489af245d11STodd Fiala {
49075f47c3aSTodd Fiala     // Start tracing this child that is about to exec.
4910c4f01d4SPavel Labath     if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1)
4920c4f01d4SPavel Labath         ExitChildAbnormally(ePtraceFailed);
493493c3a12SPavel Labath 
494af245d11STodd Fiala     // Do not inherit setgid powers.
495af245d11STodd Fiala     if (setgid(getgid()) != 0)
4960c4f01d4SPavel Labath         ExitChildAbnormally(eSetGidFailed);
497af245d11STodd Fiala 
498af245d11STodd Fiala     // Attempt to have our own process group.
499af245d11STodd Fiala     if (setpgid(0, 0) != 0)
500af245d11STodd Fiala     {
50175f47c3aSTodd Fiala         // FIXME log that this failed. This is common.
502af245d11STodd Fiala         // Don't allow this to prevent an inferior exec.
503af245d11STodd Fiala     }
504af245d11STodd Fiala 
505af245d11STodd Fiala     // Dup file descriptors if needed.
5060c4f01d4SPavel Labath     if (args.m_stdin_file_spec)
5070c4f01d4SPavel Labath         if (!DupDescriptor(args.m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
5080c4f01d4SPavel Labath             ExitChildAbnormally(eDupStdinFailed);
509af245d11STodd Fiala 
5100c4f01d4SPavel Labath     if (args.m_stdout_file_spec)
5110c4f01d4SPavel Labath         if (!DupDescriptor(args.m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
5120c4f01d4SPavel Labath             ExitChildAbnormally(eDupStdoutFailed);
513af245d11STodd Fiala 
5140c4f01d4SPavel Labath     if (args.m_stderr_file_spec)
5150c4f01d4SPavel Labath         if (!DupDescriptor(args.m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
5160c4f01d4SPavel Labath             ExitChildAbnormally(eDupStderrFailed);
517af245d11STodd Fiala 
5189cf4f2c2SChaoren Lin     // Close everything besides stdin, stdout, and stderr that has no file
5199cf4f2c2SChaoren Lin     // action to avoid leaking
5209cf4f2c2SChaoren Lin     for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
5210c4f01d4SPavel Labath         if (!args.m_launch_info.GetFileActionForFD(fd))
5229cf4f2c2SChaoren Lin             close(fd);
5239cf4f2c2SChaoren Lin 
524af245d11STodd Fiala     // Change working directory
5250c4f01d4SPavel Labath     if (args.m_working_dir && 0 != ::chdir(args.m_working_dir.GetCString()))
5260c4f01d4SPavel Labath         ExitChildAbnormally(eChdirFailed);
527af245d11STodd Fiala 
5280bce1b67STodd Fiala     // Disable ASLR if requested.
5290c4f01d4SPavel Labath     if (args.m_launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR))
5300bce1b67STodd Fiala     {
5310bce1b67STodd Fiala         const int old_personality = personality(LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
5320bce1b67STodd Fiala         if (old_personality == -1)
5330bce1b67STodd Fiala         {
53475f47c3aSTodd Fiala             // Can't retrieve Linux personality.  Cannot disable ASLR.
5350bce1b67STodd Fiala         }
5360bce1b67STodd Fiala         else
5370bce1b67STodd Fiala         {
5380bce1b67STodd Fiala             const int new_personality = personality(ADDR_NO_RANDOMIZE | old_personality);
5390bce1b67STodd Fiala             if (new_personality == -1)
5400bce1b67STodd Fiala             {
54175f47c3aSTodd Fiala                 // Disabling ASLR failed.
5420bce1b67STodd Fiala             }
5430bce1b67STodd Fiala             else
5440bce1b67STodd Fiala             {
54575f47c3aSTodd Fiala                 // Disabling ASLR succeeded.
5460bce1b67STodd Fiala             }
5470bce1b67STodd Fiala         }
5480bce1b67STodd Fiala     }
5490bce1b67STodd Fiala 
55078856474SPavel Labath     // Clear the signal mask to prevent the child from being affected by
55178856474SPavel Labath     // any masking done by the parent.
55278856474SPavel Labath     sigset_t set;
55378856474SPavel Labath     if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
5540c4f01d4SPavel Labath         ExitChildAbnormally(eSetSigMaskFailed);
5550c4f01d4SPavel Labath 
5560c4f01d4SPavel Labath     // Propagate the environment if one is not supplied.
5570c4f01d4SPavel Labath     const char **envp = args.m_envp;
5580c4f01d4SPavel Labath     if (envp == NULL || envp[0] == NULL)
5590c4f01d4SPavel Labath         envp = const_cast<const char **>(environ);
56078856474SPavel Labath 
56175f47c3aSTodd Fiala     // Execute.  We should never return...
5620c4f01d4SPavel Labath     execve(args.m_argv[0], const_cast<char *const *>(args.m_argv), const_cast<char *const *>(envp));
56375f47c3aSTodd Fiala 
564*ca92aed5SPavel Labath     if (errno == ETXTBSY)
565*ca92aed5SPavel Labath     {
566*ca92aed5SPavel Labath         // On android M and earlier we can get this error because the adb deamon can hold a write
567*ca92aed5SPavel Labath         // handle on the executable even after it has finished uploading it. This state lasts
568*ca92aed5SPavel Labath         // only a short time and happens only when there are many concurrent adb commands being
569*ca92aed5SPavel Labath         // issued, such as when running the test suite. (The file remains open when someone does
570*ca92aed5SPavel Labath         // an "adb shell" command in the fork() child before it has had a chance to exec.) Since
571*ca92aed5SPavel Labath         // this state should clear up quickly, wait a while and then give it one more go.
572*ca92aed5SPavel Labath         usleep(10000);
573*ca92aed5SPavel Labath         execve(args.m_argv[0], const_cast<char *const *>(args.m_argv), const_cast<char *const *>(envp));
574*ca92aed5SPavel Labath     }
575*ca92aed5SPavel Labath 
57675f47c3aSTodd Fiala     // ...unless exec fails.  In which case we definitely need to end the child here.
5770c4f01d4SPavel Labath     ExitChildAbnormally(eExecFailed);
578af245d11STodd Fiala }
579af245d11STodd Fiala 
5800c4f01d4SPavel Labath ::pid_t
5810c4f01d4SPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
5820c4f01d4SPavel Labath {
5830c4f01d4SPavel Labath     assert (args && "null args");
5840c4f01d4SPavel Labath 
5850c4f01d4SPavel Labath     lldb_utility::PseudoTerminal terminal;
5860c4f01d4SPavel Labath     const size_t err_len = 1024;
5870c4f01d4SPavel Labath     char err_str[err_len];
5880c4f01d4SPavel Labath     lldb::pid_t pid;
5890c4f01d4SPavel Labath 
5900c4f01d4SPavel Labath     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
5910c4f01d4SPavel Labath     {
5920c4f01d4SPavel Labath         error.SetErrorToGenericError();
5930c4f01d4SPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
5940c4f01d4SPavel Labath         return -1;
5950c4f01d4SPavel Labath     }
5960c4f01d4SPavel Labath 
5970c4f01d4SPavel Labath     // Child process.
5980c4f01d4SPavel Labath     if (pid == 0)
5990c4f01d4SPavel Labath     {
6000c4f01d4SPavel Labath         // First, make sure we disable all logging. If we are logging to stdout, our logs can be
6010c4f01d4SPavel Labath         // mistaken for inferior output.
6020c4f01d4SPavel Labath         Log::DisableAllLogChannels(nullptr);
6030c4f01d4SPavel Labath 
6040c4f01d4SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
6050c4f01d4SPavel Labath         // This closes original fd from which they were copied (and avoids
6060c4f01d4SPavel Labath         // leaking descriptors to the debugged process.
6070c4f01d4SPavel Labath         terminal.CloseSlaveFileDescriptor();
6080c4f01d4SPavel Labath 
6090c4f01d4SPavel Labath         ChildFunc(*args);
6100c4f01d4SPavel Labath     }
6110c4f01d4SPavel Labath 
61275f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
61375f47c3aSTodd Fiala 
614af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
615af245d11STodd Fiala     ::pid_t wpid;
616af245d11STodd Fiala     int status;
617af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
618af245d11STodd Fiala     {
619bd7cbc5aSPavel Labath         error.SetErrorToErrno();
620af245d11STodd Fiala         if (log)
621bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
622bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
623af245d11STodd Fiala 
624af245d11STodd Fiala         // Mark the inferior as invalid.
625af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
626bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
627af245d11STodd Fiala 
628bd7cbc5aSPavel Labath         return -1;
629af245d11STodd Fiala     }
630af245d11STodd Fiala     else if (WIFEXITED(status))
631af245d11STodd Fiala     {
6320c4f01d4SPavel Labath         auto p = DecodeChildExitCode(WEXITSTATUS(status));
6330c4f01d4SPavel Labath         Error child_error(p.second, eErrorTypePOSIX);
6340c4f01d4SPavel Labath         const char *failure_reason;
6350c4f01d4SPavel Labath         switch (p.first)
636af245d11STodd Fiala         {
637af245d11STodd Fiala             case ePtraceFailed:
6380c4f01d4SPavel Labath                 failure_reason = "Child ptrace failed";
639af245d11STodd Fiala                 break;
640af245d11STodd Fiala             case eDupStdinFailed:
6410c4f01d4SPavel Labath                 failure_reason = "Child open stdin failed";
642af245d11STodd Fiala                 break;
643af245d11STodd Fiala             case eDupStdoutFailed:
6440c4f01d4SPavel Labath                 failure_reason = "Child open stdout failed";
645af245d11STodd Fiala                 break;
646af245d11STodd Fiala             case eDupStderrFailed:
6470c4f01d4SPavel Labath                 failure_reason = "Child open stderr failed";
648af245d11STodd Fiala                 break;
649af245d11STodd Fiala             case eChdirFailed:
6500c4f01d4SPavel Labath                 failure_reason = "Child failed to set working directory";
651af245d11STodd Fiala                 break;
652af245d11STodd Fiala             case eExecFailed:
6530c4f01d4SPavel Labath                 failure_reason = "Child exec failed";
654af245d11STodd Fiala                 break;
655af245d11STodd Fiala             case eSetGidFailed:
6560c4f01d4SPavel Labath                 failure_reason = "Child setgid failed";
657af245d11STodd Fiala                 break;
65878856474SPavel Labath             case eSetSigMaskFailed:
6590c4f01d4SPavel Labath                 failure_reason = "Child failed to set signal mask";
660af245d11STodd Fiala                 break;
661af245d11STodd Fiala         }
6620c4f01d4SPavel Labath         error.SetErrorStringWithFormat("%s: %d - %s (error code truncated)", failure_reason, child_error.GetError(), child_error.AsCString());
663af245d11STodd Fiala 
664af245d11STodd Fiala         if (log)
665af245d11STodd Fiala         {
666af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
667af245d11STodd Fiala                     __FUNCTION__,
668af245d11STodd Fiala                     WEXITSTATUS(status));
669af245d11STodd Fiala         }
670af245d11STodd Fiala 
671af245d11STodd Fiala         // Mark the inferior as invalid.
672af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
673bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
674af245d11STodd Fiala 
675bd7cbc5aSPavel Labath         return -1;
676af245d11STodd Fiala     }
677af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
678af245d11STodd Fiala            "Could not sync with inferior process.");
679af245d11STodd Fiala 
680af245d11STodd Fiala     if (log)
681af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
682af245d11STodd Fiala 
683bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
684bd7cbc5aSPavel Labath     if (error.Fail())
685af245d11STodd Fiala     {
686af245d11STodd Fiala         if (log)
687af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
688bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
689af245d11STodd Fiala 
690af245d11STodd Fiala         // Mark the inferior as invalid.
691af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
692bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
693af245d11STodd Fiala 
694bd7cbc5aSPavel Labath         return -1;
695af245d11STodd Fiala     }
696af245d11STodd Fiala 
697af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
698af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
699bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
700bd7cbc5aSPavel Labath     m_pid = pid;
701af245d11STodd Fiala 
702af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
703af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
704af245d11STodd Fiala     // descriptor to read from).
705bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
706bd7cbc5aSPavel Labath     if (error.Fail())
707af245d11STodd Fiala     {
708af245d11STodd Fiala         if (log)
709af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
710bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
711af245d11STodd Fiala 
712af245d11STodd Fiala         // Mark the inferior as invalid.
713af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
714bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
715af245d11STodd Fiala 
716bd7cbc5aSPavel Labath         return -1;
717af245d11STodd Fiala     }
718af245d11STodd Fiala 
719af245d11STodd Fiala     if (log)
720af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
721af245d11STodd Fiala 
7222a86b555SPavel Labath     ResolveProcessArchitecture(m_pid, m_arch);
723f9077782SPavel Labath     NativeThreadLinuxSP thread_sp = AddThread(pid);
724af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
725f9077782SPavel Labath     thread_sp->SetStoppedBySignal(SIGSTOP);
726f9077782SPavel Labath     ThreadWasCreated(*thread_sp);
727af245d11STodd Fiala 
728af245d11STodd Fiala     // Let our process instance know the thread has stopped.
729bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
730bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
731af245d11STodd Fiala 
732af245d11STodd Fiala     if (log)
733af245d11STodd Fiala     {
734bd7cbc5aSPavel Labath         if (error.Success ())
735af245d11STodd Fiala         {
736af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
737af245d11STodd Fiala         }
738af245d11STodd Fiala         else
739af245d11STodd Fiala         {
740af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
741bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
742bd7cbc5aSPavel Labath             return -1;
743af245d11STodd Fiala         }
744af245d11STodd Fiala     }
745bd7cbc5aSPavel Labath     return pid;
746af245d11STodd Fiala }
747af245d11STodd Fiala 
748bd7cbc5aSPavel Labath ::pid_t
749bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
750af245d11STodd Fiala {
751af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
752af245d11STodd Fiala 
753af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
754af245d11STodd Fiala     Host::TidMap tids_to_attach;
755af245d11STodd Fiala     if (pid <= 1)
756af245d11STodd Fiala     {
757bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
758bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
759bd7cbc5aSPavel Labath         return -1;
760af245d11STodd Fiala     }
761af245d11STodd Fiala 
762af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
763af245d11STodd Fiala     {
764af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
765af245d11STodd Fiala              it != tids_to_attach.end();)
766af245d11STodd Fiala         {
767af245d11STodd Fiala             if (it->second == false)
768af245d11STodd Fiala             {
769af245d11STodd Fiala                 lldb::tid_t tid = it->first;
770af245d11STodd Fiala 
771af245d11STodd Fiala                 // Attach to the requested process.
772af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
7734a9babb2SPavel Labath                 error = PtraceWrapper(PTRACE_ATTACH, tid);
774bd7cbc5aSPavel Labath                 if (error.Fail())
775af245d11STodd Fiala                 {
776af245d11STodd Fiala                     // No such thread. The thread may have exited.
777af245d11STodd Fiala                     // More error handling may be needed.
778bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
779af245d11STodd Fiala                     {
780af245d11STodd Fiala                         it = tids_to_attach.erase(it);
781af245d11STodd Fiala                         continue;
782af245d11STodd Fiala                     }
783af245d11STodd Fiala                     else
784bd7cbc5aSPavel Labath                         return -1;
785af245d11STodd Fiala                 }
786af245d11STodd Fiala 
787af245d11STodd Fiala                 int status;
788af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
789af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
790af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
791af245d11STodd Fiala                 {
792af245d11STodd Fiala                     // No such thread. The thread may have exited.
793af245d11STodd Fiala                     // More error handling may be needed.
794af245d11STodd Fiala                     if (errno == ESRCH)
795af245d11STodd Fiala                     {
796af245d11STodd Fiala                         it = tids_to_attach.erase(it);
797af245d11STodd Fiala                         continue;
798af245d11STodd Fiala                     }
799af245d11STodd Fiala                     else
800af245d11STodd Fiala                     {
801bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
802bd7cbc5aSPavel Labath                         return -1;
803af245d11STodd Fiala                     }
804af245d11STodd Fiala                 }
805af245d11STodd Fiala 
806bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
807bd7cbc5aSPavel Labath                 if (error.Fail())
808bd7cbc5aSPavel Labath                     return -1;
809af245d11STodd Fiala 
810af245d11STodd Fiala                 if (log)
811af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
812af245d11STodd Fiala 
813af245d11STodd Fiala                 it->second = true;
814af245d11STodd Fiala 
815af245d11STodd Fiala                 // Create the thread, mark it as stopped.
816f9077782SPavel Labath                 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
817af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
818fa03ad2eSChaoren Lin 
819fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
820f9077782SPavel Labath                 thread_sp->SetStoppedBySignal(SIGSTOP);
821f9077782SPavel Labath                 ThreadWasCreated(*thread_sp);
822bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
823af245d11STodd Fiala             }
824af245d11STodd Fiala 
825af245d11STodd Fiala             // move the loop forward
826af245d11STodd Fiala             ++it;
827af245d11STodd Fiala         }
828af245d11STodd Fiala     }
829af245d11STodd Fiala 
830af245d11STodd Fiala     if (tids_to_attach.size() > 0)
831af245d11STodd Fiala     {
832bd7cbc5aSPavel Labath         m_pid = pid;
833af245d11STodd Fiala         // Let our process instance know the thread has stopped.
834bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
835af245d11STodd Fiala     }
836af245d11STodd Fiala     else
837af245d11STodd Fiala     {
838bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
839bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
840bd7cbc5aSPavel Labath         return -1;
841af245d11STodd Fiala     }
842af245d11STodd Fiala 
843bd7cbc5aSPavel Labath     return pid;
844af245d11STodd Fiala }
845af245d11STodd Fiala 
84697ccc294SChaoren Lin Error
847af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
848af245d11STodd Fiala {
849af245d11STodd Fiala     long ptrace_opts = 0;
850af245d11STodd Fiala 
851af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
852af245d11STodd Fiala     // limbo until it is destroyed.
853af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
854af245d11STodd Fiala 
855af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
856af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
857af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
858af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
859af245d11STodd Fiala 
860af245d11STodd Fiala     // Have the tracer notify us before execve returns
861af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
862af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
863af245d11STodd Fiala 
8644a9babb2SPavel Labath     return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
865af245d11STodd Fiala }
866af245d11STodd Fiala 
867af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
868af245d11STodd Fiala {
869af245d11STodd Fiala     if (WIFEXITED (status))
870af245d11STodd Fiala         return ExitType::eExitTypeExit;
871af245d11STodd Fiala     else if (WIFSIGNALED (status))
872af245d11STodd Fiala         return ExitType::eExitTypeSignal;
873af245d11STodd Fiala     else if (WIFSTOPPED (status))
874af245d11STodd Fiala         return ExitType::eExitTypeStop;
875af245d11STodd Fiala     else
876af245d11STodd Fiala     {
877af245d11STodd Fiala         // We don't know what this is.
878af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
879af245d11STodd Fiala     }
880af245d11STodd Fiala }
881af245d11STodd Fiala 
882af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
883af245d11STodd Fiala {
884af245d11STodd Fiala     if (WIFEXITED (status))
885af245d11STodd Fiala         return WEXITSTATUS (status);
886af245d11STodd Fiala     else if (WIFSIGNALED (status))
887af245d11STodd Fiala         return WTERMSIG (status);
888af245d11STodd Fiala     else if (WIFSTOPPED (status))
889af245d11STodd Fiala         return WSTOPSIG (status);
890af245d11STodd Fiala     else
891af245d11STodd Fiala     {
892af245d11STodd Fiala         // We don't know what this is.
893af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
894af245d11STodd Fiala     }
895af245d11STodd Fiala }
896af245d11STodd Fiala 
8971107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
8981107b5a5SPavel Labath void
8991107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
900af245d11STodd Fiala                                     bool exited,
901af245d11STodd Fiala                                     int signal,
902af245d11STodd Fiala                                     int status)
903af245d11STodd Fiala {
904af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
905af245d11STodd Fiala 
906af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
9071107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
908af245d11STodd Fiala 
909af245d11STodd Fiala     // Handle when the thread exits.
910af245d11STodd Fiala     if (exited)
911af245d11STodd Fiala     {
912af245d11STodd Fiala         if (log)
91386fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
914af245d11STodd Fiala 
915af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
9161107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
917af245d11STodd Fiala 
918af245d11STodd Fiala         if (is_main_thread)
919af245d11STodd Fiala         {
920af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
921af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
922af245d11STodd Fiala             // for the main thread.
9231107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
924af245d11STodd Fiala             if (!already_notified)
925af245d11STodd Fiala             {
926af245d11STodd Fiala                 if (log)
9271107b5a5SPavel 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 ()));
928af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
9291107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
930af245d11STodd Fiala 
931af245d11STodd Fiala                 // Notify delegate that our process has exited.
9321107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
933af245d11STodd Fiala             }
934af245d11STodd Fiala             else
935af245d11STodd Fiala             {
936af245d11STodd Fiala                 if (log)
937af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
938af245d11STodd Fiala             }
939af245d11STodd Fiala         }
940af245d11STodd Fiala         else
941af245d11STodd Fiala         {
942af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
943af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
944af245d11STodd Fiala             // and we would have done an all-stop then.
945af245d11STodd Fiala             if (log)
946af245d11STodd 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");
947af245d11STodd Fiala         }
9481107b5a5SPavel Labath         return;
949af245d11STodd Fiala     }
950af245d11STodd Fiala 
951af245d11STodd Fiala     siginfo_t info;
952b9cc0c75SPavel Labath     const auto info_err = GetSignalInfo(pid, &info);
953b9cc0c75SPavel Labath     auto thread_sp = GetThreadByID(pid);
954b9cc0c75SPavel Labath 
955b9cc0c75SPavel Labath     if (! thread_sp)
956b9cc0c75SPavel Labath     {
957b9cc0c75SPavel Labath         // Normally, the only situation when we cannot find the thread is if we have just
958b9cc0c75SPavel Labath         // received a new thread notification. This is indicated by GetSignalInfo() returning
959b9cc0c75SPavel Labath         // si_code == SI_USER and si_pid == 0
960b9cc0c75SPavel Labath         if (log)
961b9cc0c75SPavel Labath             log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
962b9cc0c75SPavel Labath 
963b9cc0c75SPavel Labath         if (info_err.Fail())
964b9cc0c75SPavel Labath         {
965b9cc0c75SPavel Labath             if (log)
966b9cc0c75SPavel Labath                 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
967b9cc0c75SPavel Labath             return;
968b9cc0c75SPavel Labath         }
969b9cc0c75SPavel Labath 
970b9cc0c75SPavel Labath         if (log && (info.si_code != SI_USER || info.si_pid != 0))
971b9cc0c75SPavel 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);
972b9cc0c75SPavel Labath 
973b9cc0c75SPavel Labath         auto thread_sp = AddThread(pid);
974b9cc0c75SPavel Labath         // Resume the newly created thread.
975b9cc0c75SPavel Labath         ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
976b9cc0c75SPavel Labath         ThreadWasCreated(*thread_sp);
977b9cc0c75SPavel Labath         return;
978b9cc0c75SPavel Labath     }
979b9cc0c75SPavel Labath 
980b9cc0c75SPavel Labath     // Get details on the signal raised.
981b9cc0c75SPavel Labath     if (info_err.Success())
982fa03ad2eSChaoren Lin     {
983fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
984fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
985b9cc0c75SPavel Labath             MonitorSIGTRAP(info, *thread_sp);
986fa03ad2eSChaoren Lin         else
987b9cc0c75SPavel Labath             MonitorSignal(info, *thread_sp, exited);
988fa03ad2eSChaoren Lin     }
989fa03ad2eSChaoren Lin     else
990af245d11STodd Fiala     {
991b9cc0c75SPavel Labath         if (info_err.GetError() == EINVAL)
992af245d11STodd Fiala         {
993fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
99439036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
99539036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
99639036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
99739036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
99839036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
99939036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
100039036ac3SPavel Labath             // correctly for all signals.
1001fa03ad2eSChaoren Lin             if (log)
100239036ac3SPavel 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);
1003b9cc0c75SPavel Labath             ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1004a9882ceeSTodd Fiala         }
1005a9882ceeSTodd Fiala         else
1006a9882ceeSTodd Fiala         {
1007af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
1008af245d11STodd Fiala 
1009af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
1010af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
1011af245d11STodd Fiala             // with it anymore.
1012af245d11STodd Fiala 
1013af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
10141107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
1015af245d11STodd Fiala 
1016af245d11STodd Fiala             if (log)
1017af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
1018b9cc0c75SPavel 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");
1019af245d11STodd Fiala 
1020af245d11STodd Fiala             if (is_main_thread)
1021af245d11STodd Fiala             {
1022af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
1023af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
10241107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
10251107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1026af245d11STodd Fiala             }
1027af245d11STodd Fiala             else
1028af245d11STodd Fiala             {
1029af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
1030af245d11STodd Fiala                 if (log)
10311107b5a5SPavel 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);
1032af245d11STodd Fiala             }
1033af245d11STodd Fiala         }
1034af245d11STodd Fiala     }
1035af245d11STodd Fiala }
1036af245d11STodd Fiala 
1037af245d11STodd Fiala void
1038426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
1039426bdf88SPavel Labath {
1040426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1041426bdf88SPavel Labath 
1042f9077782SPavel Labath     NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
1043426bdf88SPavel Labath 
1044426bdf88SPavel Labath     if (new_thread_sp)
1045426bdf88SPavel Labath     {
1046426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
1047426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
1048426bdf88SPavel Labath         return;
1049426bdf88SPavel Labath     }
1050426bdf88SPavel Labath 
1051426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
1052426bdf88SPavel Labath     int status = -1;
1053426bdf88SPavel Labath     ::pid_t wait_pid;
1054426bdf88SPavel Labath     do
1055426bdf88SPavel Labath     {
1056426bdf88SPavel Labath         if (log)
1057426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1058426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
1059426bdf88SPavel Labath     }
1060426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
1061426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
1062426bdf88SPavel Labath     // some checks just in case.
1063426bdf88SPavel Labath     if (wait_pid != tid) {
1064426bdf88SPavel Labath         if (log)
1065426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1066426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
1067426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1068426bdf88SPavel Labath         return;
1069426bdf88SPavel Labath     }
1070426bdf88SPavel Labath     if (WIFEXITED(status))
1071426bdf88SPavel Labath     {
1072426bdf88SPavel Labath         if (log)
1073426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1074426bdf88SPavel Labath         // Also a very improbable event.
1075426bdf88SPavel Labath         return;
1076426bdf88SPavel Labath     }
1077426bdf88SPavel Labath 
1078426bdf88SPavel Labath     siginfo_t info;
1079426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
1080426bdf88SPavel Labath     if (error.Fail())
1081426bdf88SPavel Labath     {
1082426bdf88SPavel Labath         if (log)
1083426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1084426bdf88SPavel Labath         return;
1085426bdf88SPavel Labath     }
1086426bdf88SPavel Labath 
1087426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1088426bdf88SPavel Labath     {
1089426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
1090426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
1091426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
1092426bdf88SPavel Labath         // created properly.
1093426bdf88SPavel 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);
1094426bdf88SPavel Labath     }
1095426bdf88SPavel Labath 
1096426bdf88SPavel Labath     if (log)
1097426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1098426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
1099426bdf88SPavel Labath 
1100f9077782SPavel Labath     new_thread_sp = AddThread(tid);
1101b9cc0c75SPavel Labath     ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1102f9077782SPavel Labath     ThreadWasCreated(*new_thread_sp);
1103426bdf88SPavel Labath }
1104426bdf88SPavel Labath 
1105426bdf88SPavel Labath void
1106b9cc0c75SPavel Labath NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
1107af245d11STodd Fiala {
1108af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1109b9cc0c75SPavel Labath     const bool is_main_thread = (thread.GetID() == GetID ());
1110af245d11STodd Fiala 
1111b9cc0c75SPavel Labath     assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
1112af245d11STodd Fiala 
1113b9cc0c75SPavel Labath     switch (info.si_code)
1114af245d11STodd Fiala     {
1115af245d11STodd 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.
1116af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1117af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1118af245d11STodd Fiala 
1119af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1120af245d11STodd Fiala     {
11215fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
1122426bdf88SPavel Labath         // creation.
1123426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
1124426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
1125426bdf88SPavel Labath         // here.
1126af245d11STodd Fiala 
1127af245d11STodd Fiala         unsigned long event_message = 0;
1128b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &event_message).Fail())
1129fa03ad2eSChaoren Lin         {
1130426bdf88SPavel Labath             if (log)
1131b9cc0c75SPavel 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());
1132426bdf88SPavel Labath         } else
1133426bdf88SPavel Labath             WaitForNewThread(event_message);
1134af245d11STodd Fiala 
1135b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1136af245d11STodd Fiala         break;
1137af245d11STodd Fiala     }
1138af245d11STodd Fiala 
1139af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1140a9882ceeSTodd Fiala     {
1141f9077782SPavel Labath         NativeThreadLinuxSP main_thread_sp;
1142af245d11STodd Fiala         if (log)
1143b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
1144a9882ceeSTodd Fiala 
11451dbc6c9cSPavel Labath         // Exec clears any pending notifications.
11460e1d729bSPavel Labath         m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1147fa03ad2eSChaoren Lin 
114857a77118SPavel Labath         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.
1149a9882ceeSTodd Fiala         if (log)
1150a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1151a9882ceeSTodd Fiala 
1152a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
1153a9882ceeSTodd Fiala         {
1154a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1155a9882ceeSTodd Fiala             if (is_main_thread)
1156a9882ceeSTodd Fiala             {
1157f9077782SPavel Labath                 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
1158a9882ceeSTodd Fiala                 if (log)
1159a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1160a9882ceeSTodd Fiala             }
1161a9882ceeSTodd Fiala             else
1162a9882ceeSTodd Fiala             {
1163a9882ceeSTodd Fiala                 if (log)
1164a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1165a9882ceeSTodd Fiala             }
1166a9882ceeSTodd Fiala         }
1167a9882ceeSTodd Fiala 
1168a9882ceeSTodd Fiala         m_threads.clear ();
1169a9882ceeSTodd Fiala 
1170a9882ceeSTodd Fiala         if (main_thread_sp)
1171a9882ceeSTodd Fiala         {
1172a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
1173a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
1174f9077782SPavel Labath             main_thread_sp->SetStoppedByExec();
1175a9882ceeSTodd Fiala         }
1176a9882ceeSTodd Fiala         else
1177a9882ceeSTodd Fiala         {
1178a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1179a9882ceeSTodd Fiala             if (log)
1180a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1181a9882ceeSTodd Fiala         }
1182a9882ceeSTodd Fiala 
1183fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
1184f9077782SPavel Labath         ThreadWasCreated(*main_thread_sp);
1185fa03ad2eSChaoren Lin 
1186a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
1187a9882ceeSTodd Fiala         NotifyDidExec ();
1188a9882ceeSTodd Fiala 
1189a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
1190a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1191fa03ad2eSChaoren Lin 
1192fa03ad2eSChaoren Lin         // Let the process know we're stopped.
1193b9cc0c75SPavel Labath         StopRunningThreads(main_thread_sp->GetID());
1194a9882ceeSTodd Fiala 
1195af245d11STodd Fiala         break;
1196a9882ceeSTodd Fiala     }
1197af245d11STodd Fiala 
1198af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1199af245d11STodd Fiala     {
1200af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
12016e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
12026e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
12036e35163cSPavel Labath         // here.
1204fa03ad2eSChaoren Lin 
1205af245d11STodd Fiala         unsigned long data = 0;
1206b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &data).Fail())
1207af245d11STodd Fiala             data = -1;
1208af245d11STodd Fiala 
1209af245d11STodd Fiala         if (log)
1210af245d11STodd Fiala         {
1211af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1212af245d11STodd Fiala                          __FUNCTION__,
1213af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1214b9cc0c75SPavel Labath                          thread.GetID(),
1215af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
1216af245d11STodd Fiala         }
1217af245d11STodd Fiala 
1218af245d11STodd Fiala         if (is_main_thread)
1219af245d11STodd Fiala         {
1220af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
122175f47c3aSTodd Fiala         }
122275f47c3aSTodd Fiala 
122386852d36SPavel Labath         StateType state = thread.GetState();
122486852d36SPavel Labath         if (! StateIsRunningState(state))
122586852d36SPavel Labath         {
122686852d36SPavel Labath             // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
122786852d36SPavel Labath             // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
122886852d36SPavel Labath             // we should not be receiving any ptrace events while the inferior is stopped. This
122986852d36SPavel Labath             // makes sure that the inferior is resumed and exits normally.
123086852d36SPavel Labath             state = eStateRunning;
123186852d36SPavel Labath         }
123286852d36SPavel Labath         ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
1233af245d11STodd Fiala 
1234af245d11STodd Fiala         break;
1235af245d11STodd Fiala     }
1236af245d11STodd Fiala 
1237af245d11STodd Fiala     case 0:
1238c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
1239c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
124086fd8e45SChaoren Lin     {
1241c16f5dcaSChaoren Lin         // If a watchpoint was hit, report it
1242c16f5dcaSChaoren Lin         uint32_t wp_index;
12431fa5c4b9STamas Berghammer         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
1244c16f5dcaSChaoren Lin         if (error.Fail() && log)
1245c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() "
1246c16f5dcaSChaoren Lin                         "received error while checking for watchpoint hits, "
1247c16f5dcaSChaoren Lin                         "pid = %" PRIu64 " error = %s",
1248b9cc0c75SPavel Labath                         __FUNCTION__, thread.GetID(), error.AsCString());
1249c16f5dcaSChaoren Lin         if (wp_index != LLDB_INVALID_INDEX32)
12505830aa75STamas Berghammer         {
1251b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
1252c16f5dcaSChaoren Lin             break;
1253c16f5dcaSChaoren Lin         }
1254b9cc0c75SPavel Labath 
1255be379e15STamas Berghammer         // Otherwise, report step over
1256be379e15STamas Berghammer         MonitorTrace(thread);
1257af245d11STodd Fiala         break;
1258b9cc0c75SPavel Labath     }
1259af245d11STodd Fiala 
1260af245d11STodd Fiala     case SI_KERNEL:
126135799963SMohit K. Bhakkad #if defined __mips__
126235799963SMohit K. Bhakkad         // For mips there is no special signal for watchpoint
126335799963SMohit K. Bhakkad         // So we check for watchpoint in kernel trap
126435799963SMohit K. Bhakkad     {
126535799963SMohit K. Bhakkad         // If a watchpoint was hit, report it
126635799963SMohit K. Bhakkad         uint32_t wp_index;
1267b9cc0c75SPavel Labath         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
126835799963SMohit K. Bhakkad         if (error.Fail() && log)
126935799963SMohit K. Bhakkad             log->Printf("NativeProcessLinux::%s() "
127035799963SMohit K. Bhakkad                         "received error while checking for watchpoint hits, "
127135799963SMohit K. Bhakkad                         "pid = %" PRIu64 " error = %s",
127216ad0321SMohit K. Bhakkad                         __FUNCTION__, thread.GetID(), error.AsCString());
127335799963SMohit K. Bhakkad         if (wp_index != LLDB_INVALID_INDEX32)
127435799963SMohit K. Bhakkad         {
1275b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
127635799963SMohit K. Bhakkad             break;
127735799963SMohit K. Bhakkad         }
127835799963SMohit K. Bhakkad     }
127935799963SMohit K. Bhakkad         // NO BREAK
128035799963SMohit K. Bhakkad #endif
1281af245d11STodd Fiala     case TRAP_BRKPT:
1282b9cc0c75SPavel Labath         MonitorBreakpoint(thread);
1283af245d11STodd Fiala         break;
1284af245d11STodd Fiala 
1285af245d11STodd Fiala     case SIGTRAP:
1286af245d11STodd Fiala     case (SIGTRAP | 0x80):
1287af245d11STodd Fiala         if (log)
1288b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
1289fa03ad2eSChaoren Lin 
1290af245d11STodd Fiala         // Ignore these signals until we know more about them.
1291b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1292af245d11STodd Fiala         break;
1293af245d11STodd Fiala 
1294af245d11STodd Fiala     default:
1295af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
1296af245d11STodd Fiala         if (log)
12976e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1298b9cc0c75SPavel Labath                     __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1299af245d11STodd Fiala         break;
1300af245d11STodd Fiala 
1301af245d11STodd Fiala     }
1302af245d11STodd Fiala }
1303af245d11STodd Fiala 
1304af245d11STodd Fiala void
1305b9cc0c75SPavel Labath NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
1306c16f5dcaSChaoren Lin {
1307c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1308c16f5dcaSChaoren Lin     if (log)
1309c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1310b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1311c16f5dcaSChaoren Lin 
13120e1d729bSPavel Labath     // This thread is currently stopped.
1313b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
1314c16f5dcaSChaoren Lin 
1315b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1316c16f5dcaSChaoren Lin }
1317c16f5dcaSChaoren Lin 
1318c16f5dcaSChaoren Lin void
1319b9cc0c75SPavel Labath NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
1320c16f5dcaSChaoren Lin {
1321c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1322c16f5dcaSChaoren Lin     if (log)
1323c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1324b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1325c16f5dcaSChaoren Lin 
1326c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
1327b9cc0c75SPavel Labath     thread.SetStoppedByBreakpoint();
1328b9cc0c75SPavel Labath     Error error = FixupBreakpointPCAsNeeded(thread);
1329c16f5dcaSChaoren Lin     if (error.Fail())
1330c16f5dcaSChaoren Lin         if (log)
1331c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1332b9cc0c75SPavel Labath                     __FUNCTION__, thread.GetID(), error.AsCString());
1333d8c338d4STamas Berghammer 
1334b9cc0c75SPavel Labath     if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1335b9cc0c75SPavel Labath         thread.SetStoppedByTrace();
1336c16f5dcaSChaoren Lin 
1337b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1338c16f5dcaSChaoren Lin }
1339c16f5dcaSChaoren Lin 
1340c16f5dcaSChaoren Lin void
1341f9077782SPavel Labath NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
1342c16f5dcaSChaoren Lin {
1343c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1344c16f5dcaSChaoren Lin     if (log)
1345c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1346c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
1347f9077782SPavel Labath                     __FUNCTION__, thread.GetID(), wp_index);
1348c16f5dcaSChaoren Lin 
1349c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
1350c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
1351f9077782SPavel Labath     thread.SetStoppedByWatchpoint(wp_index);
1352c16f5dcaSChaoren Lin 
1353c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
1354f9077782SPavel Labath     StopRunningThreads(thread.GetID());
1355c16f5dcaSChaoren Lin }
1356c16f5dcaSChaoren Lin 
1357c16f5dcaSChaoren Lin void
1358b9cc0c75SPavel Labath NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
1359af245d11STodd Fiala {
1360b9cc0c75SPavel Labath     const int signo = info.si_signo;
1361b9cc0c75SPavel Labath     const bool is_from_llgs = info.si_pid == getpid ();
1362af245d11STodd Fiala 
1363af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1364af245d11STodd Fiala 
1365af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1366af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1367af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1368af245d11STodd Fiala     //
1369af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
1370af245d11STodd Fiala     // "crash".
1371af245d11STodd Fiala     //
1372af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
1373af245d11STodd Fiala 
1374af245d11STodd Fiala     // Handle the signal.
1375b9cc0c75SPavel Labath     if (info.si_code == SI_TKILL || info.si_code == SI_USER)
1376af245d11STodd Fiala     {
1377af245d11STodd Fiala         if (log)
1378af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1379af245d11STodd Fiala                             __FUNCTION__,
138098d0a4b3SChaoren Lin                             Host::GetSignalAsCString(signo),
1381af245d11STodd Fiala                             signo,
1382b9cc0c75SPavel Labath                             (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1383b9cc0c75SPavel Labath                             info.si_pid,
1384511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
1385b9cc0c75SPavel Labath                             thread.GetID());
1386af245d11STodd Fiala     }
138758a2f669STodd Fiala 
138858a2f669STodd Fiala     // Check for thread stop notification.
1389b9cc0c75SPavel Labath     if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
1390af245d11STodd Fiala     {
1391af245d11STodd Fiala         // This is a tgkill()-based stop.
1392fa03ad2eSChaoren Lin         if (log)
1393fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1394fa03ad2eSChaoren Lin                          __FUNCTION__,
1395fa03ad2eSChaoren Lin                          GetID (),
1396b9cc0c75SPavel Labath                          thread.GetID());
1397fa03ad2eSChaoren Lin 
1398aab58633SChaoren Lin         // Check that we're not already marked with a stop reason.
1399aab58633SChaoren Lin         // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1400aab58633SChaoren Lin         // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1401aab58633SChaoren Lin         // and that, without an intervening resume, we received another stop.  It is more likely
1402aab58633SChaoren Lin         // that we are missing the marking of a run state somewhere if we find that the thread was
1403aab58633SChaoren Lin         // marked as stopped.
1404b9cc0c75SPavel Labath         const StateType thread_state = thread.GetState();
1405aab58633SChaoren Lin         if (!StateIsStoppedState (thread_state, false))
1406aab58633SChaoren Lin         {
1407ed89c7feSPavel Labath             // An inferior thread has stopped because of a SIGSTOP we have sent it.
1408ed89c7feSPavel Labath             // Generally, these are not important stops and we don't want to report them as
1409ed89c7feSPavel Labath             // they are just used to stop other threads when one thread (the one with the
1410ed89c7feSPavel Labath             // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1411ed89c7feSPavel Labath             // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1412ed89c7feSPavel Labath             // leave the signal intact if this is the thread that was chosen as the
1413ed89c7feSPavel Labath             // triggering thread.
14140e1d729bSPavel Labath             if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
14150e1d729bSPavel Labath             {
1416b9cc0c75SPavel Labath                 if (m_pending_notification_tid == thread.GetID())
1417b9cc0c75SPavel Labath                     thread.SetStoppedBySignal(SIGSTOP, &info);
1418ed89c7feSPavel Labath                 else
1419b9cc0c75SPavel Labath                     thread.SetStoppedWithNoReason();
1420ed89c7feSPavel Labath 
1421b9cc0c75SPavel Labath                 SetCurrentThreadID (thread.GetID ());
14220e1d729bSPavel Labath                 SignalIfAllThreadsStopped();
14230e1d729bSPavel Labath             }
14240e1d729bSPavel Labath             else
14250e1d729bSPavel Labath             {
14260e1d729bSPavel Labath                 // We can end up here if stop was initiated by LLGS but by this time a
14270e1d729bSPavel Labath                 // thread stop has occurred - maybe initiated by another event.
1428b9cc0c75SPavel Labath                 Error error = ResumeThread(thread, thread.GetState(), 0);
14290e1d729bSPavel Labath                 if (error.Fail() && log)
14300e1d729bSPavel Labath                 {
14310e1d729bSPavel Labath                     log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
1432b9cc0c75SPavel Labath                             __FUNCTION__, thread.GetID(), error.AsCString());
14330e1d729bSPavel Labath                 }
14340e1d729bSPavel Labath             }
1435aab58633SChaoren Lin         }
1436aab58633SChaoren Lin         else
1437aab58633SChaoren Lin         {
1438aab58633SChaoren Lin             if (log)
1439aab58633SChaoren Lin             {
1440aab58633SChaoren Lin                 // Retrieve the signal name if the thread was stopped by a signal.
1441aab58633SChaoren Lin                 int stop_signo = 0;
1442b9cc0c75SPavel Labath                 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
144398d0a4b3SChaoren Lin                 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1444aab58633SChaoren Lin                 if (!signal_name)
1445aab58633SChaoren Lin                     signal_name = "<no-signal-name>";
1446aab58633SChaoren Lin 
1447aab58633SChaoren 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",
1448aab58633SChaoren Lin                              __FUNCTION__,
1449aab58633SChaoren Lin                              GetID (),
1450b9cc0c75SPavel Labath                              thread.GetID(),
1451aab58633SChaoren Lin                              StateAsCString (thread_state),
1452aab58633SChaoren Lin                              stop_signo,
1453aab58633SChaoren Lin                              signal_name);
1454aab58633SChaoren Lin             }
14550e1d729bSPavel Labath             SignalIfAllThreadsStopped();
1456af245d11STodd Fiala         }
1457af245d11STodd Fiala 
145858a2f669STodd Fiala         // Done handling.
1459af245d11STodd Fiala         return;
1460af245d11STodd Fiala     }
1461af245d11STodd Fiala 
1462af245d11STodd Fiala     if (log)
146398d0a4b3SChaoren Lin         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
1464af245d11STodd Fiala 
146586fd8e45SChaoren Lin     // This thread is stopped.
1466b9cc0c75SPavel Labath     thread.SetStoppedBySignal(signo, &info);
146786fd8e45SChaoren Lin 
146886fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
1469b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1470511e5cdcSTodd Fiala }
1471af245d11STodd Fiala 
1472e7708688STamas Berghammer namespace {
1473e7708688STamas Berghammer 
1474e7708688STamas Berghammer struct EmulatorBaton
1475e7708688STamas Berghammer {
1476e7708688STamas Berghammer     NativeProcessLinux* m_process;
1477e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
14786648fcc3SPavel Labath 
14796648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
14806648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
1481e7708688STamas Berghammer 
1482e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
1483e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
1484e7708688STamas Berghammer };
1485e7708688STamas Berghammer 
1486e7708688STamas Berghammer } // anonymous namespace
1487e7708688STamas Berghammer 
1488e7708688STamas Berghammer static size_t
1489e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
1490e7708688STamas Berghammer                     void *baton,
1491e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
1492e7708688STamas Berghammer                     lldb::addr_t addr,
1493e7708688STamas Berghammer                     void *dst,
1494e7708688STamas Berghammer                     size_t length)
1495e7708688STamas Berghammer {
1496e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1497e7708688STamas Berghammer 
14983eb4b458SChaoren Lin     size_t bytes_read;
1499e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1500e7708688STamas Berghammer     return bytes_read;
1501e7708688STamas Berghammer }
1502e7708688STamas Berghammer 
1503e7708688STamas Berghammer static bool
1504e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
1505e7708688STamas Berghammer                       void *baton,
1506e7708688STamas Berghammer                       const RegisterInfo *reg_info,
1507e7708688STamas Berghammer                       RegisterValue &reg_value)
1508e7708688STamas Berghammer {
1509e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1510e7708688STamas Berghammer 
15116648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
15126648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
15136648fcc3SPavel Labath     {
15146648fcc3SPavel Labath         reg_value = it->second;
15156648fcc3SPavel Labath         return true;
15166648fcc3SPavel Labath     }
15176648fcc3SPavel Labath 
1518e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
1519e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
1520e7708688STamas Berghammer     // register context based on the dwarf register numbers.
1521e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1522e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1523e7708688STamas Berghammer 
1524e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
15256648fcc3SPavel Labath     if (error.Success())
15266648fcc3SPavel Labath         return true;
1527cdc22a88SMohit K. Bhakkad 
15286648fcc3SPavel Labath     return false;
1529e7708688STamas Berghammer }
1530e7708688STamas Berghammer 
1531e7708688STamas Berghammer static bool
1532e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
1533e7708688STamas Berghammer                        void *baton,
1534e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
1535e7708688STamas Berghammer                        const RegisterInfo *reg_info,
1536e7708688STamas Berghammer                        const RegisterValue &reg_value)
1537e7708688STamas Berghammer {
1538e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
15396648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
1540e7708688STamas Berghammer     return true;
1541e7708688STamas Berghammer }
1542e7708688STamas Berghammer 
1543e7708688STamas Berghammer static size_t
1544e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
1545e7708688STamas Berghammer                      void *baton,
1546e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
1547e7708688STamas Berghammer                      lldb::addr_t addr,
1548e7708688STamas Berghammer                      const void *dst,
1549e7708688STamas Berghammer                      size_t length)
1550e7708688STamas Berghammer {
1551e7708688STamas Berghammer     return length;
1552e7708688STamas Berghammer }
1553e7708688STamas Berghammer 
1554e7708688STamas Berghammer static lldb::addr_t
1555e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
1556e7708688STamas Berghammer {
1557e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1558e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1559e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1560e7708688STamas Berghammer }
1561e7708688STamas Berghammer 
1562e7708688STamas Berghammer Error
1563b9cc0c75SPavel Labath NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
1564e7708688STamas Berghammer {
1565e7708688STamas Berghammer     Error error;
1566b9cc0c75SPavel Labath     NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1567e7708688STamas Berghammer 
1568e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
1569e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1570e7708688STamas Berghammer 
1571e7708688STamas Berghammer     if (emulator_ap == nullptr)
1572e7708688STamas Berghammer         return Error("Instruction emulator not found!");
1573e7708688STamas Berghammer 
1574e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
1575e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
1576e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1577e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1578e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1579e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1580e7708688STamas Berghammer 
1581e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
1582e7708688STamas Berghammer         return Error("Read instruction failed!");
1583e7708688STamas Berghammer 
15846648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
15856648fcc3SPavel Labath 
15866648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
15876648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
15886648fcc3SPavel Labath 
15896648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
15906648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
15916648fcc3SPavel Labath 
1592e7708688STamas Berghammer     lldb::addr_t next_pc;
1593e7708688STamas Berghammer     lldb::addr_t next_flags;
15946648fcc3SPavel Labath     if (emulation_result)
1595e7708688STamas Berghammer     {
15966648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
15976648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
15986648fcc3SPavel Labath 
15996648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
16006648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
1601e7708688STamas Berghammer         else
1602e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
1603e7708688STamas Berghammer     }
16046648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
1605e7708688STamas Berghammer     {
1606e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
1607e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
1608e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
1609e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
1610e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1611e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
1612e7708688STamas Berghammer     }
1613e7708688STamas Berghammer     else
1614e7708688STamas Berghammer     {
1615e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
1616e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
1617e7708688STamas Berghammer         // modifying the PC but we don't  know how.
1618e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
1619e7708688STamas Berghammer     }
1620e7708688STamas Berghammer 
1621e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
1622e7708688STamas Berghammer     {
1623e7708688STamas Berghammer         if (next_flags & 0x20)
1624e7708688STamas Berghammer         {
1625e7708688STamas Berghammer             // Thumb mode
1626e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
1627e7708688STamas Berghammer         }
1628e7708688STamas Berghammer         else
1629e7708688STamas Berghammer         {
1630e7708688STamas Berghammer             // Arm mode
1631e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
1632e7708688STamas Berghammer         }
1633e7708688STamas Berghammer     }
1634cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
1635c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips64el
1636c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips
1637c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mipsel)
1638cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
1639e7708688STamas Berghammer     else
1640e7708688STamas Berghammer     {
1641e7708688STamas Berghammer         // No size hint is given for the next breakpoint
1642e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
1643e7708688STamas Berghammer     }
1644e7708688STamas Berghammer 
1645e7708688STamas Berghammer     if (error.Fail())
1646e7708688STamas Berghammer         return error;
1647e7708688STamas Berghammer 
1648b9cc0c75SPavel Labath     m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1649e7708688STamas Berghammer 
1650e7708688STamas Berghammer     return Error();
1651e7708688STamas Berghammer }
1652e7708688STamas Berghammer 
1653e7708688STamas Berghammer bool
1654e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
1655e7708688STamas Berghammer {
1656cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
1657c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1658c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
1659cdc22a88SMohit K. Bhakkad         return false;
1660cdc22a88SMohit K. Bhakkad     return true;
1661e7708688STamas Berghammer }
1662e7708688STamas Berghammer 
1663af245d11STodd Fiala Error
1664af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1665af245d11STodd Fiala {
1666af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1667af245d11STodd Fiala     if (log)
1668af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1669af245d11STodd Fiala 
1670e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
1671af245d11STodd Fiala 
1672e7708688STamas Berghammer     if (software_single_step)
1673e7708688STamas Berghammer     {
1674e7708688STamas Berghammer         for (auto thread_sp : m_threads)
1675e7708688STamas Berghammer         {
1676e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
1677e7708688STamas Berghammer 
1678e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1679e7708688STamas Berghammer             if (action == nullptr)
1680e7708688STamas Berghammer                 continue;
1681e7708688STamas Berghammer 
1682e7708688STamas Berghammer             if (action->state == eStateStepping)
1683e7708688STamas Berghammer             {
1684b9cc0c75SPavel Labath                 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
1685e7708688STamas Berghammer                 if (error.Fail())
1686e7708688STamas Berghammer                     return error;
1687e7708688STamas Berghammer             }
1688e7708688STamas Berghammer         }
1689e7708688STamas Berghammer     }
1690e7708688STamas Berghammer 
1691af245d11STodd Fiala     for (auto thread_sp : m_threads)
1692af245d11STodd Fiala     {
1693af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
1694af245d11STodd Fiala 
1695af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
16966a196ce6SChaoren Lin 
16976a196ce6SChaoren Lin         if (action == nullptr)
16986a196ce6SChaoren Lin         {
16996a196ce6SChaoren Lin             if (log)
17006a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
17016a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
17026a196ce6SChaoren Lin             continue;
17036a196ce6SChaoren Lin         }
1704af245d11STodd Fiala 
1705af245d11STodd Fiala         if (log)
1706af245d11STodd Fiala         {
1707af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1708af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1709af245d11STodd Fiala         }
1710af245d11STodd Fiala 
1711af245d11STodd Fiala         switch (action->state)
1712af245d11STodd Fiala         {
1713af245d11STodd Fiala         case eStateRunning:
17140e1d729bSPavel Labath         case eStateStepping:
1715fa03ad2eSChaoren Lin         {
1716af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
1717fa03ad2eSChaoren Lin             const int signo = action->signal;
1718b9cc0c75SPavel Labath             ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
1719af245d11STodd Fiala             break;
1720ae29d395SChaoren Lin         }
1721af245d11STodd Fiala 
1722af245d11STodd Fiala         case eStateSuspended:
1723af245d11STodd Fiala         case eStateStopped:
1724108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
1725af245d11STodd Fiala 
1726af245d11STodd Fiala         default:
1727af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1728af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1729af245d11STodd Fiala         }
1730af245d11STodd Fiala     }
1731af245d11STodd Fiala 
17325830aa75STamas Berghammer     return Error();
1733af245d11STodd Fiala }
1734af245d11STodd Fiala 
1735af245d11STodd Fiala Error
1736af245d11STodd Fiala NativeProcessLinux::Halt ()
1737af245d11STodd Fiala {
1738af245d11STodd Fiala     Error error;
1739af245d11STodd Fiala 
1740af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
1741af245d11STodd Fiala         error.SetErrorToErrno ();
1742af245d11STodd Fiala 
1743af245d11STodd Fiala     return error;
1744af245d11STodd Fiala }
1745af245d11STodd Fiala 
1746af245d11STodd Fiala Error
1747af245d11STodd Fiala NativeProcessLinux::Detach ()
1748af245d11STodd Fiala {
1749af245d11STodd Fiala     Error error;
1750af245d11STodd Fiala 
1751af245d11STodd Fiala     // Stop monitoring the inferior.
175219cbe96aSPavel Labath     m_sigchld_handle.reset();
1753af245d11STodd Fiala 
17547a9495bcSPavel Labath     // Tell ptrace to detach from the process.
17557a9495bcSPavel Labath     if (GetID () == LLDB_INVALID_PROCESS_ID)
17567a9495bcSPavel Labath         return error;
17577a9495bcSPavel Labath 
17587a9495bcSPavel Labath     for (auto thread_sp : m_threads)
17597a9495bcSPavel Labath     {
17607a9495bcSPavel Labath         Error e = Detach(thread_sp->GetID());
17617a9495bcSPavel Labath         if (e.Fail())
17627a9495bcSPavel Labath             error = e; // Save the error, but still attempt to detach from other threads.
17637a9495bcSPavel Labath     }
17647a9495bcSPavel Labath 
1765af245d11STodd Fiala     return error;
1766af245d11STodd Fiala }
1767af245d11STodd Fiala 
1768af245d11STodd Fiala Error
1769af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
1770af245d11STodd Fiala {
1771af245d11STodd Fiala     Error error;
1772af245d11STodd Fiala 
1773af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1774af245d11STodd Fiala     if (log)
1775af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
177698d0a4b3SChaoren Lin                 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1777af245d11STodd Fiala 
1778af245d11STodd Fiala     if (kill(GetID(), signo))
1779af245d11STodd Fiala         error.SetErrorToErrno();
1780af245d11STodd Fiala 
1781af245d11STodd Fiala     return error;
1782af245d11STodd Fiala }
1783af245d11STodd Fiala 
1784af245d11STodd Fiala Error
1785e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
1786e9547b80SChaoren Lin {
1787e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
1788e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
1789e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1790e9547b80SChaoren Lin 
1791e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
1792e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
1793e9547b80SChaoren Lin 
1794e9547b80SChaoren Lin     if (log)
1795e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1796e9547b80SChaoren Lin 
1797e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
1798e9547b80SChaoren Lin     {
1799e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
1800e9547b80SChaoren Lin         if (!thread_sp)
1801e9547b80SChaoren Lin             continue;
1802e9547b80SChaoren Lin 
1803e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
1804e9547b80SChaoren Lin         // target of the interrupt.
1805e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
1806e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
1807e9547b80SChaoren Lin             thread_state == eStateStepping)
1808e9547b80SChaoren Lin         {
1809e9547b80SChaoren Lin             running_thread_sp = thread_sp;
1810e9547b80SChaoren Lin             break;
1811e9547b80SChaoren Lin         }
1812e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1813e9547b80SChaoren Lin         {
1814e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
1815e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
1816e9547b80SChaoren Lin         }
1817e9547b80SChaoren Lin     }
1818e9547b80SChaoren Lin 
1819e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
1820e9547b80SChaoren Lin     {
18215830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
1822e9547b80SChaoren Lin         if (log)
1823e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
18245830aa75STamas Berghammer 
1825e9547b80SChaoren Lin         return error;
1826e9547b80SChaoren Lin     }
1827e9547b80SChaoren Lin 
1828e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1829e9547b80SChaoren Lin 
1830e9547b80SChaoren Lin     if (log)
1831e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1832e9547b80SChaoren Lin                      __FUNCTION__,
1833e9547b80SChaoren Lin                      GetID (),
1834e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
1835e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
1836e9547b80SChaoren Lin 
1837ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
183845f5cb31SPavel Labath 
18395830aa75STamas Berghammer     return Error();
1840e9547b80SChaoren Lin }
1841e9547b80SChaoren Lin 
1842e9547b80SChaoren Lin Error
1843af245d11STodd Fiala NativeProcessLinux::Kill ()
1844af245d11STodd Fiala {
1845af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1846af245d11STodd Fiala     if (log)
1847af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1848af245d11STodd Fiala 
1849af245d11STodd Fiala     Error error;
1850af245d11STodd Fiala 
1851af245d11STodd Fiala     switch (m_state)
1852af245d11STodd Fiala     {
1853af245d11STodd Fiala         case StateType::eStateInvalid:
1854af245d11STodd Fiala         case StateType::eStateExited:
1855af245d11STodd Fiala         case StateType::eStateCrashed:
1856af245d11STodd Fiala         case StateType::eStateDetached:
1857af245d11STodd Fiala         case StateType::eStateUnloaded:
1858af245d11STodd Fiala             // Nothing to do - the process is already dead.
1859af245d11STodd Fiala             if (log)
1860af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1861af245d11STodd Fiala             return error;
1862af245d11STodd Fiala 
1863af245d11STodd Fiala         case StateType::eStateConnected:
1864af245d11STodd Fiala         case StateType::eStateAttaching:
1865af245d11STodd Fiala         case StateType::eStateLaunching:
1866af245d11STodd Fiala         case StateType::eStateStopped:
1867af245d11STodd Fiala         case StateType::eStateRunning:
1868af245d11STodd Fiala         case StateType::eStateStepping:
1869af245d11STodd Fiala         case StateType::eStateSuspended:
1870af245d11STodd Fiala             // We can try to kill a process in these states.
1871af245d11STodd Fiala             break;
1872af245d11STodd Fiala     }
1873af245d11STodd Fiala 
1874af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
1875af245d11STodd Fiala     {
1876af245d11STodd Fiala         error.SetErrorToErrno ();
1877af245d11STodd Fiala         return error;
1878af245d11STodd Fiala     }
1879af245d11STodd Fiala 
1880af245d11STodd Fiala     return error;
1881af245d11STodd Fiala }
1882af245d11STodd Fiala 
1883af245d11STodd Fiala static Error
1884af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1885af245d11STodd Fiala {
1886af245d11STodd Fiala     memory_region_info.Clear();
1887af245d11STodd Fiala 
1888af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
1889af245d11STodd Fiala 
1890af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
1891af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
1892af245d11STodd Fiala 
1893af245d11STodd Fiala     // Parse out the starting address
1894af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1895af245d11STodd Fiala 
1896af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
1897af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1898af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1899af245d11STodd Fiala 
1900af245d11STodd Fiala     // Parse out the ending address
1901af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1902af245d11STodd Fiala 
1903af245d11STodd Fiala     // Parse out the space after the address.
1904af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1905af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1906af245d11STodd Fiala 
1907af245d11STodd Fiala     // Save the range.
1908af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
1909af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
1910af245d11STodd Fiala 
1911ad007563SHoward Hellyer     // Any memory region in /proc/{pid}/maps is by definition mapped into the process.
1912ad007563SHoward Hellyer     memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1913ad007563SHoward Hellyer 
1914af245d11STodd Fiala     // Parse out each permission entry.
1915af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
1916af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1917af245d11STodd Fiala 
1918af245d11STodd Fiala     // Handle read permission.
1919af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
1920af245d11STodd Fiala     if (read_perm_char == 'r')
1921af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1922af245d11STodd Fiala     else
1923af245d11STodd Fiala     {
1924af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1925af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1926af245d11STodd Fiala     }
1927af245d11STodd Fiala 
1928af245d11STodd Fiala     // Handle write permission.
1929af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
1930af245d11STodd Fiala     if (write_perm_char == 'w')
1931af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1932af245d11STodd Fiala     else
1933af245d11STodd Fiala     {
1934af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1935af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1936af245d11STodd Fiala     }
1937af245d11STodd Fiala 
1938af245d11STodd Fiala     // Handle execute permission.
1939af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
1940af245d11STodd Fiala     if (exec_perm_char == 'x')
1941af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1942af245d11STodd Fiala     else
1943af245d11STodd Fiala     {
1944af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1945af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1946af245d11STodd Fiala     }
1947af245d11STodd Fiala 
1948af245d11STodd Fiala     return Error ();
1949af245d11STodd Fiala }
1950af245d11STodd Fiala 
1951af245d11STodd Fiala Error
1952af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1953af245d11STodd Fiala {
1954af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
1955af245d11STodd Fiala     // with no perms if it is not mapped.
1956af245d11STodd Fiala 
1957af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
1958af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
1959af245d11STodd Fiala     // FIXME assert if we find differently.
1960af245d11STodd Fiala 
1961af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1962af245d11STodd Fiala     Error error;
1963af245d11STodd Fiala 
1964af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1965af245d11STodd Fiala     {
1966af245d11STodd Fiala         // We're done.
1967af245d11STodd Fiala         error.SetErrorString ("unsupported");
1968af245d11STodd Fiala         return error;
1969af245d11STodd Fiala     }
1970af245d11STodd Fiala 
1971af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
1972af245d11STodd Fiala     // if memory region handling is supported.
1973af245d11STodd Fiala     if (m_mem_region_cache.empty ())
1974af245d11STodd Fiala     {
1975af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1976af245d11STodd Fiala              [&] (const std::string &line) -> bool
1977af245d11STodd Fiala              {
1978af245d11STodd Fiala                  MemoryRegionInfo info;
1979af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1980af245d11STodd Fiala                  if (parse_error.Success ())
1981af245d11STodd Fiala                  {
1982af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
1983af245d11STodd Fiala                      return true;
1984af245d11STodd Fiala                  }
1985af245d11STodd Fiala                  else
1986af245d11STodd Fiala                  {
1987af245d11STodd Fiala                      if (log)
1988af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1989af245d11STodd Fiala                      return false;
1990af245d11STodd Fiala                  }
1991af245d11STodd Fiala              });
1992af245d11STodd Fiala 
1993af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
1994af245d11STodd Fiala         if (error.Fail ())
1995af245d11STodd Fiala         {
1996af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
1997af245d11STodd Fiala             return error;
1998af245d11STodd Fiala         }
1999af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
2000af245d11STodd Fiala         {
2001af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2002af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
2003af245d11STodd Fiala             if (log)
2004af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2005af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2006af245d11STodd Fiala             error.SetErrorString ("not supported");
2007af245d11STodd Fiala             return error;
2008af245d11STodd Fiala         }
2009af245d11STodd Fiala 
2010af245d11STodd Fiala         if (log)
2011af245d11STodd 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 ());
2012af245d11STodd Fiala 
2013af245d11STodd Fiala         // We support memory retrieval, remember that.
2014af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
2015af245d11STodd Fiala     }
2016af245d11STodd Fiala     else
2017af245d11STodd Fiala     {
2018af245d11STodd Fiala         if (log)
2019af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2020af245d11STodd Fiala     }
2021af245d11STodd Fiala 
2022af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
2023af245d11STodd Fiala 
2024af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2025af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
2026af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2027af245d11STodd Fiala     {
2028af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
2029af245d11STodd Fiala 
2030af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2031af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2032af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2033af245d11STodd Fiala 
2034af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
2035af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2036af245d11STodd Fiala         {
2037af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
2038af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2039af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2040af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2041af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2042ad007563SHoward Hellyer             range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
2043af245d11STodd Fiala 
2044af245d11STodd Fiala             return error;
2045af245d11STodd Fiala         }
2046af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
2047af245d11STodd Fiala         {
2048af245d11STodd Fiala             // The target address is within the memory region we're processing here.
2049af245d11STodd Fiala             range_info = proc_entry_info;
2050af245d11STodd Fiala             return error;
2051af245d11STodd Fiala         }
2052af245d11STodd Fiala 
2053af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
2054af245d11STodd Fiala     }
2055af245d11STodd Fiala 
205609839c33STamas Berghammer     // If we made it here, we didn't find an entry that contained the given address. Return the
205709839c33STamas Berghammer     // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
205809839c33STamas Berghammer     // size.
205909839c33STamas Berghammer     range_info.GetRange ().SetRangeBase (load_addr);
2060ad007563SHoward Hellyer     range_info.GetRange ().SetRangeEnd(LLDB_INVALID_ADDRESS);
206109839c33STamas Berghammer     range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
206209839c33STamas Berghammer     range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
206309839c33STamas Berghammer     range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2064ad007563SHoward Hellyer     range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
2065af245d11STodd Fiala     return error;
2066af245d11STodd Fiala }
2067af245d11STodd Fiala 
2068af245d11STodd Fiala void
2069af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2070af245d11STodd Fiala {
2071af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2072af245d11STodd Fiala     if (log)
2073af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2074af245d11STodd Fiala 
2075af245d11STodd Fiala         if (log)
2076af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2077af245d11STodd Fiala         m_mem_region_cache.clear ();
2078af245d11STodd Fiala }
2079af245d11STodd Fiala 
2080af245d11STodd Fiala Error
20813eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2082af245d11STodd Fiala {
2083af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
2084af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2085af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
2086af245d11STodd Fiala #if 1
2087af245d11STodd Fiala     return Error ("not implemented yet");
2088af245d11STodd Fiala #else
2089af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
2090af245d11STodd Fiala 
2091af245d11STodd Fiala     unsigned prot = 0;
2092af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
2093af245d11STodd Fiala         prot |= eMmapProtRead;
2094af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
2095af245d11STodd Fiala         prot |= eMmapProtWrite;
2096af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
2097af245d11STodd Fiala         prot |= eMmapProtExec;
2098af245d11STodd Fiala 
2099af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
2100af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
2101af245d11STodd Fiala     // refactored out).
2102af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
2103af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2104af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
2105af245d11STodd Fiala         return Error ();
2106af245d11STodd Fiala     } else {
2107af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
2108af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2109af245d11STodd Fiala     }
2110af245d11STodd Fiala #endif
2111af245d11STodd Fiala }
2112af245d11STodd Fiala 
2113af245d11STodd Fiala Error
2114af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2115af245d11STodd Fiala {
2116af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
2117af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
2118af245d11STodd Fiala     return Error ("not implemented");
2119af245d11STodd Fiala }
2120af245d11STodd Fiala 
2121af245d11STodd Fiala lldb::addr_t
2122af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
2123af245d11STodd Fiala {
2124af245d11STodd Fiala     // punt on this for now
2125af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2126af245d11STodd Fiala }
2127af245d11STodd Fiala 
2128af245d11STodd Fiala size_t
2129af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
2130af245d11STodd Fiala {
2131af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
2132af245d11STodd Fiala     // with respect to thread state and they keep the thread list
2133af245d11STodd Fiala     // populated properly. All this method needs to do is return the
2134af245d11STodd Fiala     // thread count.
2135af245d11STodd Fiala     return m_threads.size ();
2136af245d11STodd Fiala }
2137af245d11STodd Fiala 
2138af245d11STodd Fiala bool
2139af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2140af245d11STodd Fiala {
2141af245d11STodd Fiala     arch = m_arch;
2142af245d11STodd Fiala     return true;
2143af245d11STodd Fiala }
2144af245d11STodd Fiala 
2145af245d11STodd Fiala Error
2146b9cc0c75SPavel Labath NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
2147af245d11STodd Fiala {
2148af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
2149af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
2150af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
2151bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2152af245d11STodd Fiala 
2153af245d11STodd Fiala     switch (m_arch.GetMachine ())
2154af245d11STodd Fiala     {
2155af245d11STodd Fiala         case llvm::Triple::x86:
2156af245d11STodd Fiala         case llvm::Triple::x86_64:
2157af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2158af245d11STodd Fiala             return Error ();
2159af245d11STodd Fiala 
2160bb00d0b6SUlrich Weigand         case llvm::Triple::systemz:
2161bb00d0b6SUlrich Weigand             actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2162bb00d0b6SUlrich Weigand             return Error ();
2163bb00d0b6SUlrich Weigand 
2164ff7fd900STamas Berghammer         case llvm::Triple::arm:
2165ff7fd900STamas Berghammer         case llvm::Triple::aarch64:
2166e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
2167e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
2168ce815e45SSagar Thakur         case llvm::Triple::mips:
2169ce815e45SSagar Thakur         case llvm::Triple::mipsel:
2170ff7fd900STamas Berghammer             // On these architectures the PC don't get updated for breakpoint hits
2171c60c9452SJaydeep Patil             actual_opcode_size = 0;
2172e8659b5dSMohit K. Bhakkad             return Error ();
2173e8659b5dSMohit K. Bhakkad 
2174af245d11STodd Fiala         default:
2175af245d11STodd Fiala             assert(false && "CPU type not supported!");
2176af245d11STodd Fiala             return Error ("CPU type not supported");
2177af245d11STodd Fiala     }
2178af245d11STodd Fiala }
2179af245d11STodd Fiala 
2180af245d11STodd Fiala Error
2181af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2182af245d11STodd Fiala {
2183af245d11STodd Fiala     if (hardware)
2184af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
2185af245d11STodd Fiala     else
2186af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
2187af245d11STodd Fiala }
2188af245d11STodd Fiala 
2189af245d11STodd Fiala Error
219063c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
219163c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
219263c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
2193af245d11STodd Fiala {
219463c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
219563c8be95STamas Berghammer     // architecture.  Need MIPS support here.
21962afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2197be379e15STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2198be379e15STamas Berghammer     // linux kernel does otherwise.
2199be379e15STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
2200af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
22013df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
22022c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
2203bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2204be379e15STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
2205af245d11STodd Fiala 
2206af245d11STodd Fiala     switch (m_arch.GetMachine ())
2207af245d11STodd Fiala     {
22082afc5966STodd Fiala     case llvm::Triple::aarch64:
22092afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
22102afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
22112afc5966STodd Fiala         return Error ();
22122afc5966STodd Fiala 
221363c8be95STamas Berghammer     case llvm::Triple::arm:
221463c8be95STamas Berghammer         switch (trap_opcode_size_hint)
221563c8be95STamas Berghammer         {
221663c8be95STamas Berghammer         case 2:
221763c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
221863c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
221963c8be95STamas Berghammer             return Error ();
222063c8be95STamas Berghammer         case 4:
222163c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
222263c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
222363c8be95STamas Berghammer             return Error ();
222463c8be95STamas Berghammer         default:
222563c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
222663c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
222763c8be95STamas Berghammer         }
222863c8be95STamas Berghammer 
2229af245d11STodd Fiala     case llvm::Triple::x86:
2230af245d11STodd Fiala     case llvm::Triple::x86_64:
2231af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
2232af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
2233af245d11STodd Fiala         return Error ();
2234af245d11STodd Fiala 
2235ce815e45SSagar Thakur     case llvm::Triple::mips:
22363df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
22373df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
22383df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
22393df471c3SMohit K. Bhakkad         return Error ();
22403df471c3SMohit K. Bhakkad 
2241ce815e45SSagar Thakur     case llvm::Triple::mipsel:
22422c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
22432c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
22442c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
22452c2acf96SMohit K. Bhakkad         return Error ();
22462c2acf96SMohit K. Bhakkad 
2247bb00d0b6SUlrich Weigand     case llvm::Triple::systemz:
2248bb00d0b6SUlrich Weigand         trap_opcode_bytes = g_s390x_opcode;
2249bb00d0b6SUlrich Weigand         actual_opcode_size = sizeof(g_s390x_opcode);
2250bb00d0b6SUlrich Weigand         return Error ();
2251bb00d0b6SUlrich Weigand 
2252af245d11STodd Fiala     default:
2253af245d11STodd Fiala         assert(false && "CPU type not supported!");
2254af245d11STodd Fiala         return Error ("CPU type not supported");
2255af245d11STodd Fiala     }
2256af245d11STodd Fiala }
2257af245d11STodd Fiala 
2258af245d11STodd Fiala #if 0
2259af245d11STodd Fiala ProcessMessage::CrashReason
2260af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2261af245d11STodd Fiala {
2262af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2263af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
2264af245d11STodd Fiala 
2265af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2266af245d11STodd Fiala 
2267af245d11STodd Fiala     switch (info->si_code)
2268af245d11STodd Fiala     {
2269af245d11STodd Fiala     default:
2270af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
2271af245d11STodd Fiala         break;
2272af245d11STodd Fiala     case SI_KERNEL:
2273af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
2274af245d11STodd Fiala         // (this is poorly documented in sigaction)
2275af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
2276af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2277af245d11STodd Fiala         break;
2278af245d11STodd Fiala     case SEGV_MAPERR:
2279af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2280af245d11STodd Fiala         break;
2281af245d11STodd Fiala     case SEGV_ACCERR:
2282af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2283af245d11STodd Fiala         break;
2284af245d11STodd Fiala     }
2285af245d11STodd Fiala 
2286af245d11STodd Fiala     return reason;
2287af245d11STodd Fiala }
2288af245d11STodd Fiala #endif
2289af245d11STodd Fiala 
2290af245d11STodd Fiala 
2291af245d11STodd Fiala #if 0
2292af245d11STodd Fiala ProcessMessage::CrashReason
2293af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2294af245d11STodd Fiala {
2295af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2296af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2297af245d11STodd Fiala 
2298af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2299af245d11STodd Fiala 
2300af245d11STodd Fiala     switch (info->si_code)
2301af245d11STodd Fiala     {
2302af245d11STodd Fiala     default:
2303af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2304af245d11STodd Fiala         break;
2305af245d11STodd Fiala     case ILL_ILLOPC:
2306af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2307af245d11STodd Fiala         break;
2308af245d11STodd Fiala     case ILL_ILLOPN:
2309af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
2310af245d11STodd Fiala         break;
2311af245d11STodd Fiala     case ILL_ILLADR:
2312af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
2313af245d11STodd Fiala         break;
2314af245d11STodd Fiala     case ILL_ILLTRP:
2315af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
2316af245d11STodd Fiala         break;
2317af245d11STodd Fiala     case ILL_PRVOPC:
2318af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
2319af245d11STodd Fiala         break;
2320af245d11STodd Fiala     case ILL_PRVREG:
2321af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
2322af245d11STodd Fiala         break;
2323af245d11STodd Fiala     case ILL_COPROC:
2324af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
2325af245d11STodd Fiala         break;
2326af245d11STodd Fiala     case ILL_BADSTK:
2327af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
2328af245d11STodd Fiala         break;
2329af245d11STodd Fiala     }
2330af245d11STodd Fiala 
2331af245d11STodd Fiala     return reason;
2332af245d11STodd Fiala }
2333af245d11STodd Fiala #endif
2334af245d11STodd Fiala 
2335af245d11STodd Fiala #if 0
2336af245d11STodd Fiala ProcessMessage::CrashReason
2337af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2338af245d11STodd Fiala {
2339af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2340af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
2341af245d11STodd Fiala 
2342af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2343af245d11STodd Fiala 
2344af245d11STodd Fiala     switch (info->si_code)
2345af245d11STodd Fiala     {
2346af245d11STodd Fiala     default:
2347af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
2348af245d11STodd Fiala         break;
2349af245d11STodd Fiala     case FPE_INTDIV:
2350af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
2351af245d11STodd Fiala         break;
2352af245d11STodd Fiala     case FPE_INTOVF:
2353af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
2354af245d11STodd Fiala         break;
2355af245d11STodd Fiala     case FPE_FLTDIV:
2356af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
2357af245d11STodd Fiala         break;
2358af245d11STodd Fiala     case FPE_FLTOVF:
2359af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
2360af245d11STodd Fiala         break;
2361af245d11STodd Fiala     case FPE_FLTUND:
2362af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
2363af245d11STodd Fiala         break;
2364af245d11STodd Fiala     case FPE_FLTRES:
2365af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
2366af245d11STodd Fiala         break;
2367af245d11STodd Fiala     case FPE_FLTINV:
2368af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
2369af245d11STodd Fiala         break;
2370af245d11STodd Fiala     case FPE_FLTSUB:
2371af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
2372af245d11STodd Fiala         break;
2373af245d11STodd Fiala     }
2374af245d11STodd Fiala 
2375af245d11STodd Fiala     return reason;
2376af245d11STodd Fiala }
2377af245d11STodd Fiala #endif
2378af245d11STodd Fiala 
2379af245d11STodd Fiala #if 0
2380af245d11STodd Fiala ProcessMessage::CrashReason
2381af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2382af245d11STodd Fiala {
2383af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2384af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
2385af245d11STodd Fiala 
2386af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2387af245d11STodd Fiala 
2388af245d11STodd Fiala     switch (info->si_code)
2389af245d11STodd Fiala     {
2390af245d11STodd Fiala     default:
2391af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
2392af245d11STodd Fiala         break;
2393af245d11STodd Fiala     case BUS_ADRALN:
2394af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
2395af245d11STodd Fiala         break;
2396af245d11STodd Fiala     case BUS_ADRERR:
2397af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
2398af245d11STodd Fiala         break;
2399af245d11STodd Fiala     case BUS_OBJERR:
2400af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
2401af245d11STodd Fiala         break;
2402af245d11STodd Fiala     }
2403af245d11STodd Fiala 
2404af245d11STodd Fiala     return reason;
2405af245d11STodd Fiala }
2406af245d11STodd Fiala #endif
2407af245d11STodd Fiala 
2408af245d11STodd Fiala Error
240926438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2410af245d11STodd Fiala {
2411df7c6995SPavel Labath     if (ProcessVmReadvSupported()) {
2412df7c6995SPavel Labath         // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2413df7c6995SPavel Labath         // this syscall if it is supported.
2414df7c6995SPavel Labath 
2415df7c6995SPavel Labath         const ::pid_t pid = GetID();
2416df7c6995SPavel Labath 
2417df7c6995SPavel Labath         struct iovec local_iov, remote_iov;
2418df7c6995SPavel Labath         local_iov.iov_base = buf;
2419df7c6995SPavel Labath         local_iov.iov_len = size;
2420df7c6995SPavel Labath         remote_iov.iov_base = reinterpret_cast<void *>(addr);
2421df7c6995SPavel Labath         remote_iov.iov_len = size;
2422df7c6995SPavel Labath 
2423df7c6995SPavel Labath         bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2424df7c6995SPavel Labath         const bool success = bytes_read == size;
2425df7c6995SPavel Labath 
2426df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2427df7c6995SPavel Labath         if (log)
2428df7c6995SPavel Labath             log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2429df7c6995SPavel Labath                     __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2430df7c6995SPavel Labath 
2431df7c6995SPavel Labath         if (success)
2432df7c6995SPavel Labath             return Error();
2433df7c6995SPavel Labath         // else
2434df7c6995SPavel Labath         //     the call failed for some reason, let's retry the read using ptrace api.
2435df7c6995SPavel Labath     }
2436df7c6995SPavel Labath 
243719cbe96aSPavel Labath     unsigned char *dst = static_cast<unsigned char*>(buf);
243819cbe96aSPavel Labath     size_t remainder;
243919cbe96aSPavel Labath     long data;
244019cbe96aSPavel Labath 
244119cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
244219cbe96aSPavel Labath     if (log)
244319cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
244419cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
244519cbe96aSPavel Labath         log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
244619cbe96aSPavel Labath 
244719cbe96aSPavel Labath     for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
244819cbe96aSPavel Labath     {
244919cbe96aSPavel Labath         Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
245019cbe96aSPavel Labath         if (error.Fail())
245119cbe96aSPavel Labath         {
245219cbe96aSPavel Labath             if (log)
245319cbe96aSPavel Labath                 ProcessPOSIXLog::DecNestLevel();
245419cbe96aSPavel Labath             return error;
245519cbe96aSPavel Labath         }
245619cbe96aSPavel Labath 
245719cbe96aSPavel Labath         remainder = size - bytes_read;
245819cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
245919cbe96aSPavel Labath 
246019cbe96aSPavel Labath         // Copy the data into our buffer
2461f6ef187bSMohit K. Bhakkad         memcpy(dst, &data, remainder);
246219cbe96aSPavel Labath 
246319cbe96aSPavel Labath         if (log && ProcessPOSIXLog::AtTopNestLevel() &&
246419cbe96aSPavel Labath                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
246519cbe96aSPavel Labath                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
246619cbe96aSPavel Labath                                 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
246719cbe96aSPavel Labath         {
246819cbe96aSPavel Labath             uintptr_t print_dst = 0;
246919cbe96aSPavel Labath             // Format bytes from data by moving into print_dst for log output
247019cbe96aSPavel Labath             for (unsigned i = 0; i < remainder; ++i)
247119cbe96aSPavel Labath                 print_dst |= (((data >> i*8) & 0xFF) << i*8);
247279203995SPavel Labath             log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
247379203995SPavel Labath                     __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
247419cbe96aSPavel Labath         }
247519cbe96aSPavel Labath         addr += k_ptrace_word_size;
247619cbe96aSPavel Labath         dst += k_ptrace_word_size;
247719cbe96aSPavel Labath     }
247819cbe96aSPavel Labath 
247919cbe96aSPavel Labath     if (log)
248019cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
248119cbe96aSPavel Labath     return Error();
2482af245d11STodd Fiala }
2483af245d11STodd Fiala 
2484af245d11STodd Fiala Error
24853eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
24863eb4b458SChaoren Lin {
24873eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
24883eb4b458SChaoren Lin     if (error.Fail()) return error;
24893eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
24903eb4b458SChaoren Lin }
24913eb4b458SChaoren Lin 
24923eb4b458SChaoren Lin Error
24933eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
2494af245d11STodd Fiala {
249519cbe96aSPavel Labath     const unsigned char *src = static_cast<const unsigned char*>(buf);
249619cbe96aSPavel Labath     size_t remainder;
249719cbe96aSPavel Labath     Error error;
249819cbe96aSPavel Labath 
249919cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
250019cbe96aSPavel Labath     if (log)
250119cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
250219cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
250379203995SPavel Labath         log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
250419cbe96aSPavel Labath 
250519cbe96aSPavel Labath     for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
250619cbe96aSPavel Labath     {
250719cbe96aSPavel Labath         remainder = size - bytes_written;
250819cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
250919cbe96aSPavel Labath 
251019cbe96aSPavel Labath         if (remainder == k_ptrace_word_size)
251119cbe96aSPavel Labath         {
251219cbe96aSPavel Labath             unsigned long data = 0;
2513f6ef187bSMohit K. Bhakkad             memcpy(&data, src, k_ptrace_word_size);
251419cbe96aSPavel Labath 
251519cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
251619cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
251719cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
251819cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
251919cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
252019cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, data);
252119cbe96aSPavel Labath 
252219cbe96aSPavel Labath             error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
252319cbe96aSPavel Labath             if (error.Fail())
252419cbe96aSPavel Labath             {
252519cbe96aSPavel Labath                 if (log)
252619cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
252719cbe96aSPavel Labath                 return error;
252819cbe96aSPavel Labath             }
252919cbe96aSPavel Labath         }
253019cbe96aSPavel Labath         else
253119cbe96aSPavel Labath         {
253219cbe96aSPavel Labath             unsigned char buff[8];
253319cbe96aSPavel Labath             size_t bytes_read;
253419cbe96aSPavel Labath             error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
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             memcpy(buff, src, remainder);
254319cbe96aSPavel Labath 
254419cbe96aSPavel Labath             size_t bytes_written_rec;
254519cbe96aSPavel Labath             error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
254619cbe96aSPavel Labath             if (error.Fail())
254719cbe96aSPavel Labath             {
254819cbe96aSPavel Labath                 if (log)
254919cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
255019cbe96aSPavel Labath                 return error;
255119cbe96aSPavel Labath             }
255219cbe96aSPavel Labath 
255319cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
255419cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
255519cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
255619cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
255719cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
255819cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
255919cbe96aSPavel Labath         }
256019cbe96aSPavel Labath 
256119cbe96aSPavel Labath         addr += k_ptrace_word_size;
256219cbe96aSPavel Labath         src += k_ptrace_word_size;
256319cbe96aSPavel Labath     }
256419cbe96aSPavel Labath     if (log)
256519cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
256619cbe96aSPavel Labath     return error;
2567af245d11STodd Fiala }
2568af245d11STodd Fiala 
256997ccc294SChaoren Lin Error
257097ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
2571af245d11STodd Fiala {
257219cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2573af245d11STodd Fiala }
2574af245d11STodd Fiala 
257597ccc294SChaoren Lin Error
2576af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2577af245d11STodd Fiala {
257819cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2579af245d11STodd Fiala }
2580af245d11STodd Fiala 
2581db264a6dSTamas Berghammer Error
2582af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
2583af245d11STodd Fiala {
258497ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
258597ccc294SChaoren Lin         return Error();
258697ccc294SChaoren Lin 
258719cbe96aSPavel Labath     return PtraceWrapper(PTRACE_DETACH, tid);
2588af245d11STodd Fiala }
2589af245d11STodd Fiala 
2590af245d11STodd Fiala bool
2591d3173f34SChaoren Lin NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
2592af245d11STodd Fiala {
2593d3173f34SChaoren Lin     int target_fd = open(file_spec.GetCString(), flags, 0666);
2594af245d11STodd Fiala 
2595af245d11STodd Fiala     if (target_fd == -1)
2596af245d11STodd Fiala         return false;
2597af245d11STodd Fiala 
2598493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
2599493c3a12SPavel Labath         return false;
2600493c3a12SPavel Labath 
2601493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
2602af245d11STodd Fiala }
2603af245d11STodd Fiala 
2604af245d11STodd Fiala bool
2605af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2606af245d11STodd Fiala {
2607af245d11STodd Fiala     for (auto thread_sp : m_threads)
2608af245d11STodd Fiala     {
2609af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2610af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
2611af245d11STodd Fiala         {
2612af245d11STodd Fiala             // We have this thread.
2613af245d11STodd Fiala             return true;
2614af245d11STodd Fiala         }
2615af245d11STodd Fiala     }
2616af245d11STodd Fiala 
2617af245d11STodd Fiala     // We don't have this thread.
2618af245d11STodd Fiala     return false;
2619af245d11STodd Fiala }
2620af245d11STodd Fiala 
2621af245d11STodd Fiala bool
2622af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2623af245d11STodd Fiala {
26241dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
26251dbc6c9cSPavel Labath 
26261dbc6c9cSPavel Labath     if (log)
26271dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
26281dbc6c9cSPavel Labath 
26291dbc6c9cSPavel Labath     bool found = false;
26301dbc6c9cSPavel Labath 
2631af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2632af245d11STodd Fiala     {
2633af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
2634af245d11STodd Fiala         {
2635af245d11STodd Fiala             m_threads.erase (it);
26361dbc6c9cSPavel Labath             found = true;
26371dbc6c9cSPavel Labath             break;
2638af245d11STodd Fiala         }
2639af245d11STodd Fiala     }
2640af245d11STodd Fiala 
26419eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
26421dbc6c9cSPavel Labath 
26431dbc6c9cSPavel Labath     return found;
2644af245d11STodd Fiala }
2645af245d11STodd Fiala 
2646f9077782SPavel Labath NativeThreadLinuxSP
2647af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2648af245d11STodd Fiala {
2649af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2650af245d11STodd Fiala 
2651af245d11STodd Fiala     if (log)
2652af245d11STodd Fiala     {
2653af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2654af245d11STodd Fiala                 __FUNCTION__,
2655af245d11STodd Fiala                 GetID (),
2656af245d11STodd Fiala                 thread_id);
2657af245d11STodd Fiala     }
2658af245d11STodd Fiala 
2659af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2660af245d11STodd Fiala 
2661af245d11STodd Fiala     // If this is the first thread, save it as the current thread
2662af245d11STodd Fiala     if (m_threads.empty ())
2663af245d11STodd Fiala         SetCurrentThreadID (thread_id);
2664af245d11STodd Fiala 
2665f9077782SPavel Labath     auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2666af245d11STodd Fiala     m_threads.push_back (thread_sp);
2667af245d11STodd Fiala     return thread_sp;
2668af245d11STodd Fiala }
2669af245d11STodd Fiala 
2670af245d11STodd Fiala Error
2671b9cc0c75SPavel Labath NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
2672af245d11STodd Fiala {
267375f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2674af245d11STodd Fiala 
2675af245d11STodd Fiala     Error error;
2676af245d11STodd Fiala 
2677af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
2678b9cc0c75SPavel Labath     NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2679af245d11STodd Fiala     if (!context_sp)
2680af245d11STodd Fiala     {
2681af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2682af245d11STodd Fiala         if (log)
2683af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2684af245d11STodd Fiala         return error;
2685af245d11STodd Fiala     }
2686af245d11STodd Fiala 
2687af245d11STodd Fiala     uint32_t breakpoint_size = 0;
2688b9cc0c75SPavel Labath     error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2689af245d11STodd Fiala     if (error.Fail ())
2690af245d11STodd Fiala     {
2691af245d11STodd Fiala         if (log)
2692af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2693af245d11STodd Fiala         return error;
2694af245d11STodd Fiala     }
2695af245d11STodd Fiala     else
2696af245d11STodd Fiala     {
2697af245d11STodd Fiala         if (log)
2698af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2699af245d11STodd Fiala     }
2700af245d11STodd Fiala 
2701af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
2702c60c9452SJaydeep Patil     const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
2703af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
27043eb4b458SChaoren Lin     if (breakpoint_size > 0)
2705af245d11STodd Fiala     {
2706af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
27073eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
27083eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
2709af245d11STodd Fiala     }
2710af245d11STodd Fiala 
2711af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
2712af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
2713af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2714af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
2715af245d11STodd Fiala     {
2716af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
2717af245d11STodd Fiala         if (log)
2718af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2719af245d11STodd Fiala         return Error ();
2720af245d11STodd Fiala     }
2721af245d11STodd Fiala 
2722af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
2723af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
2724af245d11STodd Fiala     {
2725af245d11STodd Fiala         if (log)
2726af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2727af245d11STodd Fiala         return Error ();
2728af245d11STodd Fiala     }
2729af245d11STodd Fiala 
2730af245d11STodd Fiala     //
2731af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
2732af245d11STodd Fiala     //
2733af245d11STodd Fiala 
2734af245d11STodd Fiala     // Sanity check.
2735af245d11STodd Fiala     if (breakpoint_size == 0)
2736af245d11STodd Fiala     {
2737af245d11STodd Fiala         // Nothing to do!  How did we get here?
2738af245d11STodd Fiala         if (log)
2739af245d11STodd 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);
2740af245d11STodd Fiala         return Error ();
2741af245d11STodd Fiala     }
2742af245d11STodd Fiala 
2743af245d11STodd Fiala     // Change the program counter.
2744af245d11STodd Fiala     if (log)
2745b9cc0c75SPavel 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);
2746af245d11STodd Fiala 
2747af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
2748af245d11STodd Fiala     if (error.Fail ())
2749af245d11STodd Fiala     {
2750af245d11STodd Fiala         if (log)
2751b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
2752af245d11STodd Fiala         return error;
2753af245d11STodd Fiala     }
2754af245d11STodd Fiala 
2755af245d11STodd Fiala     return error;
2756af245d11STodd Fiala }
2757fa03ad2eSChaoren Lin 
27587cb18bf5STamas Berghammer Error
27597cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
27607cb18bf5STamas Berghammer {
27617cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
27627cb18bf5STamas Berghammer 
2763162fb8e8SPavel Labath     bool found = false;
27647cb18bf5STamas Berghammer     file_spec.Clear();
2765162fb8e8SPavel Labath     ProcFileReader::ProcessLineByLine(GetID(), "maps",
2766162fb8e8SPavel Labath         [&] (const std::string &line)
2767162fb8e8SPavel Labath         {
2768162fb8e8SPavel Labath             SmallVector<StringRef, 16> columns;
2769162fb8e8SPavel Labath             StringRef(line).split(columns, " ", -1, false);
2770162fb8e8SPavel Labath             if (columns.size() < 6)
2771162fb8e8SPavel Labath                 return true; // continue searching
2772162fb8e8SPavel Labath 
2773162fb8e8SPavel Labath             FileSpec this_file_spec(columns[5].str().c_str(), false);
2774162fb8e8SPavel Labath             if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2775162fb8e8SPavel Labath                 return true; // continue searching
2776162fb8e8SPavel Labath 
2777162fb8e8SPavel Labath             file_spec = this_file_spec;
2778162fb8e8SPavel Labath             found = true;
2779162fb8e8SPavel Labath             return false; // we are done
2780162fb8e8SPavel Labath         });
2781162fb8e8SPavel Labath 
2782162fb8e8SPavel Labath     if (! found)
27837cb18bf5STamas Berghammer         return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
27847cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
2785162fb8e8SPavel Labath 
2786162fb8e8SPavel Labath     return Error();
27877cb18bf5STamas Berghammer }
2788c076559aSPavel Labath 
27895eb721edSPavel Labath Error
2790783bfc8cSTamas Berghammer NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2791783bfc8cSTamas Berghammer {
2792783bfc8cSTamas Berghammer     load_addr = LLDB_INVALID_ADDRESS;
2793783bfc8cSTamas Berghammer     Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2794783bfc8cSTamas Berghammer         [&] (const std::string &line) -> bool
2795783bfc8cSTamas Berghammer         {
2796783bfc8cSTamas Berghammer             StringRef maps_row(line);
2797783bfc8cSTamas Berghammer 
2798783bfc8cSTamas Berghammer             SmallVector<StringRef, 16> maps_columns;
2799783bfc8cSTamas Berghammer             maps_row.split(maps_columns, StringRef(" "), -1, false);
2800783bfc8cSTamas Berghammer 
2801783bfc8cSTamas Berghammer             if (maps_columns.size() < 6)
2802783bfc8cSTamas Berghammer             {
2803783bfc8cSTamas Berghammer                 // Return true to continue reading the proc file
2804783bfc8cSTamas Berghammer                 return true;
2805783bfc8cSTamas Berghammer             }
2806783bfc8cSTamas Berghammer 
2807783bfc8cSTamas Berghammer             if (maps_columns[5] == file_name)
2808783bfc8cSTamas Berghammer             {
2809783bfc8cSTamas Berghammer                 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2810783bfc8cSTamas Berghammer                 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2811783bfc8cSTamas Berghammer 
2812783bfc8cSTamas Berghammer                 // Return false to stop reading the proc file further
2813783bfc8cSTamas Berghammer                 return false;
2814783bfc8cSTamas Berghammer             }
2815783bfc8cSTamas Berghammer 
2816783bfc8cSTamas Berghammer             // Return true to continue reading the proc file
2817783bfc8cSTamas Berghammer             return true;
2818783bfc8cSTamas Berghammer         });
2819783bfc8cSTamas Berghammer     return error;
2820783bfc8cSTamas Berghammer }
2821783bfc8cSTamas Berghammer 
2822f9077782SPavel Labath NativeThreadLinuxSP
2823f9077782SPavel Labath NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2824f9077782SPavel Labath {
2825f9077782SPavel Labath     return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2826f9077782SPavel Labath }
2827f9077782SPavel Labath 
2828783bfc8cSTamas Berghammer Error
2829b9cc0c75SPavel Labath NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
2830c076559aSPavel Labath {
28315eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
28325eb721edSPavel Labath 
28331dbc6c9cSPavel Labath     if (log)
28340e1d729bSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
2835b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
2836c076559aSPavel Labath 
2837c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
2838108c325dSPavel Labath     // stop notification that is currently waiting for
28390e1d729bSPavel Labath     // all threads to stop.  This is potentially a buggy situation since
2840c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
2841c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
2842c076559aSPavel Labath     // out the pending stop notification.
28430e1d729bSPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
2844c076559aSPavel Labath     {
2845b9cc0c75SPavel 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);
2846c076559aSPavel Labath     }
2847c076559aSPavel Labath 
2848c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
2849c076559aSPavel Labath     // to reflect it is running after this completes.
28500e1d729bSPavel Labath     switch (state)
2851c076559aSPavel Labath     {
28520e1d729bSPavel Labath     case eStateRunning:
28530e1d729bSPavel Labath     {
2854605b51b8SPavel Labath         const auto resume_result = thread.Resume(signo);
28550e1d729bSPavel Labath         if (resume_result.Success())
28560e1d729bSPavel Labath             SetState(eStateRunning, true);
28570e1d729bSPavel Labath         return resume_result;
2858c076559aSPavel Labath     }
28590e1d729bSPavel Labath     case eStateStepping:
28600e1d729bSPavel Labath     {
2861605b51b8SPavel Labath         const auto step_result = thread.SingleStep(signo);
28620e1d729bSPavel Labath         if (step_result.Success())
28630e1d729bSPavel Labath             SetState(eStateRunning, true);
28640e1d729bSPavel Labath         return step_result;
28650e1d729bSPavel Labath     }
28660e1d729bSPavel Labath     default:
28670e1d729bSPavel Labath         if (log)
28680e1d729bSPavel Labath             log->Printf("NativeProcessLinux::%s Unhandled state %s.",
28690e1d729bSPavel Labath                     __FUNCTION__, StateAsCString(state));
28700e1d729bSPavel Labath         llvm_unreachable("Unhandled state for resume");
28710e1d729bSPavel Labath     }
2872c076559aSPavel Labath }
2873c076559aSPavel Labath 
2874c076559aSPavel Labath //===----------------------------------------------------------------------===//
2875c076559aSPavel Labath 
2876c076559aSPavel Labath void
2877337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
2878c076559aSPavel Labath {
28795eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2880c076559aSPavel Labath 
28815eb721edSPavel Labath     if (log)
2882c076559aSPavel Labath     {
28835eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
2884c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
2885c076559aSPavel Labath     }
2886c076559aSPavel Labath 
28870e1d729bSPavel Labath     m_pending_notification_tid = triggering_tid;
28880e1d729bSPavel Labath 
28890e1d729bSPavel Labath     // Request a stop for all the thread stops that need to be stopped
28900e1d729bSPavel Labath     // and are not already known to be stopped.
28910e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
28920e1d729bSPavel Labath     {
28930e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
28940e1d729bSPavel Labath             static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
28950e1d729bSPavel Labath     }
28960e1d729bSPavel Labath 
28970e1d729bSPavel Labath     SignalIfAllThreadsStopped();
2898c076559aSPavel Labath 
28995eb721edSPavel Labath     if (log)
2900c076559aSPavel Labath     {
29015eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2902c076559aSPavel Labath     }
2903c076559aSPavel Labath }
2904c076559aSPavel Labath 
2905c076559aSPavel Labath void
29069eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
2907c076559aSPavel Labath {
29080e1d729bSPavel Labath     if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
29090e1d729bSPavel Labath         return; // No pending notification. Nothing to do.
29100e1d729bSPavel Labath 
29110e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
2912c076559aSPavel Labath     {
29130e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
29140e1d729bSPavel Labath             return; // Some threads are still running. Don't signal yet.
29150e1d729bSPavel Labath     }
29160e1d729bSPavel Labath 
29170e1d729bSPavel Labath     // We have a pending notification and all threads have stopped.
29189eb1ecb9SPavel Labath     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
29199eb1ecb9SPavel Labath 
29209eb1ecb9SPavel Labath     // Clear any temporary breakpoints we used to implement software single stepping.
29219eb1ecb9SPavel Labath     for (const auto &thread_info: m_threads_stepping_with_breakpoint)
29229eb1ecb9SPavel Labath     {
29239eb1ecb9SPavel Labath         Error error = RemoveBreakpoint (thread_info.second);
29249eb1ecb9SPavel Labath         if (error.Fail())
29259eb1ecb9SPavel Labath             if (log)
29269eb1ecb9SPavel Labath                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
29279eb1ecb9SPavel Labath                         __FUNCTION__, thread_info.first, error.AsCString());
29289eb1ecb9SPavel Labath     }
29299eb1ecb9SPavel Labath     m_threads_stepping_with_breakpoint.clear();
29309eb1ecb9SPavel Labath 
29319eb1ecb9SPavel Labath     // Notify the delegate about the stop
29320e1d729bSPavel Labath     SetCurrentThreadID(m_pending_notification_tid);
2933ed89c7feSPavel Labath     SetState(StateType::eStateStopped, true);
29340e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2935c076559aSPavel Labath }
2936c076559aSPavel Labath 
2937c076559aSPavel Labath void
2938f9077782SPavel Labath NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
2939c076559aSPavel Labath {
29401dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
29411dbc6c9cSPavel Labath 
29421dbc6c9cSPavel Labath     if (log)
2943f9077782SPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
29441dbc6c9cSPavel Labath 
2945f9077782SPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
2946c076559aSPavel Labath     {
2947c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
2948c076559aSPavel Labath         // notification.
2949f9077782SPavel Labath         thread.RequestStop();
2950c076559aSPavel Labath     }
2951c076559aSPavel Labath }
2952068f8a7eSTamas Berghammer 
295319cbe96aSPavel Labath void
295419cbe96aSPavel Labath NativeProcessLinux::SigchldHandler()
2955068f8a7eSTamas Berghammer {
295619cbe96aSPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
295719cbe96aSPavel Labath     // Process all pending waitpid notifications.
295819cbe96aSPavel Labath     while (true)
295919cbe96aSPavel Labath     {
296019cbe96aSPavel Labath         int status = -1;
296119cbe96aSPavel Labath         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
296219cbe96aSPavel Labath 
296319cbe96aSPavel Labath         if (wait_pid == 0)
296419cbe96aSPavel Labath             break; // We are done.
296519cbe96aSPavel Labath 
296619cbe96aSPavel Labath         if (wait_pid == -1)
296719cbe96aSPavel Labath         {
296819cbe96aSPavel Labath             if (errno == EINTR)
296919cbe96aSPavel Labath                 continue;
297019cbe96aSPavel Labath 
297119cbe96aSPavel Labath             Error error(errno, eErrorTypePOSIX);
297219cbe96aSPavel Labath             if (log)
297319cbe96aSPavel Labath                 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
297419cbe96aSPavel Labath                         __FUNCTION__, error.AsCString());
297519cbe96aSPavel Labath             break;
297619cbe96aSPavel Labath         }
297719cbe96aSPavel Labath 
297819cbe96aSPavel Labath         bool exited = false;
297919cbe96aSPavel Labath         int signal = 0;
298019cbe96aSPavel Labath         int exit_status = 0;
298119cbe96aSPavel Labath         const char *status_cstr = nullptr;
298219cbe96aSPavel Labath         if (WIFSTOPPED(status))
298319cbe96aSPavel Labath         {
298419cbe96aSPavel Labath             signal = WSTOPSIG(status);
298519cbe96aSPavel Labath             status_cstr = "STOPPED";
298619cbe96aSPavel Labath         }
298719cbe96aSPavel Labath         else if (WIFEXITED(status))
298819cbe96aSPavel Labath         {
298919cbe96aSPavel Labath             exit_status = WEXITSTATUS(status);
299019cbe96aSPavel Labath             status_cstr = "EXITED";
299119cbe96aSPavel Labath             exited = true;
299219cbe96aSPavel Labath         }
299319cbe96aSPavel Labath         else if (WIFSIGNALED(status))
299419cbe96aSPavel Labath         {
299519cbe96aSPavel Labath             signal = WTERMSIG(status);
299619cbe96aSPavel Labath             status_cstr = "SIGNALED";
299719cbe96aSPavel Labath             if (wait_pid == static_cast< ::pid_t>(GetID())) {
299819cbe96aSPavel Labath                 exited = true;
299919cbe96aSPavel Labath                 exit_status = -1;
300019cbe96aSPavel Labath             }
300119cbe96aSPavel Labath         }
300219cbe96aSPavel Labath         else
300319cbe96aSPavel Labath             status_cstr = "(\?\?\?)";
300419cbe96aSPavel Labath 
300519cbe96aSPavel Labath         if (log)
300619cbe96aSPavel Labath             log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
300719cbe96aSPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
300819cbe96aSPavel Labath                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
300919cbe96aSPavel Labath 
301019cbe96aSPavel Labath         MonitorCallback (wait_pid, exited, signal, exit_status);
301119cbe96aSPavel Labath     }
3012068f8a7eSTamas Berghammer }
3013068f8a7eSTamas Berghammer 
3014068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
3015068f8a7eSTamas Berghammer // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
30164a9babb2SPavel Labath Error
30174a9babb2SPavel Labath NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
3018068f8a7eSTamas Berghammer {
30194a9babb2SPavel Labath     Error error;
30204a9babb2SPavel Labath     long int ret;
3021068f8a7eSTamas Berghammer 
3022068f8a7eSTamas Berghammer     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3023068f8a7eSTamas Berghammer 
3024068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3025068f8a7eSTamas Berghammer 
3026068f8a7eSTamas Berghammer     errno = 0;
3027068f8a7eSTamas Berghammer     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
30284a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3029068f8a7eSTamas Berghammer     else
30304a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3031068f8a7eSTamas Berghammer 
30324a9babb2SPavel Labath     if (ret == -1)
3033068f8a7eSTamas Berghammer         error.SetErrorToErrno();
3034068f8a7eSTamas Berghammer 
30354a9babb2SPavel Labath     if (result)
30364a9babb2SPavel Labath         *result = ret;
30374a9babb2SPavel Labath 
3038068f8a7eSTamas Berghammer     if (log)
30394a9babb2SPavel Labath         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
3040068f8a7eSTamas Berghammer 
3041068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3042068f8a7eSTamas Berghammer 
3043068f8a7eSTamas Berghammer     if (log && error.GetError() != 0)
3044068f8a7eSTamas Berghammer     {
3045068f8a7eSTamas Berghammer         const char* str;
3046068f8a7eSTamas Berghammer         switch (error.GetError())
3047068f8a7eSTamas Berghammer         {
3048068f8a7eSTamas Berghammer         case ESRCH:  str = "ESRCH"; break;
3049068f8a7eSTamas Berghammer         case EINVAL: str = "EINVAL"; break;
3050068f8a7eSTamas Berghammer         case EBUSY:  str = "EBUSY"; break;
3051068f8a7eSTamas Berghammer         case EPERM:  str = "EPERM"; break;
3052068f8a7eSTamas Berghammer         default:     str = error.AsCString();
3053068f8a7eSTamas Berghammer         }
3054068f8a7eSTamas Berghammer         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3055068f8a7eSTamas Berghammer     }
3056068f8a7eSTamas Berghammer 
30574a9babb2SPavel Labath     return error;
3058068f8a7eSTamas Berghammer }
3059