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 
56475f47c3aSTodd Fiala     // ...unless exec fails.  In which case we definitely need to end the child here.
5650c4f01d4SPavel Labath     ExitChildAbnormally(eExecFailed);
566af245d11STodd Fiala }
567af245d11STodd Fiala 
5680c4f01d4SPavel Labath ::pid_t
5690c4f01d4SPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
5700c4f01d4SPavel Labath {
5710c4f01d4SPavel Labath     assert (args && "null args");
5720c4f01d4SPavel Labath 
5730c4f01d4SPavel Labath     lldb_utility::PseudoTerminal terminal;
5740c4f01d4SPavel Labath     const size_t err_len = 1024;
5750c4f01d4SPavel Labath     char err_str[err_len];
5760c4f01d4SPavel Labath     lldb::pid_t pid;
5770c4f01d4SPavel Labath 
5780c4f01d4SPavel Labath     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
5790c4f01d4SPavel Labath     {
5800c4f01d4SPavel Labath         error.SetErrorToGenericError();
5810c4f01d4SPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
5820c4f01d4SPavel Labath         return -1;
5830c4f01d4SPavel Labath     }
5840c4f01d4SPavel Labath 
5850c4f01d4SPavel Labath     // Child process.
5860c4f01d4SPavel Labath     if (pid == 0)
5870c4f01d4SPavel Labath     {
5880c4f01d4SPavel Labath         // First, make sure we disable all logging. If we are logging to stdout, our logs can be
5890c4f01d4SPavel Labath         // mistaken for inferior output.
5900c4f01d4SPavel Labath         Log::DisableAllLogChannels(nullptr);
5910c4f01d4SPavel Labath 
5920c4f01d4SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
5930c4f01d4SPavel Labath         // This closes original fd from which they were copied (and avoids
5940c4f01d4SPavel Labath         // leaking descriptors to the debugged process.
5950c4f01d4SPavel Labath         terminal.CloseSlaveFileDescriptor();
5960c4f01d4SPavel Labath 
5970c4f01d4SPavel Labath         ChildFunc(*args);
5980c4f01d4SPavel Labath     }
5990c4f01d4SPavel Labath 
60075f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
60175f47c3aSTodd Fiala 
602af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
603af245d11STodd Fiala     ::pid_t wpid;
604af245d11STodd Fiala     int status;
605af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
606af245d11STodd Fiala     {
607bd7cbc5aSPavel Labath         error.SetErrorToErrno();
608af245d11STodd Fiala         if (log)
609bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
610bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
611af245d11STodd Fiala 
612af245d11STodd Fiala         // Mark the inferior as invalid.
613af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
614bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
615af245d11STodd Fiala 
616bd7cbc5aSPavel Labath         return -1;
617af245d11STodd Fiala     }
618af245d11STodd Fiala     else if (WIFEXITED(status))
619af245d11STodd Fiala     {
6200c4f01d4SPavel Labath         auto p = DecodeChildExitCode(WEXITSTATUS(status));
6210c4f01d4SPavel Labath         Error child_error(p.second, eErrorTypePOSIX);
6220c4f01d4SPavel Labath         const char *failure_reason;
6230c4f01d4SPavel Labath         switch (p.first)
624af245d11STodd Fiala         {
625af245d11STodd Fiala             case ePtraceFailed:
6260c4f01d4SPavel Labath                 failure_reason = "Child ptrace failed";
627af245d11STodd Fiala                 break;
628af245d11STodd Fiala             case eDupStdinFailed:
6290c4f01d4SPavel Labath                 failure_reason = "Child open stdin failed";
630af245d11STodd Fiala                 break;
631af245d11STodd Fiala             case eDupStdoutFailed:
6320c4f01d4SPavel Labath                 failure_reason = "Child open stdout failed";
633af245d11STodd Fiala                 break;
634af245d11STodd Fiala             case eDupStderrFailed:
6350c4f01d4SPavel Labath                 failure_reason = "Child open stderr failed";
636af245d11STodd Fiala                 break;
637af245d11STodd Fiala             case eChdirFailed:
6380c4f01d4SPavel Labath                 failure_reason = "Child failed to set working directory";
639af245d11STodd Fiala                 break;
640af245d11STodd Fiala             case eExecFailed:
6410c4f01d4SPavel Labath                 failure_reason = "Child exec failed";
642af245d11STodd Fiala                 break;
643af245d11STodd Fiala             case eSetGidFailed:
6440c4f01d4SPavel Labath                 failure_reason = "Child setgid failed";
645af245d11STodd Fiala                 break;
64678856474SPavel Labath             case eSetSigMaskFailed:
6470c4f01d4SPavel Labath                 failure_reason = "Child failed to set signal mask";
648af245d11STodd Fiala                 break;
649af245d11STodd Fiala         }
6500c4f01d4SPavel Labath         error.SetErrorStringWithFormat("%s: %d - %s (error code truncated)", failure_reason, child_error.GetError(), child_error.AsCString());
651af245d11STodd Fiala 
652af245d11STodd Fiala         if (log)
653af245d11STodd Fiala         {
654af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
655af245d11STodd Fiala                     __FUNCTION__,
656af245d11STodd Fiala                     WEXITSTATUS(status));
657af245d11STodd Fiala         }
658af245d11STodd Fiala 
659af245d11STodd Fiala         // Mark the inferior as invalid.
660af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
661bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
662af245d11STodd Fiala 
663bd7cbc5aSPavel Labath         return -1;
664af245d11STodd Fiala     }
665af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
666af245d11STodd Fiala            "Could not sync with inferior process.");
667af245d11STodd Fiala 
668af245d11STodd Fiala     if (log)
669af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
670af245d11STodd Fiala 
671bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
672bd7cbc5aSPavel Labath     if (error.Fail())
673af245d11STodd Fiala     {
674af245d11STodd Fiala         if (log)
675af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
676bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
677af245d11STodd Fiala 
678af245d11STodd Fiala         // Mark the inferior as invalid.
679af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
680bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
681af245d11STodd Fiala 
682bd7cbc5aSPavel Labath         return -1;
683af245d11STodd Fiala     }
684af245d11STodd Fiala 
685af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
686af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
687bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
688bd7cbc5aSPavel Labath     m_pid = pid;
689af245d11STodd Fiala 
690af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
691af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
692af245d11STodd Fiala     // descriptor to read from).
693bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
694bd7cbc5aSPavel Labath     if (error.Fail())
695af245d11STodd Fiala     {
696af245d11STodd Fiala         if (log)
697af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
698bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
699af245d11STodd Fiala 
700af245d11STodd Fiala         // Mark the inferior as invalid.
701af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
702bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
703af245d11STodd Fiala 
704bd7cbc5aSPavel Labath         return -1;
705af245d11STodd Fiala     }
706af245d11STodd Fiala 
707af245d11STodd Fiala     if (log)
708af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
709af245d11STodd Fiala 
7102a86b555SPavel Labath     ResolveProcessArchitecture(m_pid, m_arch);
711f9077782SPavel Labath     NativeThreadLinuxSP thread_sp = AddThread(pid);
712af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
713f9077782SPavel Labath     thread_sp->SetStoppedBySignal(SIGSTOP);
714f9077782SPavel Labath     ThreadWasCreated(*thread_sp);
715af245d11STodd Fiala 
716af245d11STodd Fiala     // Let our process instance know the thread has stopped.
717bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
718bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
719af245d11STodd Fiala 
720af245d11STodd Fiala     if (log)
721af245d11STodd Fiala     {
722bd7cbc5aSPavel Labath         if (error.Success ())
723af245d11STodd Fiala         {
724af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
725af245d11STodd Fiala         }
726af245d11STodd Fiala         else
727af245d11STodd Fiala         {
728af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
729bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
730bd7cbc5aSPavel Labath             return -1;
731af245d11STodd Fiala         }
732af245d11STodd Fiala     }
733bd7cbc5aSPavel Labath     return pid;
734af245d11STodd Fiala }
735af245d11STodd Fiala 
736bd7cbc5aSPavel Labath ::pid_t
737bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
738af245d11STodd Fiala {
739af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
740af245d11STodd Fiala 
741af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
742af245d11STodd Fiala     Host::TidMap tids_to_attach;
743af245d11STodd Fiala     if (pid <= 1)
744af245d11STodd Fiala     {
745bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
746bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
747bd7cbc5aSPavel Labath         return -1;
748af245d11STodd Fiala     }
749af245d11STodd Fiala 
750af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
751af245d11STodd Fiala     {
752af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
753af245d11STodd Fiala              it != tids_to_attach.end();)
754af245d11STodd Fiala         {
755af245d11STodd Fiala             if (it->second == false)
756af245d11STodd Fiala             {
757af245d11STodd Fiala                 lldb::tid_t tid = it->first;
758af245d11STodd Fiala 
759af245d11STodd Fiala                 // Attach to the requested process.
760af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
7614a9babb2SPavel Labath                 error = PtraceWrapper(PTRACE_ATTACH, tid);
762bd7cbc5aSPavel Labath                 if (error.Fail())
763af245d11STodd Fiala                 {
764af245d11STodd Fiala                     // No such thread. The thread may have exited.
765af245d11STodd Fiala                     // More error handling may be needed.
766bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
767af245d11STodd Fiala                     {
768af245d11STodd Fiala                         it = tids_to_attach.erase(it);
769af245d11STodd Fiala                         continue;
770af245d11STodd Fiala                     }
771af245d11STodd Fiala                     else
772bd7cbc5aSPavel Labath                         return -1;
773af245d11STodd Fiala                 }
774af245d11STodd Fiala 
775af245d11STodd Fiala                 int status;
776af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
777af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
778af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
779af245d11STodd Fiala                 {
780af245d11STodd Fiala                     // No such thread. The thread may have exited.
781af245d11STodd Fiala                     // More error handling may be needed.
782af245d11STodd Fiala                     if (errno == ESRCH)
783af245d11STodd Fiala                     {
784af245d11STodd Fiala                         it = tids_to_attach.erase(it);
785af245d11STodd Fiala                         continue;
786af245d11STodd Fiala                     }
787af245d11STodd Fiala                     else
788af245d11STodd Fiala                     {
789bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
790bd7cbc5aSPavel Labath                         return -1;
791af245d11STodd Fiala                     }
792af245d11STodd Fiala                 }
793af245d11STodd Fiala 
794bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
795bd7cbc5aSPavel Labath                 if (error.Fail())
796bd7cbc5aSPavel Labath                     return -1;
797af245d11STodd Fiala 
798af245d11STodd Fiala                 if (log)
799af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
800af245d11STodd Fiala 
801af245d11STodd Fiala                 it->second = true;
802af245d11STodd Fiala 
803af245d11STodd Fiala                 // Create the thread, mark it as stopped.
804f9077782SPavel Labath                 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
805af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
806fa03ad2eSChaoren Lin 
807fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
808f9077782SPavel Labath                 thread_sp->SetStoppedBySignal(SIGSTOP);
809f9077782SPavel Labath                 ThreadWasCreated(*thread_sp);
810bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
811af245d11STodd Fiala             }
812af245d11STodd Fiala 
813af245d11STodd Fiala             // move the loop forward
814af245d11STodd Fiala             ++it;
815af245d11STodd Fiala         }
816af245d11STodd Fiala     }
817af245d11STodd Fiala 
818af245d11STodd Fiala     if (tids_to_attach.size() > 0)
819af245d11STodd Fiala     {
820bd7cbc5aSPavel Labath         m_pid = pid;
821af245d11STodd Fiala         // Let our process instance know the thread has stopped.
822bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
823af245d11STodd Fiala     }
824af245d11STodd Fiala     else
825af245d11STodd Fiala     {
826bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
827bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
828bd7cbc5aSPavel Labath         return -1;
829af245d11STodd Fiala     }
830af245d11STodd Fiala 
831bd7cbc5aSPavel Labath     return pid;
832af245d11STodd Fiala }
833af245d11STodd Fiala 
83497ccc294SChaoren Lin Error
835af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
836af245d11STodd Fiala {
837af245d11STodd Fiala     long ptrace_opts = 0;
838af245d11STodd Fiala 
839af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
840af245d11STodd Fiala     // limbo until it is destroyed.
841af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
842af245d11STodd Fiala 
843af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
844af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
845af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
846af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
847af245d11STodd Fiala 
848af245d11STodd Fiala     // Have the tracer notify us before execve returns
849af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
850af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
851af245d11STodd Fiala 
8524a9babb2SPavel Labath     return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
853af245d11STodd Fiala }
854af245d11STodd Fiala 
855af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
856af245d11STodd Fiala {
857af245d11STodd Fiala     if (WIFEXITED (status))
858af245d11STodd Fiala         return ExitType::eExitTypeExit;
859af245d11STodd Fiala     else if (WIFSIGNALED (status))
860af245d11STodd Fiala         return ExitType::eExitTypeSignal;
861af245d11STodd Fiala     else if (WIFSTOPPED (status))
862af245d11STodd Fiala         return ExitType::eExitTypeStop;
863af245d11STodd Fiala     else
864af245d11STodd Fiala     {
865af245d11STodd Fiala         // We don't know what this is.
866af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
867af245d11STodd Fiala     }
868af245d11STodd Fiala }
869af245d11STodd Fiala 
870af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
871af245d11STodd Fiala {
872af245d11STodd Fiala     if (WIFEXITED (status))
873af245d11STodd Fiala         return WEXITSTATUS (status);
874af245d11STodd Fiala     else if (WIFSIGNALED (status))
875af245d11STodd Fiala         return WTERMSIG (status);
876af245d11STodd Fiala     else if (WIFSTOPPED (status))
877af245d11STodd Fiala         return WSTOPSIG (status);
878af245d11STodd Fiala     else
879af245d11STodd Fiala     {
880af245d11STodd Fiala         // We don't know what this is.
881af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
882af245d11STodd Fiala     }
883af245d11STodd Fiala }
884af245d11STodd Fiala 
8851107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
8861107b5a5SPavel Labath void
8871107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
888af245d11STodd Fiala                                     bool exited,
889af245d11STodd Fiala                                     int signal,
890af245d11STodd Fiala                                     int status)
891af245d11STodd Fiala {
892af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
893af245d11STodd Fiala 
894af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
8951107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
896af245d11STodd Fiala 
897af245d11STodd Fiala     // Handle when the thread exits.
898af245d11STodd Fiala     if (exited)
899af245d11STodd Fiala     {
900af245d11STodd Fiala         if (log)
90186fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
902af245d11STodd Fiala 
903af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
9041107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
905af245d11STodd Fiala 
906af245d11STodd Fiala         if (is_main_thread)
907af245d11STodd Fiala         {
908af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
909af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
910af245d11STodd Fiala             // for the main thread.
9111107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
912af245d11STodd Fiala             if (!already_notified)
913af245d11STodd Fiala             {
914af245d11STodd Fiala                 if (log)
9151107b5a5SPavel 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 ()));
916af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
9171107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
918af245d11STodd Fiala 
919af245d11STodd Fiala                 // Notify delegate that our process has exited.
9201107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
921af245d11STodd Fiala             }
922af245d11STodd Fiala             else
923af245d11STodd Fiala             {
924af245d11STodd Fiala                 if (log)
925af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
926af245d11STodd Fiala             }
927af245d11STodd Fiala         }
928af245d11STodd Fiala         else
929af245d11STodd Fiala         {
930af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
931af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
932af245d11STodd Fiala             // and we would have done an all-stop then.
933af245d11STodd Fiala             if (log)
934af245d11STodd 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");
935af245d11STodd Fiala         }
9361107b5a5SPavel Labath         return;
937af245d11STodd Fiala     }
938af245d11STodd Fiala 
939af245d11STodd Fiala     siginfo_t info;
940b9cc0c75SPavel Labath     const auto info_err = GetSignalInfo(pid, &info);
941b9cc0c75SPavel Labath     auto thread_sp = GetThreadByID(pid);
942b9cc0c75SPavel Labath 
943b9cc0c75SPavel Labath     if (! thread_sp)
944b9cc0c75SPavel Labath     {
945b9cc0c75SPavel Labath         // Normally, the only situation when we cannot find the thread is if we have just
946b9cc0c75SPavel Labath         // received a new thread notification. This is indicated by GetSignalInfo() returning
947b9cc0c75SPavel Labath         // si_code == SI_USER and si_pid == 0
948b9cc0c75SPavel Labath         if (log)
949b9cc0c75SPavel Labath             log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
950b9cc0c75SPavel Labath 
951b9cc0c75SPavel Labath         if (info_err.Fail())
952b9cc0c75SPavel Labath         {
953b9cc0c75SPavel Labath             if (log)
954b9cc0c75SPavel Labath                 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
955b9cc0c75SPavel Labath             return;
956b9cc0c75SPavel Labath         }
957b9cc0c75SPavel Labath 
958b9cc0c75SPavel Labath         if (log && (info.si_code != SI_USER || info.si_pid != 0))
959b9cc0c75SPavel 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);
960b9cc0c75SPavel Labath 
961b9cc0c75SPavel Labath         auto thread_sp = AddThread(pid);
962b9cc0c75SPavel Labath         // Resume the newly created thread.
963b9cc0c75SPavel Labath         ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
964b9cc0c75SPavel Labath         ThreadWasCreated(*thread_sp);
965b9cc0c75SPavel Labath         return;
966b9cc0c75SPavel Labath     }
967b9cc0c75SPavel Labath 
968b9cc0c75SPavel Labath     // Get details on the signal raised.
969b9cc0c75SPavel Labath     if (info_err.Success())
970fa03ad2eSChaoren Lin     {
971fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
972fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
973b9cc0c75SPavel Labath             MonitorSIGTRAP(info, *thread_sp);
974fa03ad2eSChaoren Lin         else
975b9cc0c75SPavel Labath             MonitorSignal(info, *thread_sp, exited);
976fa03ad2eSChaoren Lin     }
977fa03ad2eSChaoren Lin     else
978af245d11STodd Fiala     {
979b9cc0c75SPavel Labath         if (info_err.GetError() == EINVAL)
980af245d11STodd Fiala         {
981fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
98239036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
98339036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
98439036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
98539036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
98639036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
98739036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
98839036ac3SPavel Labath             // correctly for all signals.
989fa03ad2eSChaoren Lin             if (log)
99039036ac3SPavel 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);
991b9cc0c75SPavel Labath             ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
992a9882ceeSTodd Fiala         }
993a9882ceeSTodd Fiala         else
994a9882ceeSTodd Fiala         {
995af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
996af245d11STodd Fiala 
997af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
998af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
999af245d11STodd Fiala             // with it anymore.
1000af245d11STodd Fiala 
1001af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
10021107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
1003af245d11STodd Fiala 
1004af245d11STodd Fiala             if (log)
1005af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
1006b9cc0c75SPavel 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");
1007af245d11STodd Fiala 
1008af245d11STodd Fiala             if (is_main_thread)
1009af245d11STodd Fiala             {
1010af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
1011af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
10121107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
10131107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1014af245d11STodd Fiala             }
1015af245d11STodd Fiala             else
1016af245d11STodd Fiala             {
1017af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
1018af245d11STodd Fiala                 if (log)
10191107b5a5SPavel 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);
1020af245d11STodd Fiala             }
1021af245d11STodd Fiala         }
1022af245d11STodd Fiala     }
1023af245d11STodd Fiala }
1024af245d11STodd Fiala 
1025af245d11STodd Fiala void
1026426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
1027426bdf88SPavel Labath {
1028426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1029426bdf88SPavel Labath 
1030f9077782SPavel Labath     NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
1031426bdf88SPavel Labath 
1032426bdf88SPavel Labath     if (new_thread_sp)
1033426bdf88SPavel Labath     {
1034426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
1035426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
1036426bdf88SPavel Labath         return;
1037426bdf88SPavel Labath     }
1038426bdf88SPavel Labath 
1039426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
1040426bdf88SPavel Labath     int status = -1;
1041426bdf88SPavel Labath     ::pid_t wait_pid;
1042426bdf88SPavel Labath     do
1043426bdf88SPavel Labath     {
1044426bdf88SPavel Labath         if (log)
1045426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1046426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
1047426bdf88SPavel Labath     }
1048426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
1049426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
1050426bdf88SPavel Labath     // some checks just in case.
1051426bdf88SPavel Labath     if (wait_pid != tid) {
1052426bdf88SPavel Labath         if (log)
1053426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1054426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
1055426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1056426bdf88SPavel Labath         return;
1057426bdf88SPavel Labath     }
1058426bdf88SPavel Labath     if (WIFEXITED(status))
1059426bdf88SPavel Labath     {
1060426bdf88SPavel Labath         if (log)
1061426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1062426bdf88SPavel Labath         // Also a very improbable event.
1063426bdf88SPavel Labath         return;
1064426bdf88SPavel Labath     }
1065426bdf88SPavel Labath 
1066426bdf88SPavel Labath     siginfo_t info;
1067426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
1068426bdf88SPavel Labath     if (error.Fail())
1069426bdf88SPavel Labath     {
1070426bdf88SPavel Labath         if (log)
1071426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1072426bdf88SPavel Labath         return;
1073426bdf88SPavel Labath     }
1074426bdf88SPavel Labath 
1075426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1076426bdf88SPavel Labath     {
1077426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
1078426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
1079426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
1080426bdf88SPavel Labath         // created properly.
1081426bdf88SPavel 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);
1082426bdf88SPavel Labath     }
1083426bdf88SPavel Labath 
1084426bdf88SPavel Labath     if (log)
1085426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1086426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
1087426bdf88SPavel Labath 
1088f9077782SPavel Labath     new_thread_sp = AddThread(tid);
1089b9cc0c75SPavel Labath     ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1090f9077782SPavel Labath     ThreadWasCreated(*new_thread_sp);
1091426bdf88SPavel Labath }
1092426bdf88SPavel Labath 
1093426bdf88SPavel Labath void
1094b9cc0c75SPavel Labath NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
1095af245d11STodd Fiala {
1096af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1097b9cc0c75SPavel Labath     const bool is_main_thread = (thread.GetID() == GetID ());
1098af245d11STodd Fiala 
1099b9cc0c75SPavel Labath     assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
1100af245d11STodd Fiala 
1101b9cc0c75SPavel Labath     switch (info.si_code)
1102af245d11STodd Fiala     {
1103af245d11STodd 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.
1104af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1105af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1106af245d11STodd Fiala 
1107af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1108af245d11STodd Fiala     {
11095fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
1110426bdf88SPavel Labath         // creation.
1111426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
1112426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
1113426bdf88SPavel Labath         // here.
1114af245d11STodd Fiala 
1115af245d11STodd Fiala         unsigned long event_message = 0;
1116b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &event_message).Fail())
1117fa03ad2eSChaoren Lin         {
1118426bdf88SPavel Labath             if (log)
1119b9cc0c75SPavel 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());
1120426bdf88SPavel Labath         } else
1121426bdf88SPavel Labath             WaitForNewThread(event_message);
1122af245d11STodd Fiala 
1123b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1124af245d11STodd Fiala         break;
1125af245d11STodd Fiala     }
1126af245d11STodd Fiala 
1127af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1128a9882ceeSTodd Fiala     {
1129f9077782SPavel Labath         NativeThreadLinuxSP main_thread_sp;
1130af245d11STodd Fiala         if (log)
1131b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
1132a9882ceeSTodd Fiala 
11331dbc6c9cSPavel Labath         // Exec clears any pending notifications.
11340e1d729bSPavel Labath         m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1135fa03ad2eSChaoren Lin 
113657a77118SPavel Labath         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.
1137a9882ceeSTodd Fiala         if (log)
1138a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1139a9882ceeSTodd Fiala 
1140a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
1141a9882ceeSTodd Fiala         {
1142a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1143a9882ceeSTodd Fiala             if (is_main_thread)
1144a9882ceeSTodd Fiala             {
1145f9077782SPavel Labath                 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
1146a9882ceeSTodd Fiala                 if (log)
1147a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1148a9882ceeSTodd Fiala             }
1149a9882ceeSTodd Fiala             else
1150a9882ceeSTodd Fiala             {
1151a9882ceeSTodd Fiala                 if (log)
1152a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1153a9882ceeSTodd Fiala             }
1154a9882ceeSTodd Fiala         }
1155a9882ceeSTodd Fiala 
1156a9882ceeSTodd Fiala         m_threads.clear ();
1157a9882ceeSTodd Fiala 
1158a9882ceeSTodd Fiala         if (main_thread_sp)
1159a9882ceeSTodd Fiala         {
1160a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
1161a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
1162f9077782SPavel Labath             main_thread_sp->SetStoppedByExec();
1163a9882ceeSTodd Fiala         }
1164a9882ceeSTodd Fiala         else
1165a9882ceeSTodd Fiala         {
1166a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1167a9882ceeSTodd Fiala             if (log)
1168a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1169a9882ceeSTodd Fiala         }
1170a9882ceeSTodd Fiala 
1171fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
1172f9077782SPavel Labath         ThreadWasCreated(*main_thread_sp);
1173fa03ad2eSChaoren Lin 
1174a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
1175a9882ceeSTodd Fiala         NotifyDidExec ();
1176a9882ceeSTodd Fiala 
1177a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
1178a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1179fa03ad2eSChaoren Lin 
1180fa03ad2eSChaoren Lin         // Let the process know we're stopped.
1181b9cc0c75SPavel Labath         StopRunningThreads(main_thread_sp->GetID());
1182a9882ceeSTodd Fiala 
1183af245d11STodd Fiala         break;
1184a9882ceeSTodd Fiala     }
1185af245d11STodd Fiala 
1186af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1187af245d11STodd Fiala     {
1188af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
11896e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
11906e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
11916e35163cSPavel Labath         // here.
1192fa03ad2eSChaoren Lin 
1193af245d11STodd Fiala         unsigned long data = 0;
1194b9cc0c75SPavel Labath         if (GetEventMessage(thread.GetID(), &data).Fail())
1195af245d11STodd Fiala             data = -1;
1196af245d11STodd Fiala 
1197af245d11STodd Fiala         if (log)
1198af245d11STodd Fiala         {
1199af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1200af245d11STodd Fiala                          __FUNCTION__,
1201af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1202b9cc0c75SPavel Labath                          thread.GetID(),
1203af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
1204af245d11STodd Fiala         }
1205af245d11STodd Fiala 
1206af245d11STodd Fiala         if (is_main_thread)
1207af245d11STodd Fiala         {
1208af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
120975f47c3aSTodd Fiala         }
121075f47c3aSTodd Fiala 
121186852d36SPavel Labath         StateType state = thread.GetState();
121286852d36SPavel Labath         if (! StateIsRunningState(state))
121386852d36SPavel Labath         {
121486852d36SPavel Labath             // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
121586852d36SPavel Labath             // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
121686852d36SPavel Labath             // we should not be receiving any ptrace events while the inferior is stopped. This
121786852d36SPavel Labath             // makes sure that the inferior is resumed and exits normally.
121886852d36SPavel Labath             state = eStateRunning;
121986852d36SPavel Labath         }
122086852d36SPavel Labath         ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
1221af245d11STodd Fiala 
1222af245d11STodd Fiala         break;
1223af245d11STodd Fiala     }
1224af245d11STodd Fiala 
1225af245d11STodd Fiala     case 0:
1226c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
1227c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
122886fd8e45SChaoren Lin     {
1229c16f5dcaSChaoren Lin         // If a watchpoint was hit, report it
1230c16f5dcaSChaoren Lin         uint32_t wp_index;
12311fa5c4b9STamas Berghammer         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
1232c16f5dcaSChaoren Lin         if (error.Fail() && log)
1233c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() "
1234c16f5dcaSChaoren Lin                         "received error while checking for watchpoint hits, "
1235c16f5dcaSChaoren Lin                         "pid = %" PRIu64 " error = %s",
1236b9cc0c75SPavel Labath                         __FUNCTION__, thread.GetID(), error.AsCString());
1237c16f5dcaSChaoren Lin         if (wp_index != LLDB_INVALID_INDEX32)
12385830aa75STamas Berghammer         {
1239b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
1240c16f5dcaSChaoren Lin             break;
1241c16f5dcaSChaoren Lin         }
1242b9cc0c75SPavel Labath 
1243be379e15STamas Berghammer         // Otherwise, report step over
1244be379e15STamas Berghammer         MonitorTrace(thread);
1245af245d11STodd Fiala         break;
1246b9cc0c75SPavel Labath     }
1247af245d11STodd Fiala 
1248af245d11STodd Fiala     case SI_KERNEL:
124935799963SMohit K. Bhakkad #if defined __mips__
125035799963SMohit K. Bhakkad         // For mips there is no special signal for watchpoint
125135799963SMohit K. Bhakkad         // So we check for watchpoint in kernel trap
125235799963SMohit K. Bhakkad     {
125335799963SMohit K. Bhakkad         // If a watchpoint was hit, report it
125435799963SMohit K. Bhakkad         uint32_t wp_index;
1255b9cc0c75SPavel Labath         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
125635799963SMohit K. Bhakkad         if (error.Fail() && log)
125735799963SMohit K. Bhakkad             log->Printf("NativeProcessLinux::%s() "
125835799963SMohit K. Bhakkad                         "received error while checking for watchpoint hits, "
125935799963SMohit K. Bhakkad                         "pid = %" PRIu64 " error = %s",
126016ad0321SMohit K. Bhakkad                         __FUNCTION__, thread.GetID(), error.AsCString());
126135799963SMohit K. Bhakkad         if (wp_index != LLDB_INVALID_INDEX32)
126235799963SMohit K. Bhakkad         {
1263b9cc0c75SPavel Labath             MonitorWatchpoint(thread, wp_index);
126435799963SMohit K. Bhakkad             break;
126535799963SMohit K. Bhakkad         }
126635799963SMohit K. Bhakkad     }
126735799963SMohit K. Bhakkad         // NO BREAK
126835799963SMohit K. Bhakkad #endif
1269af245d11STodd Fiala     case TRAP_BRKPT:
1270b9cc0c75SPavel Labath         MonitorBreakpoint(thread);
1271af245d11STodd Fiala         break;
1272af245d11STodd Fiala 
1273af245d11STodd Fiala     case SIGTRAP:
1274af245d11STodd Fiala     case (SIGTRAP | 0x80):
1275af245d11STodd Fiala         if (log)
1276b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
1277fa03ad2eSChaoren Lin 
1278af245d11STodd Fiala         // Ignore these signals until we know more about them.
1279b9cc0c75SPavel Labath         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1280af245d11STodd Fiala         break;
1281af245d11STodd Fiala 
1282af245d11STodd Fiala     default:
1283af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
1284af245d11STodd Fiala         if (log)
12856e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1286b9cc0c75SPavel Labath                     __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1287af245d11STodd Fiala         break;
1288af245d11STodd Fiala 
1289af245d11STodd Fiala     }
1290af245d11STodd Fiala }
1291af245d11STodd Fiala 
1292af245d11STodd Fiala void
1293b9cc0c75SPavel Labath NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
1294c16f5dcaSChaoren Lin {
1295c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1296c16f5dcaSChaoren Lin     if (log)
1297c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1298b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1299c16f5dcaSChaoren Lin 
13000e1d729bSPavel Labath     // This thread is currently stopped.
1301b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
1302c16f5dcaSChaoren Lin 
1303b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1304c16f5dcaSChaoren Lin }
1305c16f5dcaSChaoren Lin 
1306c16f5dcaSChaoren Lin void
1307b9cc0c75SPavel Labath NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
1308c16f5dcaSChaoren Lin {
1309c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1310c16f5dcaSChaoren Lin     if (log)
1311c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1312b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1313c16f5dcaSChaoren Lin 
1314c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
1315b9cc0c75SPavel Labath     thread.SetStoppedByBreakpoint();
1316b9cc0c75SPavel Labath     Error error = FixupBreakpointPCAsNeeded(thread);
1317c16f5dcaSChaoren Lin     if (error.Fail())
1318c16f5dcaSChaoren Lin         if (log)
1319c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1320b9cc0c75SPavel Labath                     __FUNCTION__, thread.GetID(), error.AsCString());
1321d8c338d4STamas Berghammer 
1322b9cc0c75SPavel Labath     if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1323b9cc0c75SPavel Labath         thread.SetStoppedByTrace();
1324c16f5dcaSChaoren Lin 
1325b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1326c16f5dcaSChaoren Lin }
1327c16f5dcaSChaoren Lin 
1328c16f5dcaSChaoren Lin void
1329f9077782SPavel Labath NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
1330c16f5dcaSChaoren Lin {
1331c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1332c16f5dcaSChaoren Lin     if (log)
1333c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1334c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
1335f9077782SPavel Labath                     __FUNCTION__, thread.GetID(), wp_index);
1336c16f5dcaSChaoren Lin 
1337c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
1338c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
1339f9077782SPavel Labath     thread.SetStoppedByWatchpoint(wp_index);
1340c16f5dcaSChaoren Lin 
1341c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
1342f9077782SPavel Labath     StopRunningThreads(thread.GetID());
1343c16f5dcaSChaoren Lin }
1344c16f5dcaSChaoren Lin 
1345c16f5dcaSChaoren Lin void
1346b9cc0c75SPavel Labath NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
1347af245d11STodd Fiala {
1348b9cc0c75SPavel Labath     const int signo = info.si_signo;
1349b9cc0c75SPavel Labath     const bool is_from_llgs = info.si_pid == getpid ();
1350af245d11STodd Fiala 
1351af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1352af245d11STodd Fiala 
1353af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1354af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1355af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1356af245d11STodd Fiala     //
1357af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
1358af245d11STodd Fiala     // "crash".
1359af245d11STodd Fiala     //
1360af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
1361af245d11STodd Fiala 
1362af245d11STodd Fiala     // Handle the signal.
1363b9cc0c75SPavel Labath     if (info.si_code == SI_TKILL || info.si_code == SI_USER)
1364af245d11STodd Fiala     {
1365af245d11STodd Fiala         if (log)
1366af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1367af245d11STodd Fiala                             __FUNCTION__,
136898d0a4b3SChaoren Lin                             Host::GetSignalAsCString(signo),
1369af245d11STodd Fiala                             signo,
1370b9cc0c75SPavel Labath                             (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1371b9cc0c75SPavel Labath                             info.si_pid,
1372511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
1373b9cc0c75SPavel Labath                             thread.GetID());
1374af245d11STodd Fiala     }
137558a2f669STodd Fiala 
137658a2f669STodd Fiala     // Check for thread stop notification.
1377b9cc0c75SPavel Labath     if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
1378af245d11STodd Fiala     {
1379af245d11STodd Fiala         // This is a tgkill()-based stop.
1380fa03ad2eSChaoren Lin         if (log)
1381fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1382fa03ad2eSChaoren Lin                          __FUNCTION__,
1383fa03ad2eSChaoren Lin                          GetID (),
1384b9cc0c75SPavel Labath                          thread.GetID());
1385fa03ad2eSChaoren Lin 
1386aab58633SChaoren Lin         // Check that we're not already marked with a stop reason.
1387aab58633SChaoren Lin         // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1388aab58633SChaoren Lin         // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1389aab58633SChaoren Lin         // and that, without an intervening resume, we received another stop.  It is more likely
1390aab58633SChaoren Lin         // that we are missing the marking of a run state somewhere if we find that the thread was
1391aab58633SChaoren Lin         // marked as stopped.
1392b9cc0c75SPavel Labath         const StateType thread_state = thread.GetState();
1393aab58633SChaoren Lin         if (!StateIsStoppedState (thread_state, false))
1394aab58633SChaoren Lin         {
1395ed89c7feSPavel Labath             // An inferior thread has stopped because of a SIGSTOP we have sent it.
1396ed89c7feSPavel Labath             // Generally, these are not important stops and we don't want to report them as
1397ed89c7feSPavel Labath             // they are just used to stop other threads when one thread (the one with the
1398ed89c7feSPavel Labath             // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1399ed89c7feSPavel Labath             // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1400ed89c7feSPavel Labath             // leave the signal intact if this is the thread that was chosen as the
1401ed89c7feSPavel Labath             // triggering thread.
14020e1d729bSPavel Labath             if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
14030e1d729bSPavel Labath             {
1404b9cc0c75SPavel Labath                 if (m_pending_notification_tid == thread.GetID())
1405b9cc0c75SPavel Labath                     thread.SetStoppedBySignal(SIGSTOP, &info);
1406ed89c7feSPavel Labath                 else
1407b9cc0c75SPavel Labath                     thread.SetStoppedWithNoReason();
1408ed89c7feSPavel Labath 
1409b9cc0c75SPavel Labath                 SetCurrentThreadID (thread.GetID ());
14100e1d729bSPavel Labath                 SignalIfAllThreadsStopped();
14110e1d729bSPavel Labath             }
14120e1d729bSPavel Labath             else
14130e1d729bSPavel Labath             {
14140e1d729bSPavel Labath                 // We can end up here if stop was initiated by LLGS but by this time a
14150e1d729bSPavel Labath                 // thread stop has occurred - maybe initiated by another event.
1416b9cc0c75SPavel Labath                 Error error = ResumeThread(thread, thread.GetState(), 0);
14170e1d729bSPavel Labath                 if (error.Fail() && log)
14180e1d729bSPavel Labath                 {
14190e1d729bSPavel Labath                     log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
1420b9cc0c75SPavel Labath                             __FUNCTION__, thread.GetID(), error.AsCString());
14210e1d729bSPavel Labath                 }
14220e1d729bSPavel Labath             }
1423aab58633SChaoren Lin         }
1424aab58633SChaoren Lin         else
1425aab58633SChaoren Lin         {
1426aab58633SChaoren Lin             if (log)
1427aab58633SChaoren Lin             {
1428aab58633SChaoren Lin                 // Retrieve the signal name if the thread was stopped by a signal.
1429aab58633SChaoren Lin                 int stop_signo = 0;
1430b9cc0c75SPavel Labath                 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
143198d0a4b3SChaoren Lin                 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1432aab58633SChaoren Lin                 if (!signal_name)
1433aab58633SChaoren Lin                     signal_name = "<no-signal-name>";
1434aab58633SChaoren Lin 
1435aab58633SChaoren 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",
1436aab58633SChaoren Lin                              __FUNCTION__,
1437aab58633SChaoren Lin                              GetID (),
1438b9cc0c75SPavel Labath                              thread.GetID(),
1439aab58633SChaoren Lin                              StateAsCString (thread_state),
1440aab58633SChaoren Lin                              stop_signo,
1441aab58633SChaoren Lin                              signal_name);
1442aab58633SChaoren Lin             }
14430e1d729bSPavel Labath             SignalIfAllThreadsStopped();
1444af245d11STodd Fiala         }
1445af245d11STodd Fiala 
144658a2f669STodd Fiala         // Done handling.
1447af245d11STodd Fiala         return;
1448af245d11STodd Fiala     }
1449af245d11STodd Fiala 
1450af245d11STodd Fiala     if (log)
145198d0a4b3SChaoren Lin         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
1452af245d11STodd Fiala 
145386fd8e45SChaoren Lin     // This thread is stopped.
1454b9cc0c75SPavel Labath     thread.SetStoppedBySignal(signo, &info);
145586fd8e45SChaoren Lin 
145686fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
1457b9cc0c75SPavel Labath     StopRunningThreads(thread.GetID());
1458511e5cdcSTodd Fiala }
1459af245d11STodd Fiala 
1460e7708688STamas Berghammer namespace {
1461e7708688STamas Berghammer 
1462e7708688STamas Berghammer struct EmulatorBaton
1463e7708688STamas Berghammer {
1464e7708688STamas Berghammer     NativeProcessLinux* m_process;
1465e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
14666648fcc3SPavel Labath 
14676648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
14686648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
1469e7708688STamas Berghammer 
1470e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
1471e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
1472e7708688STamas Berghammer };
1473e7708688STamas Berghammer 
1474e7708688STamas Berghammer } // anonymous namespace
1475e7708688STamas Berghammer 
1476e7708688STamas Berghammer static size_t
1477e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
1478e7708688STamas Berghammer                     void *baton,
1479e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
1480e7708688STamas Berghammer                     lldb::addr_t addr,
1481e7708688STamas Berghammer                     void *dst,
1482e7708688STamas Berghammer                     size_t length)
1483e7708688STamas Berghammer {
1484e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1485e7708688STamas Berghammer 
14863eb4b458SChaoren Lin     size_t bytes_read;
1487e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1488e7708688STamas Berghammer     return bytes_read;
1489e7708688STamas Berghammer }
1490e7708688STamas Berghammer 
1491e7708688STamas Berghammer static bool
1492e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
1493e7708688STamas Berghammer                       void *baton,
1494e7708688STamas Berghammer                       const RegisterInfo *reg_info,
1495e7708688STamas Berghammer                       RegisterValue &reg_value)
1496e7708688STamas Berghammer {
1497e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1498e7708688STamas Berghammer 
14996648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
15006648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
15016648fcc3SPavel Labath     {
15026648fcc3SPavel Labath         reg_value = it->second;
15036648fcc3SPavel Labath         return true;
15046648fcc3SPavel Labath     }
15056648fcc3SPavel Labath 
1506e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
1507e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
1508e7708688STamas Berghammer     // register context based on the dwarf register numbers.
1509e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1510e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1511e7708688STamas Berghammer 
1512e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
15136648fcc3SPavel Labath     if (error.Success())
15146648fcc3SPavel Labath         return true;
1515cdc22a88SMohit K. Bhakkad 
15166648fcc3SPavel Labath     return false;
1517e7708688STamas Berghammer }
1518e7708688STamas Berghammer 
1519e7708688STamas Berghammer static bool
1520e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
1521e7708688STamas Berghammer                        void *baton,
1522e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
1523e7708688STamas Berghammer                        const RegisterInfo *reg_info,
1524e7708688STamas Berghammer                        const RegisterValue &reg_value)
1525e7708688STamas Berghammer {
1526e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
15276648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
1528e7708688STamas Berghammer     return true;
1529e7708688STamas Berghammer }
1530e7708688STamas Berghammer 
1531e7708688STamas Berghammer static size_t
1532e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
1533e7708688STamas Berghammer                      void *baton,
1534e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
1535e7708688STamas Berghammer                      lldb::addr_t addr,
1536e7708688STamas Berghammer                      const void *dst,
1537e7708688STamas Berghammer                      size_t length)
1538e7708688STamas Berghammer {
1539e7708688STamas Berghammer     return length;
1540e7708688STamas Berghammer }
1541e7708688STamas Berghammer 
1542e7708688STamas Berghammer static lldb::addr_t
1543e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
1544e7708688STamas Berghammer {
1545e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1546e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1547e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1548e7708688STamas Berghammer }
1549e7708688STamas Berghammer 
1550e7708688STamas Berghammer Error
1551b9cc0c75SPavel Labath NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
1552e7708688STamas Berghammer {
1553e7708688STamas Berghammer     Error error;
1554b9cc0c75SPavel Labath     NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1555e7708688STamas Berghammer 
1556e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
1557e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1558e7708688STamas Berghammer 
1559e7708688STamas Berghammer     if (emulator_ap == nullptr)
1560e7708688STamas Berghammer         return Error("Instruction emulator not found!");
1561e7708688STamas Berghammer 
1562e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
1563e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
1564e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1565e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1566e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1567e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1568e7708688STamas Berghammer 
1569e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
1570e7708688STamas Berghammer         return Error("Read instruction failed!");
1571e7708688STamas Berghammer 
15726648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
15736648fcc3SPavel Labath 
15746648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
15756648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
15766648fcc3SPavel Labath 
15776648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
15786648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
15796648fcc3SPavel Labath 
1580e7708688STamas Berghammer     lldb::addr_t next_pc;
1581e7708688STamas Berghammer     lldb::addr_t next_flags;
15826648fcc3SPavel Labath     if (emulation_result)
1583e7708688STamas Berghammer     {
15846648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
15856648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
15866648fcc3SPavel Labath 
15876648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
15886648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
1589e7708688STamas Berghammer         else
1590e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
1591e7708688STamas Berghammer     }
15926648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
1593e7708688STamas Berghammer     {
1594e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
1595e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
1596e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
1597e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
1598e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1599e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
1600e7708688STamas Berghammer     }
1601e7708688STamas Berghammer     else
1602e7708688STamas Berghammer     {
1603e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
1604e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
1605e7708688STamas Berghammer         // modifying the PC but we don't  know how.
1606e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
1607e7708688STamas Berghammer     }
1608e7708688STamas Berghammer 
1609e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
1610e7708688STamas Berghammer     {
1611e7708688STamas Berghammer         if (next_flags & 0x20)
1612e7708688STamas Berghammer         {
1613e7708688STamas Berghammer             // Thumb mode
1614e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
1615e7708688STamas Berghammer         }
1616e7708688STamas Berghammer         else
1617e7708688STamas Berghammer         {
1618e7708688STamas Berghammer             // Arm mode
1619e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
1620e7708688STamas Berghammer         }
1621e7708688STamas Berghammer     }
1622cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
1623c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips64el
1624c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips
1625c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mipsel)
1626cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
1627e7708688STamas Berghammer     else
1628e7708688STamas Berghammer     {
1629e7708688STamas Berghammer         // No size hint is given for the next breakpoint
1630e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
1631e7708688STamas Berghammer     }
1632e7708688STamas Berghammer 
1633e7708688STamas Berghammer     if (error.Fail())
1634e7708688STamas Berghammer         return error;
1635e7708688STamas Berghammer 
1636b9cc0c75SPavel Labath     m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1637e7708688STamas Berghammer 
1638e7708688STamas Berghammer     return Error();
1639e7708688STamas Berghammer }
1640e7708688STamas Berghammer 
1641e7708688STamas Berghammer bool
1642e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
1643e7708688STamas Berghammer {
1644cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
1645c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1646c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
1647cdc22a88SMohit K. Bhakkad         return false;
1648cdc22a88SMohit K. Bhakkad     return true;
1649e7708688STamas Berghammer }
1650e7708688STamas Berghammer 
1651af245d11STodd Fiala Error
1652af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1653af245d11STodd Fiala {
1654af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1655af245d11STodd Fiala     if (log)
1656af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1657af245d11STodd Fiala 
1658e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
1659af245d11STodd Fiala 
1660e7708688STamas Berghammer     if (software_single_step)
1661e7708688STamas Berghammer     {
1662e7708688STamas Berghammer         for (auto thread_sp : m_threads)
1663e7708688STamas Berghammer         {
1664e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
1665e7708688STamas Berghammer 
1666e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1667e7708688STamas Berghammer             if (action == nullptr)
1668e7708688STamas Berghammer                 continue;
1669e7708688STamas Berghammer 
1670e7708688STamas Berghammer             if (action->state == eStateStepping)
1671e7708688STamas Berghammer             {
1672b9cc0c75SPavel Labath                 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
1673e7708688STamas Berghammer                 if (error.Fail())
1674e7708688STamas Berghammer                     return error;
1675e7708688STamas Berghammer             }
1676e7708688STamas Berghammer         }
1677e7708688STamas Berghammer     }
1678e7708688STamas Berghammer 
1679af245d11STodd Fiala     for (auto thread_sp : m_threads)
1680af245d11STodd Fiala     {
1681af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
1682af245d11STodd Fiala 
1683af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
16846a196ce6SChaoren Lin 
16856a196ce6SChaoren Lin         if (action == nullptr)
16866a196ce6SChaoren Lin         {
16876a196ce6SChaoren Lin             if (log)
16886a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
16896a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
16906a196ce6SChaoren Lin             continue;
16916a196ce6SChaoren Lin         }
1692af245d11STodd Fiala 
1693af245d11STodd Fiala         if (log)
1694af245d11STodd Fiala         {
1695af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1696af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1697af245d11STodd Fiala         }
1698af245d11STodd Fiala 
1699af245d11STodd Fiala         switch (action->state)
1700af245d11STodd Fiala         {
1701af245d11STodd Fiala         case eStateRunning:
17020e1d729bSPavel Labath         case eStateStepping:
1703fa03ad2eSChaoren Lin         {
1704af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
1705fa03ad2eSChaoren Lin             const int signo = action->signal;
1706b9cc0c75SPavel Labath             ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
1707af245d11STodd Fiala             break;
1708ae29d395SChaoren Lin         }
1709af245d11STodd Fiala 
1710af245d11STodd Fiala         case eStateSuspended:
1711af245d11STodd Fiala         case eStateStopped:
1712108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
1713af245d11STodd Fiala 
1714af245d11STodd Fiala         default:
1715af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1716af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1717af245d11STodd Fiala         }
1718af245d11STodd Fiala     }
1719af245d11STodd Fiala 
17205830aa75STamas Berghammer     return Error();
1721af245d11STodd Fiala }
1722af245d11STodd Fiala 
1723af245d11STodd Fiala Error
1724af245d11STodd Fiala NativeProcessLinux::Halt ()
1725af245d11STodd Fiala {
1726af245d11STodd Fiala     Error error;
1727af245d11STodd Fiala 
1728af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
1729af245d11STodd Fiala         error.SetErrorToErrno ();
1730af245d11STodd Fiala 
1731af245d11STodd Fiala     return error;
1732af245d11STodd Fiala }
1733af245d11STodd Fiala 
1734af245d11STodd Fiala Error
1735af245d11STodd Fiala NativeProcessLinux::Detach ()
1736af245d11STodd Fiala {
1737af245d11STodd Fiala     Error error;
1738af245d11STodd Fiala 
1739af245d11STodd Fiala     // Stop monitoring the inferior.
174019cbe96aSPavel Labath     m_sigchld_handle.reset();
1741af245d11STodd Fiala 
17427a9495bcSPavel Labath     // Tell ptrace to detach from the process.
17437a9495bcSPavel Labath     if (GetID () == LLDB_INVALID_PROCESS_ID)
17447a9495bcSPavel Labath         return error;
17457a9495bcSPavel Labath 
17467a9495bcSPavel Labath     for (auto thread_sp : m_threads)
17477a9495bcSPavel Labath     {
17487a9495bcSPavel Labath         Error e = Detach(thread_sp->GetID());
17497a9495bcSPavel Labath         if (e.Fail())
17507a9495bcSPavel Labath             error = e; // Save the error, but still attempt to detach from other threads.
17517a9495bcSPavel Labath     }
17527a9495bcSPavel Labath 
1753af245d11STodd Fiala     return error;
1754af245d11STodd Fiala }
1755af245d11STodd Fiala 
1756af245d11STodd Fiala Error
1757af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
1758af245d11STodd Fiala {
1759af245d11STodd Fiala     Error error;
1760af245d11STodd Fiala 
1761af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1762af245d11STodd Fiala     if (log)
1763af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
176498d0a4b3SChaoren Lin                 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1765af245d11STodd Fiala 
1766af245d11STodd Fiala     if (kill(GetID(), signo))
1767af245d11STodd Fiala         error.SetErrorToErrno();
1768af245d11STodd Fiala 
1769af245d11STodd Fiala     return error;
1770af245d11STodd Fiala }
1771af245d11STodd Fiala 
1772af245d11STodd Fiala Error
1773e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
1774e9547b80SChaoren Lin {
1775e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
1776e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
1777e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1778e9547b80SChaoren Lin 
1779e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
1780e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
1781e9547b80SChaoren Lin 
1782e9547b80SChaoren Lin     if (log)
1783e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1784e9547b80SChaoren Lin 
1785e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
1786e9547b80SChaoren Lin     {
1787e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
1788e9547b80SChaoren Lin         if (!thread_sp)
1789e9547b80SChaoren Lin             continue;
1790e9547b80SChaoren Lin 
1791e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
1792e9547b80SChaoren Lin         // target of the interrupt.
1793e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
1794e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
1795e9547b80SChaoren Lin             thread_state == eStateStepping)
1796e9547b80SChaoren Lin         {
1797e9547b80SChaoren Lin             running_thread_sp = thread_sp;
1798e9547b80SChaoren Lin             break;
1799e9547b80SChaoren Lin         }
1800e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1801e9547b80SChaoren Lin         {
1802e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
1803e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
1804e9547b80SChaoren Lin         }
1805e9547b80SChaoren Lin     }
1806e9547b80SChaoren Lin 
1807e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
1808e9547b80SChaoren Lin     {
18095830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
1810e9547b80SChaoren Lin         if (log)
1811e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
18125830aa75STamas Berghammer 
1813e9547b80SChaoren Lin         return error;
1814e9547b80SChaoren Lin     }
1815e9547b80SChaoren Lin 
1816e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1817e9547b80SChaoren Lin 
1818e9547b80SChaoren Lin     if (log)
1819e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1820e9547b80SChaoren Lin                      __FUNCTION__,
1821e9547b80SChaoren Lin                      GetID (),
1822e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
1823e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
1824e9547b80SChaoren Lin 
1825ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
182645f5cb31SPavel Labath 
18275830aa75STamas Berghammer     return Error();
1828e9547b80SChaoren Lin }
1829e9547b80SChaoren Lin 
1830e9547b80SChaoren Lin Error
1831af245d11STodd Fiala NativeProcessLinux::Kill ()
1832af245d11STodd Fiala {
1833af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1834af245d11STodd Fiala     if (log)
1835af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1836af245d11STodd Fiala 
1837af245d11STodd Fiala     Error error;
1838af245d11STodd Fiala 
1839af245d11STodd Fiala     switch (m_state)
1840af245d11STodd Fiala     {
1841af245d11STodd Fiala         case StateType::eStateInvalid:
1842af245d11STodd Fiala         case StateType::eStateExited:
1843af245d11STodd Fiala         case StateType::eStateCrashed:
1844af245d11STodd Fiala         case StateType::eStateDetached:
1845af245d11STodd Fiala         case StateType::eStateUnloaded:
1846af245d11STodd Fiala             // Nothing to do - the process is already dead.
1847af245d11STodd Fiala             if (log)
1848af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1849af245d11STodd Fiala             return error;
1850af245d11STodd Fiala 
1851af245d11STodd Fiala         case StateType::eStateConnected:
1852af245d11STodd Fiala         case StateType::eStateAttaching:
1853af245d11STodd Fiala         case StateType::eStateLaunching:
1854af245d11STodd Fiala         case StateType::eStateStopped:
1855af245d11STodd Fiala         case StateType::eStateRunning:
1856af245d11STodd Fiala         case StateType::eStateStepping:
1857af245d11STodd Fiala         case StateType::eStateSuspended:
1858af245d11STodd Fiala             // We can try to kill a process in these states.
1859af245d11STodd Fiala             break;
1860af245d11STodd Fiala     }
1861af245d11STodd Fiala 
1862af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
1863af245d11STodd Fiala     {
1864af245d11STodd Fiala         error.SetErrorToErrno ();
1865af245d11STodd Fiala         return error;
1866af245d11STodd Fiala     }
1867af245d11STodd Fiala 
1868af245d11STodd Fiala     return error;
1869af245d11STodd Fiala }
1870af245d11STodd Fiala 
1871af245d11STodd Fiala static Error
1872af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1873af245d11STodd Fiala {
1874af245d11STodd Fiala     memory_region_info.Clear();
1875af245d11STodd Fiala 
1876af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
1877af245d11STodd Fiala 
1878af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
1879af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
1880af245d11STodd Fiala 
1881af245d11STodd Fiala     // Parse out the starting address
1882af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1883af245d11STodd Fiala 
1884af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
1885af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1886af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1887af245d11STodd Fiala 
1888af245d11STodd Fiala     // Parse out the ending address
1889af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1890af245d11STodd Fiala 
1891af245d11STodd Fiala     // Parse out the space after the address.
1892af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1893af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1894af245d11STodd Fiala 
1895af245d11STodd Fiala     // Save the range.
1896af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
1897af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
1898af245d11STodd Fiala 
1899*ad007563SHoward Hellyer     // Any memory region in /proc/{pid}/maps is by definition mapped into the process.
1900*ad007563SHoward Hellyer     memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1901*ad007563SHoward Hellyer 
1902af245d11STodd Fiala     // Parse out each permission entry.
1903af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
1904af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1905af245d11STodd Fiala 
1906af245d11STodd Fiala     // Handle read permission.
1907af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
1908af245d11STodd Fiala     if (read_perm_char == 'r')
1909af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1910af245d11STodd Fiala     else
1911af245d11STodd Fiala     {
1912af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1913af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1914af245d11STodd Fiala     }
1915af245d11STodd Fiala 
1916af245d11STodd Fiala     // Handle write permission.
1917af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
1918af245d11STodd Fiala     if (write_perm_char == 'w')
1919af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1920af245d11STodd Fiala     else
1921af245d11STodd Fiala     {
1922af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1923af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1924af245d11STodd Fiala     }
1925af245d11STodd Fiala 
1926af245d11STodd Fiala     // Handle execute permission.
1927af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
1928af245d11STodd Fiala     if (exec_perm_char == 'x')
1929af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1930af245d11STodd Fiala     else
1931af245d11STodd Fiala     {
1932af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1933af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1934af245d11STodd Fiala     }
1935af245d11STodd Fiala 
1936af245d11STodd Fiala     return Error ();
1937af245d11STodd Fiala }
1938af245d11STodd Fiala 
1939af245d11STodd Fiala Error
1940af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1941af245d11STodd Fiala {
1942af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
1943af245d11STodd Fiala     // with no perms if it is not mapped.
1944af245d11STodd Fiala 
1945af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
1946af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
1947af245d11STodd Fiala     // FIXME assert if we find differently.
1948af245d11STodd Fiala 
1949af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1950af245d11STodd Fiala     Error error;
1951af245d11STodd Fiala 
1952af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1953af245d11STodd Fiala     {
1954af245d11STodd Fiala         // We're done.
1955af245d11STodd Fiala         error.SetErrorString ("unsupported");
1956af245d11STodd Fiala         return error;
1957af245d11STodd Fiala     }
1958af245d11STodd Fiala 
1959af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
1960af245d11STodd Fiala     // if memory region handling is supported.
1961af245d11STodd Fiala     if (m_mem_region_cache.empty ())
1962af245d11STodd Fiala     {
1963af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1964af245d11STodd Fiala              [&] (const std::string &line) -> bool
1965af245d11STodd Fiala              {
1966af245d11STodd Fiala                  MemoryRegionInfo info;
1967af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1968af245d11STodd Fiala                  if (parse_error.Success ())
1969af245d11STodd Fiala                  {
1970af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
1971af245d11STodd Fiala                      return true;
1972af245d11STodd Fiala                  }
1973af245d11STodd Fiala                  else
1974af245d11STodd Fiala                  {
1975af245d11STodd Fiala                      if (log)
1976af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1977af245d11STodd Fiala                      return false;
1978af245d11STodd Fiala                  }
1979af245d11STodd Fiala              });
1980af245d11STodd Fiala 
1981af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
1982af245d11STodd Fiala         if (error.Fail ())
1983af245d11STodd Fiala         {
1984af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
1985af245d11STodd Fiala             return error;
1986af245d11STodd Fiala         }
1987af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
1988af245d11STodd Fiala         {
1989af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
1990af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
1991af245d11STodd Fiala             if (log)
1992af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
1993af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
1994af245d11STodd Fiala             error.SetErrorString ("not supported");
1995af245d11STodd Fiala             return error;
1996af245d11STodd Fiala         }
1997af245d11STodd Fiala 
1998af245d11STodd Fiala         if (log)
1999af245d11STodd 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 ());
2000af245d11STodd Fiala 
2001af245d11STodd Fiala         // We support memory retrieval, remember that.
2002af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
2003af245d11STodd Fiala     }
2004af245d11STodd Fiala     else
2005af245d11STodd Fiala     {
2006af245d11STodd Fiala         if (log)
2007af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2008af245d11STodd Fiala     }
2009af245d11STodd Fiala 
2010af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
2011af245d11STodd Fiala 
2012af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2013af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
2014af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2015af245d11STodd Fiala     {
2016af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
2017af245d11STodd Fiala 
2018af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2019af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2020af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2021af245d11STodd Fiala 
2022af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
2023af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2024af245d11STodd Fiala         {
2025af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
2026af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2027af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2028af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2029af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2030*ad007563SHoward Hellyer             range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
2031af245d11STodd Fiala 
2032af245d11STodd Fiala             return error;
2033af245d11STodd Fiala         }
2034af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
2035af245d11STodd Fiala         {
2036af245d11STodd Fiala             // The target address is within the memory region we're processing here.
2037af245d11STodd Fiala             range_info = proc_entry_info;
2038af245d11STodd Fiala             return error;
2039af245d11STodd Fiala         }
2040af245d11STodd Fiala 
2041af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
2042af245d11STodd Fiala     }
2043af245d11STodd Fiala 
204409839c33STamas Berghammer     // If we made it here, we didn't find an entry that contained the given address. Return the
204509839c33STamas Berghammer     // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
204609839c33STamas Berghammer     // size.
204709839c33STamas Berghammer     range_info.GetRange ().SetRangeBase (load_addr);
2048*ad007563SHoward Hellyer     range_info.GetRange ().SetRangeEnd(LLDB_INVALID_ADDRESS);
204909839c33STamas Berghammer     range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
205009839c33STamas Berghammer     range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
205109839c33STamas Berghammer     range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2052*ad007563SHoward Hellyer     range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
2053af245d11STodd Fiala     return error;
2054af245d11STodd Fiala }
2055af245d11STodd Fiala 
2056af245d11STodd Fiala void
2057af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2058af245d11STodd Fiala {
2059af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2060af245d11STodd Fiala     if (log)
2061af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2062af245d11STodd Fiala 
2063af245d11STodd Fiala         if (log)
2064af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2065af245d11STodd Fiala         m_mem_region_cache.clear ();
2066af245d11STodd Fiala }
2067af245d11STodd Fiala 
2068af245d11STodd Fiala Error
20693eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2070af245d11STodd Fiala {
2071af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
2072af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2073af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
2074af245d11STodd Fiala #if 1
2075af245d11STodd Fiala     return Error ("not implemented yet");
2076af245d11STodd Fiala #else
2077af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
2078af245d11STodd Fiala 
2079af245d11STodd Fiala     unsigned prot = 0;
2080af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
2081af245d11STodd Fiala         prot |= eMmapProtRead;
2082af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
2083af245d11STodd Fiala         prot |= eMmapProtWrite;
2084af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
2085af245d11STodd Fiala         prot |= eMmapProtExec;
2086af245d11STodd Fiala 
2087af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
2088af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
2089af245d11STodd Fiala     // refactored out).
2090af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
2091af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2092af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
2093af245d11STodd Fiala         return Error ();
2094af245d11STodd Fiala     } else {
2095af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
2096af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2097af245d11STodd Fiala     }
2098af245d11STodd Fiala #endif
2099af245d11STodd Fiala }
2100af245d11STodd Fiala 
2101af245d11STodd Fiala Error
2102af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2103af245d11STodd Fiala {
2104af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
2105af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
2106af245d11STodd Fiala     return Error ("not implemented");
2107af245d11STodd Fiala }
2108af245d11STodd Fiala 
2109af245d11STodd Fiala lldb::addr_t
2110af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
2111af245d11STodd Fiala {
2112af245d11STodd Fiala     // punt on this for now
2113af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2114af245d11STodd Fiala }
2115af245d11STodd Fiala 
2116af245d11STodd Fiala size_t
2117af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
2118af245d11STodd Fiala {
2119af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
2120af245d11STodd Fiala     // with respect to thread state and they keep the thread list
2121af245d11STodd Fiala     // populated properly. All this method needs to do is return the
2122af245d11STodd Fiala     // thread count.
2123af245d11STodd Fiala     return m_threads.size ();
2124af245d11STodd Fiala }
2125af245d11STodd Fiala 
2126af245d11STodd Fiala bool
2127af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2128af245d11STodd Fiala {
2129af245d11STodd Fiala     arch = m_arch;
2130af245d11STodd Fiala     return true;
2131af245d11STodd Fiala }
2132af245d11STodd Fiala 
2133af245d11STodd Fiala Error
2134b9cc0c75SPavel Labath NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
2135af245d11STodd Fiala {
2136af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
2137af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
2138af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
2139bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2140af245d11STodd Fiala 
2141af245d11STodd Fiala     switch (m_arch.GetMachine ())
2142af245d11STodd Fiala     {
2143af245d11STodd Fiala         case llvm::Triple::x86:
2144af245d11STodd Fiala         case llvm::Triple::x86_64:
2145af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2146af245d11STodd Fiala             return Error ();
2147af245d11STodd Fiala 
2148bb00d0b6SUlrich Weigand         case llvm::Triple::systemz:
2149bb00d0b6SUlrich Weigand             actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2150bb00d0b6SUlrich Weigand             return Error ();
2151bb00d0b6SUlrich Weigand 
2152ff7fd900STamas Berghammer         case llvm::Triple::arm:
2153ff7fd900STamas Berghammer         case llvm::Triple::aarch64:
2154e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
2155e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
2156ce815e45SSagar Thakur         case llvm::Triple::mips:
2157ce815e45SSagar Thakur         case llvm::Triple::mipsel:
2158ff7fd900STamas Berghammer             // On these architectures the PC don't get updated for breakpoint hits
2159c60c9452SJaydeep Patil             actual_opcode_size = 0;
2160e8659b5dSMohit K. Bhakkad             return Error ();
2161e8659b5dSMohit K. Bhakkad 
2162af245d11STodd Fiala         default:
2163af245d11STodd Fiala             assert(false && "CPU type not supported!");
2164af245d11STodd Fiala             return Error ("CPU type not supported");
2165af245d11STodd Fiala     }
2166af245d11STodd Fiala }
2167af245d11STodd Fiala 
2168af245d11STodd Fiala Error
2169af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2170af245d11STodd Fiala {
2171af245d11STodd Fiala     if (hardware)
2172af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
2173af245d11STodd Fiala     else
2174af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
2175af245d11STodd Fiala }
2176af245d11STodd Fiala 
2177af245d11STodd Fiala Error
217863c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
217963c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
218063c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
2181af245d11STodd Fiala {
218263c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
218363c8be95STamas Berghammer     // architecture.  Need MIPS support here.
21842afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2185be379e15STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2186be379e15STamas Berghammer     // linux kernel does otherwise.
2187be379e15STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
2188af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
21893df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
21902c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
2191bb00d0b6SUlrich Weigand     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2192be379e15STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
2193af245d11STodd Fiala 
2194af245d11STodd Fiala     switch (m_arch.GetMachine ())
2195af245d11STodd Fiala     {
21962afc5966STodd Fiala     case llvm::Triple::aarch64:
21972afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
21982afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
21992afc5966STodd Fiala         return Error ();
22002afc5966STodd Fiala 
220163c8be95STamas Berghammer     case llvm::Triple::arm:
220263c8be95STamas Berghammer         switch (trap_opcode_size_hint)
220363c8be95STamas Berghammer         {
220463c8be95STamas Berghammer         case 2:
220563c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
220663c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
220763c8be95STamas Berghammer             return Error ();
220863c8be95STamas Berghammer         case 4:
220963c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
221063c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
221163c8be95STamas Berghammer             return Error ();
221263c8be95STamas Berghammer         default:
221363c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
221463c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
221563c8be95STamas Berghammer         }
221663c8be95STamas Berghammer 
2217af245d11STodd Fiala     case llvm::Triple::x86:
2218af245d11STodd Fiala     case llvm::Triple::x86_64:
2219af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
2220af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
2221af245d11STodd Fiala         return Error ();
2222af245d11STodd Fiala 
2223ce815e45SSagar Thakur     case llvm::Triple::mips:
22243df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
22253df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
22263df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
22273df471c3SMohit K. Bhakkad         return Error ();
22283df471c3SMohit K. Bhakkad 
2229ce815e45SSagar Thakur     case llvm::Triple::mipsel:
22302c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
22312c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
22322c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
22332c2acf96SMohit K. Bhakkad         return Error ();
22342c2acf96SMohit K. Bhakkad 
2235bb00d0b6SUlrich Weigand     case llvm::Triple::systemz:
2236bb00d0b6SUlrich Weigand         trap_opcode_bytes = g_s390x_opcode;
2237bb00d0b6SUlrich Weigand         actual_opcode_size = sizeof(g_s390x_opcode);
2238bb00d0b6SUlrich Weigand         return Error ();
2239bb00d0b6SUlrich Weigand 
2240af245d11STodd Fiala     default:
2241af245d11STodd Fiala         assert(false && "CPU type not supported!");
2242af245d11STodd Fiala         return Error ("CPU type not supported");
2243af245d11STodd Fiala     }
2244af245d11STodd Fiala }
2245af245d11STodd Fiala 
2246af245d11STodd Fiala #if 0
2247af245d11STodd Fiala ProcessMessage::CrashReason
2248af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2249af245d11STodd Fiala {
2250af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2251af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
2252af245d11STodd Fiala 
2253af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2254af245d11STodd Fiala 
2255af245d11STodd Fiala     switch (info->si_code)
2256af245d11STodd Fiala     {
2257af245d11STodd Fiala     default:
2258af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
2259af245d11STodd Fiala         break;
2260af245d11STodd Fiala     case SI_KERNEL:
2261af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
2262af245d11STodd Fiala         // (this is poorly documented in sigaction)
2263af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
2264af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2265af245d11STodd Fiala         break;
2266af245d11STodd Fiala     case SEGV_MAPERR:
2267af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2268af245d11STodd Fiala         break;
2269af245d11STodd Fiala     case SEGV_ACCERR:
2270af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2271af245d11STodd Fiala         break;
2272af245d11STodd Fiala     }
2273af245d11STodd Fiala 
2274af245d11STodd Fiala     return reason;
2275af245d11STodd Fiala }
2276af245d11STodd Fiala #endif
2277af245d11STodd Fiala 
2278af245d11STodd Fiala 
2279af245d11STodd Fiala #if 0
2280af245d11STodd Fiala ProcessMessage::CrashReason
2281af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2282af245d11STodd Fiala {
2283af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2284af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2285af245d11STodd Fiala 
2286af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2287af245d11STodd Fiala 
2288af245d11STodd Fiala     switch (info->si_code)
2289af245d11STodd Fiala     {
2290af245d11STodd Fiala     default:
2291af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2292af245d11STodd Fiala         break;
2293af245d11STodd Fiala     case ILL_ILLOPC:
2294af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2295af245d11STodd Fiala         break;
2296af245d11STodd Fiala     case ILL_ILLOPN:
2297af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
2298af245d11STodd Fiala         break;
2299af245d11STodd Fiala     case ILL_ILLADR:
2300af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
2301af245d11STodd Fiala         break;
2302af245d11STodd Fiala     case ILL_ILLTRP:
2303af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
2304af245d11STodd Fiala         break;
2305af245d11STodd Fiala     case ILL_PRVOPC:
2306af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
2307af245d11STodd Fiala         break;
2308af245d11STodd Fiala     case ILL_PRVREG:
2309af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
2310af245d11STodd Fiala         break;
2311af245d11STodd Fiala     case ILL_COPROC:
2312af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
2313af245d11STodd Fiala         break;
2314af245d11STodd Fiala     case ILL_BADSTK:
2315af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
2316af245d11STodd Fiala         break;
2317af245d11STodd Fiala     }
2318af245d11STodd Fiala 
2319af245d11STodd Fiala     return reason;
2320af245d11STodd Fiala }
2321af245d11STodd Fiala #endif
2322af245d11STodd Fiala 
2323af245d11STodd Fiala #if 0
2324af245d11STodd Fiala ProcessMessage::CrashReason
2325af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2326af245d11STodd Fiala {
2327af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2328af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
2329af245d11STodd Fiala 
2330af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2331af245d11STodd Fiala 
2332af245d11STodd Fiala     switch (info->si_code)
2333af245d11STodd Fiala     {
2334af245d11STodd Fiala     default:
2335af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
2336af245d11STodd Fiala         break;
2337af245d11STodd Fiala     case FPE_INTDIV:
2338af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
2339af245d11STodd Fiala         break;
2340af245d11STodd Fiala     case FPE_INTOVF:
2341af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
2342af245d11STodd Fiala         break;
2343af245d11STodd Fiala     case FPE_FLTDIV:
2344af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
2345af245d11STodd Fiala         break;
2346af245d11STodd Fiala     case FPE_FLTOVF:
2347af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
2348af245d11STodd Fiala         break;
2349af245d11STodd Fiala     case FPE_FLTUND:
2350af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
2351af245d11STodd Fiala         break;
2352af245d11STodd Fiala     case FPE_FLTRES:
2353af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
2354af245d11STodd Fiala         break;
2355af245d11STodd Fiala     case FPE_FLTINV:
2356af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
2357af245d11STodd Fiala         break;
2358af245d11STodd Fiala     case FPE_FLTSUB:
2359af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
2360af245d11STodd Fiala         break;
2361af245d11STodd Fiala     }
2362af245d11STodd Fiala 
2363af245d11STodd Fiala     return reason;
2364af245d11STodd Fiala }
2365af245d11STodd Fiala #endif
2366af245d11STodd Fiala 
2367af245d11STodd Fiala #if 0
2368af245d11STodd Fiala ProcessMessage::CrashReason
2369af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2370af245d11STodd Fiala {
2371af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2372af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
2373af245d11STodd Fiala 
2374af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2375af245d11STodd Fiala 
2376af245d11STodd Fiala     switch (info->si_code)
2377af245d11STodd Fiala     {
2378af245d11STodd Fiala     default:
2379af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
2380af245d11STodd Fiala         break;
2381af245d11STodd Fiala     case BUS_ADRALN:
2382af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
2383af245d11STodd Fiala         break;
2384af245d11STodd Fiala     case BUS_ADRERR:
2385af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
2386af245d11STodd Fiala         break;
2387af245d11STodd Fiala     case BUS_OBJERR:
2388af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
2389af245d11STodd Fiala         break;
2390af245d11STodd Fiala     }
2391af245d11STodd Fiala 
2392af245d11STodd Fiala     return reason;
2393af245d11STodd Fiala }
2394af245d11STodd Fiala #endif
2395af245d11STodd Fiala 
2396af245d11STodd Fiala Error
239726438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2398af245d11STodd Fiala {
2399df7c6995SPavel Labath     if (ProcessVmReadvSupported()) {
2400df7c6995SPavel Labath         // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2401df7c6995SPavel Labath         // this syscall if it is supported.
2402df7c6995SPavel Labath 
2403df7c6995SPavel Labath         const ::pid_t pid = GetID();
2404df7c6995SPavel Labath 
2405df7c6995SPavel Labath         struct iovec local_iov, remote_iov;
2406df7c6995SPavel Labath         local_iov.iov_base = buf;
2407df7c6995SPavel Labath         local_iov.iov_len = size;
2408df7c6995SPavel Labath         remote_iov.iov_base = reinterpret_cast<void *>(addr);
2409df7c6995SPavel Labath         remote_iov.iov_len = size;
2410df7c6995SPavel Labath 
2411df7c6995SPavel Labath         bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2412df7c6995SPavel Labath         const bool success = bytes_read == size;
2413df7c6995SPavel Labath 
2414df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2415df7c6995SPavel Labath         if (log)
2416df7c6995SPavel Labath             log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2417df7c6995SPavel Labath                     __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2418df7c6995SPavel Labath 
2419df7c6995SPavel Labath         if (success)
2420df7c6995SPavel Labath             return Error();
2421df7c6995SPavel Labath         // else
2422df7c6995SPavel Labath         //     the call failed for some reason, let's retry the read using ptrace api.
2423df7c6995SPavel Labath     }
2424df7c6995SPavel Labath 
242519cbe96aSPavel Labath     unsigned char *dst = static_cast<unsigned char*>(buf);
242619cbe96aSPavel Labath     size_t remainder;
242719cbe96aSPavel Labath     long data;
242819cbe96aSPavel Labath 
242919cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
243019cbe96aSPavel Labath     if (log)
243119cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
243219cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
243319cbe96aSPavel Labath         log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
243419cbe96aSPavel Labath 
243519cbe96aSPavel Labath     for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
243619cbe96aSPavel Labath     {
243719cbe96aSPavel Labath         Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
243819cbe96aSPavel Labath         if (error.Fail())
243919cbe96aSPavel Labath         {
244019cbe96aSPavel Labath             if (log)
244119cbe96aSPavel Labath                 ProcessPOSIXLog::DecNestLevel();
244219cbe96aSPavel Labath             return error;
244319cbe96aSPavel Labath         }
244419cbe96aSPavel Labath 
244519cbe96aSPavel Labath         remainder = size - bytes_read;
244619cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
244719cbe96aSPavel Labath 
244819cbe96aSPavel Labath         // Copy the data into our buffer
2449f6ef187bSMohit K. Bhakkad         memcpy(dst, &data, remainder);
245019cbe96aSPavel Labath 
245119cbe96aSPavel Labath         if (log && ProcessPOSIXLog::AtTopNestLevel() &&
245219cbe96aSPavel Labath                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
245319cbe96aSPavel Labath                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
245419cbe96aSPavel Labath                                 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
245519cbe96aSPavel Labath         {
245619cbe96aSPavel Labath             uintptr_t print_dst = 0;
245719cbe96aSPavel Labath             // Format bytes from data by moving into print_dst for log output
245819cbe96aSPavel Labath             for (unsigned i = 0; i < remainder; ++i)
245919cbe96aSPavel Labath                 print_dst |= (((data >> i*8) & 0xFF) << i*8);
246079203995SPavel Labath             log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
246179203995SPavel Labath                     __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
246219cbe96aSPavel Labath         }
246319cbe96aSPavel Labath         addr += k_ptrace_word_size;
246419cbe96aSPavel Labath         dst += k_ptrace_word_size;
246519cbe96aSPavel Labath     }
246619cbe96aSPavel Labath 
246719cbe96aSPavel Labath     if (log)
246819cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
246919cbe96aSPavel Labath     return Error();
2470af245d11STodd Fiala }
2471af245d11STodd Fiala 
2472af245d11STodd Fiala Error
24733eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
24743eb4b458SChaoren Lin {
24753eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
24763eb4b458SChaoren Lin     if (error.Fail()) return error;
24773eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
24783eb4b458SChaoren Lin }
24793eb4b458SChaoren Lin 
24803eb4b458SChaoren Lin Error
24813eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
2482af245d11STodd Fiala {
248319cbe96aSPavel Labath     const unsigned char *src = static_cast<const unsigned char*>(buf);
248419cbe96aSPavel Labath     size_t remainder;
248519cbe96aSPavel Labath     Error error;
248619cbe96aSPavel Labath 
248719cbe96aSPavel Labath     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
248819cbe96aSPavel Labath     if (log)
248919cbe96aSPavel Labath         ProcessPOSIXLog::IncNestLevel();
249019cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
249179203995SPavel Labath         log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
249219cbe96aSPavel Labath 
249319cbe96aSPavel Labath     for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
249419cbe96aSPavel Labath     {
249519cbe96aSPavel Labath         remainder = size - bytes_written;
249619cbe96aSPavel Labath         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
249719cbe96aSPavel Labath 
249819cbe96aSPavel Labath         if (remainder == k_ptrace_word_size)
249919cbe96aSPavel Labath         {
250019cbe96aSPavel Labath             unsigned long data = 0;
2501f6ef187bSMohit K. Bhakkad             memcpy(&data, src, k_ptrace_word_size);
250219cbe96aSPavel Labath 
250319cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
250419cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
250519cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
250619cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
250719cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
250819cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, data);
250919cbe96aSPavel Labath 
251019cbe96aSPavel Labath             error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
251119cbe96aSPavel Labath             if (error.Fail())
251219cbe96aSPavel Labath             {
251319cbe96aSPavel Labath                 if (log)
251419cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
251519cbe96aSPavel Labath                 return error;
251619cbe96aSPavel Labath             }
251719cbe96aSPavel Labath         }
251819cbe96aSPavel Labath         else
251919cbe96aSPavel Labath         {
252019cbe96aSPavel Labath             unsigned char buff[8];
252119cbe96aSPavel Labath             size_t bytes_read;
252219cbe96aSPavel Labath             error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
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             memcpy(buff, src, remainder);
253119cbe96aSPavel Labath 
253219cbe96aSPavel Labath             size_t bytes_written_rec;
253319cbe96aSPavel Labath             error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
253419cbe96aSPavel Labath             if (error.Fail())
253519cbe96aSPavel Labath             {
253619cbe96aSPavel Labath                 if (log)
253719cbe96aSPavel Labath                     ProcessPOSIXLog::DecNestLevel();
253819cbe96aSPavel Labath                 return error;
253919cbe96aSPavel Labath             }
254019cbe96aSPavel Labath 
254119cbe96aSPavel Labath             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
254219cbe96aSPavel Labath                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
254319cbe96aSPavel Labath                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
254419cbe96aSPavel Labath                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
254519cbe96aSPavel Labath                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
254619cbe96aSPavel Labath                         (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
254719cbe96aSPavel Labath         }
254819cbe96aSPavel Labath 
254919cbe96aSPavel Labath         addr += k_ptrace_word_size;
255019cbe96aSPavel Labath         src += k_ptrace_word_size;
255119cbe96aSPavel Labath     }
255219cbe96aSPavel Labath     if (log)
255319cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
255419cbe96aSPavel Labath     return error;
2555af245d11STodd Fiala }
2556af245d11STodd Fiala 
255797ccc294SChaoren Lin Error
255897ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
2559af245d11STodd Fiala {
256019cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2561af245d11STodd Fiala }
2562af245d11STodd Fiala 
256397ccc294SChaoren Lin Error
2564af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2565af245d11STodd Fiala {
256619cbe96aSPavel Labath     return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2567af245d11STodd Fiala }
2568af245d11STodd Fiala 
2569db264a6dSTamas Berghammer Error
2570af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
2571af245d11STodd Fiala {
257297ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
257397ccc294SChaoren Lin         return Error();
257497ccc294SChaoren Lin 
257519cbe96aSPavel Labath     return PtraceWrapper(PTRACE_DETACH, tid);
2576af245d11STodd Fiala }
2577af245d11STodd Fiala 
2578af245d11STodd Fiala bool
2579d3173f34SChaoren Lin NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
2580af245d11STodd Fiala {
2581d3173f34SChaoren Lin     int target_fd = open(file_spec.GetCString(), flags, 0666);
2582af245d11STodd Fiala 
2583af245d11STodd Fiala     if (target_fd == -1)
2584af245d11STodd Fiala         return false;
2585af245d11STodd Fiala 
2586493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
2587493c3a12SPavel Labath         return false;
2588493c3a12SPavel Labath 
2589493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
2590af245d11STodd Fiala }
2591af245d11STodd Fiala 
2592af245d11STodd Fiala bool
2593af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2594af245d11STodd Fiala {
2595af245d11STodd Fiala     for (auto thread_sp : m_threads)
2596af245d11STodd Fiala     {
2597af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2598af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
2599af245d11STodd Fiala         {
2600af245d11STodd Fiala             // We have this thread.
2601af245d11STodd Fiala             return true;
2602af245d11STodd Fiala         }
2603af245d11STodd Fiala     }
2604af245d11STodd Fiala 
2605af245d11STodd Fiala     // We don't have this thread.
2606af245d11STodd Fiala     return false;
2607af245d11STodd Fiala }
2608af245d11STodd Fiala 
2609af245d11STodd Fiala bool
2610af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2611af245d11STodd Fiala {
26121dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
26131dbc6c9cSPavel Labath 
26141dbc6c9cSPavel Labath     if (log)
26151dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
26161dbc6c9cSPavel Labath 
26171dbc6c9cSPavel Labath     bool found = false;
26181dbc6c9cSPavel Labath 
2619af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2620af245d11STodd Fiala     {
2621af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
2622af245d11STodd Fiala         {
2623af245d11STodd Fiala             m_threads.erase (it);
26241dbc6c9cSPavel Labath             found = true;
26251dbc6c9cSPavel Labath             break;
2626af245d11STodd Fiala         }
2627af245d11STodd Fiala     }
2628af245d11STodd Fiala 
26299eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
26301dbc6c9cSPavel Labath 
26311dbc6c9cSPavel Labath     return found;
2632af245d11STodd Fiala }
2633af245d11STodd Fiala 
2634f9077782SPavel Labath NativeThreadLinuxSP
2635af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2636af245d11STodd Fiala {
2637af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2638af245d11STodd Fiala 
2639af245d11STodd Fiala     if (log)
2640af245d11STodd Fiala     {
2641af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2642af245d11STodd Fiala                 __FUNCTION__,
2643af245d11STodd Fiala                 GetID (),
2644af245d11STodd Fiala                 thread_id);
2645af245d11STodd Fiala     }
2646af245d11STodd Fiala 
2647af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2648af245d11STodd Fiala 
2649af245d11STodd Fiala     // If this is the first thread, save it as the current thread
2650af245d11STodd Fiala     if (m_threads.empty ())
2651af245d11STodd Fiala         SetCurrentThreadID (thread_id);
2652af245d11STodd Fiala 
2653f9077782SPavel Labath     auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2654af245d11STodd Fiala     m_threads.push_back (thread_sp);
2655af245d11STodd Fiala     return thread_sp;
2656af245d11STodd Fiala }
2657af245d11STodd Fiala 
2658af245d11STodd Fiala Error
2659b9cc0c75SPavel Labath NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
2660af245d11STodd Fiala {
266175f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2662af245d11STodd Fiala 
2663af245d11STodd Fiala     Error error;
2664af245d11STodd Fiala 
2665af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
2666b9cc0c75SPavel Labath     NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2667af245d11STodd Fiala     if (!context_sp)
2668af245d11STodd Fiala     {
2669af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2670af245d11STodd Fiala         if (log)
2671af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2672af245d11STodd Fiala         return error;
2673af245d11STodd Fiala     }
2674af245d11STodd Fiala 
2675af245d11STodd Fiala     uint32_t breakpoint_size = 0;
2676b9cc0c75SPavel Labath     error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2677af245d11STodd Fiala     if (error.Fail ())
2678af245d11STodd Fiala     {
2679af245d11STodd Fiala         if (log)
2680af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2681af245d11STodd Fiala         return error;
2682af245d11STodd Fiala     }
2683af245d11STodd Fiala     else
2684af245d11STodd Fiala     {
2685af245d11STodd Fiala         if (log)
2686af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2687af245d11STodd Fiala     }
2688af245d11STodd Fiala 
2689af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
2690c60c9452SJaydeep Patil     const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
2691af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
26923eb4b458SChaoren Lin     if (breakpoint_size > 0)
2693af245d11STodd Fiala     {
2694af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
26953eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
26963eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
2697af245d11STodd Fiala     }
2698af245d11STodd Fiala 
2699af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
2700af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
2701af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2702af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
2703af245d11STodd Fiala     {
2704af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
2705af245d11STodd Fiala         if (log)
2706af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2707af245d11STodd Fiala         return Error ();
2708af245d11STodd Fiala     }
2709af245d11STodd Fiala 
2710af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
2711af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
2712af245d11STodd Fiala     {
2713af245d11STodd Fiala         if (log)
2714af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2715af245d11STodd Fiala         return Error ();
2716af245d11STodd Fiala     }
2717af245d11STodd Fiala 
2718af245d11STodd Fiala     //
2719af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
2720af245d11STodd Fiala     //
2721af245d11STodd Fiala 
2722af245d11STodd Fiala     // Sanity check.
2723af245d11STodd Fiala     if (breakpoint_size == 0)
2724af245d11STodd Fiala     {
2725af245d11STodd Fiala         // Nothing to do!  How did we get here?
2726af245d11STodd Fiala         if (log)
2727af245d11STodd 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);
2728af245d11STodd Fiala         return Error ();
2729af245d11STodd Fiala     }
2730af245d11STodd Fiala 
2731af245d11STodd Fiala     // Change the program counter.
2732af245d11STodd Fiala     if (log)
2733b9cc0c75SPavel 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);
2734af245d11STodd Fiala 
2735af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
2736af245d11STodd Fiala     if (error.Fail ())
2737af245d11STodd Fiala     {
2738af245d11STodd Fiala         if (log)
2739b9cc0c75SPavel Labath             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
2740af245d11STodd Fiala         return error;
2741af245d11STodd Fiala     }
2742af245d11STodd Fiala 
2743af245d11STodd Fiala     return error;
2744af245d11STodd Fiala }
2745fa03ad2eSChaoren Lin 
27467cb18bf5STamas Berghammer Error
27477cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
27487cb18bf5STamas Berghammer {
27497cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
27507cb18bf5STamas Berghammer 
2751162fb8e8SPavel Labath     bool found = false;
27527cb18bf5STamas Berghammer     file_spec.Clear();
2753162fb8e8SPavel Labath     ProcFileReader::ProcessLineByLine(GetID(), "maps",
2754162fb8e8SPavel Labath         [&] (const std::string &line)
2755162fb8e8SPavel Labath         {
2756162fb8e8SPavel Labath             SmallVector<StringRef, 16> columns;
2757162fb8e8SPavel Labath             StringRef(line).split(columns, " ", -1, false);
2758162fb8e8SPavel Labath             if (columns.size() < 6)
2759162fb8e8SPavel Labath                 return true; // continue searching
2760162fb8e8SPavel Labath 
2761162fb8e8SPavel Labath             FileSpec this_file_spec(columns[5].str().c_str(), false);
2762162fb8e8SPavel Labath             if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2763162fb8e8SPavel Labath                 return true; // continue searching
2764162fb8e8SPavel Labath 
2765162fb8e8SPavel Labath             file_spec = this_file_spec;
2766162fb8e8SPavel Labath             found = true;
2767162fb8e8SPavel Labath             return false; // we are done
2768162fb8e8SPavel Labath         });
2769162fb8e8SPavel Labath 
2770162fb8e8SPavel Labath     if (! found)
27717cb18bf5STamas Berghammer         return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
27727cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
2773162fb8e8SPavel Labath 
2774162fb8e8SPavel Labath     return Error();
27757cb18bf5STamas Berghammer }
2776c076559aSPavel Labath 
27775eb721edSPavel Labath Error
2778783bfc8cSTamas Berghammer NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2779783bfc8cSTamas Berghammer {
2780783bfc8cSTamas Berghammer     load_addr = LLDB_INVALID_ADDRESS;
2781783bfc8cSTamas Berghammer     Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2782783bfc8cSTamas Berghammer         [&] (const std::string &line) -> bool
2783783bfc8cSTamas Berghammer         {
2784783bfc8cSTamas Berghammer             StringRef maps_row(line);
2785783bfc8cSTamas Berghammer 
2786783bfc8cSTamas Berghammer             SmallVector<StringRef, 16> maps_columns;
2787783bfc8cSTamas Berghammer             maps_row.split(maps_columns, StringRef(" "), -1, false);
2788783bfc8cSTamas Berghammer 
2789783bfc8cSTamas Berghammer             if (maps_columns.size() < 6)
2790783bfc8cSTamas Berghammer             {
2791783bfc8cSTamas Berghammer                 // Return true to continue reading the proc file
2792783bfc8cSTamas Berghammer                 return true;
2793783bfc8cSTamas Berghammer             }
2794783bfc8cSTamas Berghammer 
2795783bfc8cSTamas Berghammer             if (maps_columns[5] == file_name)
2796783bfc8cSTamas Berghammer             {
2797783bfc8cSTamas Berghammer                 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2798783bfc8cSTamas Berghammer                 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2799783bfc8cSTamas Berghammer 
2800783bfc8cSTamas Berghammer                 // Return false to stop reading the proc file further
2801783bfc8cSTamas Berghammer                 return false;
2802783bfc8cSTamas Berghammer             }
2803783bfc8cSTamas Berghammer 
2804783bfc8cSTamas Berghammer             // Return true to continue reading the proc file
2805783bfc8cSTamas Berghammer             return true;
2806783bfc8cSTamas Berghammer         });
2807783bfc8cSTamas Berghammer     return error;
2808783bfc8cSTamas Berghammer }
2809783bfc8cSTamas Berghammer 
2810f9077782SPavel Labath NativeThreadLinuxSP
2811f9077782SPavel Labath NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2812f9077782SPavel Labath {
2813f9077782SPavel Labath     return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2814f9077782SPavel Labath }
2815f9077782SPavel Labath 
2816783bfc8cSTamas Berghammer Error
2817b9cc0c75SPavel Labath NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
2818c076559aSPavel Labath {
28195eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
28205eb721edSPavel Labath 
28211dbc6c9cSPavel Labath     if (log)
28220e1d729bSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
2823b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
2824c076559aSPavel Labath 
2825c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
2826108c325dSPavel Labath     // stop notification that is currently waiting for
28270e1d729bSPavel Labath     // all threads to stop.  This is potentially a buggy situation since
2828c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
2829c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
2830c076559aSPavel Labath     // out the pending stop notification.
28310e1d729bSPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
2832c076559aSPavel Labath     {
2833b9cc0c75SPavel 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);
2834c076559aSPavel Labath     }
2835c076559aSPavel Labath 
2836c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
2837c076559aSPavel Labath     // to reflect it is running after this completes.
28380e1d729bSPavel Labath     switch (state)
2839c076559aSPavel Labath     {
28400e1d729bSPavel Labath     case eStateRunning:
28410e1d729bSPavel Labath     {
2842605b51b8SPavel Labath         const auto resume_result = thread.Resume(signo);
28430e1d729bSPavel Labath         if (resume_result.Success())
28440e1d729bSPavel Labath             SetState(eStateRunning, true);
28450e1d729bSPavel Labath         return resume_result;
2846c076559aSPavel Labath     }
28470e1d729bSPavel Labath     case eStateStepping:
28480e1d729bSPavel Labath     {
2849605b51b8SPavel Labath         const auto step_result = thread.SingleStep(signo);
28500e1d729bSPavel Labath         if (step_result.Success())
28510e1d729bSPavel Labath             SetState(eStateRunning, true);
28520e1d729bSPavel Labath         return step_result;
28530e1d729bSPavel Labath     }
28540e1d729bSPavel Labath     default:
28550e1d729bSPavel Labath         if (log)
28560e1d729bSPavel Labath             log->Printf("NativeProcessLinux::%s Unhandled state %s.",
28570e1d729bSPavel Labath                     __FUNCTION__, StateAsCString(state));
28580e1d729bSPavel Labath         llvm_unreachable("Unhandled state for resume");
28590e1d729bSPavel Labath     }
2860c076559aSPavel Labath }
2861c076559aSPavel Labath 
2862c076559aSPavel Labath //===----------------------------------------------------------------------===//
2863c076559aSPavel Labath 
2864c076559aSPavel Labath void
2865337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
2866c076559aSPavel Labath {
28675eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2868c076559aSPavel Labath 
28695eb721edSPavel Labath     if (log)
2870c076559aSPavel Labath     {
28715eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
2872c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
2873c076559aSPavel Labath     }
2874c076559aSPavel Labath 
28750e1d729bSPavel Labath     m_pending_notification_tid = triggering_tid;
28760e1d729bSPavel Labath 
28770e1d729bSPavel Labath     // Request a stop for all the thread stops that need to be stopped
28780e1d729bSPavel Labath     // and are not already known to be stopped.
28790e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
28800e1d729bSPavel Labath     {
28810e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
28820e1d729bSPavel Labath             static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
28830e1d729bSPavel Labath     }
28840e1d729bSPavel Labath 
28850e1d729bSPavel Labath     SignalIfAllThreadsStopped();
2886c076559aSPavel Labath 
28875eb721edSPavel Labath     if (log)
2888c076559aSPavel Labath     {
28895eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2890c076559aSPavel Labath     }
2891c076559aSPavel Labath }
2892c076559aSPavel Labath 
2893c076559aSPavel Labath void
28949eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
2895c076559aSPavel Labath {
28960e1d729bSPavel Labath     if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
28970e1d729bSPavel Labath         return; // No pending notification. Nothing to do.
28980e1d729bSPavel Labath 
28990e1d729bSPavel Labath     for (const auto &thread_sp: m_threads)
2900c076559aSPavel Labath     {
29010e1d729bSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
29020e1d729bSPavel Labath             return; // Some threads are still running. Don't signal yet.
29030e1d729bSPavel Labath     }
29040e1d729bSPavel Labath 
29050e1d729bSPavel Labath     // We have a pending notification and all threads have stopped.
29069eb1ecb9SPavel Labath     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
29079eb1ecb9SPavel Labath 
29089eb1ecb9SPavel Labath     // Clear any temporary breakpoints we used to implement software single stepping.
29099eb1ecb9SPavel Labath     for (const auto &thread_info: m_threads_stepping_with_breakpoint)
29109eb1ecb9SPavel Labath     {
29119eb1ecb9SPavel Labath         Error error = RemoveBreakpoint (thread_info.second);
29129eb1ecb9SPavel Labath         if (error.Fail())
29139eb1ecb9SPavel Labath             if (log)
29149eb1ecb9SPavel Labath                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
29159eb1ecb9SPavel Labath                         __FUNCTION__, thread_info.first, error.AsCString());
29169eb1ecb9SPavel Labath     }
29179eb1ecb9SPavel Labath     m_threads_stepping_with_breakpoint.clear();
29189eb1ecb9SPavel Labath 
29199eb1ecb9SPavel Labath     // Notify the delegate about the stop
29200e1d729bSPavel Labath     SetCurrentThreadID(m_pending_notification_tid);
2921ed89c7feSPavel Labath     SetState(StateType::eStateStopped, true);
29220e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2923c076559aSPavel Labath }
2924c076559aSPavel Labath 
2925c076559aSPavel Labath void
2926f9077782SPavel Labath NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
2927c076559aSPavel Labath {
29281dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
29291dbc6c9cSPavel Labath 
29301dbc6c9cSPavel Labath     if (log)
2931f9077782SPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
29321dbc6c9cSPavel Labath 
2933f9077782SPavel Labath     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
2934c076559aSPavel Labath     {
2935c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
2936c076559aSPavel Labath         // notification.
2937f9077782SPavel Labath         thread.RequestStop();
2938c076559aSPavel Labath     }
2939c076559aSPavel Labath }
2940068f8a7eSTamas Berghammer 
294119cbe96aSPavel Labath void
294219cbe96aSPavel Labath NativeProcessLinux::SigchldHandler()
2943068f8a7eSTamas Berghammer {
294419cbe96aSPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
294519cbe96aSPavel Labath     // Process all pending waitpid notifications.
294619cbe96aSPavel Labath     while (true)
294719cbe96aSPavel Labath     {
294819cbe96aSPavel Labath         int status = -1;
294919cbe96aSPavel Labath         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
295019cbe96aSPavel Labath 
295119cbe96aSPavel Labath         if (wait_pid == 0)
295219cbe96aSPavel Labath             break; // We are done.
295319cbe96aSPavel Labath 
295419cbe96aSPavel Labath         if (wait_pid == -1)
295519cbe96aSPavel Labath         {
295619cbe96aSPavel Labath             if (errno == EINTR)
295719cbe96aSPavel Labath                 continue;
295819cbe96aSPavel Labath 
295919cbe96aSPavel Labath             Error error(errno, eErrorTypePOSIX);
296019cbe96aSPavel Labath             if (log)
296119cbe96aSPavel Labath                 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
296219cbe96aSPavel Labath                         __FUNCTION__, error.AsCString());
296319cbe96aSPavel Labath             break;
296419cbe96aSPavel Labath         }
296519cbe96aSPavel Labath 
296619cbe96aSPavel Labath         bool exited = false;
296719cbe96aSPavel Labath         int signal = 0;
296819cbe96aSPavel Labath         int exit_status = 0;
296919cbe96aSPavel Labath         const char *status_cstr = nullptr;
297019cbe96aSPavel Labath         if (WIFSTOPPED(status))
297119cbe96aSPavel Labath         {
297219cbe96aSPavel Labath             signal = WSTOPSIG(status);
297319cbe96aSPavel Labath             status_cstr = "STOPPED";
297419cbe96aSPavel Labath         }
297519cbe96aSPavel Labath         else if (WIFEXITED(status))
297619cbe96aSPavel Labath         {
297719cbe96aSPavel Labath             exit_status = WEXITSTATUS(status);
297819cbe96aSPavel Labath             status_cstr = "EXITED";
297919cbe96aSPavel Labath             exited = true;
298019cbe96aSPavel Labath         }
298119cbe96aSPavel Labath         else if (WIFSIGNALED(status))
298219cbe96aSPavel Labath         {
298319cbe96aSPavel Labath             signal = WTERMSIG(status);
298419cbe96aSPavel Labath             status_cstr = "SIGNALED";
298519cbe96aSPavel Labath             if (wait_pid == static_cast< ::pid_t>(GetID())) {
298619cbe96aSPavel Labath                 exited = true;
298719cbe96aSPavel Labath                 exit_status = -1;
298819cbe96aSPavel Labath             }
298919cbe96aSPavel Labath         }
299019cbe96aSPavel Labath         else
299119cbe96aSPavel Labath             status_cstr = "(\?\?\?)";
299219cbe96aSPavel Labath 
299319cbe96aSPavel Labath         if (log)
299419cbe96aSPavel Labath             log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
299519cbe96aSPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
299619cbe96aSPavel Labath                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
299719cbe96aSPavel Labath 
299819cbe96aSPavel Labath         MonitorCallback (wait_pid, exited, signal, exit_status);
299919cbe96aSPavel Labath     }
3000068f8a7eSTamas Berghammer }
3001068f8a7eSTamas Berghammer 
3002068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
3003068f8a7eSTamas Berghammer // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
30044a9babb2SPavel Labath Error
30054a9babb2SPavel Labath NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
3006068f8a7eSTamas Berghammer {
30074a9babb2SPavel Labath     Error error;
30084a9babb2SPavel Labath     long int ret;
3009068f8a7eSTamas Berghammer 
3010068f8a7eSTamas Berghammer     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3011068f8a7eSTamas Berghammer 
3012068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3013068f8a7eSTamas Berghammer 
3014068f8a7eSTamas Berghammer     errno = 0;
3015068f8a7eSTamas Berghammer     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
30164a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3017068f8a7eSTamas Berghammer     else
30184a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3019068f8a7eSTamas Berghammer 
30204a9babb2SPavel Labath     if (ret == -1)
3021068f8a7eSTamas Berghammer         error.SetErrorToErrno();
3022068f8a7eSTamas Berghammer 
30234a9babb2SPavel Labath     if (result)
30244a9babb2SPavel Labath         *result = ret;
30254a9babb2SPavel Labath 
3026068f8a7eSTamas Berghammer     if (log)
30274a9babb2SPavel Labath         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
3028068f8a7eSTamas Berghammer 
3029068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3030068f8a7eSTamas Berghammer 
3031068f8a7eSTamas Berghammer     if (log && error.GetError() != 0)
3032068f8a7eSTamas Berghammer     {
3033068f8a7eSTamas Berghammer         const char* str;
3034068f8a7eSTamas Berghammer         switch (error.GetError())
3035068f8a7eSTamas Berghammer         {
3036068f8a7eSTamas Berghammer         case ESRCH:  str = "ESRCH"; break;
3037068f8a7eSTamas Berghammer         case EINVAL: str = "EINVAL"; break;
3038068f8a7eSTamas Berghammer         case EBUSY:  str = "EBUSY"; break;
3039068f8a7eSTamas Berghammer         case EPERM:  str = "EPERM"; break;
3040068f8a7eSTamas Berghammer         default:     str = error.AsCString();
3041068f8a7eSTamas Berghammer         }
3042068f8a7eSTamas Berghammer         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3043068f8a7eSTamas Berghammer     }
3044068f8a7eSTamas Berghammer 
30454a9babb2SPavel Labath     return error;
3046068f8a7eSTamas Berghammer }
3047