[PATCH] D105461: [Support] CommandLine.cpp - Fix thread race condition in addOption

Wenju He via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 5 23:57:25 PDT 2021


wenju created this revision.
wenju added reviewers: hintonda, aaron.ballman, fzou1.
Herald added subscribers: dexonsmith, hiraditya.
wenju requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

If multiple threads executes addOption concurrently, there is a race condition between find and insert operation to SC->OptionsMap.

It is fixed by adding a mutex.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D105461

Files:
  llvm/lib/Support/CommandLine.cpp


Index: llvm/lib/Support/CommandLine.cpp
===================================================================
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -43,6 +43,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include <cstdlib>
 #include <map>
+#include <mutex>
 #include <string>
 using namespace llvm;
 using namespace cl;
@@ -207,6 +208,9 @@
   void addOption(Option *O, SubCommand *SC) {
     bool HadErrors = false;
     if (O->hasArgStr()) {
+      // Guard find/insert operations to SC->OptionsMap.
+      std::lock_guard<std::mutex> Lock(OptionsMapMutex);
+
       // If it's a DefaultOption, check to make sure it isn't already there.
       if (O->isDefaultOption() &&
           SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
@@ -417,6 +421,7 @@
 
 private:
   SubCommand *ActiveSubCommand;
+  std::mutex OptionsMapMutex;
 
   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D105461.356613.patch
Type: text/x-patch
Size: 1030 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210706/057dc293/attachment.bin>


More information about the llvm-commits mailing list