Always pick up the attach PID from the master engine, as that's where it's set in...
[qt-creator:qnx-qt-creator.git] / src / plugins / debugger / gdb / remotegdbserveradapter.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 **
10 ** GNU Lesser General Public License Usage
11 **
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 **
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 **
23 ** Other Usage
24 **
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **************************************************************************/
32
33 #include "remotegdbserveradapter.h"
34
35 #include "debuggeractions.h"
36 #include "debuggerstartparameters.h"
37 #include "debuggercore.h"
38 #include "debuggerstringutils.h"
39 #include "gdbengine.h"
40 #include "gdbmi.h"
41
42 #include <utils/qtcassert.h>
43 #include <utils/fancymainwindow.h>
44 #include <projectexplorer/abi.h>
45
46 #include <QFileInfo>
47 #include <QMessageBox>
48
49 namespace Debugger {
50 namespace Internal {
51
52 #define CB(callback) \
53     static_cast<GdbEngine::AdapterCallback>(&RemoteGdbServerAdapter::callback), \
54     STRINGIFY(callback)
55
56 ///////////////////////////////////////////////////////////////////////
57 //
58 // RemoteGdbAdapter
59 //
60 ///////////////////////////////////////////////////////////////////////
61
62 RemoteGdbServerAdapter::RemoteGdbServerAdapter(GdbEngine *engine)
63     : AbstractGdbAdapter(engine)
64 {
65     connect(&m_uploadProc, SIGNAL(error(QProcess::ProcessError)),
66         SLOT(uploadProcError(QProcess::ProcessError)));
67     connect(&m_uploadProc, SIGNAL(readyReadStandardOutput()),
68         SLOT(readUploadStandardOutput()));
69     connect(&m_uploadProc, SIGNAL(readyReadStandardError()),
70         SLOT(readUploadStandardError()));
71     connect(&m_uploadProc, SIGNAL(finished(int)),
72         SLOT(uploadProcFinished()));
73 }
74
75 AbstractGdbAdapter::DumperHandling RemoteGdbServerAdapter::dumperHandling() const
76 {
77     using namespace ProjectExplorer;
78     const Abi abi = startParameters().toolChainAbi;
79     if (abi.os() == Abi::SymbianOS
80             || abi.os() == Abi::WindowsOS
81             || abi.binaryFormat() == Abi::ElfFormat)
82         return DumperLoadedByGdb;
83     return DumperLoadedByGdbPreload;
84 }
85
86 void RemoteGdbServerAdapter::startAdapter()
87 {
88     QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
89     showMessage(_("TRYING TO START ADAPTER"));
90     if (startParameters().useServerStartScript) {
91         if (startParameters().serverStartScript.isEmpty()) {
92             showMessage(_("No server start script given. "), StatusBar);
93         } else {
94             m_uploadProc.start(_("/bin/sh ") + startParameters().serverStartScript);
95             m_uploadProc.waitForStarted();
96         }
97     }
98     if (startParameters().requestRemoteSetup)
99         m_engine->notifyEngineRequestRemoteSetup();
100     else
101         handleSetupDone();
102 }
103
104 void RemoteGdbServerAdapter::uploadProcError(QProcess::ProcessError error)
105 {
106     QString msg;
107     switch (error) {
108         case QProcess::FailedToStart:
109             msg = tr("The upload process failed to start. Shell missing?");
110             break;
111         case QProcess::Crashed:
112             msg = tr("The upload process crashed some time after starting "
113                 "successfully.");
114             break;
115         case QProcess::Timedout:
116             msg = tr("The last waitFor...() function timed out. "
117                 "The state of QProcess is unchanged, and you can try calling "
118                 "waitFor...() again.");
119             break;
120         case QProcess::WriteError:
121             msg = tr("An error occurred when attempting to write "
122                 "to the upload process. For example, the process may not be running, "
123                 "or it may have closed its input channel.");
124             break;
125         case QProcess::ReadError:
126             msg = tr("An error occurred when attempting to read from "
127                 "the upload process. For example, the process may not be running.");
128             break;
129         default:
130             msg = tr("An unknown error in the upload process occurred. "
131                 "This is the default return value of error().");
132     }
133
134     showMessage(msg, StatusBar);
135     showMessageBox(QMessageBox::Critical, tr("Error"), msg);
136 }
137
138 void RemoteGdbServerAdapter::readUploadStandardOutput()
139 {
140     const QByteArray ba = m_uploadProc.readAllStandardOutput();
141     const QString msg = QString::fromLocal8Bit(ba, ba.length());
142     showMessage(msg, LogOutput);
143     showMessage(msg, AppOutput);
144 }
145
146 void RemoteGdbServerAdapter::readUploadStandardError()
147 {
148     const QByteArray ba = m_uploadProc.readAllStandardError();
149     const QString msg = QString::fromLocal8Bit(ba, ba.length());
150     showMessage(msg, LogOutput);
151     showMessage(msg, AppError);
152 }
153
154 void RemoteGdbServerAdapter::uploadProcFinished()
155 {
156     if (m_uploadProc.exitStatus() == QProcess::NormalExit
157         && m_uploadProc.exitCode() == 0)
158         handleSetupDone();
159     else
160         handleRemoteSetupFailed(m_uploadProc.errorString());
161 }
162
163 void RemoteGdbServerAdapter::setupInferior()
164 {
165     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
166     const DebuggerStartParameters &sp = startParameters();
167
168     QString executableFileName;
169     if (!sp.executable.isEmpty()) {
170         QFileInfo fi(sp.executable);
171         executableFileName = fi.absoluteFilePath();
172     }
173     QString symbolFileName;
174     if (!sp.symbolFileName.isEmpty()) {
175         QFileInfo fi(sp.symbolFileName);
176         symbolFileName = fi.absoluteFilePath();
177     }
178
179     const QByteArray sysroot = sp.sysroot.toLocal8Bit();
180     const QByteArray remoteArch = sp.remoteArchitecture.toLatin1();
181     const QByteArray gnuTarget = sp.gnuTarget.toLatin1();
182     const QByteArray searchPath = startParameters().searchPath.toLocal8Bit();
183     const QString args = sp.processArgs;
184
185     if (!remoteArch.isEmpty())
186         m_engine->postCommand("set architecture " + remoteArch);
187     if (!gnuTarget.isEmpty())
188         m_engine->postCommand("set gnutarget " + gnuTarget);
189     if (!sysroot.isEmpty())
190         m_engine->postCommand("set sysroot " + sysroot);
191     if (!searchPath.isEmpty())
192         m_engine->postCommand("set solib-search-path " + searchPath);
193     if (!args.isEmpty())
194         m_engine->postCommand("-exec-arguments " + args.toLocal8Bit());
195
196     // This has to be issued before 'target remote'. On pre-7.0 the
197     // command is not present and will result in ' No symbol table is
198     // loaded.  Use the "file" command.' as gdb tries to set the
199     // value of a variable with name 'target-async'.
200     //
201     // Testing with -list-target-features which was introduced at
202     // the same time would not work either, as this need an existing
203     // target.
204     //
205     // Using it even without a target and having it fail might still
206     // be better as:
207     // Some external comment: '[but] "set target-async on" with a native
208     // windows gdb will work, but then fail when you actually do
209     // "run"/"attach", I think..
210
211
212     // gdb/mi/mi-main.c:1958: internal-error:
213     // mi_execute_async_cli_command: Assertion `is_running (inferior_ptid)'
214     // failed.\nA problem internal to GDB has been detected,[...]
215     if (debuggerCore()->boolSetting(TargetAsync))
216         m_engine->postCommand("set target-async on", CB(handleSetTargetAsync));
217
218     if (executableFileName.isEmpty() && symbolFileName.isEmpty()) {
219         showMessage(tr("No symbol file given."), StatusBar);
220         callTargetRemote();
221         return;
222     }
223
224     if (!symbolFileName.isEmpty()) {
225         m_engine->postCommand("-file-symbol-file \""
226                               + symbolFileName.toLocal8Bit() + '"',
227                               CB(handleFileExecAndSymbols));
228     }
229     if (!executableFileName.isEmpty()) {
230         m_engine->postCommand("-file-exec-and-symbols \""
231             + executableFileName.toLocal8Bit() + '"',
232             CB(handleFileExecAndSymbols));
233     }
234 }
235
236 void RemoteGdbServerAdapter::handleSetTargetAsync(const GdbResponse &response)
237 {
238     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
239     if (response.resultClass == GdbResultError)
240         qDebug() << "Adapter too old: does not support asynchronous mode.";
241 }
242
243 void RemoteGdbServerAdapter::handleFileExecAndSymbols(const GdbResponse &response)
244 {
245     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
246     if (response.resultClass == GdbResultDone) {
247         callTargetRemote();
248     } else {
249         QString msg = tr("Reading debug information failed:\n");
250         msg += QString::fromLocal8Bit(response.data.findChild("msg").data());
251         m_engine->notifyInferiorSetupFailed(msg);
252     }
253 }
254
255 void RemoteGdbServerAdapter::callTargetRemote()
256 {
257     //m_breakHandler->clearBreakMarkers();
258
259     // "target remote" does three things:
260     //     (1) connects to the gdb server
261     //     (2) starts the remote application
262     //     (3) stops the remote application (early, e.g. in the dynamic linker)
263     QString channel = startParameters().remoteChannel;
264     if (m_engine->m_isQnxGdb) {
265         m_engine->postCommand("target qnx " + channel.toLatin1(),
266             CB(handleTargetQnx));
267     } else {
268         m_engine->postCommand("target remote " + channel.toLatin1(),
269             CB(handleTargetRemote));
270     }
271 }
272
273 void RemoteGdbServerAdapter::handleTargetRemote(const GdbResponse &record)
274 {
275     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
276     if (record.resultClass == GdbResultDone) {
277         // gdb server will stop the remote application itself.
278         showMessage(_("INFERIOR STARTED"));
279         showMessage(msgAttachedToStoppedInferior(), StatusBar);
280         m_engine->handleInferiorPrepared();
281     } else {
282         // 16^error,msg="hd:5555: Connection timed out."
283         QString msg = msgConnectRemoteServerFailed(
284             QString::fromLocal8Bit(record.data.findChild("msg").data()));
285         m_engine->notifyInferiorSetupFailed(msg);
286     }
287 }
288
289 void RemoteGdbServerAdapter::handleTargetQnx(const GdbResponse &response)
290 {
291     QTC_ASSERT(m_engine->m_isQnxGdb, qDebug() << m_engine->m_isQnxGdb);
292     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
293     if (response.resultClass == GdbResultDone) {
294         // gdb server will stop the remote application itself.
295         showMessage(_("INFERIOR STARTED"));
296         showMessage(msgAttachedToStoppedInferior(), StatusBar);
297
298         const qint64 pid = m_engine->isMasterEngine() ? startParameters().attachPID : m_engine->masterEngine()->startParameters().attachPID;
299         if (pid > -1) {
300             m_engine->postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
301         } else {
302             m_engine->handleInferiorPrepared();
303         }
304     } else {
305         // 16^error,msg="hd:5555: Connection timed out."
306         QString msg = msgConnectRemoteServerFailed(
307             QString::fromLocal8Bit(response.data.findChild("msg").data()));
308         m_engine->notifyInferiorSetupFailed(msg);
309     }
310 }
311
312 void RemoteGdbServerAdapter::handleAttach(const GdbResponse &response)
313 {
314     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
315     switch (response.resultClass) {
316     case GdbResultDone:
317     case GdbResultRunning: {
318         showMessage(_("INFERIOR ATTACHED"));
319         showMessage(msgAttachedToStoppedInferior(), StatusBar);
320         m_engine->handleInferiorPrepared();
321         break;
322     }
323     case GdbResultError:
324         if (response.data.findChild("msg").data() == "ptrace: Operation not permitted.") {
325             m_engine->notifyInferiorSetupFailed(DumperHelper::msgPtraceError(startParameters().startMode));
326             break;
327         }
328         // if msg != "ptrace: ..." fall through
329     default:
330         QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
331         m_engine->notifyInferiorSetupFailed(msg);
332     }
333 }
334
335 void RemoteGdbServerAdapter::runEngine()
336 {
337     QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
338
339     const QString remoteExecutable = startParameters().remoteExecutable;
340     if (!remoteExecutable.isEmpty()) {
341         m_engine->postCommand("-exec-run " + remoteExecutable.toLocal8Bit(), GdbEngine::RunRequest, CB(handleExecRun));
342     } else {
343         m_engine->notifyEngineRunAndInferiorStopOk();
344         m_engine->continueInferiorInternal();
345     }
346 }
347
348 void RemoteGdbServerAdapter::handleExecRun(const GdbResponse &response)
349 {
350     QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
351     if (response.resultClass == GdbResultRunning) {
352         m_engine->notifyEngineRunAndInferiorRunOk();
353         showMessage(_("INFERIOR STARTED"));
354         showMessage(msgInferiorSetupOk(), StatusBar);
355         // FIXME: That's the wrong place for it.
356         if (debuggerCore()->boolSetting(EnableReverseDebugging))
357             m_engine->postCommand("target record");
358     } else {
359         QString msg = QString::fromLocal8Bit(response.data.findChild("msg").data());
360         showMessage(msg);
361         m_engine->notifyEngineRunFailed();
362     }
363 }
364
365 void RemoteGdbServerAdapter::interruptInferior()
366 {
367     QTC_ASSERT(state() == InferiorStopRequested, qDebug() << state());
368     if (debuggerCore()->boolSetting(TargetAsync)) {
369         m_engine->postCommand("-exec-interrupt", GdbEngine::Immediate,
370             CB(handleInterruptInferior));
371     } else {
372         bool ok = m_gdbProc.interrupt();
373         if (!ok) {
374             // FIXME: Extra state needed?
375             m_engine->showMessage(_("NOTE: INFERIOR STOP NOT POSSIBLE"));
376             m_engine->showStatusMessage(tr("Interrupting not possible"));
377             m_engine->notifyInferiorRunOk();
378         }
379     }
380 }
381
382 void RemoteGdbServerAdapter::handleInterruptInferior(const GdbResponse &response)
383 {
384     if (response.resultClass == GdbResultDone) {
385         // The gdb server will trigger extra output that we will pick up
386         // to do a proper state transition.
387     } else {
388         // FIXME: On some gdb versions like git 170ffa5d7dd this produces
389         // >810^error,msg="mi_cmd_exec_interrupt: Inferior not executing."
390         m_engine->notifyInferiorStopOk();
391     }
392 }
393
394 void RemoteGdbServerAdapter::shutdownInferior()
395 {
396     if (m_engine->startParameters().startMode == AttachToRemoteServer
397             && m_engine->startParameters().remoteExecutable.isEmpty())
398         m_engine->defaultInferiorShutdown("detach");
399     else
400         m_engine->defaultInferiorShutdown("kill");
401 }
402
403 void RemoteGdbServerAdapter::shutdownAdapter()
404 {
405     m_engine->notifyAdapterShutdownOk();
406 }
407
408 void RemoteGdbServerAdapter::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
409 {
410     QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
411
412     if (qmlPort != -1)
413         startParameters().qmlServerPort = qmlPort;
414     if (gdbServerPort != -1) {
415         QString &rc = startParameters().remoteChannel;
416         const int sepIndex = rc.lastIndexOf(QLatin1Char(':'));
417         if (sepIndex != -1) {
418             rc.replace(sepIndex + 1, rc.count() - sepIndex - 1,
419                        QString::number(gdbServerPort));
420         }
421     }
422     handleSetupDone();
423 }
424
425 void RemoteGdbServerAdapter::handleSetupDone()
426 {
427     if (m_engine->startGdb())
428         m_engine->handleAdapterStarted();
429 }
430
431 void RemoteGdbServerAdapter::handleRemoteSetupFailed(const QString &reason)
432 {
433     QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
434
435     m_engine->handleAdapterStartFailed(reason);
436 }
437
438 } // namespace Internal
439 } // namespace Debugger