Bug Summary

File:tools/lldb/source/Expression/ClangExpressionParser.cpp
Location:line 315, column 13
Description:Call to function 'mktemp' is insecure as it always creates or uses insecure temporary file. Use 'mkstemp' instead

Annotated Source Code

1//===-- ClangExpressionParser.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 "lldb/lldb-python.h"
11
12#include "lldb/Expression/ClangExpressionParser.h"
13
14#include "lldb/Core/ArchSpec.h"
15#include "lldb/Core/DataBufferHeap.h"
16#include "lldb/Core/Debugger.h"
17#include "lldb/Core/Disassembler.h"
18#include "lldb/Core/Module.h"
19#include "lldb/Core/Stream.h"
20#include "lldb/Core/StreamFile.h"
21#include "lldb/Core/StreamString.h"
22#include "lldb/Expression/ClangASTSource.h"
23#include "lldb/Expression/ClangExpression.h"
24#include "lldb/Expression/ClangExpressionDeclMap.h"
25#include "lldb/Expression/IRExecutionUnit.h"
26#include "lldb/Expression/IRDynamicChecks.h"
27#include "lldb/Expression/IRInterpreter.h"
28#include "lldb/Host/File.h"
29#include "lldb/Host/HostInfo.h"
30#include "lldb/Symbol/SymbolVendor.h"
31#include "lldb/Target/ExecutionContext.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
33#include "lldb/Target/Process.h"
34#include "lldb/Target/Target.h"
35
36#include "clang/AST/ASTContext.h"
37#include "clang/AST/ExternalASTSource.h"
38#include "clang/Basic/FileManager.h"
39#include "clang/Basic/TargetInfo.h"
40#include "clang/Basic/Version.h"
41#include "clang/CodeGen/CodeGenAction.h"
42#include "clang/CodeGen/ModuleBuilder.h"
43#include "clang/Frontend/CompilerInstance.h"
44#include "clang/Frontend/CompilerInvocation.h"
45#include "clang/Frontend/FrontendActions.h"
46#include "clang/Frontend/FrontendDiagnostic.h"
47#include "clang/Frontend/FrontendPluginRegistry.h"
48#include "clang/Frontend/TextDiagnosticBuffer.h"
49#include "clang/Frontend/TextDiagnosticPrinter.h"
50#include "clang/Lex/Preprocessor.h"
51#include "clang/Parse/ParseAST.h"
52#include "clang/Rewrite/Frontend/FrontendActions.h"
53#include "clang/Sema/SemaConsumer.h"
54#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
55
56#include "llvm/ADT/StringRef.h"
57#include "llvm/ExecutionEngine/ExecutionEngine.h"
58#include "llvm/Support/Debug.h"
59#include "llvm/Support/FileSystem.h"
60#include "llvm/Support/TargetSelect.h"
61
62#include "llvm/ExecutionEngine/MCJIT.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Module.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include "llvm/Support/DynamicLibrary.h"
68#include "llvm/Support/Host.h"
69#include "llvm/Support/Signals.h"
70
71using namespace clang;
72using namespace llvm;
73using namespace lldb_private;
74
75//===----------------------------------------------------------------------===//
76// Utility Methods for Clang
77//===----------------------------------------------------------------------===//
78
79std::string GetBuiltinIncludePath(const char *Argv0) {
80 SmallString<128> P(llvm::sys::fs::getMainExecutable(
81 Argv0, (void *)(intptr_t) GetBuiltinIncludePath));
82
83 if (!P.empty()) {
84 llvm::sys::path::remove_filename(P); // Remove /clang from foo/bin/clang
85 llvm::sys::path::remove_filename(P); // Remove /bin from foo/bin
86
87 // Get foo/lib/clang/<version>/include
88 llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING"3.6.0",
89 "include");
90 }
91
92 return P.str();
93}
94
95//===----------------------------------------------------------------------===//
96// Implementation of ClangExpressionParser
97//===----------------------------------------------------------------------===//
98
99ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
100 ClangExpression &expr,
101 bool generate_debug_info) :
102 m_expr (expr),
103 m_compiler (),
104 m_code_generator ()
105{
106 // 1. Create a new compiler instance.
107 m_compiler.reset(new CompilerInstance());
108
109 // 2. Install the target.
110
111 lldb::TargetSP target_sp;
112 if (exe_scope)
113 target_sp = exe_scope->CalculateTarget();
114
115 // TODO: figure out what to really do when we don't have a valid target.
116 // Sometimes this will be ok to just use the host target triple (when we
117 // evaluate say "2+3", but other expressions like breakpoint conditions
118 // and other things that _are_ target specific really shouldn't just be
119 // using the host triple. This needs to be fixed in a better way.
120 if (target_sp && target_sp->GetArchitecture().IsValid())
121 {
122 std::string triple = target_sp->GetArchitecture().GetTriple().str();
123 m_compiler->getTargetOpts().Triple = triple;
124 }
125 else
126 {
127 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
128 }
129
130 if (target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86 ||
131 target_sp->GetArchitecture().GetMachine() == llvm::Triple::x86_64)
132 {
133 m_compiler->getTargetOpts().Features.push_back("+sse");
134 m_compiler->getTargetOpts().Features.push_back("+sse2");
135 }
136
137 // Any arm32 iOS environment, but not on arm64
138 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
139 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
140 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
141 {
142 m_compiler->getTargetOpts().ABI = "apcs-gnu";
143 }
144
145 m_compiler->createDiagnostics();
146
147 // Create the target instance.
148 m_compiler->setTarget(TargetInfo::CreateTargetInfo(
149 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts));
150
151 assert (m_compiler->hasTarget())((m_compiler->hasTarget()) ? static_cast<void> (0) :
__assert_fail ("m_compiler->hasTarget()", "/tmp/buildd/llvm-toolchain-snapshot-3.6~svn219601/tools/lldb/source/Expression/ClangExpressionParser.cpp"
, 151, __PRETTY_FUNCTION__))
;
152
153 // 3. Set options.
154
155 lldb::LanguageType language = expr.Language();
156
157 switch (language)
158 {
159 case lldb::eLanguageTypeC:
160 break;
161 case lldb::eLanguageTypeObjC:
162 m_compiler->getLangOpts().ObjC1 = true;
163 m_compiler->getLangOpts().ObjC2 = true;
164 break;
165 case lldb::eLanguageTypeC_plus_plus:
166 m_compiler->getLangOpts().CPlusPlus = true;
167 m_compiler->getLangOpts().CPlusPlus11 = true;
168 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
169 break;
170 case lldb::eLanguageTypeObjC_plus_plus:
171 default:
172 m_compiler->getLangOpts().ObjC1 = true;
173 m_compiler->getLangOpts().ObjC2 = true;
174 m_compiler->getLangOpts().CPlusPlus = true;
175 m_compiler->getLangOpts().CPlusPlus11 = true;
176 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
177 break;
178 }
179
180 m_compiler->getLangOpts().Bool = true;
181 m_compiler->getLangOpts().WChar = true;
182 m_compiler->getLangOpts().Blocks = true;
183 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
184 if (expr.DesiredResultType() == ClangExpression::eResultTypeId)
185 m_compiler->getLangOpts().DebuggerCastResultToId = true;
186
187 // Spell checking is a nice feature, but it ends up completing a
188 // lot of types that we didn't strictly speaking need to complete.
189 // As a result, we spend a long time parsing and importing debug
190 // information.
191 m_compiler->getLangOpts().SpellChecking = false;
192
193 lldb::ProcessSP process_sp;
194 if (exe_scope)
195 process_sp = exe_scope->CalculateProcess();
196
197 if (process_sp && m_compiler->getLangOpts().ObjC1)
198 {
199 if (process_sp->GetObjCLanguageRuntime())
200 {
201 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
202 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
203 else
204 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
205
206 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
207 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
208 }
209 }
210
211 m_compiler->getLangOpts().ThreadsafeStatics = false;
212 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
213 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
214
215 // Set CodeGen options
216 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
217 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
218 m_compiler->getCodeGenOpts().DisableFPElim = true;
219 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
220 if (generate_debug_info)
221 m_compiler->getCodeGenOpts().setDebugInfo(CodeGenOptions::FullDebugInfo);
222 else
223 m_compiler->getCodeGenOpts().setDebugInfo(CodeGenOptions::NoDebugInfo);
224
225 // Disable some warnings.
226 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
227 "unused-value", clang::diag::Severity::Ignored, SourceLocation());
228 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
229 "odr", clang::diag::Severity::Ignored, SourceLocation());
230
231 // Inform the target of the language options
232 //
233 // FIXME: We shouldn't need to do this, the target should be immutable once
234 // created. This complexity should be lifted elsewhere.
235 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
236
237 // 4. Set up the diagnostic buffer for reporting errors
238
239 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
240
241 // 5. Set up the source management objects inside the compiler
242
243 clang::FileSystemOptions file_system_options;
244 m_file_manager.reset(new clang::FileManager(file_system_options));
245
246 if (!m_compiler->hasSourceManager())
247 m_compiler->createSourceManager(*m_file_manager.get());
248
249 m_compiler->createFileManager();
250 m_compiler->createPreprocessor(TU_Complete);
251
252 // 6. Most of this we get from the CompilerInstance, but we
253 // also want to give the context an ExternalASTSource.
254 m_selector_table.reset(new SelectorTable());
255 m_builtin_context.reset(new Builtin::Context());
256
257 std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
258 m_compiler->getSourceManager(),
259 m_compiler->getPreprocessor().getIdentifierTable(),
260 *m_selector_table.get(),
261 *m_builtin_context.get()));
262 ast_context->InitBuiltinTypes(m_compiler->getTarget());
263
264 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
265
266 if (decl_map)
267 {
268 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
269 decl_map->InstallASTContext(ast_context.get());
270 ast_context->setExternalSource(ast_source);
271 }
272
273 m_compiler->setASTContext(ast_context.release());
274
275 std::string module_name("$__lldb_module");
276
277 m_llvm_context.reset(new LLVMContext());
278 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
279 module_name,
280 m_compiler->getCodeGenOpts(),
281 m_compiler->getTargetOpts(),
282 *m_llvm_context));
283}
284
285ClangExpressionParser::~ClangExpressionParser()
286{
287}
288
289unsigned
290ClangExpressionParser::Parse (Stream &stream)
291{
292 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
293
294 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
295
296 const char *expr_text = m_expr.Text();
297
298 clang::SourceManager &SourceMgr = m_compiler->getSourceManager();
299 bool created_main_file = false;
300 if (m_compiler->getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo)
301 {
302 std::string temp_source_path;
303
304 FileSpec tmpdir_file_spec;
305 if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
306 {
307 tmpdir_file_spec.AppendPathComponent("expr.XXXXXX");
308 temp_source_path = std::move(tmpdir_file_spec.GetPath());
309 }
310 else
311 {
312 temp_source_path = "/tmp/expr.XXXXXX";
313 }
314
315 if (mktemp(&temp_source_path[0]))
Call to function 'mktemp' is insecure as it always creates or uses insecure temporary file. Use 'mkstemp' instead
316 {
317 lldb_private::File file (temp_source_path.c_str(),
318 File::eOpenOptionWrite | File::eOpenOptionCanCreateNewOnly,
319 lldb::eFilePermissionsFileDefault);
320 const size_t expr_text_len = strlen(expr_text);
321 size_t bytes_written = expr_text_len;
322 if (file.Write(expr_text, bytes_written).Success())
323 {
324 if (bytes_written == expr_text_len)
325 {
326 file.Close();
327 SourceMgr.setMainFileID(SourceMgr.createFileID(
328 m_file_manager->getFile(temp_source_path),
329 SourceLocation(), SrcMgr::C_User));
330 created_main_file = true;
331 }
332 }
333 }
334 }
335
336 if (!created_main_file)
337 {
338 std::unique_ptr<MemoryBuffer> memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
339 SourceMgr.setMainFileID(SourceMgr.createFileID(std::move(memory_buffer)));
340 }
341
342 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
343
344 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
345
346 if (ast_transformer)
347 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
348 else
349 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
350
351 diag_buf->EndSourceFile();
352
353 TextDiagnosticBuffer::const_iterator diag_iterator;
354
355 int num_errors = 0;
356
357 for (diag_iterator = diag_buf->warn_begin();
358 diag_iterator != diag_buf->warn_end();
359 ++diag_iterator)
360 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
361
362 num_errors = 0;
363
364 for (diag_iterator = diag_buf->err_begin();
365 diag_iterator != diag_buf->err_end();
366 ++diag_iterator)
367 {
368 num_errors++;
369 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
370 }
371
372 for (diag_iterator = diag_buf->note_begin();
373 diag_iterator != diag_buf->note_end();
374 ++diag_iterator)
375 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
376
377 if (!num_errors)
378 {
379 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
380 {
381 stream.Printf("error: Couldn't infer the type of a variable\n");
382 num_errors++;
383 }
384 }
385
386 return num_errors;
387}
388
389static bool FindFunctionInModule (ConstString &mangled_name,
390 llvm::Module *module,
391 const char *orig_name)
392{
393 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
394 fi != fe;
395 ++fi)
396 {
397 if (fi->getName().str().find(orig_name) != std::string::npos)
398 {
399 mangled_name.SetCString(fi->getName().str().c_str());
400 return true;
401 }
402 }
403
404 return false;
405}
406
407Error
408ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
409 lldb::addr_t &func_end,
410 std::shared_ptr<IRExecutionUnit> &execution_unit_sp,
411 ExecutionContext &exe_ctx,
412 bool &can_interpret,
413 ExecutionPolicy execution_policy)
414{
415 func_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
416 func_end = LLDB_INVALID_ADDRESS(18446744073709551615UL);
417 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
418
419 Error err;
420
421 std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule());
422
423 if (!llvm_module_ap.get())
424 {
425 err.SetErrorToGenericError();
426 err.SetErrorString("IR doesn't contain a module");
427 return err;
428 }
429
430 // Find the actual name of the function (it's often mangled somehow)
431
432 ConstString function_name;
433
434 if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName()))
435 {
436 err.SetErrorToGenericError();
437 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
438 return err;
439 }
440 else
441 {
442 if (log)
443 log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName());
444 }
445
446 execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here
447 llvm_module_ap, // handed off here
448 function_name,
449 exe_ctx.GetTargetSP(),
450 m_compiler->getTargetOpts().Features));
451
452 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
453
454 if (decl_map)
455 {
456 Stream *error_stream = NULL__null;
457 Target *target = exe_ctx.GetTargetPtr();
458 if (target)
459 error_stream = target->GetDebugger().GetErrorFile().get();
460
461 IRForTarget ir_for_target(decl_map,
462 m_expr.NeedsVariableResolution(),
463 *execution_unit_sp,
464 error_stream,
465 function_name.AsCString());
466
467 bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule());
468
469 Error interpret_error;
470
471 can_interpret = IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(), interpret_error);
472
473 Process *process = exe_ctx.GetProcessPtr();
474
475 if (!ir_can_run)
476 {
477 err.SetErrorString("The expression could not be prepared to run in the target");
478 return err;
479 }
480
481 if (!can_interpret && execution_policy == eExecutionPolicyNever)
482 {
483 err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString());
484 return err;
485 }
486
487 if (!process && execution_policy == eExecutionPolicyAlways)
488 {
489 err.SetErrorString("Expression needed to run in the target, but the target can't be run");
490 return err;
491 }
492
493 if (execution_policy == eExecutionPolicyAlways || !can_interpret)
494 {
495 if (m_expr.NeedsValidation() && process)
496 {
497 if (!process->GetDynamicCheckers())
498 {
499 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
500
501 StreamString install_errors;
502
503 if (!dynamic_checkers->Install(install_errors, exe_ctx))
504 {
505 if (install_errors.GetString().empty())
506 err.SetErrorString ("couldn't install checkers, unknown error");
507 else
508 err.SetErrorString (install_errors.GetString().c_str());
509
510 return err;
511 }
512
513 process->SetDynamicCheckers(dynamic_checkers);
514
515 if (log)
516 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
517 }
518
519 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString());
520
521 if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule()))
522 {
523 err.SetErrorToGenericError();
524 err.SetErrorString("Couldn't add dynamic checks to the expression");
525 return err;
526 }
527 }
528
529 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
530 }
531 }
532 else
533 {
534 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
535 }
536
537 return err;
538}
539
540bool
541ClangExpressionParser::GetGenerateDebugInfo () const
542{
543 if (m_compiler)
544 return m_compiler->getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
545 return false;
546}