blob: 8001db20a72ca056abb9ac012bc08ae5ba4ef196 [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 {
Johnny Chen2341d352012-01-05 21:48:15 +0000325 case ProcessMessage::eInvalidMessage:
326 return;
327
328 case ProcessMessage::eLimboMessage:
329 m_in_limbo = true;
330 m_exit_status = message.GetExitStatus();
331 if (m_exit_now)
332 {
333 SetPrivateState(eStateExited);
334 m_monitor->Detach();
335 }
336 else
337 SetPrivateState(eStateStopped);
338 break;
339
340 case ProcessMessage::eExitMessage:
341 m_exit_status = message.GetExitStatus();
342 SetExitStatus(m_exit_status, NULL);
343 break;
344
345 case ProcessMessage::eTraceMessage:
346 case ProcessMessage::eBreakpointMessage:
347 SetPrivateState(eStateStopped);
348 break;
349
350 case ProcessMessage::eSignalMessage:
351 case ProcessMessage::eSignalDeliveredMessage:
352 SetPrivateState(eStateStopped);
353 break;
354
355 case ProcessMessage::eCrashMessage:
356 SetPrivateState(eStateCrashed);
357 break;
358 }
359
360 m_message_queue.push(message);
361}
362
363void
364ProcessPOSIX::RefreshStateAfterStop()
365{
366 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
367 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
368 log->Printf ("ProcessPOSIX::%s()", __FUNCTION__);
369
370 Mutex::Locker lock(m_message_mutex);
371 if (m_message_queue.empty())
372 return;
373
374 ProcessMessage &message = m_message_queue.front();
375
376 // Resolve the thread this message corresponds to and pass it along.
377 // FIXME: we're really dealing with the pid here. This should get
378 // fixed when this code is fixed to handle multiple threads.
379 lldb::tid_t tid = message.GetTID();
380 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000381 log->Printf ("ProcessPOSIX::%s() pid = %" PRIi64, __FUNCTION__, tid);
Johnny Chen2341d352012-01-05 21:48:15 +0000382 POSIXThread *thread = static_cast<POSIXThread*>(
383 GetThreadList().FindThreadByID(tid, false).get());
384
385 assert(thread);
386 thread->Notify(message);
387
388 m_message_queue.pop();
389}
390
391bool
392ProcessPOSIX::IsAlive()
393{
394 StateType state = GetPrivateState();
395 return state != eStateDetached && state != eStateExited && state != eStateInvalid;
396}
397
398size_t
399ProcessPOSIX::DoReadMemory(addr_t vm_addr,
400 void *buf, size_t size, Error &error)
401{
402 assert(m_monitor);
403 return m_monitor->ReadMemory(vm_addr, buf, size, error);
404}
405
406size_t
407ProcessPOSIX::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size,
408 Error &error)
409{
410 assert(m_monitor);
411 return m_monitor->WriteMemory(vm_addr, buf, size, error);
412}
413
414addr_t
415ProcessPOSIX::DoAllocateMemory(size_t size, uint32_t permissions,
416 Error &error)
417{
418 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
419
420 unsigned prot = 0;
421 if (permissions & lldb::ePermissionsReadable)
422 prot |= eMmapProtRead;
423 if (permissions & lldb::ePermissionsWritable)
424 prot |= eMmapProtWrite;
425 if (permissions & lldb::ePermissionsExecutable)
426 prot |= eMmapProtExec;
427
428 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
429 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
430 m_addr_to_mmap_size[allocated_addr] = size;
431 error.Clear();
432 } else {
433 allocated_addr = LLDB_INVALID_ADDRESS;
434 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
435 }
436
437 return allocated_addr;
438}
439
440Error
441ProcessPOSIX::DoDeallocateMemory(lldb::addr_t addr)
442{
443 Error error;
444 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
445 if (pos != m_addr_to_mmap_size.end() &&
446 InferiorCallMunmap(this, addr, pos->second))
447 m_addr_to_mmap_size.erase (pos);
448 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000449 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Johnny Chen2341d352012-01-05 21:48:15 +0000450
451 return error;
452}
453
454size_t
455ProcessPOSIX::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site)
456{
457 static const uint8_t g_i386_opcode[] = { 0xCC };
458
459 ArchSpec arch = GetTarget().GetArchitecture();
460 const uint8_t *opcode = NULL;
461 size_t opcode_size = 0;
462
463 switch (arch.GetCore())
464 {
465 default:
466 assert(false && "CPU type not supported!");
467 break;
468
469 case ArchSpec::eCore_x86_32_i386:
470 case ArchSpec::eCore_x86_64_x86_64:
471 opcode = g_i386_opcode;
472 opcode_size = sizeof(g_i386_opcode);
473 break;
474 }
475
476 bp_site->SetTrapOpcode(opcode, opcode_size);
477 return opcode_size;
478}
479
480Error
481ProcessPOSIX::EnableBreakpoint(BreakpointSite *bp_site)
482{
483 return EnableSoftwareBreakpoint(bp_site);
484}
485
486Error
487ProcessPOSIX::DisableBreakpoint(BreakpointSite *bp_site)
488{
489 return DisableSoftwareBreakpoint(bp_site);
490}
491
492uint32_t
493ProcessPOSIX::UpdateThreadListIfNeeded()
494{
495 // Do not allow recursive updates.
496 return m_thread_list.GetSize(false);
497}
498
Greg Claytonc8dd5702012-04-12 19:04:34 +0000499bool
Johnny Chen2341d352012-01-05 21:48:15 +0000500ProcessPOSIX::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
501{
502 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
503 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000504 log->Printf ("ProcessPOSIX::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
Johnny Chen2341d352012-01-05 21:48:15 +0000505
506 // Update the process thread list with this new thread.
507 // FIXME: We should be using tid, not pid.
508 assert(m_monitor);
509 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
Greg Claytone5eaa302012-02-21 18:40:07 +0000510 if (!thread_sp) {
Greg Clayton5e91e372012-10-12 16:23:23 +0000511 thread_sp.reset(new POSIXThread(*this, GetID()));
Greg Claytone5eaa302012-02-21 18:40:07 +0000512 }
Johnny Chen2341d352012-01-05 21:48:15 +0000513
514 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000515 log->Printf ("ProcessPOSIX::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
Johnny Chen2341d352012-01-05 21:48:15 +0000516 new_thread_list.AddThread(thread_sp);
517
Greg Claytonc8dd5702012-04-12 19:04:34 +0000518 return new_thread_list.GetSize(false) > 0;
Johnny Chen2341d352012-01-05 21:48:15 +0000519}
520
521ByteOrder
522ProcessPOSIX::GetByteOrder() const
523{
524 // FIXME: We should be able to extract this value directly. See comment in
525 // ProcessPOSIX().
526 return m_byte_order;
527}
528
529size_t
530ProcessPOSIX::PutSTDIN(const char *buf, size_t len, Error &error)
531{
532 ssize_t status;
533 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0)
534 {
535 error.SetErrorToErrno();
536 return 0;
537 }
538 return status;
539}
540
541size_t
542ProcessPOSIX::GetSTDOUT(char *buf, size_t len, Error &error)
543{
544 ssize_t bytes_read;
545
546 // The terminal file descriptor is always in non-block mode.
547 if ((bytes_read = read(m_monitor->GetTerminalFD(), buf, len)) < 0)
548 {
549 if (errno != EAGAIN)
550 error.SetErrorToErrno();
551 return 0;
552 }
553 return bytes_read;
554}
555
556size_t
557ProcessPOSIX::GetSTDERR(char *buf, size_t len, Error &error)
558{
559 return GetSTDOUT(buf, len, error);
560}
561
562UnixSignals &
563ProcessPOSIX::GetUnixSignals()
564{
565 return m_signals;
566}
567
568//------------------------------------------------------------------------------
569// Utility functions.
570
571bool
572ProcessPOSIX::HasExited()
573{
574 switch (GetPrivateState())
575 {
576 default:
577 break;
578
579 case eStateDetached:
580 case eStateExited:
581 return true;
582 }
583
584 return false;
585}
586
587bool
588ProcessPOSIX::IsStopped()
589{
590 switch (GetPrivateState())
591 {
592 default:
593 break;
594
595 case eStateStopped:
596 case eStateCrashed:
597 case eStateSuspended:
598 return true;
599 }
600
601 return false;
602}