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     ScanContext(exe_ctx, err);
341 
342     if (!err.Success())
343     {
344         error_stream.Printf("warning: %s\n", err.AsCString());
345     }
346 
347     StreamString m_transformed_stream;
348 
349     ////////////////////////////////////
350     // Generate the expression
351     //
352 
353     ApplyObjcCastHack(m_expr_text);
354     //ApplyUnicharHack(m_expr_text);
355 
356     std::string prefix = m_expr_prefix;
357 
358     if (ClangModulesDeclVendor *decl_vendor = m_target->GetClangModulesDeclVendor())
359     {
360         const ClangModulesDeclVendor::ModuleVector &hand_imported_modules = llvm::cast<ClangPersistentVariables>(m_target->GetScratchTypeSystemForLanguage(lldb::eLanguageTypeC)->GetPersistentExpressionState())->GetHandLoadedClangModules();
361         ClangModulesDeclVendor::ModuleVector modules_for_macros;
362 
363         for (ClangModulesDeclVendor::ModuleID module : hand_imported_modules)
364         {
365             modules_for_macros.push_back(module);
366         }
367 
368         if (m_target->GetEnableAutoImportClangModules())
369         {
370             if (StackFrame *frame = exe_ctx.GetFramePtr())
371             {
372                 if (Block *block = frame->GetFrameBlock())
373                 {
374                     SymbolContext sc;
375 
376                     block->CalculateSymbolContext(&sc);
377 
378                     if (sc.comp_unit)
379                     {
380                         StreamString error_stream;
381 
382                         decl_vendor->AddModulesForCompileUnit(*sc.comp_unit, modules_for_macros, error_stream);
383                     }
384                 }
385             }
386         }
387     }
388 
389     std::unique_ptr<ExpressionSourceCode> source_code (ExpressionSourceCode::CreateWrapped(prefix.c_str(), m_expr_text.c_str()));
390 
391     lldb::LanguageType lang_type;
392 
393     if (m_in_cplusplus_method)
394         lang_type = lldb::eLanguageTypeC_plus_plus;
395     else if (m_in_objectivec_method)
396         lang_type = lldb::eLanguageTypeObjC;
397     else
398         lang_type = lldb::eLanguageTypeC;
399 
400     if (!source_code->GetText(m_transformed_text, lang_type, m_const_object, m_in_static_method, exe_ctx))
401     {
402         error_stream.PutCString ("error: couldn't construct expression body");
403         return false;
404     }
405 
406     if (log)
407         log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
408 
409     ////////////////////////////////////
410     // Set up the target and compiler
411     //
412 
413     Target *target = exe_ctx.GetTargetPtr();
414 
415     if (!target)
416     {
417         error_stream.PutCString ("error: invalid target\n");
418         return false;
419     }
420 
421     //////////////////////////
422     // Parse the expression
423     //
424 
425     m_materializer_ap.reset(new Materializer());
426 
427     ResetDeclMap(exe_ctx, keep_result_in_memory);
428 
429     class OnExit
430     {
431     public:
432         typedef std::function <void (void)> Callback;
433 
434         OnExit (Callback const &callback) :
435             m_callback(callback)
436         {
437         }
438 
439         ~OnExit ()
440         {
441             m_callback();
442         }
443     private:
444         Callback m_callback;
445     };
446 
447     OnExit on_exit([this]() { ResetDeclMap(); });
448 
449     if (!DeclMap()->WillParse(exe_ctx, m_materializer_ap.get()))
450     {
451         error_stream.PutCString ("error: current process state is unsuitable for expression parsing\n");
452 
453         ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.
454 
455         return false;
456     }
457 
458     Process *process = exe_ctx.GetProcessPtr();
459     ExecutionContextScope *exe_scope = process;
460 
461     if (!exe_scope)
462         exe_scope = exe_ctx.GetTargetPtr();
463 
464     ClangExpressionParser parser(exe_scope, *this, generate_debug_info);
465 
466     unsigned num_errors = parser.Parse (error_stream);
467 
468     if (num_errors)
469     {
470         error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
471 
472         ResetDeclMap(); // We are being careful here in the case of breakpoint conditions.
473 
474         return false;
475     }
476 
477     //////////////////////////////////////////////////////////////////////////////////////////
478     // Prepare the output of the parser for execution, evaluating it statically if possible
479     //
480 
481     Error jit_error = parser.PrepareForExecution (m_jit_start_addr,
482                                                   m_jit_end_addr,
483                                                   m_execution_unit_sp,
484                                                   exe_ctx,
485                                                   m_can_interpret,
486                                                   execution_policy);
487 
488     if (generate_debug_info)
489     {
490         lldb::ModuleSP jit_module_sp ( m_execution_unit_sp->GetJITModule());
491 
492         if (jit_module_sp)
493         {
494             ConstString const_func_name(FunctionName());
495             FileSpec jit_file;
496             jit_file.GetFilename() = const_func_name;
497             jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString());
498             m_jit_module_wp = jit_module_sp;
499             target->GetImages().Append(jit_module_sp);
500         }
501 //        lldb_private::ObjectFile *jit_obj_file = jit_module_sp->GetObjectFile();
502 //        StreamFile strm (stdout, false);
503 //        if (jit_obj_file)
504 //        {
505 //            jit_obj_file->GetSectionList();
506 //            jit_obj_file->GetSymtab();
507 //            jit_obj_file->Dump(&strm);
508 //        }
509 //        lldb_private::SymbolVendor *jit_sym_vendor = jit_module_sp->GetSymbolVendor();
510 //        if (jit_sym_vendor)
511 //        {
512 //            lldb_private::SymbolContextList sc_list;
513 //            jit_sym_vendor->FindFunctions(const_func_name, NULL, lldb::eFunctionNameTypeFull, true, false, sc_list);
514 //            sc_list.Dump(&strm, target);
515 //            jit_sym_vendor->Dump(&strm);
516 //        }
517     }
518 
519     ResetDeclMap(); // Make this go away since we don't need any of its state after parsing.  This also gets rid of any ClangASTImporter::Minions.
520 
521     if (jit_error.Success())
522     {
523         if (process && m_jit_start_addr != LLDB_INVALID_ADDRESS)
524             m_jit_process_wp = lldb::ProcessWP(process->shared_from_this());
525         return true;
526     }
527     else
528     {
529         const char *error_cstr = jit_error.AsCString();
530         if (error_cstr && error_cstr[0])
531             error_stream.Printf ("error: %s\n", error_cstr);
532         else
533             error_stream.Printf ("error: expression can't be interpreted or run\n");
534         return false;
535     }
536 }
537 
538 bool
539 ClangUserExpression::AddInitialArguments (ExecutionContext &exe_ctx,
540                                           std::vector<lldb::addr_t> &args,
541                                           Stream &error_stream)
542 {
543     lldb::addr_t object_ptr = LLDB_INVALID_ADDRESS;
544     lldb::addr_t cmd_ptr    = LLDB_INVALID_ADDRESS;
545 
546     if (m_needs_object_ptr)
547     {
548         lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP();
549         if (!frame_sp)
550             return true;
551 
552         ConstString object_name;
553 
554         if (m_in_cplusplus_method)
555         {
556             object_name.SetCString("this");
557         }
558         else if (m_in_objectivec_method)
559         {
560             object_name.SetCString("self");
561         }
562         else
563         {
564             error_stream.Printf("Need object pointer but don't know the language\n");
565             return false;
566         }
567 
568         Error object_ptr_error;
569 
570         object_ptr = GetObjectPointer(frame_sp, object_name, object_ptr_error);
571 
572         if (!object_ptr_error.Success())
573         {
574             error_stream.Printf("warning: couldn't get required object pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
575             object_ptr = 0;
576         }
577 
578         if (m_in_objectivec_method)
579         {
580             ConstString cmd_name("_cmd");
581 
582             cmd_ptr = GetObjectPointer(frame_sp, cmd_name, object_ptr_error);
583 
584             if (!object_ptr_error.Success())
585             {
586                 error_stream.Printf("warning: couldn't get cmd pointer (substituting NULL): %s\n", object_ptr_error.AsCString());
587                 cmd_ptr = 0;
588             }
589         }
590         if (object_ptr)
591             args.push_back(object_ptr);
592 
593         if (m_in_objectivec_method)
594             args.push_back(cmd_ptr);
595 
596 
597     }
598     return true;
599 }
600 
601 void
602 ClangUserExpression::ClangUserExpressionHelper::ResetDeclMap(ExecutionContext &exe_ctx, bool keep_result_in_memory)
603 {
604     m_expr_decl_map_up.reset(new ClangExpressionDeclMap(keep_result_in_memory, exe_ctx));
605 }
606 
607 clang::ASTConsumer *
608 ClangUserExpression::ClangUserExpressionHelper::ASTTransformer (clang::ASTConsumer *passthrough)
609 {
610     m_result_synthesizer_up.reset(new ASTResultSynthesizer(passthrough,
611                                                            m_target));
612 
613     return m_result_synthesizer_up.get();
614 }
615 
616