blob: 56cf400789239b2dd966f968b311f31b5e023f0f [file] [log] [blame]
Johnny Chen2341d352012-01-05 21:48:15 +00001//===-- ProcessPOSIX.cpp ----------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Johnny Chen2341d352012-01-05 21:48:15 +000012// C Includes
13#include <errno.h>
14
15// C++ Includes
16// Other libraries and framework includes
Greg Clayton8ac035d2012-09-04 14:55:50 +000017#include "lldb/Core/Module.h"
Johnny Chen2341d352012-01-05 21:48:15 +000018#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/State.h"
20#include "lldb/Host/Host.h"
21#include "lldb/Symbol/ObjectFile.h"
22#include "lldb/Target/DynamicLoader.h"
23#include "lldb/Target/Target.h"
24
25#include "ProcessPOSIX.h"
26#include "ProcessPOSIXLog.h"
27#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
28#include "ProcessMonitor.h"
29#include "POSIXThread.h"
30
31using namespace lldb;
32using namespace lldb_private;
33
34//------------------------------------------------------------------------------
35// Static functions.
36#if 0
37Process*
38ProcessPOSIX::CreateInstance(Target& target, Listener &listener)
39{
40 return new ProcessPOSIX(target, listener);
41}
42
43
44void
45ProcessPOSIX::Initialize()
46{
47 static bool g_initialized = false;
48
49 if (!g_initialized)
50 {
51 g_initialized = true;
52 PluginManager::RegisterPlugin(GetPluginNameStatic(),
53 GetPluginDescriptionStatic(),
54 CreateInstance);
55
56 Log::Callbacks log_callbacks = {
57 ProcessPOSIXLog::DisableLog,
58 ProcessPOSIXLog::EnableLog,
59 ProcessPOSIXLog::ListLogCategories
60 };
61
62 Log::RegisterLogChannel (ProcessPOSIX::GetPluginNameStatic(), log_callbacks);
63 }
64}
65#endif
66
67//------------------------------------------------------------------------------
68// Constructors and destructors.
69
70ProcessPOSIX::ProcessPOSIX(Target& target, Listener &listener)
71 : Process(target, listener),
Johnny Chen78dae822012-04-14 00:54:42 +000072 m_byte_order(lldb::endian::InlHostByteOrder()),
Johnny Chen2341d352012-01-05 21:48:15 +000073 m_monitor(NULL),
74 m_module(NULL),
75 m_in_limbo(false),
76 m_exit_now(false)
77{
78 // FIXME: Putting this code in the ctor and saving the byte order in a
79 // member variable is a hack to avoid const qual issues in GetByteOrder.
Johnny Chen78dae822012-04-14 00:54:42 +000080 lldb::ModuleSP module = GetTarget().GetExecutableModule();
81 if (module != NULL && module->GetObjectFile() != NULL)
82 m_byte_order = module->GetObjectFile()->GetByteOrder();
Johnny Chen2341d352012-01-05 21:48:15 +000083}
84
85ProcessPOSIX::~ProcessPOSIX()
86{
87 delete m_monitor;
88}
89
90//------------------------------------------------------------------------------
91// Process protocol.
92
93bool
94ProcessPOSIX::CanDebug(Target &target, bool plugin_specified_by_name)
95{
96 // For now we are just making sure the file exists for a given module
97 ModuleSP exe_module_sp(target.GetExecutableModule());
98 if (exe_module_sp.get())
99 return exe_module_sp->GetFileSpec().Exists();
100 return false;
101}
102
103Error
104ProcessPOSIX::DoAttachToProcessWithID(lldb::pid_t pid)
105{
106 Error error;
107 assert(m_monitor == NULL);
108
109 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
110 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000111 log->Printf ("ProcessPOSIX::%s(pid = %" PRIi64 ")", __FUNCTION__, GetID());
Johnny Chen2341d352012-01-05 21:48:15 +0000112
113 m_monitor = new ProcessMonitor(this, pid, error);
114
115 if (!error.Success())
116 return error;
117
118 SetID(pid);
119 return error;
120}
121
122Error
Greg Claytonc6430772012-09-07 17:51:47 +0000123ProcessPOSIX::DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info)
124{
125 return DoAttachToProcessWithID(pid);
126}
127
128Error
Johnny Chen2341d352012-01-05 21:48:15 +0000129ProcessPOSIX::WillLaunch(Module* module)
130{
131 Error error;
132 return error;
133}
134
135const char *
136ProcessPOSIX::GetFilePath(
137 const lldb_private::ProcessLaunchInfo::FileAction *file_action,
138 const char *default_path)
139{
140 const char *pts_name = "/dev/pts/";
141 const char *path = NULL;
142
143 if (file_action)
144 {
145 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
146 path = file_action->GetPath();
147 // By default the stdio paths passed in will be pseudo-terminal
148 // (/dev/pts). If so, convert to using a different default path
149 // instead to redirect I/O to the debugger console. This should
150 // also handle user overrides to /dev/null or a different file.
151 if (::strncmp(path, pts_name, ::strlen(pts_name)) == 0)
152 path = default_path;
153 }
154
155 return path;
156}
157
158Error
159ProcessPOSIX::DoLaunch (Module *module,
160 const ProcessLaunchInfo &launch_info)
161{
162 Error error;
163 assert(m_monitor == NULL);
164
165 SetPrivateState(eStateLaunching);
166
167 const lldb_private::ProcessLaunchInfo::FileAction *file_action;
168
169 // Default of NULL will mean to use existing open file descriptors
170 const char *stdin_path = NULL;
171 const char *stdout_path = NULL;
172 const char *stderr_path = NULL;
173
174 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
175 stdin_path = GetFilePath(file_action, stdin_path);
176
177 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
178 stdout_path = GetFilePath(file_action, stdout_path);
179
180 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
181 stderr_path = GetFilePath(file_action, stderr_path);
182
183 m_monitor = new ProcessMonitor (this,
184 module,
185 launch_info.GetArguments().GetConstArgumentVector(),
186 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
187 stdin_path,
188 stdout_path,
189 stderr_path,
190 error);
191
192 m_module = module;
193
194 if (!error.Success())
195 return error;
196
197 SetID(m_monitor->GetPID());
198 return error;
199}
200
201void
202ProcessPOSIX::DidLaunch()
203{
204}
205
206Error
207ProcessPOSIX::DoResume()
208{
209 StateType state = GetPrivateState();
210
211 assert(state == eStateStopped || state == eStateCrashed);
212
213 // We are about to resume a thread that will cause the process to exit so
214 // set our exit status now. Do not change our state if the inferior
215 // crashed.
216 if (state == eStateStopped)
217 {
218 if (m_in_limbo)
219 SetExitStatus(m_exit_status, NULL);
220 else
221 SetPrivateState(eStateRunning);
222 }
223
224 bool did_resume = false;
225 uint32_t thread_count = m_thread_list.GetSize(false);
226 for (uint32_t i = 0; i < thread_count; ++i)
227 {
228 POSIXThread *thread = static_cast<POSIXThread*>(
229 m_thread_list.GetThreadAtIndex(i, false).get());
230 did_resume = thread->Resume() || did_resume;
231 }
232 assert(did_resume && "Process resume failed!");
233
234 return Error();
235}
236
237addr_t
238ProcessPOSIX::GetImageInfoAddress()
239{
240 Target *target = &GetTarget();
241 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
242 Address addr = obj_file->GetImageInfoAddress();
243
244 if (addr.IsValid())
245 return addr.GetLoadAddress(target);
246 else
247 return LLDB_INVALID_ADDRESS;
248}
249
250Error
251ProcessPOSIX::DoHalt(bool &caused_stop)
252{
253 Error error;
254
255 if (IsStopped())
256 {
257 caused_stop = false;
258 }
259 else if (kill(GetID(), SIGSTOP))
260 {
261 caused_stop = false;
262 error.SetErrorToErrno();
263 }
264 else
265 {
266 caused_stop = true;
267 }
268
269 return error;
270}
271
272Error
273ProcessPOSIX::DoDetach()
274{
275 Error error;
276
277 error = m_monitor->Detach();
278 if (error.Success())
279 SetPrivateState(eStateDetached);
280
281 return error;
282}
283
284Error
285ProcessPOSIX::DoSignal(int signal)
286{
287 Error error;
288
289 if (kill(GetID(), signal))
290 error.SetErrorToErrno();
291
292 return error;
293}
294
295Error
296ProcessPOSIX::DoDestroy()
297{
298 Error error;
299
300 if (!HasExited())
301 {
302 // Drive the exit event to completion (do not keep the inferior in
303 // limbo).
304 m_exit_now = true;
305
Greg Clayton972c4382012-03-30 19:56:32 +0000306 if ((m_monitor == NULL || kill(m_monitor->GetPID(), SIGKILL)) && error.Success())
Johnny Chen2341d352012-01-05 21:48:15 +0000307 {
308 error.SetErrorToErrno();
309 return error;
310 }
311
312 SetPrivateState(eStateExited);
313 }
314
315 return error;
316}
317
318void
319ProcessPOSIX::SendMessage(const ProcessMessage &message)
320{
321 Mutex::Locker lock(m_message_mutex);
322
323 switch (message.GetKind())
324 {
325 default:
326 assert(false && "Unexpected process message!");
327 break;
328
329 case ProcessMessage::eInvalidMessage:
330 return;
331
332 case ProcessMessage::eLimboMessage:
333 m_in_limbo = true;
334 m_exit_status = message.GetExitStatus();
335 if (m_exit_now)
336 {
337 SetPrivateState(eStateExited);
338 m_monitor->Detach();
339 }
340 else
341 SetPrivateState(eStateStopped);
342 break;
343
344 case ProcessMessage::eExitMessage:
345 m_exit_status = message.GetExitStatus();
346 SetExitStatus(m_exit_status, NULL);
347 break;
348
349 case ProcessMessage::eTraceMessage:
350 case ProcessMessage::eBreakpointMessage:
351 SetPrivateState(eStateStopped);
352 break;
353
354 case ProcessMessage::eSignalMessage:
355 case ProcessMessage::eSignalDeliveredMessage:
356 SetPrivateState(eStateStopped);
357 break;
358
359 case ProcessMessage::eCrashMessage:
360 SetPrivateState(eStateCrashed);
361 break;
362 }
363
364 m_message_queue.push(message);
365}
366
367void
368ProcessPOSIX::RefreshStateAfterStop()
369{
370 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
371 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
372 log->Printf ("ProcessPOSIX::%s()", __FUNCTION__);
373
374 Mutex::Locker lock(m_message_mutex);
375 if (m_message_queue.empty())
376 return;
377
378 ProcessMessage &message = m_message_queue.front();
379
380 // Resolve the thread this message corresponds to and pass it along.
381 // FIXME: we're really dealing with the pid here. This should get
382 // fixed when this code is fixed to handle multiple threads.
383 lldb::tid_t tid = message.GetTID();
384 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000385 log->Printf ("ProcessPOSIX::%s() pid = %" PRIi64, __FUNCTION__, tid);
Johnny Chen2341d352012-01-05 21:48:15 +0000386 POSIXThread *thread = static_cast<POSIXThread*>(
387 GetThreadList().FindThreadByID(tid, false).get());
388
389 assert(thread);
390 thread->Notify(message);
391
392 m_message_queue.pop();
393}
394
395bool
396ProcessPOSIX::IsAlive()
397{
398 StateType state = GetPrivateState();
399 return state != eStateDetached && state != eStateExited && state != eStateInvalid;
400}
401
402size_t
403ProcessPOSIX::DoReadMemory(addr_t vm_addr,
404 void *buf, size_t size, Error &error)
405{
406 assert(m_monitor);
407 return m_monitor->ReadMemory(vm_addr, buf, size, error);
408}
409
410size_t
411ProcessPOSIX::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size,
412 Error &error)
413{
414 assert(m_monitor);
415 return m_monitor->WriteMemory(vm_addr, buf, size, error);
416}
417
418addr_t
419ProcessPOSIX::DoAllocateMemory(size_t size, uint32_t permissions,
420 Error &error)
421{
422 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
423
424 unsigned prot = 0;
425 if (permissions & lldb::ePermissionsReadable)
426 prot |= eMmapProtRead;
427 if (permissions & lldb::ePermissionsWritable)
428 prot |= eMmapProtWrite;
429 if (permissions & lldb::ePermissionsExecutable)
430 prot |= eMmapProtExec;
431
432 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
433 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
434 m_addr_to_mmap_size[allocated_addr] = size;
435 error.Clear();
436 } else {
437 allocated_addr = LLDB_INVALID_ADDRESS;
438 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
439 }
440
441 return allocated_addr;
442}
443
444Error
445ProcessPOSIX::DoDeallocateMemory(lldb::addr_t addr)
446{
447 Error error;
448 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
449 if (pos != m_addr_to_mmap_size.end() &&
450 InferiorCallMunmap(this, addr, pos->second))
451 m_addr_to_mmap_size.erase (pos);
452 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000453 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Johnny Chen2341d352012-01-05 21:48:15 +0000454
455 return error;
456}
457
458size_t
459ProcessPOSIX::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site)
460{
461 static const uint8_t g_i386_opcode[] = { 0xCC };
462
463 ArchSpec arch = GetTarget().GetArchitecture();
464 const uint8_t *opcode = NULL;
465 size_t opcode_size = 0;
466
467 switch (arch.GetCore())
468 {
469 default:
470 assert(false && "CPU type not supported!");
471 break;
472
473 case ArchSpec::eCore_x86_32_i386:
474 case ArchSpec::eCore_x86_64_x86_64:
475 opcode = g_i386_opcode;
476 opcode_size = sizeof(g_i386_opcode);
477 break;
478 }
479
480 bp_site->SetTrapOpcode(opcode, opcode_size);
481 return opcode_size;
482}
483
484Error
485ProcessPOSIX::EnableBreakpoint(BreakpointSite *bp_site)
486{
487 return EnableSoftwareBreakpoint(bp_site);
488}
489
490Error
491ProcessPOSIX::DisableBreakpoint(BreakpointSite *bp_site)
492{
493 return DisableSoftwareBreakpoint(bp_site);
494}
495
496uint32_t
497ProcessPOSIX::UpdateThreadListIfNeeded()
498{
499 // Do not allow recursive updates.
500 return m_thread_list.GetSize(false);
501}
502
Greg Claytonc8dd5702012-04-12 19:04:34 +0000503bool
Johnny Chen2341d352012-01-05 21:48:15 +0000504ProcessPOSIX::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
505{
506 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
507 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000508 log->Printf ("ProcessPOSIX::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
Johnny Chen2341d352012-01-05 21:48:15 +0000509
510 // Update the process thread list with this new thread.
511 // FIXME: We should be using tid, not pid.
512 assert(m_monitor);
513 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
Greg Claytone5eaa302012-02-21 18:40:07 +0000514 if (!thread_sp) {
Greg Clayton5e91e372012-10-12 16:23:23 +0000515 thread_sp.reset(new POSIXThread(*this, GetID()));
Greg Claytone5eaa302012-02-21 18:40:07 +0000516 }
Johnny Chen2341d352012-01-05 21:48:15 +0000517
518 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000519 log->Printf ("ProcessPOSIX::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
Johnny Chen2341d352012-01-05 21:48:15 +0000520 new_thread_list.AddThread(thread_sp);
521
Greg Claytonc8dd5702012-04-12 19:04:34 +0000522 return new_thread_list.GetSize(false) > 0;
Johnny Chen2341d352012-01-05 21:48:15 +0000523}
524
525ByteOrder
526ProcessPOSIX::GetByteOrder() const
527{
528 // FIXME: We should be able to extract this value directly. See comment in
529 // ProcessPOSIX().
530 return m_byte_order;
531}
532
533size_t
534ProcessPOSIX::PutSTDIN(const char *buf, size_t len, Error &error)
535{
536 ssize_t status;
537 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0)
538 {
539 error.SetErrorToErrno();
540 return 0;
541 }
542 return status;
543}
544
545size_t
546ProcessPOSIX::GetSTDOUT(char *buf, size_t len, Error &error)
547{
548 ssize_t bytes_read;
549
550 // The terminal file descriptor is always in non-block mode.
551 if ((bytes_read = read(m_monitor->GetTerminalFD(), buf, len)) < 0)
552 {
553 if (errno != EAGAIN)
554 error.SetErrorToErrno();
555 return 0;
556 }
557 return bytes_read;
558}
559
560size_t
561ProcessPOSIX::GetSTDERR(char *buf, size_t len, Error &error)
562{
563 return GetSTDOUT(buf, len, error);
564}
565
566UnixSignals &
567ProcessPOSIX::GetUnixSignals()
568{
569 return m_signals;
570}
571
572//------------------------------------------------------------------------------
573// Utility functions.
574
575bool
576ProcessPOSIX::HasExited()
577{
578 switch (GetPrivateState())
579 {
580 default:
581 break;
582
583 case eStateDetached:
584 case eStateExited:
585 return true;
586 }
587
588 return false;
589}
590
591bool
592ProcessPOSIX::IsStopped()
593{
594 switch (GetPrivateState())
595 {
596 default:
597 break;
598
599 case eStateStopped:
600 case eStateCrashed:
601 case eStateSuspended:
602 return true;
603 }
604
605 return false;
606}