1 //===-- ClangUserExpression.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 #include <stdio.h>
11 #if HAVE_SYS_TYPES_H
12 #  include <sys/types.h>
13 #endif
14 
15 #include <cstdlib>
16 #include <string>
17 #include <map>
18 
19 #include "ClangUserExpression.h"
20 
21 #include "ASTResultSynthesizer.h"
22 #include "ClangExpressionDeclMap.h"
23 #include "ClangExpressionParser.h"
24 #include "ClangModulesDeclVendor.h"
25 #include "ClangPersistentVariables.h"
26 
27 #include "lldb/Core/ConstString.h"
28 #include "lldb/Core/Log.h"
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/StreamString.h"
32 #include "lldb/Core/ValueObjectConstResult.h"
33 #include "lldb/Expression/ExpressionSourceCode.h"
34 #include "lldb/Expression/IRExecutionUnit.h"
35 #include "lldb/Expression/IRInterpreter.h"
36 #include "lldb/Expression/Materializer.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Symbol/Block.h"
39 #include "lldb/Symbol/ClangASTContext.h"
40 #include "lldb/Symbol/Function.h"
41 #include "lldb/Symbol/ObjectFile.h"
42 #include "lldb/Symbol/SymbolVendor.h"
43 #include "lldb/Symbol/Type.h"
44 #include "lldb/Symbol/ClangExternalASTSourceCommon.h"
45 #include "lldb/Symbol/VariableList.h"
46 #include "lldb/Target/ExecutionContext.h"
47 #include "lldb/Target/Process.h"
48 #include "lldb/Target/StackFrame.h"
49 #include "lldb/Target/Target.h"
50 #include "lldb/Target/ThreadPlan.h"
51 #include "lldb/Target/ThreadPlanCallUserExpression.h"
52 
53 #include "clang/AST/DeclCXX.h"
54 #include "clang/AST/DeclObjC.h"
55 
56 using namespace lldb_private;
57 
58 ClangUserExpression::ClangUserExpression (ExecutionContextScope &exe_scope,
59                                           const char *expr,
60                                           const char *expr_prefix,
61                                           lldb::LanguageType language,
62                                           ResultType desired_type) :
63     UserExpression (exe_scope, expr, expr_prefix, language, desired_type),
64     m_type_system_helper(*m_target_wp.lock().get())
65 {
66     switch (m_language)
67     {
68     case lldb::eLanguageTypeC_plus_plus:
69         m_allow_cxx = true;
70         break;
71     case lldb::eLanguageTypeObjC:
72         m_allow_objc = true;
73         break;
74     case lldb::eLanguageTypeObjC_plus_plus:
75     default:
76         m_allow_cxx = true;
77         m_allow_objc = true;
78         break;
79     }
80 }
81 
82 ClangUserExpression::~ClangUserExpression ()
83 {
84 }
85 
86 void
87 ClangUserExpression::ScanContext(ExecutionContext &exe_ctx, Error &err)
88 {
89     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
90 
91     if (log)
92         log->Printf("ClangUserExpression::ScanContext()");
93 
94     m_target = exe_ctx.GetTargetPtr();
95 
96     if (!(m_allow_cxx || m_allow_objc))
97     {
98         if (log)
99             log->Printf("  [CUE::SC] Settings inhibit C++ and Objective-C");
100         return;
101     }
102 
103     StackFrame *frame = exe_ctx.GetFramePtr();
104     if (frame == NULL)
105     {
106         if (log)
107             log->Printf("  [CUE::SC] Null stack frame");
108         return;
109     }
110 
111     SymbolContext sym_ctx = frame->GetSymbolContext(lldb::eSymbolContextFunction | lldb::eSymbolContextBlock);
112 
113     if (!sym_ctx.function)
114     {
115         if (log)
116             log->Printf("  [CUE::SC] Null function");
117         return;
118     }
119 
120     // Find the block that defines the function represented by "sym_ctx"
121     Block *function_block = sym_ctx.GetFunctionBlock();
122 
123     if (!function_block)
124     {
125         if (log)
126             log->Printf("  [CUE::SC] Null function block");
127         return;
128     }
129 
130     CompilerDeclContext decl_context = function_block->GetDeclContext();
131 
132     if (!decl_context)
133     {
134         if (log)
135             log->Printf("  [CUE::SC] Null decl context");
136         return;
137     }
138 
139     if (clang::CXXMethodDecl *method_decl = ClangASTContext::DeclContextGetAsCXXMethodDecl(decl_context))
140     {
141         if (m_allow_cxx && method_decl->isInstance())
142         {
143             if (m_enforce_valid_object)
144             {
145                 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
146 
147                 const char *thisErrorString = "Stopped in a C++ method, but 'this' isn't available; pretending we are in a generic context";
148 
149                 if (!variable_list_sp)
150                 {
151                     err.SetErrorString(thisErrorString);
152                     return;
153                 }
154 
155                 lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
156 
157                 if (!this_var_sp ||
158                     !this_var_sp->IsInScope(frame) ||
159                     !this_var_sp->LocationIsValidForFrame (frame))
160                 {
161                     err.SetErrorString(thisErrorString);
162                     return;
163                 }
164             }
165 
166             m_in_cplusplus_method = true;
167             m_needs_object_ptr = true;
168         }
169     }
170     else if (clang::ObjCMethodDecl *method_decl = ClangASTContext::DeclContextGetAsObjCMethodDecl(decl_context))
171     {
172         if (m_allow_objc)
173         {
174             if (m_enforce_valid_object)
175             {
176                 lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
177 
178                 const char *selfErrorString = "Stopped in an Objective-C method, but 'self' isn't available; pretending we are in a generic context";
179 
180                 if (!variable_list_sp)
181                 {
182                     err.SetErrorString(selfErrorString);
183                     return;
184                 }
185 
186                 lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
187 
188                 if (!self_variable_sp ||
189                     !self_variable_sp->IsInScope(frame) ||
190                     !self_variable_sp->LocationIsValidForFrame (frame))
191                 {
192                     err.SetErrorString(selfErrorString);
193                     return;
194                 }
195             }
196 
197             m_in_objectivec_method = true;
198             m_needs_object_ptr = true;
199 
200             if (!method_decl->isInstanceMethod())
201                 m_in_static_method = true;
202         }
203     }
204     else if (clang::FunctionDecl *function_decl = ClangASTContext::DeclContextGetAsFunctionDecl(decl_context))
205     {
206         // We might also have a function that said in the debug information that it captured an
207         // object pointer.  The best way to deal with getting to the ivars at present is by pretending
208         // that this is a method of a class in whatever runtime the debug info says the object pointer
209         // belongs to.  Do that here.
210 
211         ClangASTMetadata *metadata = ClangASTContext::DeclContextGetMetaData (decl_context, function_decl);
212         if (metadata && metadata->HasObjectPtr())
213         {
214             lldb::LanguageType language = metadata->GetObjectPtrLanguage();
215             if (language == lldb::eLanguageTypeC_plus_plus)
216             {
217                 if (m_enforce_valid_object)
218                 {
219                     lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
220 
221                     const char *thisErrorString = "Stopped in a context claiming to capture a C++ object pointer, but 'this' isn't available; pretending we are in a generic context";
222 
223                     if (!variable_list_sp)
224                     {
225                         err.SetErrorString(thisErrorString);
226                         return;
227                     }
228 
229                     lldb::VariableSP this_var_sp (variable_list_sp->FindVariable(ConstString("this")));
230 
231                     if (!this_var_sp ||
232                         !this_var_sp->IsInScope(frame) ||
233                         !this_var_sp->LocationIsValidForFrame (frame))
234                     {
235                         err.SetErrorString(thisErrorString);
236                         return;
237                     }
238                 }
239 
240                 m_in_cplusplus_method = true;
241                 m_needs_object_ptr = true;
242             }
243             else if (language == lldb::eLanguageTypeObjC)
244             {
245                 if (m_enforce_valid_object)
246                 {
247                     lldb::VariableListSP variable_list_sp (function_block->GetBlockVariableList (true));
248 
249                     const char *selfErrorString = "Stopped in a context claiming to capture an Objective-C object pointer, but 'self' isn't available; pretending we are in a generic context";
250 
251                     if (!variable_list_sp)
252                     {
253                         err.SetErrorString(selfErrorString);
254                         return;
255                     }
256 
257                     lldb::VariableSP self_variable_sp = variable_list_sp->FindVariable(ConstString("self"));
258 
259                     if (!self_variable_sp ||
260                         !self_variable_sp->IsInScope(frame) ||
261                         !self_variable_sp->LocationIsValidForFrame (frame))
262                     {
263                         err.SetErrorString(selfErrorString);
264                         return;
265                     }
266 
267                     Type *self_type = self_variable_sp->GetType();
268 
269                     if (!self_type)
270                     {
271                         err.SetErrorString(selfErrorString);
272                         return;
273                     }
274 
275                     CompilerType self_clang_type = self_type->GetForwardCompilerType ();
276 
277                     if (!self_clang_type)
278                     {
279                         err.SetErrorString(selfErrorString);
280                         return;
281                     }
282 
283                     if (ClangASTContext::IsObjCClassType(self_clang_type))
284                     {
285                         return;
286                     }
287                     else if (ClangASTContext::IsObjCObjectPointerType(self_clang_type))
288                     {
289                         m_in_objectivec_method = true;
290                         m_needs_object_ptr = true;
291                     }
292                     else
293                     {
294                         err.SetErrorString(selfErrorString);
295                         return;
296                     }
297                 }
298                 else
299                 {
300                     m_in_objectivec_method = true;
301                     m_needs_object_ptr = true;
302                 }
303             }
304         }
305     }
306 }
307 
308 // This is a really nasty hack, meant to fix Objective-C expressions of the form
309 // (int)[myArray count].  Right now, because the type information for count is
310 // not available, [myArray count] returns id, which can't be directly cast to
311 // int without causing a clang error.
312 static void
313 ApplyObjcCastHack(std::string &expr)
314 {
315 #define OBJC_CAST_HACK_FROM "(int)["
316 #define OBJC_CAST_HACK_TO   "(int)(long long)["
317 
318     size_t from_offset;
319 
320     while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
321         expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1, OBJC_CAST_HACK_TO);
322 
323 #undef OBJC_CAST_HACK_TO
324 #undef OBJC_CAST_HACK_FROM
325 }
326 
327 bool
328 ClangUserExpression::Parse (Stream &error_stream,
329                             ExecutionContext &exe_ctx,
330                             lldb_private::ExecutionPolicy execution_policy,
331                             bool keep_result_in_memory,
332                             bool generate_debug_info)
333 {
334     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
335 
336     Error err;
337 
338     InstallContext(exe_ctx);
339 
340     if (Target *target = exe_ctx.GetTargetPtr())
341     {
342         if (PersistentExpressionState *persistent_state = target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))
343         {
344             m_result_delegate.RegisterPersistentState(persistent_state);
345         }
346         else
347         {
348             error_stream.PutCString ("error: couldn't start parsing (no persistent data)");
349             return false;
350         }
351     }
352     else
353     {
354         error_stream.PutCString ("error: couldn't start parsing (no target)");
355         return false;
356     }
357 
358     ScanContext(exe_ctx, err);
359 
360     if (!err.Success())
361     {
362         error_stream.Printf("warning: %s\n", err.AsCString());
363     }
364 
365     StreamString m_transformed_stream;
366 
367     ////////////////////////////////////
368     // Generate the expression
369     //
370 
371     ApplyObjcCastHack(m_expr_text);
372     //ApplyUnicharHack(m_expr_text);
373 
374     std::string prefix = m_expr_prefix;
375 
376     if (ClangModulesDeclVendor *decl_vendor = m_target->GetClangModulesDeclVendor())
377     {
378         const ClangModulesDeclVendor::ModuleVector &hand_imported_modules = llvm::cast<ClangPersistentVariables>(m_target->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC))->GetHandLoadedClangModules();
379         ClangModulesDeclVendor::ModuleVector modules_for_macros;
380 
381         for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules)
382         {
383             modules_for_macros.push_back(module);
384         }
385 
386         if (m_target->GetEnableAutoImportClangModules())
387         {
388             if (StackFrame *frame = exe_ctx.GetFramePtr())
389             {
390                 if (Block *block = frame->GetFrameBlock())
391                 {
392                     SymbolContext sc;
393 
394                     block->CalculateSymbolContext(&sc);
395 
396                     if (sc.comp_unit)
397                     {
398                         StreamString error_stream;
399 
400                         decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros, error_stream);
401                     }
402                 }
403             }
404         }
405     }
406 
407     std::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(prefix.c_str(), m_expr_text.c_str()));
408 
409     lldb::LanguageType lang_type;
410 
411     if (m_in_cplusplus_method)
412         lang_type = lldb::eLanguageTypeC_plus_plus;
413     else if (m_in_objectivec_method)
414         lang_type = lldb::eLanguageTypeObjC;
415     else
416         lang_type = lldb::eLanguageTypeC;
417 
418     if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_in_static_method, exe_ctx))
419     {
420         error_stream.PutCString ("error: couldn't construct expression body");
421         return false;
422     }
423 
424     if (log)
425         log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
426 
427     ////////////////////////////////////
428     // Set up the target and compiler
429     //
430 
431     Target *target = exe_ctx.GetTargetPtr();
432 
433     if (!target)
434     {
435         error_stream.PutCString ("error: invalid target\n");
436         return false;
437     }
438 
439     //////////////////////////
440     // Parse the expression
441     //
442 
443     m_materializer_ap.reset(new Materializer());
444 
445     ResetDeclMap(exe_ctx, m_result_delegate, keep_result_in_memory);
446 
447     class OnExit
448     {
449     public:
450         typedef std::function <void (void)> Callback;
451 
452         OnExit (Callback const &callback) :
453             m_callback(callback)
454         {
455         }
456 
457         ~OnExit ()
458         {
459             m_callback();
460         }
461     private:
462         Callback m_callback;
463     };
464 
465     OnExit on_exit([this]() { ResetDeclMap(); });
466 
467     if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get()))
468     {
469         error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");
470 
471         ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.
472 
473         return false;
474     }
475 
476     Process *process = exe_ctx.GetProcessPtr();
477     ExecutionContextScope *exe_scope = process;
478 
479     if (!exe_scope)
480         exe_scope = exe_ctx.GetTargetPtr();
481 
482     ClangExpressionParser parser(exe_scope, *this, generate_debug_info);
483 
484     unsigned num_errors = parser.Parse (error_stream);
485 
486     if (num_errors)
487     {
488         error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
489 
490         ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.
491 
492         return false;
493     }
494 
495     //////////////////////////////////////////////////////////////////////////////////////////
496     // Prepare the output of the parser for execution, evaluating it statically if possible
497     //
498 
499     Error jit_error = parser.PrepareForExecution (m_jit_start_addr,
500                                                   m_jit_end_addr,
501                                                   m_execution_unit_sp,
502                                                   exe_ctx,
503                                                   m_can_interpret,
504                                                   execution_policy);
505 
506     if (generate_debug_info)
507     {
508         lldb::ModuleSP jit_module_sp ( m_execution_unit_sp->GetJITModule());
509 
510         if (jit_module_sp)
511         {
512             ConstString const_func_name(FunctionName());
513             FileSpec jit_file;
514             jit_file.GetFilename() = const_func_name;
515             jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString());
516             m_jit_module_wp = jit_module_sp;
517             target->GetImages().Append(jit_module_sp);
518         }
519 //        lldb_private::ObjectFile *jit_obj_file = jit_module_sp->GetObjectFile();
520 //        StreamFile strm (stdout, false);
521 //        if (jit_obj_file)
522 //        {
523 //            jit_obj_file->GetSectionList();
524 //            jit_obj_file->GetSymtab();
525 //            jit_obj_file->Dump(&strm);
526 //        }
527 //        lldb_private::SymbolVendor *jit_sym_vendor = jit_module_sp->GetSymbolVendor();
528 //        if (jit_sym_vendor)
529 //        {
530 //            lldb_private::SymbolContextList sc_list;
531 //            jit_sym_vendor->FindFunctions(const_func_name, NULL, lldb::eFunctionNameTypeFull, true, false, sc_list);
532 //            sc_list.Dump(&strm, target);
533 //            jit_sym_vendor->Dump(&strm);
534 //        }
535     }
536 
537     ResetDeclMap(); // Make this go away since we don't need any of its state after parsing.  This also gets rid of any ClangASTImporter::Minions.
538 
539     if (jit_error.Success())
540     {
541         if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
542             m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
543         return true;
544     }
545     else
546     {
547         const char *error_cstr = jit_error.AsCString();
548         if (error_cstr && error_cstr[0])
549             error_stream.Printf ("error: %s\n", error_cstr);
550         else
551             error_stream.Printf ("error: expression can't be interpreted or run\n");
552         return false;
553     }
554 }
555 
556 bool
557 ClangUserExpression::AddInitialArguments (ExecutionContext &exe_ctx,
558                                           std::vector<lldb::addr_t> &args,
559                                           Stream &error_stream)
560 {
561     lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
562     lldb::addr_t cmd_ptr    = LLDB_INVALID_ADDRESS;
563 
564     if (m_needs_object_ptr)
565     {
566         lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
567         if (!frame_sp)
568             return true;
569 
570         ConstString object_name;
571 
572         if (m_in_cplusplus_method)
573         {
574             object_name.SetCString("this");
575         }
576         else if (m_in_objectivec_method)
577         {
578             object_name.SetCString("self");
579         }
580         else
581         {
582             error_stream.Printf("Need object pointer but don't know the language\n");
583             return false;
584         }
585 
586         Error object_ptr_error;
587 
588         object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
589 
590         if (!object_ptr_error.Success())
591         {
592             error_stream.Printf("warning: couldn't get required object pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
593             object_ptr = 0;
594         }
595 
596         if (m_in_objectivec_method)
597         {
598             ConstString cmd_name("_cmd");
599 
600             cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
601 
602             if (!object_ptr_error.Success())
603             {
604                 error_stream.Printf("warning: couldn't get cmd pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
605                 cmd_ptr = 0;
606             }
607         }
608         if (object_ptr)
609             args.push_back(object_ptr);
610 
611         if (m_in_objectivec_method)
612             args.push_back(cmd_ptr);
613 
614 
615     }
616     return true;
617 }
618 
619 lldb::ExpressionVariableSP
620 ClangUserExpression::GetResultAfterDematerialization(ExecutionContextScope *exe_scope)
621 {
622     return m_result_delegate.GetVariable();
623 }
624 
625 void
626 ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(ExecutionContext &exe_ctx, Materializer::PersistentVariableDelegate &delegate, bool keep_result_in_memory)
627 {
628     m_expr_decl_map_up.reset(new ClangExpressionDeclMap(keep_result_in_memory, &delegate, exe_ctx));
629 }
630 
631 clang::ASTConsumer *
632 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer (clang::ASTConsumer *passthrough)
633 {
634     m_result_synthesizer_up.reset(new ASTResultSynthesizer(passthrough,
635                                                            m_target));
636 
637     return m_result_synthesizer_up.get();
638 }
639 
640 ClangUserExpression::ResultDelegate::ResultDelegate()
641 {
642 }
643 
644 ConstString
645 ClangUserExpression::ResultDelegate::GetName()
646 {
647     return m_persistent_state->GetNextPersistentVariableName();
648 }
649 
650 void
651 ClangUserExpression::ResultDelegate::DidDematerialize(lldb::ExpressionVariableSP &variable)
652 {
653     m_variable = variable;
654 }
655 
656 void
657 ClangUserExpression::ResultDelegate::RegisterPersistentState(PersistentExpressionState *persistent_state)
658 {
659     m_persistent_state = persistent_state;
660 }
661 
662 lldb::ExpressionVariableSP &
663 ClangUserExpression::ResultDelegate::GetVariable()
664 {
665     return m_variable;
666 }
667 
668