[debugger]crash fixed when an execution finished after a Step Out
[scilab.git] / scilab / modules / ast / src / cpp / ast / debuggervisitor.cpp
1 /*
2  *  Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  *  Copyright (C) 2015 - Scilab Enterprises - Antoine ELIAS
4  *
5  * Copyright (C) 2012 - 2016 - Scilab Enterprises
6  *
7  * This file is hereby licensed under the terms of the GNU GPL v2.0,
8  * pursuant to article 5.3.4 of the CeCILL v.2.1.
9  * This file was originally licensed under the terms of the CeCILL v2.1,
10  * and continues to be available under such terms.
11  * For more information, see the COPYING file which you should have received
12  * along with this program.
13  *
14  */
15
16 #include "debuggervisitor.hxx"
17 #include "debugmanager.hxx"
18 #include "printvisitor.hxx"
19 #include "execvisitor.hxx"
20 #include "threadId.hxx"
21 #include "macrofile.hxx"
22 #include "commentexp.hxx"
23 #include "UTF8.hxx"
24 #include "runner.hxx"
25
26 extern "C"
27 {
28 #include "filemanager_interface.h"
29 #include "FileExist.h"
30 }
31
32 static bool getMacroSourceFile(std::string* filename = nullptr);
33
34 namespace ast
35 {
36 void DebuggerVisitor::visit(const SeqExp  &e)
37 {
38     std::list<Exp *>::const_iterator itExp;
39
40     debugger::DebuggerManager* manager = debugger::DebuggerManager::getInstance();
41     if(manager->isAborted())
42     {
43         // abort a running execution
44         throw ast::InternalAbort();
45     }
46
47     for (const auto & exp : e.getExps())
48     {
49         if (exp->isCommentExp())
50         {
51             continue;
52         }
53
54         if (e.isBreakable())
55         {
56             exp->resetBreak();
57             exp->setBreakable();
58         }
59
60         if (e.isContinuable())
61         {
62             exp->resetContinue();
63             exp->setContinuable();
64         }
65
66         if (e.isReturnable())
67         {
68             exp->setReturnable();
69         }
70
71         //debugger check !
72         int iBreakPoint = -1;
73         if (ConfigVariable::getEnableDebug())
74         {
75             bool stopExecution = false;
76             if (manager->isStepIn())
77             {
78                 manager->resetStepIn();
79                 stopExecution = true;
80                 if(getMacroSourceFile() == false)
81                 {
82                     stopExecution = false;
83                     manager->setStepIn();
84                 }
85             }
86             else if (manager->isStepNext())
87             {
88                 manager->resetStepNext();
89                 stopExecution = true;
90                 if(getMacroSourceFile() == false)
91                 {
92                     stopExecution = false;
93                     manager->setStepOut();
94                 }
95             }
96             else
97             {
98                 const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
99                 //set information from debugger commands
100                 if (lWhereAmI.size() != 0 && manager->getBreakPointCount() != 0)
101                 {
102                     debugger::Breakpoints& bps = manager->getAllBreakPoint();
103
104                     int i = -1;
105                     for (const auto & bp : bps)
106                     {
107                         ++i;
108                         if (bp->isEnable() == false)
109                         {
110                             continue;
111                         }
112
113                         // look for a breakpoint on this line and update breakpoint information when possible
114                         int iLine = exp->getLocation().first_line - ConfigVariable::getMacroFirstLines();
115                         if (bp->hasMacro())
116                         {
117                             char* functionName = wide_string_to_UTF8(lWhereAmI.back().call->getName().data());
118                             if (bp->getFunctioName().compare(functionName) == 0)
119                             {
120                                 if (bp->getMacroLine() == 0)
121                                 {
122                                     //first pass in macro.
123                                     //update first line with real value
124                                     bp->setMacroLine(iLine);
125                                 }
126
127                                 stopExecution = bp->getMacroLine() == iLine;
128                             }
129
130                             FREE(functionName);
131                         }
132                         else if (bp->hasFile())
133                         {
134                             if (bp->getFileLine() == exp->getLocation().first_line)
135                             {
136                                 std::string pFileName;
137                                 bool hasSource = getMacroSourceFile(&pFileName);
138                                 if (hasSource && bp->getFileName() == pFileName)
139                                 {
140                                     stopExecution = true;
141                                     // set function information
142                                     if (lWhereAmI.back().call->getFirstLine())
143                                     {
144                                         bp->setFunctionName(scilab::UTF8::toUTF8(lWhereAmI.back().call->getName()));
145                                         bp->setMacroLine(iLine);
146                                     }
147                                 }
148                             }
149                         }
150
151                         if(stopExecution == false)
152                         {
153                             // no breakpoint for this line
154                             continue;
155                         }
156
157                         // Set the begin of line if not yet done
158                         if(bp->getBeginLine() == 0)
159                         {
160                             bp->setBeginLine(exp->getLocation().first_column);
161                         }
162                         // check if this exp is at the begin of the breakpoint line
163                         else if(bp->getBeginLine() != exp->getLocation().first_column)
164                         {
165                             // stop only if we are at the line begins
166                             stopExecution = false;
167                             continue;
168                         }
169
170                         //check condition
171                         if (bp->getConditionExp() != NULL)
172                         {
173                             //do not use debuggervisitor !
174                             symbol::Context* pCtx = symbol::Context::getInstance();
175                             try
176                             {
177                                 ExecVisitor execCond;
178                                 //protect current env during condition execution
179                                 pCtx->scope_begin();
180                                 bp->getConditionExp()->accept(execCond);
181                                 types::InternalType* pIT = pCtx->getCurrentLevel(symbol::Symbol(L"ans"));
182                                 if (pIT == NULL ||
183                                         pIT->isBool() == false ||
184                                         ((types::Bool*)pIT)->isScalar() == false ||
185                                         ((types::Bool*)pIT)->get(0) == 0)
186                                 {
187                                     pCtx->scope_end();
188                                     //not a boolean, not scalar or false
189                                     stopExecution = false;
190                                     continue;
191                                 }
192
193                                 pCtx->scope_end();
194                                 //ok condition is valid and true
195                             }
196                             catch (ast::ScilabException &/*e*/)
197                             {
198                                 pCtx->scope_end();
199                                 stopExecution = false;
200                                 //not work !
201                                 //invalid breakpoint
202                                 continue;
203                             }
204                         }
205
206                         //we have a breakpoint !
207                         //stop execution and wait signal from debugger to restart
208                         iBreakPoint = i;
209
210                         //only one breakpoint can be "call" on same exp
211                         break;
212                     }
213                 }
214             }
215
216             if(stopExecution)
217             {
218                 manager->stop(exp, iBreakPoint);
219                 if (manager->isAborted())
220                 {
221                     throw ast::InternalAbort();
222                 }
223             }
224         }
225
226         // interrupt me to execute a prioritary command
227         while (StaticRunner_isRunnerAvailable() == 1 && StaticRunner_isInterruptibleCommand() == 1)
228         {
229             StaticRunner_launch();
230         }
231
232         //copy from runvisitor::seqexp
233         try
234         {
235             //reset default values
236             setResult(NULL);
237             int iExpectedSize = getExpectedSize();
238             setExpectedSize(-1);
239             exp->accept(*this);
240             setExpectedSize(iExpectedSize);
241             types::InternalType * pIT = getResult();
242
243             // In case of exec file, set the file name in the Macro to store where it is defined.
244             int iFileID = ConfigVariable::getExecutedFileID();
245             if (iFileID && exp->isFunctionDec())
246             {
247                 types::InternalType* pITMacro = symbol::Context::getInstance()->get(exp->getAs<ast::FunctionDec>()->getSymbol());
248                 if (pITMacro)
249                 {
250                     types::Macro* pMacro = pITMacro->getAs<types::Macro>();
251                     const wchar_t* filename = getfile_filename(iFileID);
252                     // scilab.quit is not open with mopen
253                     // in this case filename is NULL because FileManager have not been filled.
254                     if (filename)
255                     {
256                         pMacro->setFileName(filename);
257                     }
258                 }
259             }
260
261             if (pIT != NULL)
262             {
263                 bool bImplicitCall = false;
264                 if (pIT->isCallable()) //to manage call without ()
265                 {
266                     types::Callable *pCall = pIT->getAs<types::Callable>();
267                     types::typed_list out;
268                     types::typed_list in;
269                     types::optional_list opt;
270
271                     try
272                     {
273                         //in this case of calling, we can return only one value
274                         int iSaveExpectedSize = getExpectedSize();
275                         setExpectedSize(1);
276
277                         pCall->invoke(in, opt, getExpectedSize(), out, *exp);
278                         setExpectedSize(iSaveExpectedSize);
279
280                         if (out.size() == 0)
281                         {
282                             setResult(NULL);
283                         }
284                         else
285                         {
286                             setResult(out[0]);
287                         }
288
289                         bImplicitCall = true;
290                     }
291                     catch (const InternalError& ie)
292                     {
293                         if (ConfigVariable::getLastErrorFunction() == L"")
294                         {
295                             ConfigVariable::setLastErrorFunction(pCall->getName());
296                             ConfigVariable::setLastErrorLine(e.getLocation().first_line);
297                         }
298
299                         throw ie;
300                     }
301                 }
302
303                 //don't output Simplevar and empty result
304                 if (getResult() != NULL && (!exp->isSimpleVar() || bImplicitCall))
305                 {
306                     //symbol::Context::getInstance()->put(symbol::Symbol(L"ans"), *execMe.getResult());
307                     types::InternalType* pITAns = getResult();
308                     symbol::Context::getInstance()->put(m_pAns, pITAns);
309                     if (exp->isVerbose() && ConfigVariable::isPrintOutput())
310                     {
311                         //TODO manage multiple returns
312                         scilabWriteW(L" ans  =\n\n");
313                         std::wostringstream ostrName;
314                         ostrName << L"ans";
315                         types::VariableToString(pITAns, ostrName.str().c_str());
316                     }
317                 }
318
319                 pIT->killMe();
320             }
321
322             if ((&e)->isBreakable() && exp->isBreak())
323             {
324                 const_cast<SeqExp *>(&e)->setBreak();
325                 exp->resetBreak();
326                 break;
327             }
328
329             if ((&e)->isContinuable() && exp->isContinue())
330             {
331                 const_cast<SeqExp *>(&e)->setContinue();
332                 exp->resetContinue();
333                 break;
334             }
335
336             if ((&e)->isReturnable() && exp->isReturn())
337             {
338                 const_cast<SeqExp *>(&e)->setReturn();
339                 exp->resetReturn();
340                 break;
341             }
342
343             // Stop execution at the end of the seqexp of the caller
344             // Do it at the end of the seqexp will make the debugger stop
345             // even if the caller is at the last line
346             // ie: the caller is followed by endfunction
347             if(manager->isStepOut())
348             {
349                 manager->resetStepOut();
350                 if(getMacroSourceFile() == false)
351                 {
352                     // no sources
353                     manager->setStepOut();
354                 }
355                 else
356                 {
357                     manager->stop(exp, iBreakPoint);
358                 }
359
360                 if (manager->isAborted())
361                 {
362                     throw ast::InternalAbort();
363                 }
364             }
365
366         }
367         catch (const InternalError& ie)
368         {
369             ConfigVariable::fillWhereError(ie.GetErrorLocation().first_line);
370
371             const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
372
373             //where can be empty on last stepout, on first calling expression
374             if (lWhereAmI.size())
375             {
376                 const std::wstring* filename = lWhereAmI.back().m_file_name;
377
378                 if (filename == nullptr)
379                 {
380                     //error in a console script
381                     std::wstring functionName = lWhereAmI.back().call->getName();
382                     manager->errorInScript(functionName, exp);
383                 }
384                 else
385                 {
386                     manager->errorInFile(*filename, exp);
387                 }
388
389                 // Debugger just restart after been stopped on an error.
390                 if (manager->isAborted())
391                 {
392                     throw ast::InternalAbort();
393                 }
394             }
395
396             throw ie;
397         }
398
399         // If something other than NULL is given to setResult, then that would imply
400         // to make a cleanup in visit(ForExp) for example (e.getBody().accept(*this);)
401         setResult(NULL);
402
403     }
404
405     if (e.getParent() == NULL && e.getExecFrom() == SeqExp::SCRIPT && (manager->isStepNext() || manager->isStepIn()))
406     {
407         const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
408         if (lWhereAmI.size())
409         {
410             std::wstring functionName = lWhereAmI.back().call->getName();
411             types::InternalType* pIT = symbol::Context::getInstance()->get(symbol::Symbol(functionName));
412             if (pIT && (pIT->isMacro() || pIT->isMacroFile()))
413             {
414                 types::Macro* m = nullptr;
415                 if (pIT->isMacroFile())
416                 {
417                     types::MacroFile* mf = pIT->getAs<types::MacroFile>();
418                     m = mf->getMacro();
419                 }
420                 else
421                 {
422                     m = pIT->getAs<types::Macro>();
423                 }
424
425                 //create a fake exp to represente end/enfunction
426
427                 //will be deleted by CommentExp
428                 std::wstring* comment = new std::wstring(L"end of function");
429                 Location loc(m->getLastLine(), m->getLastLine(), 0, 0);
430                 CommentExp fakeExp(loc, comment);
431                 manager->stop(&fakeExp, -1);
432
433                 if (manager->isAborted())
434                 {
435                     throw ast::InternalAbort();
436                 }
437
438                 //transform stepnext after endfunction as a stepout to show line marker on current statement
439                 if (manager->isStepNext())
440                 {
441                     manager->resetStepNext();
442                     manager->setStepOut();
443                 }
444                 else if (manager->isStepIn())
445                 {
446                     manager->resetStepIn();
447                     manager->setStepOut();
448                 }
449             }
450         }
451     }
452 }
453 }
454
455 // return false if a file .sci of a file .bin doesn't exists
456 // return true for others files or existing .sci
457 bool getMacroSourceFile(std::string* filename)
458 {
459     const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
460     // "Where" can be empty at the end of script execution
461     // this function is called when the script ends after a step out
462     if(lWhereAmI.empty())
463     {
464         return false;
465     }
466
467     std::string file = scilab::UTF8::toUTF8(*lWhereAmI.back().m_file_name);
468     if (file.rfind(".bin") != std::string::npos)
469     {
470         file.replace(file.size() - 4, 4, ".sci");
471         // stop on bp only if the file exist
472         if (!FileExist(file.data()))
473         {
474             return false;
475         }
476     }
477
478     if(filename != nullptr)
479     {
480         filename->assign(file);
481     }
482
483     return true;
484 }