1 //===-- MICmdCmdTarget.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 
10 // Overview:    CMICmdCmdTargetSelect           implementation.
11 
12 // Third Party Headers:
13 #include "lldb/API/SBStream.h"
14 #include "lldb/API/SBCommandInterpreter.h"
15 #include "lldb/API/SBCommandReturnObject.h"
16 
17 // In-house headers:
18 #include "MICmdCmdTarget.h"
19 #include "MICmnMIResultRecord.h"
20 #include "MICmnMIValueConst.h"
21 #include "MICmnMIOutOfBandRecord.h"
22 #include "MICmnLLDBDebugger.h"
23 #include "MICmnLLDBDebugSessionInfo.h"
24 #include "MICmdArgValString.h"
25 #include "MICmdArgValOptionLong.h"
26 #include "MICmdArgValOptionShort.h"
27 #include "MICmdArgValNumber.h"
28 
29 //++ ------------------------------------------------------------------------------------
30 // Details: CMICmdCmdTargetSelect constructor.
31 // Type:    Method.
32 // Args:    None.
33 // Return:  None.
34 // Throws:  None.
35 //--
36 CMICmdCmdTargetSelect::CMICmdCmdTargetSelect()
37     : m_constStrArgNamedType("type")
38     , m_constStrArgNamedParameters("parameters")
39 {
40     // Command factory matches this name with that received from the stdin stream
41     m_strMiCmd = "target-select";
42 
43     // Required by the CMICmdFactory when registering *this command
44     m_pSelfCreatorFn = &CMICmdCmdTargetSelect::CreateSelf;
45 }
46 
47 //++ ------------------------------------------------------------------------------------
48 // Details: CMICmdCmdTargetSelect destructor.
49 // Type:    Overrideable.
50 // Args:    None.
51 // Return:  None.
52 // Throws:  None.
53 //--
54 CMICmdCmdTargetSelect::~CMICmdCmdTargetSelect()
55 {
56 }
57 
58 //++ ------------------------------------------------------------------------------------
59 // Details: The invoker requires this function. The parses the command line options
60 //          arguments to extract values for each of those arguments.
61 // Type:    Overridden.
62 // Args:    None.
63 // Return:  MIstatus::success - Functional succeeded.
64 //          MIstatus::failure - Functional failed.
65 // Throws:  None.
66 //--
67 bool
68 CMICmdCmdTargetSelect::ParseArgs()
69 {
70     m_setCmdArgs.Add(new CMICmdArgValString(m_constStrArgNamedType, true, true));
71     m_setCmdArgs.Add(new CMICmdArgValString(m_constStrArgNamedParameters, true, true));
72     return ParseValidateCmdOptions();
73 }
74 
75 //++ ------------------------------------------------------------------------------------
76 // Details: The invoker requires this function. The command does work in this function.
77 //          The command is likely to communicate with the LLDB SBDebugger in here.
78 //          Synopsis: -target-select type parameters ...
79 //          Ref: http://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Target-Manipulation.html#GDB_002fMI-Target-Manipulation
80 // Type:    Overridden.
81 // Args:    None.
82 // Return:  MIstatus::success - Functional succeeded.
83 //          MIstatus::failure - Functional failed.
84 // Throws:  None.
85 //--
86 bool
87 CMICmdCmdTargetSelect::Execute()
88 {
89     CMICMDBASE_GETOPTION(pArgType, String, m_constStrArgNamedType);
90     CMICMDBASE_GETOPTION(pArgParameters, String, m_constStrArgNamedParameters);
91 
92     CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
93 
94     // Check we have a valid target
95     // Note: target created via 'file-exec-and-symbols' command
96     if (!rSessionInfo.GetTarget().IsValid())
97     {
98         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_INVALID_TARGET_CURRENT), m_cmdData.strMiCmd.c_str()));
99         return MIstatus::failure;
100     }
101 
102     // Verify that we are executing remotely
103     const CMIUtilString &rRemoteType(pArgType->GetValue());
104     if (rRemoteType != "remote")
105     {
106         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_INVALID_TARGET_TYPE), m_cmdData.strMiCmd.c_str(), rRemoteType.c_str()));
107         return MIstatus::failure;
108     }
109 
110     // Create a URL pointing to the remote gdb stub
111     const CMIUtilString strUrl = CMIUtilString::Format("connect://%s", pArgParameters->GetValue().c_str());
112 
113     // Ask LLDB to collect to the target port
114     const char *pPlugin("gdb-remote");
115     lldb::SBError error;
116     lldb::SBProcess process = rSessionInfo.GetTarget().ConnectRemote(rSessionInfo.GetListener(), strUrl.c_str(), pPlugin, error);
117 
118     // Verify that we have managed to connect successfully
119     lldb::SBStream errMsg;
120     if (!process.IsValid())
121     {
122         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_INVALID_TARGET_PLUGIN), m_cmdData.strMiCmd.c_str(), errMsg.GetData()));
123         return MIstatus::failure;
124     }
125     if (error.Fail())
126     {
127         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_CONNECT_TO_TARGET), m_cmdData.strMiCmd.c_str(), errMsg.GetData()));
128         return MIstatus::failure;
129     }
130 
131     // Set the environment path if we were given one
132     CMIUtilString strWkDir;
133     if (rSessionInfo.SharedDataRetrieve<CMIUtilString>(rSessionInfo.m_constStrSharedDataKeyWkDir, strWkDir))
134     {
135         lldb::SBDebugger &rDbgr = rSessionInfo.GetDebugger();
136         if (!rDbgr.SetCurrentPlatformSDKRoot(strWkDir.c_str()))
137         {
138             SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_FNFAILED), m_cmdData.strMiCmd.c_str(), "target-select"));
139             return MIstatus::failure;
140         }
141     }
142 
143     // Set the shared object path if we were given one
144     CMIUtilString strSolibPath;
145     if (rSessionInfo.SharedDataRetrieve<CMIUtilString>(rSessionInfo.m_constStrSharedDataSolibPath, strSolibPath))
146     {
147         lldb::SBDebugger &rDbgr = rSessionInfo.GetDebugger();
148         lldb::SBCommandInterpreter cmdIterpreter = rDbgr.GetCommandInterpreter();
149 
150         CMIUtilString strCmdString = CMIUtilString::Format("target modules search-paths add . %s", strSolibPath.c_str());
151 
152         lldb::SBCommandReturnObject retObj;
153         cmdIterpreter.HandleCommand(strCmdString.c_str(), retObj, false);
154 
155         if (!retObj.Succeeded())
156         {
157             SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_FNFAILED), m_cmdData.strMiCmd.c_str(), "target-select"));
158             return MIstatus::failure;
159         }
160     }
161 
162     return MIstatus::success;
163 }
164 
165 //++ ------------------------------------------------------------------------------------
166 // Details: The invoker requires this function. The command prepares a MI Record Result
167 //          for the work carried out in the Execute().
168 // Type:    Overridden.
169 // Args:    None.
170 // Return:  MIstatus::success - Functional succeeded.
171 //          MIstatus::failure - Functional failed.
172 // Throws:  None.
173 //--
174 bool
175 CMICmdCmdTargetSelect::Acknowledge()
176 {
177     const CMICmnMIResultRecord miRecordResult(m_cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Connected);
178     m_miResultRecord = miRecordResult;
179 
180     CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
181     lldb::pid_t pid = rSessionInfo.GetProcess().GetProcessID();
182     // Prod the client i.e. Eclipse with out-of-band results to help it 'continue' because it is using LLDB debugger
183     // Give the client '=thread-group-started,id="i1"'
184     m_bHasResultRecordExtra = true;
185     const CMICmnMIValueConst miValueConst2("i1");
186     const CMICmnMIValueResult miValueResult2("id", miValueConst2);
187     const CMIUtilString strPid(CMIUtilString::Format("%lld", pid));
188     const CMICmnMIValueConst miValueConst(strPid);
189     const CMICmnMIValueResult miValueResult("pid", miValueConst);
190     CMICmnMIOutOfBandRecord miOutOfBand(CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted, miValueResult2);
191     miOutOfBand.Add(miValueResult);
192     m_miResultRecordExtra = miOutOfBand.GetString();
193 
194     return MIstatus::success;
195 }
196 
197 //++ ------------------------------------------------------------------------------------
198 // Details: Required by the CMICmdFactory when registering *this command. The factory
199 //          calls this function to create an instance of *this command.
200 // Type:    Static method.
201 // Args:    None.
202 // Return:  CMICmdBase * - Pointer to a new command.
203 // Throws:  None.
204 //--
205 CMICmdBase *
206 CMICmdCmdTargetSelect::CreateSelf()
207 {
208     return new CMICmdCmdTargetSelect();
209 }
210 
211 //++ ------------------------------------------------------------------------------------
212 // Details: CMICmdCmdTargetAttach constructor.
213 // Type:    Method.
214 // Args:    None.
215 // Return:  None.
216 // Throws:  None.
217 //--
218 CMICmdCmdTargetAttach::CMICmdCmdTargetAttach()
219 : m_constStrArgPid("pid")
220 , m_constStrArgNamedFile("n")
221 , m_constStrArgWaitFor("waitfor")
222 {
223     // Command factory matches this name with that received from the stdin stream
224     m_strMiCmd = "target-attach";
225 
226     // Required by the CMICmdFactory when registering *this command
227     m_pSelfCreatorFn = &CMICmdCmdTargetAttach::CreateSelf;
228 }
229 
230 //++ ------------------------------------------------------------------------------------
231 // Details: CMICmdCmdTargetAttach destructor.
232 // Type:    Overrideable.
233 // Args:    None.
234 // Return:  None.
235 // Throws:  None.
236 //--
237 CMICmdCmdTargetAttach::~CMICmdCmdTargetAttach()
238 {
239 }
240 
241 //++ ------------------------------------------------------------------------------------
242 // Details: The invoker requires this function. The parses the command line options
243 //          arguments to extract values for each of those arguments.
244 // Type:    Overridden.
245 // Args:    None.
246 // Return:  MIstatus::success - Functional succeeded.
247 //          MIstatus::failure - Functional failed.
248 // Throws:  None.
249 //--
250 bool
251 CMICmdCmdTargetAttach::ParseArgs()
252 {
253     m_setCmdArgs.Add(new CMICmdArgValNumber(m_constStrArgPid, false, true));
254     m_setCmdArgs.Add(new CMICmdArgValOptionShort(m_constStrArgNamedFile, false, true,
255                                                  CMICmdArgValListBase::eArgValType_String, 1));
256     m_setCmdArgs.Add(new CMICmdArgValOptionLong(m_constStrArgWaitFor, false, true));
257     return ParseValidateCmdOptions();
258 }
259 
260 //++ ------------------------------------------------------------------------------------
261 // Details: The invoker requires this function. The command does work in this function.
262 //          The command is likely to communicate with the LLDB SBDebugger in here.
263 //          Synopsis: -target-attach file
264 //          Ref: http://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Target-Manipulation.html#GDB_002fMI-Target-Manipulation
265 // Type:    Overridden.
266 // Args:    None.
267 // Return:  MIstatus::success - Functional succeeded.
268 //          MIstatus::failure - Functional failed.
269 // Throws:  None.
270 //--
271 bool
272 CMICmdCmdTargetAttach::Execute()
273 {
274     CMICMDBASE_GETOPTION(pArgPid, Number, m_constStrArgPid);
275     CMICMDBASE_GETOPTION(pArgFile, OptionShort, m_constStrArgNamedFile);
276     CMICMDBASE_GETOPTION(pArgWaitFor, OptionLong, m_constStrArgWaitFor);
277 
278     CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
279 
280     // If the current target is invalid, create one
281     lldb::SBTarget target = rSessionInfo.GetTarget();
282     if (!target.IsValid())
283     {
284         target = rSessionInfo.GetDebugger().CreateTarget(NULL);
285         if (!target.IsValid())
286         {
287             SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_INVALID_TARGET_CURRENT), m_cmdData.strMiCmd.c_str()));
288             return MIstatus::failure;
289         }
290     }
291 
292     lldb::SBError error;
293     lldb::SBListener listener;
294     if (pArgPid->GetFound() && pArgPid->GetValid())
295     {
296         lldb::pid_t pid;
297         pid = pArgPid->GetValue();
298         target.AttachToProcessWithID(listener, pid, error);
299     }
300     else if (pArgFile->GetFound() && pArgFile->GetValid())
301     {
302         bool bWaitFor = (pArgWaitFor->GetFound());
303         CMIUtilString file;
304         pArgFile->GetExpectedOption<CMICmdArgValString>(file);
305         target.AttachToProcessWithName(listener, file.c_str(), bWaitFor, error);
306     }
307     else
308     {
309         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_ATTACH_BAD_ARGS), m_cmdData.strMiCmd.c_str()));
310         return MIstatus::failure;
311     }
312 
313     lldb::SBStream errMsg;
314     if (error.Fail())
315     {
316         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_ATTACH_FAILED), m_cmdData.strMiCmd.c_str(), errMsg.GetData()));
317         return MIstatus::failure;
318     }
319 
320     return MIstatus::success;
321 }
322 
323 //++ ------------------------------------------------------------------------------------
324 // Details: The invoker requires this function. The command prepares a MI Record Result
325 //          for the work carried out in the Execute().
326 // Type:    Overridden.
327 // Args:    None.
328 // Return:  MIstatus::success - Functional succeeded.
329 //          MIstatus::failure - Functional failed.
330 // Throws:  None.
331 //--
332 bool
333 CMICmdCmdTargetAttach::Acknowledge()
334 {
335     const CMICmnMIResultRecord miRecordResult(m_cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Done);
336     m_miResultRecord = miRecordResult;
337 
338     CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
339     lldb::pid_t pid = rSessionInfo.GetProcess().GetProcessID();
340     // Prod the client i.e. Eclipse with out-of-band results to help it 'continue' because it is using LLDB debugger
341     // Give the client '=thread-group-started,id="i1"'
342     m_bHasResultRecordExtra = true;
343     const CMICmnMIValueConst miValueConst2("i1");
344     const CMICmnMIValueResult miValueResult2("id", miValueConst2);
345     const CMIUtilString strPid(CMIUtilString::Format("%lld", pid));
346     const CMICmnMIValueConst miValueConst(strPid);
347     const CMICmnMIValueResult miValueResult("pid", miValueConst);
348     CMICmnMIOutOfBandRecord miOutOfBand(CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted, miValueResult2);
349     miOutOfBand.Add(miValueResult);
350     m_miResultRecordExtra = miOutOfBand.GetString();
351 
352     return MIstatus::success;
353 }
354 
355 //++ ------------------------------------------------------------------------------------
356 // Details: Required by the CMICmdFactory when registering *this command. The factory
357 //          calls this function to create an instance of *this command.
358 // Type:    Static method.
359 // Args:    None.
360 // Return:  CMICmdBase * - Pointer to a new command.
361 // Throws:  None.
362 //--
363 CMICmdBase *
364 CMICmdCmdTargetAttach::CreateSelf()
365 {
366     return new CMICmdCmdTargetAttach();
367 }
368 
369 //++ ------------------------------------------------------------------------------------
370 // Details: CMICmdCmdTargetDetach constructor.
371 // Type:    Method.
372 // Args:    None.
373 // Return:  None.
374 // Throws:  None.
375 //--
376 CMICmdCmdTargetDetach::CMICmdCmdTargetDetach()
377 {
378     // Command factory matches this name with that received from the stdin stream
379     m_strMiCmd = "target-detach";
380 
381     // Required by the CMICmdFactory when registering *this command
382     m_pSelfCreatorFn = &CMICmdCmdTargetDetach::CreateSelf;
383 }
384 
385 //++ ------------------------------------------------------------------------------------
386 // Details: CMICmdCmdTargetDetach destructor.
387 // Type:    Overrideable.
388 // Args:    None.
389 // Return:  None.
390 // Throws:  None.
391 //--
392 CMICmdCmdTargetDetach::~CMICmdCmdTargetDetach()
393 {
394 }
395 
396 //++ ------------------------------------------------------------------------------------
397 // Details: The invoker requires this function. The parses the command line options
398 //          arguments to extract values for each of those arguments.
399 // Type:    Overridden.
400 // Args:    None.
401 // Return:  MIstatus::success - Functional succeeded.
402 //          MIstatus::failure - Functional failed.
403 // Throws:  None.
404 //--
405 bool
406 CMICmdCmdTargetDetach::ParseArgs()
407 {
408     return MIstatus::success;
409 }
410 
411 //++ ------------------------------------------------------------------------------------
412 // Details: The invoker requires this function. The command does work in this function.
413 //          The command is likely to communicate with the LLDB SBDebugger in here.
414 //          Synopsis: -target-attach file
415 //          Ref: http://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Target-Manipulation.html#GDB_002fMI-Target-Manipulation
416 // Type:    Overridden.
417 // Args:    None.
418 // Return:  MIstatus::success - Functional succeeded.
419 //          MIstatus::failure - Functional failed.
420 // Throws:  None.
421 //--
422 bool
423 CMICmdCmdTargetDetach::Execute()
424 {
425     CMICmnLLDBDebugSessionInfo &rSessionInfo(CMICmnLLDBDebugSessionInfo::Instance());
426 
427     lldb::SBProcess process = rSessionInfo.GetProcess();
428 
429     if (!process.IsValid())
430     {
431         SetError(CMIUtilString::Format(MIRSRC(IDS_CMD_ERR_INVALID_PROCESS), m_cmdData.strMiCmd.c_str()));
432         return MIstatus::failure;
433     }
434 
435     process.Detach();
436 
437     return MIstatus::success;
438 }
439 
440 //++ ------------------------------------------------------------------------------------
441 // Details: The invoker requires this function. The command prepares a MI Record Result
442 //          for the work carried out in the Execute().
443 // Type:    Overridden.
444 // Args:    None.
445 // Return:  MIstatus::success - Functional succeeded.
446 //          MIstatus::failure - Functional failed.
447 // Throws:  None.
448 //--
449 bool
450 CMICmdCmdTargetDetach::Acknowledge()
451 {
452     const CMICmnMIResultRecord miRecordResult(m_cmdData.strMiCmdToken, CMICmnMIResultRecord::eResultClass_Done);
453     m_miResultRecord = miRecordResult;
454     return MIstatus::success;
455 }
456 
457 //++ ------------------------------------------------------------------------------------
458 // Details: Required by the CMICmdFactory when registering *this command. The factory
459 //          calls this function to create an instance of *this command.
460 // Type:    Static method.
461 // Args:    None.
462 // Return:  CMICmdBase * - Pointer to a new command.
463 // Throws:  None.
464 //--
465 CMICmdBase *
466 CMICmdCmdTargetDetach::CreateSelf()
467 {
468     return new CMICmdCmdTargetDetach();
469 }
470