Skip to content

Some cleanup now that it's the external repo - #2

Closed
chipturner wants to merge 1 commit into
meta:masterfrom
chipturner:master
Closed

chipturner wants to merge 1 commit into
meta:masterfrom
chipturner:master

Conversation

@chipturner

Copy link
Copy Markdown
Contributor

Needed a .gitignore and folly-config.h is generated by configure so isn't needed in this repo.

@jdelong jdelong closed this Jun 5, 2012
@jdelong

jdelong commented Jun 5, 2012

Copy link
Copy Markdown
Contributor

Merged upstream and pushed

@jdelong jdelong mentioned this pull request Mar 23, 2014
ghost pushed a commit that referenced this pull request Sep 15, 2015
Summary: avoid sillyness:

```
$ _build/opt/folly/io/async/test/async_test --gtest_list_tests
ASAN:SIGSEGV
=================================================================
==3245135==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010 (pc 0x000000583444 sp 0x7fff17ba0c40 bp 0x7fff17ba0c80 T0)
    #0 0x583443 in std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&) third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_tree.h:1138
    #1 0x583443 in std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&) third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_map.h:295
    #2 0x583443 in folly::SSLContext::setSSLLockTypes(std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >) folly/io/async/SSLContext.cpp:682
    #3 0x40e028 in Initializer folly/io/async/test/AsyncSSLSocketTest2.cpp:143
    #4 0x40e028 in __static_initialization_and_destruction_0 folly/io/async/test/AsyncSSLSocketTest2.cpp:146
    #5 0x40e028 in _GLOBAL__sub_I__ZN5folly47AsyncSSLSocketTest2_AttachDetachSSLContext_Test10test_info_E folly/io/async/test/AsyncSSLSocketTest2.cpp:147
    #6 0x66cf2e in __libc_csu_init /home/engshare/third-party2/glibc/2.20/src/glibc-2.20/csu/elf-init.c:88
    #7 0x7f7145600084 in __libc_start_main (/usr/local/fbcode/gcc-4.9-glibc-2.20-fb/lib/libc.so.6+0x20084)
    #8 0x410be5 (/data/users/lucian/fbcode2/_build/opt/folly/io/async/test/async_test+0x410be5)

AddressSanitizer can not provide additional info.
AAAAAAASUMMARY: AddressSanitizer: SEGV third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_tree.h:1138 std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&)
==3245135==ABORTING
```

Reviewed By: @philippv

Differential Revision: D2440796
ghost pushed a commit that referenced this pull request Sep 17, 2015
Summary: Instead of the default lazy-loading behavior (still the default) some singletons might need to get initialized at startup time.  This would be for singletons which take a long time for the instance's constructor to run, e.g. expensive initialization by reading some large dataset, talking to an outside service, and so on.

Provides a way for singletons to opt-in to this, and get populated at the time  `registrationComplete()` is called, instead of lazily.

Some notes about the way I implemented here, mainly, why I did this as a "builder-pattern" kind of thing and not some other way.  I could probably be convinced to do otherwise. :)

* Changing the constructor: the constructor's already slightly fiddly with the two optional -- well, one optional construct function, and another optional-but-only-if-construct-provided, destruct function.  Didn't want to pile more into the ctor.
* New superclass called `EagerLoadedSingleton`; just didn't want to add more classes, esp. if it's just to add one more option.
* Method like `void setEagerLoad()` that makes this eager-load; not sure where one would write the `shouldEagerLoad()` call, probably in some central initialization spot in `main()`, but all the maintenance would have to go there.  I like that it's "attached" to the singleton being defined.  (Though you can still do this.)  Bonus #2; the rule that builds the cpp containing "main" doesn't need to import this dependency and the cpp doesn't have to include Singleton just to do this eager-load call, nor the header for the type itself.
* Omitting this altogether and just saying `folly::Singleton<Foo>::get_weak()` to "ping" the singleton and bring into existence: see last point.  Still might need to have the file containing this initialization decorum include/link against Foo, as well as have one place to maintain the list of things to load up-front.

Reviewed By: @meyering

Differential Revision: D2449081
korovkin pushed a commit to korovkin/folly that referenced this pull request Oct 1, 2015
Summary: avoid sillyness:

```
$ _build/opt/folly/io/async/test/async_test --gtest_list_tests
ASAN:SIGSEGV
=================================================================
==3245135==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010 (pc 0x000000583444 sp 0x7fff17ba0c40 bp 0x7fff17ba0c80 T0)
    #0 0x583443 in std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&) third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_tree.h:1138
    meta#1 0x583443 in std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&) third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_map.h:295
    meta#2 0x583443 in folly::SSLContext::setSSLLockTypes(std::map<int, folly::SSLContext::SSLLockType, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >) folly/io/async/SSLContext.cpp:682
    meta#3 0x40e028 in Initializer folly/io/async/test/AsyncSSLSocketTest2.cpp:143
    meta#4 0x40e028 in __static_initialization_and_destruction_0 folly/io/async/test/AsyncSSLSocketTest2.cpp:146
    meta#5 0x40e028 in _GLOBAL__sub_I__ZN5folly47AsyncSSLSocketTest2_AttachDetachSSLContext_Test10test_info_E folly/io/async/test/AsyncSSLSocketTest2.cpp:147
    meta#6 0x66cf2e in __libc_csu_init /home/engshare/third-party2/glibc/2.20/src/glibc-2.20/csu/elf-init.c:88
    meta#7 0x7f7145600084 in __libc_start_main (/usr/local/fbcode/gcc-4.9-glibc-2.20-fb/lib/libc.so.6+0x20084)
    meta#8 0x410be5 (/data/users/lucian/fbcode2/_build/opt/folly/io/async/test/async_test+0x410be5)

AddressSanitizer can not provide additional info.
AAAAAAASUMMARY: AddressSanitizer: SEGV third-party2/libgcc/4.9.x/gcc-4.9-glibc-2.20-fb/024dbc3/include/c++/4.9.x/bits/stl_tree.h:1138 std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > >::operator=(std::_Rb_tree<int, std::pair<int const, folly::SSLContext::SSLLockType>, std::_Select1st<std::pair<int const, folly::SSLContext::SSLLockType> >, std::less<int>, std::allocator<std::pair<int const, folly::SSLContext::SSLLockType> > > const&)
==3245135==ABORTING
```

Reviewed By: @philippv

Differential Revision: D2440796
korovkin pushed a commit to korovkin/folly that referenced this pull request Oct 1, 2015
Summary: Instead of the default lazy-loading behavior (still the default) some singletons might need to get initialized at startup time.  This would be for singletons which take a long time for the instance's constructor to run, e.g. expensive initialization by reading some large dataset, talking to an outside service, and so on.

Provides a way for singletons to opt-in to this, and get populated at the time  `registrationComplete()` is called, instead of lazily.

Some notes about the way I implemented here, mainly, why I did this as a "builder-pattern" kind of thing and not some other way.  I could probably be convinced to do otherwise. :)

* Changing the constructor: the constructor's already slightly fiddly with the two optional -- well, one optional construct function, and another optional-but-only-if-construct-provided, destruct function.  Didn't want to pile more into the ctor.
* New superclass called `EagerLoadedSingleton`; just didn't want to add more classes, esp. if it's just to add one more option.
* Method like `void setEagerLoad()` that makes this eager-load; not sure where one would write the `shouldEagerLoad()` call, probably in some central initialization spot in `main()`, but all the maintenance would have to go there.  I like that it's "attached" to the singleton being defined.  (Though you can still do this.)  Bonus meta#2; the rule that builds the cpp containing "main" doesn't need to import this dependency and the cpp doesn't have to include Singleton just to do this eager-load call, nor the header for the type itself.
* Omitting this altogether and just saying `folly::Singleton<Foo>::get_weak()` to "ping" the singleton and bring into existence: see last point.  Still might need to have the file containing this initialization decorum include/link against Foo, as well as have one place to maintain the list of things to load up-front.

Reviewed By: @meyering

Differential Revision: D2449081
ghost pushed a commit that referenced this pull request Apr 28, 2016
Summary:
Currently you need to depend on the destructor of `ReadHolder` (using closures as in code block #1 below or empty assignment as in code block #2 below) to ensure that a `ReadHolder` goes out of scope (and unlocks) in order to subsequently acquire a write lock via `WriteHolder` without deadlocking.
This diff introduces a way of unlocking a `ReadHolder` while it's still in scope such that a `WriteHolder` can be acquired. This makes the code more straight forward (reducing the risk of deadlock due to a programmer's misunderstanding of how `SharedMutex` / the holder framework works) => see code block # 3 below
Also add some documentation about why `WriteHolder::WriteHolder(ReadHolder&&)` doesn't exist

Code Block #1 : Use of closures
```
class foo {
 public:
  std::string getMemoizedData() {
    {
      folly::SharedMutex::ReadHolder readHolder(lock_);
      if (!data_.empty()) {
        // important to return by value, otherwise caller might access
        // data_ after we release the read lock
        return data_;
      }
    }
    {
      // try again with a write lock
      folly::SharedMutex::WriteHolder writeHolder(lock_);
      if (data_.empty()) {
        data_ = "my awesome string";
      }
      return data_;
    }
  }

 private:
  folly::SharedMutex lock_;
  std::string data_;
};
```

Code Block #2 : Use of empty assignment
```
class foo {
 public:
  std::string getMemoizedData() {
    folly::SharedMutex::ReadHolder readHolder(lock_);
    if (!data_.empty()) {
      // important to return by value, otherwise caller might access
      // data_ after we release the read lock
      return data_;
    }
    readHolder = {};

    // try again with a write lock
    folly::SharedMutex::WriteHolder writeHolder(lock_);
    if (data_.empty()) {
      data_ = "my awesome string";
    }
    return data_;
  }

 private:
  folly::SharedMutex lock_;
  std::string data_;
};
```

Code Block #3 : Use of unlock()
```
class foo {
 public:
  std::string getMemoizedData() {
    folly::SharedMutex::ReadHolder readHolder(lock_);
    if (!data_.empty()) {
      // important to return by value, otherwise caller might access
      // data_ after we release the read lock
      return data_;
    }
    readHolder->unlock();

    // try again with a write lock
    folly::SharedMutex::WriteHolder writeHolder(lock_);
    if (data_.empty()) {
      data_ = "my awesome string";
    }
    return data_;
  }

 private:
  folly::SharedMutex lock_;
  std::string data_;
};
```

Reviewed By: yfeldblum

Differential Revision: D3176025

fb-gh-sync-id: c7d47ca71df08673c7c1f1fd5ed9e01a663c1797
fbshipit-source-id: c7d47ca71df08673c7c1f1fd5ed9e01a663c1797
ghost pushed a commit that referenced this pull request May 19, 2016
Summary:
```
buck-out/gen/folly/__default_headers__#default,headers/folly/FBString.h:365:7: runtime error: null pointer passed as argument 2, which is declared to never be null
third-party-buck/build/glibc/include/string.h:70:33: note: nonnull attribute specified here
    #0 0x433a39 in _ZZN5folly13fbstring_coreIcEC1EPKcmbENKUlvE_clEv ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////buck-out/gen/folly/__default_headers__#default,headers/folly/FBString.h:365:7
    #1 0x4335a9 in _ZN5folly14ScopeGuardImplIZNS_13fbstring_coreIcEC1EPKcmbEUlvE_E7executeEv ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////buck-out/gen/folly/__default_headers__#default,headers/folly/ScopeGuard.h:153:29
    #2 0x4335a9 in _ZN5folly14ScopeGuardImplIZNS_13fbstring_coreIcEC1EPKcmbEUlvE_ED2Ev ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////buck-out/gen/folly/__default_headers__#default,headers/folly/ScopeGuard.h:130
    #3 0x4335a9 in folly::fbstring_core<char>::fbstring_core(char const*, unsigned long, bool) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////buck-out/gen/folly/__default_headers__#default,headers/folly/FBString.h:427
    #4 0x4353fa in folly::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, folly::fbstring_core<char> >::basic_fbstring(char const*, unsigned long, std::allocator<char> const&) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////buck-out/gen/folly/__default_headers__#default,headers/folly/FBString.h:1038:9
```

Reviewed By: Gownta

Differential Revision: D3321266

fbshipit-source-id: 28d5aef16e91a98066a1de6bab95403fbc63eaab
ghost pushed a commit that referenced this pull request May 30, 2016
Summary: Diff #2 of 14.

Reviewed By: mzlee

Differential Revision: D3115972

fbshipit-source-id: c75cbc95f37e8f2c2bf81311a8ca08ee766fc107
@tian-yuan tian-yuan mentioned this pull request Jul 23, 2016
@tdauth tdauth mentioned this pull request Mar 3, 2017
facebook-github-bot pushed a commit that referenced this pull request Mar 31, 2017
Summary:
ubsan flags this problem:

```
buck-out/opt-ubsan/gen/folly/__default_headers__#header-mode-symlink-tree-with-header-map,headers/folly/experimental/StringKeyedCommon.h:31:18: runtime error: null pointer passed as argument 2, which is declared to never be null
third-party-buck/gcc-4.9-glibc-2.20-fb/build/glibc/include/string.h:47:28: note: nonnull attribute specified here
    #0 0x5cb88f in std::pair<std::__detail::_Node_iterator<std::pair<folly::Range<char const*> const, facebook::eden::GitIgnore>, false, true>, bool> folly::StringKeyedUnorderedMap<facebook::eden::GitIgnore, folly::Hash, std::equal_to<folly::Range<char const*> >, std::allocator<std::pair<folly::Range<char const*> const, facebook::eden::GitIgnore> > >::emplace<facebook::eden::GitIgnore>(folly::Range<char const*>, facebook::eden::GitIgnore&&) buck-out/opt-ubsan/gen/folly/__default_headers__#header-mode-symlink-tree-with-header-map,headers/folly/experimental/StringKeyedCommon.h:31
    #1 0x5c6652 in facebook::eden::(anonymous namespace)::IgnoreChecker::isIgnored(facebook::eden::detail::RelativePathBase<folly::Range<char const*> >) eden/fs/inodes/Dirstate.cpp:226
    #2 0x5c6037 in facebook::eden::(anonymous namespace)::IgnoreChecker::isIgnored(facebook::eden::detail::RelativePathBase<folly::Range<char const*> >) eden/fs/inodes/Dirstate.cpp:180
    #3 0x5c5173 in facebook::eden::Dirstate::getStatusForExistingDirectory(facebook::eden::detail::RelativePathBase<folly::Range<char const*> >) const eden/fs/inodes/Dirstate.cpp:372
    #4 0x5c4509 in facebook::eden::Dirstate::getStatus() const eden/fs/inodes/Dirstate.cpp:272
    #5 0x50a448 in verifyExpectedDirstate(facebook::eden::Dirstate const*, std::unordered_map<std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> >, facebook::eden::StatusCode, std::hash<std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > >, std::equal_to<std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > >, std::allocator<std::pair<std::basic_fbstring<char, std::char_traits<char>, std::allocator<char>, std::fbstring_core<char> > const, facebook::eden::StatusCode> > >&&) eden/fs/inodes/test/DirstateTest.cpp:48
    #6 0x50c70c in Dirstate_addDirectoriesWithMixOfFiles_Test::TestBody() eden/fs/inodes/test/DirstateTest.cpp:220
    #7 0xb45857 in void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:2364
    #8 0xb36784 in testing::Test::Run() /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:2437
    #9 0xb36957 in testing::TestInfo::Run() [clone .part.558] /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:2612
    #10 0xb36b74 in testing::TestCase::Run() [clone .part.559] /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:2587
    #11 0xb3806e in testing::internal::UnitTestImpl::RunAllTests() [clone .part.561] /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:4571
    #12 0xb382d9 in testing::UnitTest::Run() /home/engshare/third-party2/gtest/1.7.0/src/gtest-1.7.0/./src/gtest.cc:4519
    #13 0x861ca7 in main third-party-buck/gcc-4.9-glibc-2.20-fb/build/gtest/include/gtest/gtest.h:2326
    #14 0x7f20be0740f5 in __libc_start_main /home/engshare/third-party2/glibc/2.20/src/glibc-2.20/csu/libc-start.c:289
    #15 0x4a552c in _start /home/engshare/third-party2/glibc/2.20/src/glibc-2.20/csu/../sysdeps/x86_64/start.S:122

UndefinedBehaviorSanitizer: undefined-behavior buck-out/opt-ubsan/gen/folly/__default_headers__#header-mode-symlink-tree-with-header-map,headers/folly/experimental/StringKeyedCommon.h:31:18
```

The issue is that `StringPiece` default constructs to `{nullptr, nullptr}` as a valid representation of an empty string.
This is tripping up UBSAN in this case.

The fix is a trivial nullptr check

Reviewed By: igorsugak

Differential Revision: D4791015

fbshipit-source-id: dec7484b29ecb29c17b8dd6a9b0e8093f07d63cb
facebook-github-bot pushed a commit that referenced this pull request Jun 1, 2017
Summary:
Test output before the fix is applied:
```
folly/experimental/Bits.h:247:59: runtime error: signed integer overflow: -2147483648 - 1 cannot be represented in type 'int'
     #0 folly/experimental/Bits.h:247 folly::Bits<...>::set(int*, unsigned long, unsigned long, int)
     #1 folly/experimental/test/BitsTest.cpp:228 std::enable_if<...>::type (anonymous namespace)::testSet<...>(unsigned char*, unsigned long, unsigned long, int)
     #2 folly/experimental/test/BitsTest.cpp:263 Bits_Boundaries_Test::TestBody()
    #17 folly/experimental/test/BitsTest.cpp:381 main
```

Reviewed By: philippv

Differential Revision: D5160789

fbshipit-source-id: 43f1926d58f1a5c019d4f8794d10a7a80a5c4749
facebook-github-bot pushed a commit that referenced this pull request Oct 26, 2017
Summary:
Data race reported by TSAN:

```
WARNING: ThreadSanitizer: data race (pid=608219)
  Read of size 1 at 0x7b5800000c29 by thread T314:
    #0 0x60b3441 in folly::Codel::overloaded(std::chrono::duration<long, std::ratio<1l, 1000000000l> >) ./folly/executors/Codel.cpp:76
    #1 0x5c1222 in apache::thrift::concurrency::ThreadManager::ImplT<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > >::Worker<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > >::run() ./thrift/lib/cpp/concurrency/ThreadManager.tcc:119
    #2 0x5d803e7 in apache::thrift::concurrency::PthreadThread::threadMain(void*) ./thrift/lib/cpp/concurrency/PosixThreadFactory.cpp:200
    #3 0x619739d in __tsan_thread_start_func crtstuff.c:?

  Previous write of size 1 at 0x7b5800000c29 by thread T315:
    #0 0x60b33e4 in folly::Codel::overloaded(std::chrono::duration<long, std::ratio<1l, 1000000000l> >) ??:?
    #1 0x5c1222 in apache::thrift::concurrency::ThreadManager::ImplT<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > >::Worker<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > >::run() ./thrift/lib/cpp/concurrency/ThreadManager.tcc:119
    #2 0x5d803e7 in apache::thrift::concurrency::PthreadThread::threadMain(void*) ./thrift/lib/cpp/concurrency/PosixThreadFactory.cpp:200
    #3 0x619739d in __tsan_thread_start_func crtstuff.c:?

  Location is heap block of size 768 at 0x7b5800000c00 allocated by main thread:
    #0 0x616ab83 in operator new(unsigned long) ??:?
    #1 0x53cb92 in __gnu_cxx::new_allocator<std::_Sp_counted_ptr_inplace<apache::thrift::concurrency::SimpleThreadManager<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > >, std::allocator<apache::thrift::concurrency::SimpleThreadManager<folly::LifoSemImpl<std::atomic, folly::Baton<std::atomic, true, true> > > >, (__gnu_cxx::_Lock_policy)2> >::allocate(unsigned long, void const*)
    ...
```

It looks like there are multiple threads reading and writing the `overloaded_` bool. To fix it, wrap it in a `std::atomic`.

Reviewed By: yfeldblum, meyering

Differential Revision: D6149766

fbshipit-source-id: 605b29fa2f602d2ed2dfc22e46b739ef169f914e
facebook-github-bot pushed a commit that referenced this pull request Oct 4, 2018
Summary:
TSAN flagged the following lock inversion below. The reason for this lock inversion
is because of the following example usage:

1. set request context B, save old one A (lock B, lock A)
2. later on, reset request context back to A, get the old one back B (lock A, lock B)

In the two calls, we always locked the the new context first, resulting
in a lock inversion. The fix is to always acquire them in a consistent
order using `folly::acquireLocked`

TSAN report:

```
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) (pid=1574307)
  Cycle in lock order graph: M159 (0x7b1400000138) => M157 (0x7b14000000e8) => M159

  Mutex M157 acquired here while holding mutex M159 in main thread:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    #2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    #3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    #4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    #5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    #6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    #7 0x1c7530 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:243
    #8 0x36a7b in folly::RequestContext::create() ./folly/io/async/Request.h:119
    #9 0x34916 in RequestContextScopeGuard ./folly/io/async/Request.h:269

  Mutex M159 previously acquired by the same thread here:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    #2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    #3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    #4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    #5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    #6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    #7 0x1c7516 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:242
    #8 0x36a7b in folly::RequestContext::create() ./folly/io/async/Request.h:119
    #9 0x34916 in RequestContextScopeGuard ./folly/io/async/Request.h:269

  Mutex M159 acquired here while holding mutex M157 in main thread:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    #2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    #3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    #4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    #5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    #6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    #7 0x1c7530 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:243
    #8 0x34b99 in ~RequestContextScopeGuard ./folly/io/async/Request.h:278

  Mutex M157 previously acquired by the same thread here:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    #2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    #3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    #4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    #5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    #6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    #7 0x1c7516 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:242
    #8 0x34b99 in ~RequestContextScopeGuard ./folly/io/async/Request.h:278

```

Reviewed By: igorsugak

Differential Revision: D9797715

fbshipit-source-id: a0f991ae0ec8f3e9d33af6e05db49eceaf3a5174
sandraiser pushed a commit to sandraiser/folly that referenced this pull request Mar 4, 2019
Summary:
TSAN flagged the following lock inversion below. The reason for this lock inversion
is because of the following example usage:

1. set request context B, save old one A (lock B, lock A)
2. later on, reset request context back to A, get the old one back B (lock A, lock B)

In the two calls, we always locked the the new context first, resulting
in a lock inversion. The fix is to always acquire them in a consistent
order using `folly::acquireLocked`

TSAN report:

```
WARNING: ThreadSanitizer: lock-order-inversion (potential deadlock) (pid=1574307)
  Cycle in lock order graph: M159 (0x7b1400000138) => M157 (0x7b14000000e8) => M159

  Mutex M157 acquired here while holding mutex M159 in main thread:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    meta#2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    meta#3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    meta#4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    meta#5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    meta#6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    meta#7 0x1c7530 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:243
    meta#8 0x36a7b in folly::RequestContext::create() ./folly/io/async/Request.h:119
    meta#9 0x34916 in RequestContextScopeGuard ./folly/io/async/Request.h:269

  Mutex M159 previously acquired by the same thread here:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    meta#2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    meta#3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    meta#4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    meta#5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    meta#6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    meta#7 0x1c7516 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:242
    meta#8 0x36a7b in folly::RequestContext::create() ./folly/io/async/Request.h:119
    meta#9 0x34916 in RequestContextScopeGuard ./folly/io/async/Request.h:269

  Mutex M159 acquired here while holding mutex M157 in main thread:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    meta#2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    meta#3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    meta#4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    meta#5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    meta#6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    meta#7 0x1c7530 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:243
    meta#8 0x34b99 in ~RequestContextScopeGuard ./folly/io/async/Request.h:278

  Mutex M157 previously acquired by the same thread here:
    #0 0x48f18c in AnnotateRWLockAcquired ??:?
    #1 0x315495 in folly::SharedMutexImpl<false, void, std::atomic, false>::lock_shared() ./folly/SharedMutex.h:385
    meta#2 0x1b0eb8 in folly::detail::LockTraitsImpl<folly::SharedMutexImpl<false, void, std::atomic, false>, (folly::detail::MutexLevel)1, false>::lock_shared(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:157
    meta#3 0x1b0e68 in std::integral_constant<bool, true> folly::LockPolicyShared::lock<folly::SharedMutexImpl<false, void, std::atomic, false> >(folly::SharedMutexImpl<false, void, std::atomic, false>&) ./folly/LockTraits.h:493
    meta#4 0x1d63a9 in LockedPtrBase ./folly/Synchronized.h:1026
    meta#5 0x1d6258 in LockedPtr ./folly/Synchronized.h:1326
    meta#6 0x1c9a17 in folly::SynchronizedBase<folly::Synchronized<folly::RequestContext::State, folly::SharedMutexImpl<false, void, std::atomic, false> >, (folly::detail::MutexLevel)1>::rlock() const ./folly/Synchronized.h:123
    meta#7 0x1c7516 in folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>) ./folly/io/async/Request.cpp:242
    meta#8 0x34b99 in ~RequestContextScopeGuard ./folly/io/async/Request.h:278

```

Reviewed By: igorsugak

Differential Revision: D9797715

fbshipit-source-id: a0f991ae0ec8f3e9d33af6e05db49eceaf3a5174
facebook-github-bot pushed a commit that referenced this pull request Apr 10, 2019
…t (attempt #2)

Summary:
The file descriptor API here needs to go away, so switch this API to NetworkSocket

It is expected that this commit will cause a number of Open Source projects to temporarily show up as broken. This is due to the fact that not all projects get synced to Github at the exact same time, so the builds may temporarily be fetching an older version of it's dependencies than it needs to :) It should fix itself quickly.

Reviewed By: yfeldblum

Differential Revision: D14673328

fbshipit-source-id: c5842fa5dc383d50043e0d8228e35d03b10a1c6b
facebook-github-bot pushed a commit that referenced this pull request Dec 18, 2019
Summary:
Exposed by UBSAN's unsigned-integer-overflow:
```
> folly/experimental/observer/detail/Core.cpp:179:9: runtime error: unsigned integer overflow: 0 - 1 cannot be represented in type 'size_t' (aka 'unsigned long')
>     #0 0x7f605837dfea in folly::observer_detail::Core::removeStaleDependents()::$_4::operator()(std::vector<std::weak_ptr<folly::observer_detail::Core>, std::allocator<std::weak_ptr<folly::observer_detail::Core> > >&) const folly/experimental/observer/detail/Core.cpp:179
>     #1 0x7f6058344b0c in auto folly::SynchronizedBase<folly::Synchronized<std::vector<std::weak_ptr<folly::observer_detail::Core>, std::allocator<std::weak_ptr<folly::observer_detail::Core> > >, folly::SharedMutexImpl<false, void, std::atomic, false, false> >, (folly::detail::MutexLevel)1>::withWLock<folly::observer_detail::Core::removeStaleDependents()::$_4>(folly::observer_detail::Core::removeStaleDependents()::$_4&&) folly/Synchronized.h:210
>     #2 0x7f6058344917 in folly::observer_detail::Core::removeStaleDependents() folly/experimental/observer/detail/Core.cpp:174
>     #3 0x7f60583785cb in folly::observer_detail::Core::~Core()::$_2::operator()(std::unordered_set<std::shared_ptr<folly::observer_detail::Core>, std::hash<std::shared_ptr<folly::observer_detail::Core> >, std::equal_to<std::shared_ptr<folly::observer_detail::Core> >, std::allocator<std::shared_ptr<folly::observer_detail::Core> > > const&) const folly/experimental/observer/detail/Core.cpp:156
>     #4 0x7f6058343cdc in auto folly::SynchronizedBase<folly::Synchronized<std::unordered_set<std::shared_ptr<folly::observer_detail::Core>, std::hash<std::shared_ptr<folly::observer_detail::Core> >, std::equal_to<std::shared_ptr<folly::observer_detail::Core> >, std::allocator<std::shared_ptr<folly::observer_detail::Core> > >, folly::SharedMutexImpl<false, void, std::atomic, false, false> >, (folly::detail::MutexLevel)1>::withWLock<folly::observer_detail::Core::~Core()::$_2>(folly::ob
server_detail::Core::~Core()::$_2&&) folly/Synchronized.h:210
>     #5 0x7f6058343a17 in folly::observer_detail::Core::~Core() folly/experimental/observer/detail/Core.cpp:154
>     #6 0x7f605838b8ca in std::_Sp_counted_ptr<folly::observer_detail::Core*, (__gnu_cxx::_Lock_policy)2>::_M_dispose() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/shared_ptr_base.h:378
>     #7 0x7f605834d411 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/shared_ptr_base.h:156
>     #8 0x7f605834d332 in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/shared_ptr_base.h:686
>     #9 0x7f605834d23a in std::__shared_ptr<folly::observer_detail::Core, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/shared_ptr_base.h:1125
>     #10 0x7f605833c416 in std::shared_ptr<folly::observer_detail::Core>::~shared_ptr() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/shared_ptr.h:93
>     #11 0x7f6058376413 in folly::observer_detail::ObserverManager::scheduleRefresh(std::shared_ptr<folly::observer_detail::Core>, unsigned long)::'lambda'()::~() folly/experimental/observer/detail/ObserverManager.h:91
>     #12 0x7f6058377014 in unsigned long folly::detail::function::execSmall<folly::observer_detail::ObserverManager::scheduleRefresh(std::shared_ptr<folly::observer_detail::Core>, unsigned long)::'lambda'()>(folly::detail::function::Op, folly::detail::function::Data*, folly::detail::function::Data*) folly/Function.h:592
>     #13 0x7f6058377788 in folly::Function<void ()>::exec(folly::detail::function::Op, folly::detail::function::Data*, folly::detail::function::Data*) const folly/Function.h:649
>     #14 0x7f6058376380 in folly::Function<void ()>::~Function() folly/Function.h:781
>     #15 0x7f6058477b99 in folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()::operator()() const folly/experimental/observer/detail/ObserverManager.cpp:73
>     #16 0x7f6058473de8 in void std::__invoke_impl<void, folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()>(std::__invoke_other, folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()&&) buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/invoke.h:60
>     #17 0x7f6058473c08 in std::__invoke_result<folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()>::type std::__invoke<folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()>(folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()&&) buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/bits/invok
e.h:95
>     #18 0x7f6058473b66 in decltype(std::__invoke(_S_declval<0ul>())) std::thread::_Invoker<std::tuple<folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()> >::_M_invoke<0ul>(std::_Index_tuple<0ul>) buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/thread:234
>     #19 0x7f6058473a43 in std::thread::_Invoker<std::tuple<folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()> >::operator()() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/thread:243
>     #20 0x7f6058473549 in std::thread::_State_impl<std::thread::_Invoker<std::tuple<folly::observer_detail::ObserverManager::UpdatesManager::CurrentQueue::CurrentQueue()::'lambda'()> > >::_M_run() buck-out/cells/fbsource/gen/third-party/gcc/7.x/stdc++-headers#header-mode-symlink-tree-with-header-map,headers/thread:186
>     #21 0x7f60576bac5f in std::execute_native_thread_routine(void*) third-party/gcc/7.x/libstdc++-v3/src/c++11/thread.cc:83
>     #22 0x7f605639e6b5 in start_thread /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/nptl/pthread_create.c:465:7
>     #23 0x7f6055ecdebe in __GI___clone /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/sysdeps/unix/sysv/linux/x86_64/clone.S:95
>
> SUMMARY: UndefinedBehaviorSanitizer: unsigned-integer-overflow folly/experimental/observer/detail/Core.cpp:179:9
```

Fix the error by rearranging increment and decrement operations.

Reviewed By: leikahing

Differential Revision: D19164999

fbshipit-source-id: d3c9b638492d0bf44c2acaac1e95fafe8b785182
facebook-github-bot pushed a commit that referenced this pull request Dec 19, 2019
Summary:
Exposed by UBSAN's misaligned-pointer-use:
```lang=bash
> folly/test/stl_tests/StlVectorTest.cpp:544:12: runtime error: upcast of misaligned address 0x0000feebdaed for type 'DataTracker<false>', which requires 8 byte alignment
> 0x0000feebdaed: note: pointer points here
> <memory cannot be printed>
>     #0 0x6c9b93 in DataTracker<false>::~DataTracker() folly/test/stl_tests/StlVectorTest.cpp:544
>     #1 0x6c94fe in Data<0u, 0ul>::~Data() folly/test/stl_tests/StlVectorTest.cpp:605
>     #2 0xcc5f93 in void test_iteratorInsertionN2<folly::fbvector<Data<0u, 0ul>, std::allocator<Data<0u, 0ul> > > >(std::integral_constant<bool, true>) folly/test/stl_tests/StlVectorTest.cpp:2422
>     #3 0x5c9bac in void test_iteratorInsertionN3<folly::fbvector<Data<0u, 0ul>, std::allocator<Data<0u, 0ul> > > >() folly/test/stl_tests/StlVectorTest.cpp:2422
>     #4 0x5c67bd in FBVector_iteratorInsertionN_Test::TestBody() folly/test/stl_tests/StlVectorTest.cpp:2422
>     #5 0x7f9c4e5316c9 in void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:2464
>     #6 0x7f9c4e530dcc in testing::Test::Run() xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:2480
>     #7 0x7f9c4e5350a0 in testing::TestInfo::Run() xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:2662
>     #8 0x7f9c4e539408 in testing::TestCase::Run() xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:2780
>     #9 0x7f9c4e55a672 in testing::internal::UnitTestImpl::RunAllTests() xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:4655
>     #10 0x7f9c4e5595de in bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:2464
>     #11 0x7f9c4e558b72 in testing::UnitTest::Run() xplat/third-party/gmock/googletest-1.8.0/googletest/src/gtest.cc:4263
>     #12 0x6591f3 in RUN_ALL_TESTS() buck-out/cells/fbsource/gen/xplat/third-party/gmock/gtest_headers#header-mode-symlink-tree-with-header-map,headers/gtest/gtest.h:2247
>     #13 0x659139 in main folly/test/stl_tests/StlVectorTest.cpp:3074
>     #14 0x7f9c4c75b1a5 in __libc_start_main /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/csu/libc-start.c:308:16
>     #15 0x4de029 in _start /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/sysdeps/x86_64/start.S:120
>
> SUMMARY: UndefinedBehaviorSanitizer: misaligned-pointer-use folly/test/stl_tests/StlVectorTest.cpp:544:12
```

Make the crafted pointer address aligned.

Reviewed By: Gownta

Differential Revision: D19166262

fbshipit-source-id: f766656d031079350838598b135275bdbc047642
facebook-github-bot pushed a commit that referenced this pull request Jul 9, 2020
Summary:
Use sized-deallocation (`sdallocx`) if possible in `folly::SysAllocator` and `folly::Arena`.

`Arena` has always allocated two types of blocks:
1. Normal (fixed-sized): size is the "goodSize adjusted" `minBlockSize`
2. Large (variable-sized): when #1 is too small

Type #2 makes sized-deallocation tricky -- we need somewhere to remember the allocated sizes.

The old code used a single type `Block` and kept a single list. Here I change to have two types and two lists.  The `LargeBlock` has an additional `allocSize` data member.

This makes the Arena object itself 16B larger, but seems better than adding a 4B `allocSize` to each and every block, regardless of type.

Note that, prior to this change, it was possible to `merge()` arenas with different `minBlockSize`.  This is no longer possible.

Reviewed By: yfeldblum

Differential Revision: D22189916

fbshipit-source-id: e6fba48eaae0b5cc8456b856b02d2cfc71c03834
facebook-github-bot pushed a commit that referenced this pull request Jul 10, 2020
Summary:
Use sized-deallocation (`sdallocx`) if possible in `folly::SysAllocator` and `folly::Arena`.

`Arena` has always allocated two types of blocks:
1. Normal (fixed-sized): size is the "goodSize adjusted" `minBlockSize`
2. Large (variable-sized): when #1 is too small

Type #2 makes sized-deallocation tricky -- we need somewhere to remember the allocated sizes.

The old code used a single type `Block` and kept a single list. Here I change to have two types and two lists.  The `LargeBlock` has an additional `allocSize` data member.

This makes the Arena object itself 16B larger, but seems better than adding a 4B `allocSize` to each and every block, regardless of type.

Note that, prior to this change, it was possible to `merge()` arenas with different `minBlockSize`.  This is no longer possible.

Reviewed By: davidtgoldblatt

Differential Revision: D22466906

fbshipit-source-id: 719f357a0a1f6cfcda3208391837195c3859ab69
machogallo2 pushed a commit to machogallo2/folly that referenced this pull request Sep 5, 2020
Update from upstream facebook/folly
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
I have been encountering

```
AddressSanitizer:DEADLYSIGNAL
=================================================================
==937752==ERROR: AddressSanitizer: SEGV on unknown address 0x24a12000e4f18 (pc 0x7f3902a6e696 bp 0x7f37bc5e4380 sp 0x7f37bc5e42a0 T107)
==937752==The signal is caused by a READ memory access.
SCARINESS: 20 (wild-addr-read)

    #0 0x7f3902a6e695 in folly::ThreadLocalPtr<folly::SingletonThreadLocal<folly::hazptr_tc<std::atomic>, void, folly::detail::DefaultMake<folly::hazptr_tc<std::atomic> >, void>::Wrapper, void, void>::get() const folly/ThreadLocal.h:160
    meta#1 0x7f3902a6d600 in get folly/ThreadLocal.h:69
    meta#2 0x7f3902a6d600 in folly::ThreadLocal<folly::SingletonThreadLocal<folly::hazptr_tc<std::atomic>, void, folly::detail::DefaultMake<folly::hazptr_tc<std::atomic> >, void>::Wrapper, void, void>::operator*() const folly/ThreadLocal.h:78
    meta#3 0x7f3902a6ca1b in folly::SingletonThreadLocal<folly::hazptr_tc<std::atomic>, void, folly::detail::DefaultMake<folly::hazptr_tc<std::atomic> >, void>::getWrapper() folly/SingletonThreadLocal.h:149
    meta#4 0x7f3902a6cbe5 in folly::SingletonThreadLocal<folly::hazptr_tc<std::atomic>, void, folly::detail::DefaultMake<folly::hazptr_tc<std::atomic> >, void>::LocalLifetime::~LocalLifetime() folly/SingletonThreadLocal.h:121
    meta#5 0x7f38f04d9fd5 in (anonymous namespace)::run(void*) /data/users/kirkshoop/gcc/trunk/libstdc++-v3/libsupc++/atexit_thread.cc:75:16
    meta#6 0x7f38ef9ee551 in __nptl_deallocate_tsd.part.8 /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/nptl/pthread_create.c:301:8
    meta#7 0x7f38ef9ef7c8 in __nptl_deallocate_tsd /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/sysdeps/nptl/futex-internal.h:200:3
    meta#8 0x7f38ef9ef7c8 in start_thread /home/engshare/third-party2/glibc/2.26/src/glibc-2.26/nptl/pthread_create.c:475:3
```

I tried using a unique Tag for the SingletonThreadLocal for debugging purposes and this seemed to fix the issue.

Reviewed By: magedm

Differential Revision: D19356179

fbshipit-source-id: a18c6b02f0a40e0509753075614eeff71d859bf7
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
Until C++17 types with extended alignment need special handling
in eg. std::vector and also std::unique_ptr. CPUThreadPoolExecutor has a
default queue that requires extended alignment, but also allows the user
to provide their own blocking queue. To handle this we move the private
member to a shared_ptr which supported type erased destructors, and then
use allocate_shared for the default queue type with a custom allocator
that will satisfy alignment constraints.

```
.../unique_ptr.h:825:34: runtime error: constructor call on misaligned address 0x613000000040 for type 'folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask>', which requires 128 byte alignment
0x613000000040: note: pointer points here
 02 00 00 1c  be be be be be be be be  be be be be be be be be  be be be be be be be be  be be be be
              ^
    #0 0x75b35e in std::_MakeUniq<folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask> >::__single_object std::make_unique<folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask> >() .../unique_ptr.h:825:30
    meta#1 0x75602f in folly::CPUThreadPoolExecutor::CPUThreadPoolExecutor(unsigned long, std::shared_ptr<folly::ThreadFactory>) xplat/folly/executors/CPUThreadPoolExecutor.cpp:66:18
    meta#2 0x756c6c in folly::CPUThreadPoolExecutor::CPUThreadPoolExecutor(unsigned long) xplat/folly/executors/CPUThreadPoolExecutor.cpp:84:7
```

Differential Revision: D19237477

fbshipit-source-id: c88b26e2ca17e168f124ba27c0989f787b1ce4fd
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
The default allocator for `new` does not apparently respect the extended alignment requirement for `hasptr_rec<Atom>`. We use folly's AlignedSysAllocator for these cases, which will then pass UBSan checks for alignment.

```
xplat/folly/synchronization/HazptrDomain.h:572:20: runtime error: constructor call on misaligned address 0x60c0000004c0 for type 'hazptr_rec<atomic>', which requires 128 byte alignment
0x60c0000004c0: note: pointer points here
 02 00 00 7f  be be be be be be be be  be be be be be be be be  be be be be be be be be  be be be be
              ^
    #0 0x77949e in folly::hazptr_domain<std::atomic>::acquire_new_hprec() xplat/folly/synchronization/HazptrDomain.h:572:16
    meta#1 0x7791cc in folly::hazptr_domain<std::atomic>::hprec_acquire() xplat/folly/synchronization/HazptrDomain.h:227:35
    meta#2 0x766a7f in folly::hazptr_holder<std::atomic>::hazptr_holder(folly::hazptr_domain<std::atomic>&) xplat/folly/synchronization/HazptrHolder.h:71:21
    meta#3 0x766a7f in void folly::UnboundedQueue<folly::CPUThreadPoolExecutor::CPUTask, false, false, false, 6ul, 7ul, std::atomic>::enqueueImpl<folly::CPUThreadPoolExecutor::CPUTask>(folly::CPUThreadPoolExecutor::CPUTask&&) xplat/folly/concurrency/UnboundedQueue.h:374
```

Reviewed By: magedm

Differential Revision: D19237973

fbshipit-source-id: 0edea12bb3f028d21830689d52f7e0290d187ff9
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
Until C++17 types with extended alignment need special handling
in eg. std::vector and also std::unique_ptr. CPUThreadPoolExecutor has a
default queue that requires extended alignment, but also allows the user
to provide their own blocking queue. To handle this we move the private
member to a shared_ptr which supported type erased destructors, and then
use allocate_shared for the default queue type with a custom allocator
that will satisfy alignment constraints.

```
.../unique_ptr.h:825:34: runtime error: constructor call on misaligned address 0x613000000040 for type 'folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask>', which requires 128 byte alignment
0x613000000040: note: pointer points here
 02 00 00 1c  be be be be be be be be  be be be be be be be be  be be be be be be be be  be be be be
              ^
    #0 0x75b35e in std::_MakeUniq<folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask> >::__single_object std::make_unique<folly::UnboundedBlockingQueue<folly::CPUThreadPoolExecutor::CPUTask> >() .../unique_ptr.h:825:30
    meta#1 0x75602f in folly::CPUThreadPoolExecutor::CPUThreadPoolExecutor(unsigned long, std::shared_ptr<folly::ThreadFactory>) xplat/folly/executors/CPUThreadPoolExecutor.cpp:66:18
    meta#2 0x756c6c in folly::CPUThreadPoolExecutor::CPUThreadPoolExecutor(unsigned long) xplat/folly/executors/CPUThreadPoolExecutor.cpp:84:7
```

Differential Revision: D19669832

fbshipit-source-id: 7fb60a06dbb6a04edddb6b619af7a8cef4995fd2
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
Use sized-deallocation (`sdallocx`) if possible in `folly::SysAllocator` and `folly::Arena`.

`Arena` has always allocated two types of blocks:
1. Normal (fixed-sized): size is the "goodSize adjusted" `minBlockSize`
2. Large (variable-sized): when meta#1 is too small

Type meta#2 makes sized-deallocation tricky -- we need somewhere to remember the allocated sizes.

The old code used a single type `Block` and kept a single list. Here I change to have two types and two lists.  The `LargeBlock` has an additional `allocSize` data member.

This makes the Arena object itself 16B larger, but seems better than adding a 4B `allocSize` to each and every block, regardless of type.

Note that, prior to this change, it was possible to `merge()` arenas with different `minBlockSize`.  This is no longer possible.

Reviewed By: yfeldblum

Differential Revision: D22189916

fbshipit-source-id: e6fba48eaae0b5cc8456b856b02d2cfc71c03834
dotconnor pushed a commit to 5448C8/folly that referenced this pull request Mar 19, 2021
Summary:
Use sized-deallocation (`sdallocx`) if possible in `folly::SysAllocator` and `folly::Arena`.

`Arena` has always allocated two types of blocks:
1. Normal (fixed-sized): size is the "goodSize adjusted" `minBlockSize`
2. Large (variable-sized): when meta#1 is too small

Type meta#2 makes sized-deallocation tricky -- we need somewhere to remember the allocated sizes.

The old code used a single type `Block` and kept a single list. Here I change to have two types and two lists.  The `LargeBlock` has an additional `allocSize` data member.

This makes the Arena object itself 16B larger, but seems better than adding a 4B `allocSize` to each and every block, regardless of type.

Note that, prior to this change, it was possible to `merge()` arenas with different `minBlockSize`.  This is no longer possible.

Reviewed By: davidtgoldblatt

Differential Revision: D22466906

fbshipit-source-id: 719f357a0a1f6cfcda3208391837195c3859ab69
facebook-github-bot pushed a commit that referenced this pull request May 10, 2022
Summary:
TSAN aborts on a data-race of the form:
```
WARNING: ThreadSanitizer: data race (pid=978596)
  Write of size 8 at 0x7b0400000b40 by thread T2:
    #0 operator delete(void*, unsigned long) <null>
    #1 folly::coro::timed_wait</*...*/>(/*...*/)::'lambda'(/*...*/)::operator()</*...*/>(/*...*/) const folly/experimental/coro/TimedWait.h:51
  Previous atomic write of size 1 at 0x7b0400000b40 by thread T1:
    #0 __tsan_atomic8_exchange <null>
    #1 std::atomic<bool>::exchange(bool, std::memory_order) libgcc/include/c++/bits/atomic_base.h:499
    #2 folly::coro::timed_wait</*...*/>(/*...*/)::'lambda'(/*...*/)::operator()</*...*/>(/*...*/) const folly/experimental/coro/TimedWait.h:64
```

Reviewed By: davidtgoldblatt, iahs

Differential Revision: D36159450

fbshipit-source-id: 860fcbbc1f689f9e166934f75a2ef60abdcad421
@zhngs zhngs mentioned this pull request Nov 21, 2022
facebook-github-bot pushed a commit that referenced this pull request Mar 8, 2023
Summary:
AsyncUDPSocket test cases are crashing when running under llvm15. During
debugging it seems that the issue is the fact that the code tries to allocated 0
size array. Changing the code to prevent such allocation.

This is not very clean why to fix, but I am not sure if there is better one.
Please let me know if you have any suggestions.

Sample crash:
```
$ buck test //folly/io/async/test:async_udp_socket_test
...
stdout:
Note: Google Test filter = AsyncUDPSocketTest.TestDetachAttach
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from AsyncUDPSocketTest
[ RUN      ] AsyncUDPSocketTest.TestDetachAttach

stderr:
fbcode/folly/io/async/AsyncUDPSocket.cpp:699:10: runtime error: variable length array bound evaluates to non-positive value 0
    #0 0x7f4d8ed93704 in folly::AsyncUDPSocket::writev(folly::SocketAddress const&, iovec const*, unsigned long, int) fbcode/folly/io/async/AsyncUDPSocket.cpp:698
    #1 0x7f4d8ed9081f in folly::AsyncUDPSocket::writeGSO(folly::SocketAddress const&, std::unique_ptr<folly::IOBuf, std::default_delete<folly::IOBuf>> const&, int) fbcode/folly/io/async/AsyncUDPSocket.cpp:528
    #2 0x7f4d8ed900b2 in folly::AsyncUDPSocket::write(folly::SocketAddress const&, std::unique_ptr<folly::IOBuf, std::default_delete<folly::IOBuf>> const&) fbcode/folly/io/async/AsyncUDPSocket.cpp:660
    #3 0x350a05 in AsyncUDPSocketTest_TestDetachAttach_Test::TestBody() fbcode/folly/io/async/test/AsyncUDPSocketTest.cpp:914
    #4 0x7f4d90dd1ad5 in testing::Test::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2682:50
    #5 0x7f4d90dd1ad5 in testing::Test::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2672:6
    #6 0x7f4d90dd1c64 in testing::TestInfo::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2861:14
    #7 0x7f4d90dd1c64 in testing::TestInfo::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2833:6
    #8 0x7f4d90dd2321 in testing::TestSuite::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:3015:31
    #9 0x7f4d90dd2321 in testing::TestSuite::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2993:6
    #10 0x7f4d90dd2b1e in testing::internal::UnitTestImpl::RunAllTests() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:5855:47
    #11 0x7f4d90dd1d87 in bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:2665:29
    #12 0x7f4d90dd1d87 in testing::UnitTest::Run() /home/engshare/third-party2/googletest/1.11.0/src/googletest/googletest/src/gtest.cc:5438:55
    #13 0x7f4d90d5c990 in RUN_ALL_TESTS() fbcode/third-party-buck/platform010/build/googletest/include/gtest/gtest.h:2490
    #14 0x7f4d90d5c618 in main fbcode/common/gtest/LightMain.cpp:20
    #15 0x7f4d8ea2c656 in __libc_start_call_main /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/csu/../sysdeps/nptl/libc_start_call_main.h:58:16
    #16 0x7f4d8ea2c717 in __libc_start_main@GLIBC_2.2.5 /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/csu/../csu/libc-start.c:409:3
    #17 0x33ea60 in _start /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/csu/../sysdeps/x86_64/start.S:116
...
```

Reviewed By: russoue, dmm-fb

Differential Revision: D43858875

fbshipit-source-id: 93749bab17027b6dfc0dbc01b6c183e501a5494c
facebook-github-bot pushed a commit that referenced this pull request Apr 27, 2024
Summary:
ThreadLocalDetailTest.MultiThreadedTest had a data race on std::vector because multiple threads were accessing and modifying the std::vector without a mutex. I update the code to use indexes such that the vector is not updated concurrently.

Previous run failure that this fixes:

```
stderr:
==================
WARNING: ThreadSanitizer: data race (pid=1249005)
  Write of size 8 at 0x7fff195936d0 by main thread:
    #0 std::vector<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>, std::allocator<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>>>::pop_back() fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/stl_vector.h:1228 (thread_local_detail_test+0x116c28)
    #1 folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody() fbcode/folly/detail/test/ThreadLocalDetailTest.cpp:121 (thread_local_detail_test+0x101aba)
    #2 void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) fbsource/src/gtest.cc:2675 (libthird-party_googletest_1.14.0_gtest.so+0xacf3c)
    #3 testing::Test::Run() fbsource/src/gtest.cc:2692 (libthird-party_googletest_1.14.0_gtest.so+0xacb9c)
    #4 testing::TestInfo::Run() fbsource/src/gtest.cc:2841 (libthird-party_googletest_1.14.0_gtest.so+0xafa4a)
    #5 testing::TestSuite::Run() fbsource/src/gtest.cc:3020 (libthird-party_googletest_1.14.0_gtest.so+0xb4303)
    #6 testing::internal::UnitTestImpl::RunAllTests() fbsource/src/gtest.cc:5925 (libthird-party_googletest_1.14.0_gtest.so+0xd105e)
    #7 bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) fbsource/src/gtest.cc:2675 (libthird-party_googletest_1.14.0_gtest.so+0xd08f1)
    #8 testing::UnitTest::Run() fbsource/src/gtest.cc:5489 (libthird-party_googletest_1.14.0_gtest.so+0xd037e)
    #9 RUN_ALL_TESTS() fbsource/gtest/gtest.h:2317 (libcommon_gtest_light_main.so+0x22a7)
    #10 main fbcode/common/gtest/LightMain.cpp:20 (libcommon_gtest_light_main.so+0x2131)

  Previous read of size 8 at 0x7fff195936d0 by thread T123:
    #0 std::vector<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>, std::allocator<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>>>::size() const fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/stl_vector.h:919 (thread_local_detail_test+0x11b0bd)
    #1 std::vector<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>, std::allocator<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>>>::operator[](unsigned long) fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/stl_vector.h:1045 (thread_local_detail_test+0x11d101)
    #2 folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0::operator()() const fbcode/folly/detail/test/ThreadLocalDetailTest.cpp:97 (thread_local_detail_test+0x11d08c)
    #3 void std::__invoke_impl<void, folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>(std::__invoke_other, folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0&&) fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/invoke.h:61 (thread_local_detail_test+0x11cf95)
    #4 std::__invoke_result<folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>::type std::__invoke<folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>(folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0&&) fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/invoke.h:96 (thread_local_detail_test+0x11cf05)
    #5 void std::thread::_Invoker<std::tuple<folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>>::_M_invoke<0ul>(std::_Index_tuple<0ul>) fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/std_thread.h:253 (thread_local_detail_test+0x11cebd)
    #6 std::thread::_Invoker<std::tuple<folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>>::operator()() fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/std_thread.h:260 (thread_local_detail_test+0x11ce65)
    #7 std::thread::_State_impl<std::thread::_Invoker<std::tuple<folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody()::$_0>>>::_M_run() fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/std_thread.h:211 (thread_local_detail_test+0x11cd79)
    #8 execute_native_thread_routine /home/engshare/third-party2/libgcc/11.x/src/gcc-11.x/x86_64-facebook-linux/libstdc++-v3/src/c++11/../../../.././libstdc++-v3/src/c++11/thread.cc:82:18 (libstdc++.so.6+0xdf4e4) (BuildId: 452d1cdae868baeeb2fdf1ab140f1c219bf50c6e)

  Location is stack of main thread.

  Location is global '??' at 0x7fff19575000 ([stack]+0x1e6d0)

  Thread T123 (tid=1249233, running) created by main thread at:
    #0 pthread_create <null> (thread_local_detail_test+0x156bef)
    #1 __gthread_create /home/engshare/third-party2/libgcc/11.x/src/gcc-11.x/x86_64-facebook-linux/libstdc++-v3/include/x86_64-facebook-linux/bits/gthr-default.h:663:35 (libstdc++.so.6+0xdf80e) (BuildId: 452d1cdae868baeeb2fdf1ab140f1c219bf50c6e)
    #2 std::thread::_M_start_thread(std::unique_ptr<std::thread::_State, std::default_delete<std::thread::_State>>, void (*)()) /home/engshare/third-party2/libgcc/11.x/src/gcc-11.x/x86_64-facebook-linux/libstdc++-v3/src/c++11/../../../.././libstdc++-v3/src/c++11/thread.cc:147:37 (libstdc++.so.6+0xdf80e)
    #3 folly::threadlocal_detail::ThreadLocalDetailTest_MultiThreadedTest_Test::TestBody() fbcode/folly/detail/test/ThreadLocalDetailTest.cpp:93 (thread_local_detail_test+0x1015cd)
    #4 void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) fbsource/src/gtest.cc:2675 (libthird-party_googletest_1.14.0_gtest.so+0xacf3c)
    #5 testing::Test::Run() fbsource/src/gtest.cc:2692 (libthird-party_googletest_1.14.0_gtest.so+0xacb9c)
    #6 testing::TestInfo::Run() fbsource/src/gtest.cc:2841 (libthird-party_googletest_1.14.0_gtest.so+0xafa4a)
    #7 testing::TestSuite::Run() fbsource/src/gtest.cc:3020 (libthird-party_googletest_1.14.0_gtest.so+0xb4303)
    #8 testing::internal::UnitTestImpl::RunAllTests() fbsource/src/gtest.cc:5925 (libthird-party_googletest_1.14.0_gtest.so+0xd105e)
    #9 bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) fbsource/src/gtest.cc:2675 (libthird-party_googletest_1.14.0_gtest.so+0xd08f1)
    #10 testing::UnitTest::Run() fbsource/src/gtest.cc:5489 (libthird-party_googletest_1.14.0_gtest.so+0xd037e)
    #11 RUN_ALL_TESTS() fbsource/gtest/gtest.h:2317 (libcommon_gtest_light_main.so+0x22a7)
    #12 main fbcode/common/gtest/LightMain.cpp:20 (libcommon_gtest_light_main.so+0x2131)

ThreadSanitizer: data race fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/stl_vector.h:1228 in std::vector<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>, std::allocator<std::unique_ptr<folly::test::Barrier, std::default_delete<folly::test::Barrier>>>>::pop_back()
==================
ThreadSanitizer: reported 1 warnings
```

Reviewed By: yfeldblum

Differential Revision: D56643303

fbshipit-source-id: cc364817ae79bc6418cc07faa35e1bcd21830c66
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Aug 6, 2024
Summary: detail::UnrollStep should go away, because otherwise it would be exposed to the user of `simdForEach`.

Reviewed By: yfeldblum

Differential Revision: D60587842
facebook-github-bot pushed a commit that referenced this pull request Aug 6, 2024
Summary: detail::UnrollStep should go away, because otherwise it would be exposed to the user of `simdForEach`.

Reviewed By: yfeldblum

Differential Revision: D60587842

fbshipit-source-id: 34c75dcbb6ddeefeeae55c98f0656f7008d57e0e
facebook-github-bot pushed a commit that referenced this pull request Aug 12, 2024
Summary:
Ucache with io_uring is crashing with this stack trace:

```
(lldb) bt
* thread #1, name = 'ucache', stop reason = signal SIGSEGV: address not mapped to object
  * frame #0: 0x0000000000000000
    frame #1: 0x00007f517ba44560 libc.so.6`__restore_rt at libc_sigaction.c:13
    frame #2: 0x000000000a16e249 ucache`folly::AsyncIoUringSocket::ReadSqe::callback(this=0x00007f498c5955e0, cqe=<unavailable>) at AsyncIoUringSocket.cpp:639
    frame #3: 0x000000000964196a ucache`folly::IoUringBackend::getActiveEvents(folly::IoUringBackend::WaitForEventsMode) [inlined] folly::IoSqeBase::internalCallback(this=<unavailable>, cqe=<unavailable>) at IoUringBackend.cpp:0
    frame #4: 0x000000000964195c ucache`folly::IoUringBackend::getActiveEvents(folly::IoUringBackend::WaitForEventsMode) [inlined] folly::IoUringBackend::internalProcessCqe(this=0x00007f4a8f989c00, maxGet=4294967295, mode=NORMAL) at IoUringBackend.cpp:1556
    frame #5: 0x000000000964190f ucache`folly::IoUringBackend::getActiveEvents(this=0x00007f4a8f989c00, waitForEvents=<unavailable>) at IoUringBackend.cpp:1527
    frame #6: 0x0000000009640ac9 ucache`folly::IoUringBackend::eb_event_base_loop(this=0x00007f4a8f989c00, flags=1) at IoUringBackend.cpp:1178
    frame #7: 0x000000001b61547c ucache`folly::EventBase::loopMain(this=0x00007f4a8f97af00, flags=0, options=<unavailable>) at EventBase.cpp:0
    frame #8: 0x000000001bab9a2d ucache`folly::EventBase::loopBody(this=0x00007f4a8f97af00, flags=0, options=(ignoreKeepAlive = false, allowSuspension = false)) at EventBase.cpp:513
    frame #9: 0x000000000a3a6c90 ucache`folly::EventBase::loop(this=<unavailable>) at EventBase.cpp:474
    frame #10: 0x000000000a3a75f7 ucache`folly::EventBase::loopForever(this=<unavailable>) at EventBase.cpp:781
    frame #11: 0x000000000a436907 ucache`folly::IOThreadPoolExecutor::threadRun(this=0x00007f4da3fce1c0, thread=<unavailable>) at IOThreadPoolExecutor.cpp:240
    frame #12: 0x0000000009ed68b8 ucache`void std::__invoke_impl<void, void (folly::ThreadPoolExecutor::*&)(std::shared_ptr<folly::ThreadPoolExecutor::Thread>), folly::ThreadPoolExecutor*&, std::shared_ptr<folly::ThreadPoolExecutor::Thread>&>((null)=<unavailable>, __f=<unavailable>, __t=<unavailable>, __args=<unavailable>) at invoke.h:74
    frame #13: 0x00007f517b6df4e5 libstdc++.so.6`std::execute_native_thread_routine(__p=0x00007f4da01bdbe0) at thread.cc:82:18
    frame #14: 0x00007f517ba9abc9 libc.so.6`start_thread(arg=<unavailable>) at pthread_create.c:434:8
    frame #15: 0x00007f517bb2cf5c libc.so.6`__clone3 at clone3.S:81
```

In frame 2 the offending function is `ReadSqe::callback()`: https://fburl.com/code/4fb46hdq

The problem is that `readCallback_` is null:

```
(lldb) fr v readCallback_
(folly::AsyncReader::ReadCallback *) readCallback_ = nullptr
```

However, `readCallback_` is checked earlier in the the function `ReadSqe::callback()`: https://fburl.com/code/dhnndk29

`AsyncIoUringSocket::readError()` now fails all pending writes and calls `writeErr()`, whose implementation can then close out a socket and call `AsyncIoUringSocket::setReadCB(nullptr)` to change the callback.

Move the call to `AsyncIoUringSocket::readError()` after the call to `readCallback_`.

Reviewed By: dmm-fb

Differential Revision: D60880377

fbshipit-source-id: 42d2f430cd3dc3f4787d0e4c29da7c8ef31ba9a8
facebook-github-bot pushed a commit that referenced this pull request Mar 27, 2025
Summary:
When C++ thread destroys folly.python.iobuf wrapper around
Python-managed memory, it can result in a segfault.

The reasoning goes as follows:
 - Python code calls some Cython code that creates a folly.python.iobuf wrapper
   around Python-managed bytes and gives it to C++ code
 - Python code runs to its end and interpreter starts shutting down
 - Later on, C++ code destroys folly.python.iobuf wrapper on non-Python thread
 - In this state, `PyGILState_Check()` returns 1

I haven't confirmed the exact reason of this behavior, but I suspect it's due
to this check in `pystate.c`:
```
if (!gilstate->check_enabled) {
    return 1;
}
```
so while Python interpreter is shutting down, every thread thinks it holds GIL.
The resulting attempt to `Py_DECREF` ends in a segfault because there's no
Python thread state and no interpreter state.

This commit reproduces the problem. If the disabled test is run, it results in:
```
AddressSanitizer:DEADLYSIGNAL
=================================================================
==2105846==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010 (pc 0x000000321fc7 bp 0x7f5c609fe900 sp 0x7f5c609fe8d8 T1)
==2105846==The signal is caused by a READ memory access.
==2105846==Hint: address points to the zero page.
SCARINESS: 10 (null-deref)
    #0 0x321fc7 in _PyInterpreterState_GET() (.__uniq.137703359133237359249323886361199135396) third-party/python/3.10/Include/internal/pycore_pystate.h:117
    #1 0x321fc7 in get_gc_state() (.__uniq.137703359133237359249323886361199135396) third-party/python/3.10/Modules/gcmodule.c:134
    #2 0x321fc7 in PyObject_GC_Del third-party/python/3.10/Modules/gcmodule.c:2371
    #3 0x5290a1 in _Py_Dealloc third-party/python/3.10/Objects/object.c:2301
    #4 0x5290a1 in _Py_DECREF(_object*) (.__uniq.337871127465368605150080511148319906877) third-party/python/3.10/Include/object.h:500
    #5 0x5290a1 in memory_dealloc(PyMemoryViewObject*) (.__uniq.337871127465368605150080511148319906877) third-party/python/3.10/Objects/memoryobject.c:1088
    #6 0x7f5c74705db2 in _Py_DECREF(_object*) third-party/python/3.10/Include/object.h:500
    #7 0x7f5c74705875 in folly::python::iobuf_from_memoryview(folly::Executor*, _object*, void*, unsigned long)::$_0::operator()(void*, void*) const fbcode/folly/python/iobuf_ext.cpp:53
    ...
```

Reviewed By: yfeldblum

Differential Revision: D70874850

fbshipit-source-id: 7f3a4394c63d46f05b33bafe2e821ef734ac5e97
facebook-github-bot pushed a commit that referenced this pull request Apr 25, 2025
…hRttiImpl

Summary:
### Overview

I observed failures like:
```
==33555==ERROR: AddressSanitizer: unknown-crash on address 0x800000010516ecee at pc 0x0001062597f4 bp 0x00016b80d470 sp 0x00016b80cc08
READ of size 155 at 0x800000010516ecee thread T0
    #0 0x0001062597f0  (libclang_rt.asan_osx_dynamic.dylib:arm64+0x157f0)
    #1 0x000104f58508 in std::type_info::before[abi:ne180100](std::type_info const&) const+0x8c (core_tests_binary:arm64+0x10096c508)
    #2 0x000104f58418 in std::__1::type_index::operator<[abi:ne180100](std::__1::type_index const&) const+0xa4 (core_tests_binary:arm64+0x10096c418)
    #3 0x000104f57c00 in void* folly::detail::(anonymous namespace)::StaticSingletonManagerWithRttiImpl::create<folly::detail::StaticSingletonManagerWithRtti::Arg>(folly::detail::StaticSingletonManagerWithRtti::Arg&)+0x148 (core_tests_binary:arm64+0x10096bc00)
    #4 0x000104f58110 in void* folly::detail::StaticSingletonManagerWithRtti::create_<true>(folly::detail::StaticSingletonManagerWithRtti::Arg&)+0xc (core_tests_binary:arm64+0x10096c110)
    #5 0x000104fc0b64 in folly::detail::UniqueInstance::enforce(folly::detail::UniqueInstance::Arg&)+0x30c (core_tests_binary:arm64+0x1009d4b64)
    #6 0x000104793064 in __cxx_global_var_init.286+0x34 (core_tests_binary:arm64+0x1001a7064)
    #7 0x00018fc4ac14  (<unknown module>)
    #8 0x00018fc87014  (<unknown module>)
    #9 0x00018fca6ccc  (<unknown module>)
    #10 0x00018fca3abc  (<unknown module>)
    #11 0x00018fca51fc  (<unknown module>)
    #12 0x00018fc86ae4  (<unknown module>)
    #13 0x00018fc4a9cc  (<unknown module>)
    #14 0x00018fc52358  (<unknown module>)
    #15 0x00018fc4b168  (<unknown module>)
    #16 0x00018fc4f8d8  (<unknown module>)
    #17 0x00018fc4b474  (<unknown module>)
    #18 0x00018fc6c284  (<unknown module>)
    #19 0x00018fc2fda8  (<unknown module>)
    #20 0x00018fc2f180  (<unknown module>)
    #21 0x00018fc2eafc  (<unknown module>)

Address 0x800000010516ecee is a wild pointer inside of access range of size 0x00000000009b.
AddressSanitizer: unknown-crash (core_tests_binary:arm64+0x10096c508) in std::type_info::before[abi:ne180100](std::type_info const&) const+0x8c
==33555==ABORTING
```

Looks like the address sanitizer found a memory issue in the implementation of `std::type_info::before`, when I force it to use the more robust type_info comparison algorithm. I couldn't find any references to known problems around this, internally or externally, and unfortunately that's code we can't easily fix.

Instead of relying on the seemingly problematic implementation of `std::type_info::before`, I'm changing the `std::map` to an `std::unordered_map` which instead relies on equality comparison, which is in turn directly controlled by `_LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION`. See discussion in the comments for additional context on this decision.

Reviewed By: yfeldblum

Differential Revision: D73379250

fbshipit-source-id: 257bb77a8b6bb69b364bf4c6edcbdb160c84ca74
facebook-github-bot pushed a commit that referenced this pull request Jun 15, 2025
Summary:
The `MicroLock` tests fail under libc++ with asan-abort `stack-buffer-overflow`.

Example:
```
SCARINESS: 32 (4-byte-read-stack-buffer-overflow)
    #0 unsigned int std::__2::__cxx_atomic_load[abi:ue170004]<unsigned int>(std::__2::__cxx_atomic_base_impl<unsigned int> const*, std::__2::memory_order) libcxx/include/c++/v1/__atomic/cxx_atomic_impl.h:375
    #1 std::__2::__atomic_base<unsigned int, false>::load[abi:ue170004](std::__2::memory_order) const libcxx/include/c++/v1/__atomic/atomic_base.h:60
    #2 folly::MicroLockBase<1000u, 0u>::try_lock() folly/MicroLock.h:319
    #3 SmallLocks_MicroLockTryLock_Test::TestBody() folly/synchronization/test/SmallLocksTest.cpp:314
```

The trouble is accessing the lock state as a 4-byte word, where the asan stack has allocated only 1 byte for the lock object - asan tracks this and aborts.

It is UB for `MicroLock` to perform atomic stores or atomic read-modify-write operations on the entire 4-byte aligned word containing the `MicroLock` which may be concurrent with other accesses to other bytes in the word. The 4-byte aligned word accesses are necessary in order to support using the `MicroLock` itself as a futex, on Linux platforms. The trouble is that Linux does not provide futex operations on all sizes of integer, only on 32-bit (4-byte) integers. If Linux were to provide futex operations on all sizes of integer, we would immediately switch to 8-bit (1-byte) integers here.

This diff fixes the UB and gets the tests passing under libc++ by switching to the `folly::ParkingLot`, as wrapped by `folly::atomic_notify_one` and `folly::atomic_wait` over `std::atomic<uint8_t>`, which indirects the 32-bit (4-byte) futex behind a sharded hashtable.

Alternatives are possible for getting the tests passing, although these alternatives would not fix the UB.
* We can disable sanitizers on even more functions, as well as switch to atomic builtins since the members of `std::atomic` are not marked as disabling the sanitizers.
* We can workaround just in the unit-tests by padding the on-stack `MicroLock` instances.

Reviewed By: praihan, ot, aary

Differential Revision: D76612658

fbshipit-source-id: 75e9f03e63c85c30c6201b9bce5cd303c9a2b530
facebook-github-bot pushed a commit that referenced this pull request Jun 17, 2025
Summary:
After recent Python 3.12 rollout we started seeing crashes, e.g. T223049180.

Crash stack from core dumps points to tstate being null when `_PyErr_GetRaisedException` is called

```
* thread #1, name = 'server#native-m', stop reason = SIGSEGV: address not mapped to object (fault address=0x60)
  * frame #0: 0x00007f94039e0197 libpython3.12.so.1.0`_PyFrame_MakeAndSetFrameObject [inlined] _PyErr_GetRaisedException(tstate=0x0000000000000000) at errors.c:490
    frame #1: 0x00007f94039e0197 libpython3.12.so.1.0`_PyFrame_MakeAndSetFrameObject [inlined] PyErr_GetRaisedException at errors.c:499
    frame #2: 0x00007f94039e0184 libpython3.12.so.1.0`_PyFrame_MakeAndSetFrameObject(frame=0x00007f940977f340) at frame.c:32
    frame #3: 0x00007f9403b9d3de libpython3.12.so.1.0`PyThreadState_GetFrame [inlined] _PyFrame_GetFrameObject(frame=<unavailable>) (.__uniq.305758459065587366612134685926705492046) at pycore_frame.h:213
    frame #4: 0x00007f9403b9d3d0 libpython3.12.so.1.0`PyThreadState_GetFrame(tstate=<unavailable>) at pystate.c:1754
```

The problem happens when this code is called (https://fburl.com/26dhwv4v)

```
PyObject *
PyErr_GetRaisedException(void)
{
    PyThreadState *tstate = _PyThreadState_GET();
    return _PyErr_GetRaisedException(tstate);
}
```

Where `_PyThreadState_GET` is implemented as follows https://fburl.com/92hrrluf
```

/* Get the current Python thread state.

   This function is unsafe: it does not check for error and it can return NULL.

   The caller must hold the GIL

   See also PyThreadState_Get() and _PyThreadState_UncheckedGet(). */

static inline PyThreadState*
_PyThreadState_GET(void)
{
#if defined(HAVE_THREAD_LOCAL) && !defined(Py_BUILD_CORE_MODULE)
    return _Py_tss_tstate;
#else
    return _PyThreadState_GetCurrent();
#endif
```
**The caller must hold the GIL** is a problem for us, since the whole idea behind implementing this hook this way is to get the stack when we **don't** have the GIL. This code implements a copy of the current

To work around the issue we are copying the Python runtime code, but WITHOUT the GIL checks

[_PyFrame_MakeAndSetFrameObject](https://github.com/python/cpython/blob/3.12/Python/frame.c#L28C1-L64C1) is reimplemented to skip the `PyErr_GetRaisedException` call, e.g.

[_PyFrame_New_NoTrack](https://github.com/python/cpython/blob/main/Objects/frameobject.c#L2107C1-L2125C2) Changes from

```
PyFrameObject*
_PyFrame_New_NoTrack(PyCodeObject *code)
{
    CALL_STAT_INC(frame_objects_created);
    int slots = code->co_nlocalsplus + code->co_stacksize;
    PyFrameObject *f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, slots);
    if (f == NULL) {
        return NULL;
    }
    f->f_back = NULL;
    f->f_trace = NULL;
    f->f_trace_lines = 1;
    f->f_trace_opcodes = 0;
    f->f_lineno = 0;
    f->f_extra_locals = NULL;
    f->f_locals_cache = NULL;
    f->f_overwritten_fast_locals = NULL;
    return f;
}
```

to
```
thread_local PyFrameObject my_frame;
PyFrameObject* MyPyFrame_New_NoTrack(_PyInterpreterFrame* frame) {
  PyFrameObject* f = &my_frame;
  if (f == NULL) {
    return NULL;
  }
  f->f_back = NULL;
  f->f_trace = NULL;
  f->f_trace_lines = 1;
  f->f_trace_opcodes = 0;
  f->f_fast_as_locals = 0;
  f->f_lineno = 0;
  f->f_frame = frame;
  frame->frame_obj = f;
  Py_SET_TYPE(reinterpret_cast<PyObject*>(frame->frame_obj), &PyFrame_Type);
  return f;
}
```

A thread local variable is being reused since we don't want to keep allocating and deallocating on the heap while doing heap profiling.

Reviewed By: fried

Differential Revision: D74118996

fbshipit-source-id: 65b9a9a10d6aa26f9c1cd93e30486333f20f4b24
facebook-github-bot pushed a commit that referenced this pull request Jul 7, 2025
Summary:
Fix for issue #2 in Post [Broken whitespace offset calculation for UserCounters](https://fb.workplace.com/groups/560979627394613/permalink/3320975644728317/)

Printing `Folly::Benchmark` results with a column width exceeding [bm_result_width](https://www.internalfb.com/code/fbsource/[f51516f2368d]/fbcode/folly/Benchmark.cpp?lines=112)(extra padding from `UserCounters`) results in misalignment of the values under reach counter name.

This diff corrects whitespace offset calculation for benchmark headers and benchmark datum names so they account for any additional space added by UserMetric [counterNames](https://www.internalfb.com/code/fbsource/[f51516f2368d8097604a13de292824a7d85d7de1]/fbcode/folly/Benchmark.cpp?lines=445-451).

Reviewed By: yfeldblum

Differential Revision: D77319953

fbshipit-source-id: 0121cae8fe5453ccf15e521830bbf97661d70aba
facebook-github-bot pushed a commit that referenced this pull request Aug 8, 2025
Summary:
https://www.internalfb.com/wiki/IOS_at_Meta/switch_statements_in_C_languages/

*Exhaustive Switches*, i.e. using `-Wswitch-enum` and `-Wswitch-default`, are the ideal default for all C language code at Meta.

This diff is part of the migration of *Instagram* to adopting *Exhaustive Switches* by default.  Currently only `-Wswitch-enum` is enabled for *Instagram* apps, but we want to add `-Wswitch-default` to prevent bugs from undefined/unpredicted behavior (which means adding these `default:` cases will NOT interfere with the compiler putting up an error when a new value is added to an enum, like we want).

We will follow the recommended solutions as outlined in https://www.internalfb.com/wiki/Apple_Build_Errors/Missing_switch_default_Label/

  1. **Fail Fast**: [the vast majority of cases] use an `abort()` to forcibly crash the app on unexpected values, `FB_SWITCH_UNEXPECTED_VALUE_ABORT()` for `fbobjc`, `folly::assume_unexpected()` for `folly`, `std::terminate()` or `abort()` or `assert(false)` for other `xplat` / `fbcode` code.  Always fail fast when the existing behavior would be unpredictable/undefined if you were to introduce `default: break;` -- in particular, if all `case` statements yield a `return`, you know you should fail fast.  Also use this if one of the other options do not fit.
  2. **Handle unexpected values (A)**: when there is minimal code after the `switch` that only the unhandled values would reach, pull it into the `default:`.  Sometimes, you\'ll have a minimal number of `case` statements that `break` to also reach that out-of-switch code, and you can move those cases to be above the `default:` case so they fall through to the default handling.
  3. **Handle unexpected values (B)**: when the code after the `switch` is safe for unhandled values but also needed for handled values (too much code or too much complexity to do #2), add a `default: break;` statement (usually with a `FB_SWITCH_UNAVAILABLE_VALUE_REPORT(type, value)`).
  4. **Handle unexpected values (C)**: when the enum type is from the platform itself (not our monorepo), and is an `NS_ENUM` type, we can make a judgement call if think the enum might expand and thus add a default handling behavior.  If there is a reasonable chance the platform could expand the enum in a future OS release, we can avoid crashing until we start building against the new SDK where the `-Wswitch-enum` will help us explicitly handle the new case.
  5. **Handle unexpected values (D)**: when the value being switched is coerced from an integer (coming from a dictionary or coersing a table view row into an enum), presume that it is more likely to switch on a value outside of the enum.  In this case, use add the the `default:` case with `FB_SWITCH_UNEXPECTED_VALUE_REPORT(type, value)` to introduce a Must Fix report but leave the default behavior as simply providing a `break;`.
  6. **Convert to *Flexible Switch* or to `if` checks**: on the rare occasion, it can be evident that we do not need an *exhaustive* switch and can use `FB_FLEXIBLE_SWITCH_BEGIN|END` or just use `if` checks.

Reviewed By: aary

Differential Revision: D77051161

fbshipit-source-id: 0883815dd3c0a0ccfa76f536bcecb2e25b4d1dc2
meta-codesync Bot pushed a commit that referenced this pull request Dec 1, 2025
Summary:
## TL;DR
The `setgid()` libc implementation should not be used after vfork, as there is a potential for deadlock due to shared address space.

## Context
Folly::Subprocess uses vfork() instead of fork(), mainly for efficiency reasons. As an interaction of `vfork()`, the child process shares the address space with the parent process.

Folly::Subprocess currently uses the setgid() glibc function. **For only linux**, gilbc manually iterates through all threads, and sets the gid for each thread, in https://fburl.com/ler48t68. Therefore, setgid() holds a lock while iterating through each thread. Note that this lock is shared with the parent, because the child and parent share the same memory space.

Therefore, there is a possible interaction, where if the parent process acquires the lock and is killed for any reason (SIGTERM, crash, etc), the child process is blocked indefinitely

Example stack trace:
```
[[email protected] ~]# quickstack -p 4111332
2025-11-22 12:30:42 761077: Setting mount namespace failed. Errno: 22
2025-11-22 12:30:42 761120: Target pid: 4111332 (inside container: 4111332)
2025-11-22 12:30:42 761528: Reading process symbols..
2025-11-22 12:30:42 869656: Gathering stack traces..
2025-11-22 12:30:42 869817: Printing stack traces..
2025-11-22 12:30:42 869836: Total Traced Time:  0.126 milliseconds
2025-11-22 12:30:42 869844: Average Traced Time Per LWP:  0.126 milliseconds
2025-11-22 12:30:42 869850: Longest Traced LWP: LWP 4111332,  0.126 milliseconds

Thread 1 (LWP 4111332):
#1  0x00007f03a8297377 in __GI___lll_lock_wait_private () from /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/nptl/lowlevellock.c:35
#2  0x00007f03a82f298e in __setgid () from /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/posix/../sysdeps/unix/sysv/linux/setgid.c:31
#3  0x000000000a523c6f in folly::Subprocess::prepareChild () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#4  0x0000000004152801 in folly::Subprocess::spawnInternalDoFork () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#5  0x0000000004153578 in folly::Subprocess::spawn () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#6  0x0000000004152270 in folly::Subprocess::Subprocess () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#7  0x00000000041568bc in facebook::fbagent::FollyRunner::run () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#8  0x0000000003d542b2 in facebook::fbagent::DefaultTask::run () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#9  0x0000000004095836 in apache::thrift::concurrency::ThreadManager::Impl::Worker::run () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#10  0x000000000ae7e570 in apache::thrift::concurrency::(anonymous namespace)::InitRunnable::run () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#11  0x000000000ae7f312 in apache::thrift::concurrency::PthreadThread::threadMain () from /usr/local/fbprojects/fbagent/bin/cppfbagentd
#12  0x00007f03a829abc9 in start_thread () from /home/engshare/third-party2/glibc/2.34/src/glibc-2.34/nptl/pthread_create.c:434
2025-11-22 12:30:42 882619: Done.
```

## Fix
Call the setgid syscall directly, rather than using glibc.

Reviewed By: yfeldblum

Differential Revision: D87717072

fbshipit-source-id: d3c13f6b70912f02192870d94dbca8fe14493373
meta-codesync Bot pushed a commit that referenced this pull request Jan 6, 2026
Summary:
Before this change we evaluated two branches for each find: one for
`sz == 0` and one for `sz == 1`. In cases, when container is not empty we can
evaluate only one branch. Moreover, turns out, when we nest branches compiler
is smart enough to avoid shifts for size calculation.

Before:

`F14Value`:

```
00000000002252d0 <codeSize_find_F14Value(<...>)>:
  2252d0: mov    0x8(%rdi),%rax
  2252d4: mov    %rax,%rcx
  2252d7: shr    $0x8,%rcx                                      ; This shift can
                                                                ; be avoided.
  2252db: je     2252ff <codeSize_find_F14Value(<...>)+0x2f>    ; Branch #1.
  2252dd: push   %rbp
  2252de: mov    %rsp,%rbp
  2252e1: push   %r14
  2252e3: push   %rbx
  2252e4: cmp    $0x1,%rcx
  2252e8: jne    225302 <codeSize_find_F14Value(<...>)+0x32>    ; Branch #2.
  2252ea: mov    0x10(%rdi),%rcx
  2252ee: and    $0xfffffffffffffff8,%rcx
  2252f2: xor    %eax,%eax
  2252f4: cmp    %si,(%rcx)
  2252f7: sete   %al
  2252fa: pop    %rbx
  2252fb: pop    %r14
  2252fd: pop    %rbp
  2252fe: ret
  2252ff: xor    %eax,%eax
  225301: ret
  225302: movswq %si,%rdx
  <...>
```

`F14Vector`:

```
0000000000225490 <codeSize_find_F14Vector(<...>)>:
  225490: mov    0x10(%rdi),%r8
  225494: xor    %eax,%eax
  225496: cmp    $0x100,%r8                         ; No shift here:
                                                    ; 0x100 >> 8 == 1 (size).
  22549d: jb     22554b <codeSize_find_F14Vector(<...>)+0xbb>
  2254a3: push   %rbp
  2254a4: mov    %rsp,%rbp
  2254a7: push   %r15
  2254a9: push   %r14
  2254ab: push   %rbx
  2254ac: movswq %si,%rax
  <...>
```

After:

`F14Value`:

```
00000000002252c0 <codeSize_find_F14Value(<...>)>:
  2252c0: push   %rbp
  2252c1: mov    %rsp,%rbp
  2252c4: push   %r14
  2252c6: push   %rbx
  2252c7: mov    0x8(%rdi),%r8
  2252cb: cmp    $0x1ff,%r8                                  ; No shift anymore.
  2252d2: ja     2252f4 <codeSize_find_F14Value(<...>)+0x34> ; We jump directly
                                                             ; to findImpl from
                                                             ; here.
  2252d4: xor    %eax,%eax
  2252d6: cmp    $0x100,%r8                                  ;
  2252dd: jb     2252ef <codeSize_find_F14Value(<...>)+0x2f>
  2252df: mov    0x10(%rdi),%rcx
  2252e3: and    $0xfffffffffffffff8,%rcx
  2252e7: xor    %eax,%eax
  2252e9: cmp    %si,(%rcx)
  2252ec: sete   %al
  2252ef: pop    %rbx
  2252f0: pop    %r14
  2252f2: pop    %rbp
  2252f3: ret
  2252f4: movswq %si,%rax
  <...>
```

`F14Vector`:

```
0000000000225480 <codeSize_find_F14Vector(<...>)>:
  225480: mov    0x10(%rdi),%r8
  225484: xor    %eax,%eax
  225486: cmp    $0x100,%r8
  22548d: jb     22553b <codeSize_find_F14Vector(<...>)+0xbb>
  225493: push   %rbp
  225494: mov    %rsp,%rbp
  225497: push   %r15
  225499: push   %r14
  22549b: push   %rbx
  22549c: movswq %si,%rax
  <...>
```

Reviewed By: ot

Differential Revision: D89190976

fbshipit-source-id: 43015f030f4b9792f28157ffd47f4f989913689c
meta-codesync Bot pushed a commit that referenced this pull request Jul 14, 2026
…CallbackWithState

Summary:
What: Deliver `writeStarting()` to the `WriteCallback` exactly once per write on the native `AsyncSocket` + io_uring send path. `IoUringSend`'s `SendRequest` now holds the `WriteCallbackWithState`, and `onSendStarted()` calls `notifyOnWrite()` (which dedups via `writeInProgress_`); `AsyncSocket::writeImpl` passes its `callbackWithState` into `iouSendHandle_->write()` so an immediate write arrives already-notified.

Why: The io_uring send handle fired `writeStarting()` on every SQE submit while `AsyncSocket` also fired it via `notifyOnWrite()`, so a single write got two calls (and more on partial / event-re-registration re-submits). `RocketServerConnection::writeStarting()` DCHECKs that `startRawByteOffset` is unset, so the duplicate aborts the process (`RocketServerConnection.cpp:718`); in opt builds it silently corrupts the byte offset. This crashed graphstore once it served on native `AsyncSocket` over io_uring with zero-copy (D111176951).

```
Rocket flushWrites
  -> AsyncSocket::writeImpl
       |- notifyOnWrite() --------------> writeStarting() #1   (sets startRawByteOffset)
       `- iouSendHandle_->write -> submit
            `- onSendStarted() ---------> writeStarting() #2   -> DCHECK abort
                                          (+ again on every partial / re-arm re-submit)

  fix: both paths funnel through one WriteCallbackWithState.notifyOnWrite() -> fires once
```

Rendered flow: https://pxl.cl/bBVG9

Reviewed By: spikeh

Differential Revision: D111316678

fbshipit-source-id: 037ff58303d0fbff4e8e77af6b3921f9463a7196
meta-codesync Bot pushed a commit that referenced this pull request Aug 27, 2026
Summary:
On by default wherever `svmatch` is available.

`F14Chunk::tagMatchIter` computes the match as an SVE predicate via `svmatch_u8`
and then throws it away, rebuilding the same 4-bit-spaced mask the plain-NEON
path uses so it can hand back a `SparseMaskIter`. On Neoverse V2 the generated
hot path is:

```
match  p1.b, p0/z, z1.b, z0.b     // sets NZCV itself
b.eq   <no-match>                 // svptest_any is free, folds into MATCH flags
mov    z1.b, p1/z, #17            -.
shrn   v1.8b, v1.8h, #4            | five instructions purely to rebuild
fmov   x3, d1                      | the index the predicate already held
rbit   x3, x3                      |
clz    x6, x3                     -'
```

`BRKB` sets the active lanes preceding the first match, so `CNTP` of that is the
index directly. That replaces the five-instruction chain with two, and keeps the
free `b.eq` early-out off MATCH's own flags.

After the optimization, hot path becomes:
```
match   p1.b, p0/z, z1.b, z0.b
b.eq   <no-match>
brkb    p2.b, p0/z, p1.b // -> lanes before first match
cntp    x3,   p0,  p2.b // -> first-match index i
```

`svbool_t` is a sizeless type, so it cannot be a class member or travel back
inside a `std::pair` — a predicate-native `SparseMaskIter` is not expressible.
Instead this adds `F14Chunk::forEachTagMatch`, which inverts the loop so the
predicate stays in a register. Everything except the SVE2 build gets a
`FOLLY_ALWAYS_INLINE` wrapper over the existing `tagMatchIter`, so the other
backends are unchanged. `tagMatchIter` had exactly two callers, `findImpl` and
`findMatching`, and both are rewritten to take a callback.

`FOLLY_F14_SVE_PREDICATE_NATIVE_ACTIVE` is `FOLLY_NEON &&
FOLLY_ARM_FEATURE_NEON_SVE_BRIDGE && FOLLY_ARM_FEATURE_SVE2` — exactly the
condition the `svmatch` `tagMatchIter` this replaces already compiles under — so
it turns on automatically wherever that path exists and is inert everywhere
else. `svmatch` is the only SVE2-only intrinsic in the sequence — `BRKB`,
`BRKA`, `CNTP` and predicate `BIC` are all SVE1 — so SVE2 is the correct gate.
There is no build knob: the two configurations where `FOLLY_ARM_FEATURE_SVE2` is
set but the body still cannot compile — an SVE2 target whose toolchain has no
`arm_neon_sve_bridge.h`, and `__CUDACC__`, where `Portability.h` forces
`FOLLY_NEON` to 0 — keep the generic wrapper because the macro tests those two
terms as well.

== Generated code ==

Full annotated probe loop for `F14ValueMap<K, std::array<uint8_t, 1>>` `Find`,
with `findImpl` inlined, `fbcode//mode/opt`, Grace (Neoverse V2). The two
excerpts above are taken from these. The source being compiled is one iteration
of:

```
ChunkPtr chunk = chunks_ + (index & chunkMask);
if (prefetch == Prefetch::ENABLED && Chunk::kChunkStride > 64)
  prefetchAddr(chunk->itemAddr(8));
ItemIter found{};
if (chunk->forEachTagMatch(needleV, [&](unsigned i) {
      if (FOLLY_LIKELY(this->keyMatchesItem(key, chunk->item(i)))) {
        found = ItemIter{chunk, i}; return true;
      }
      return false;
    })) { return found; }
if (FOLLY_LIKELY(chunk->outboundOverflowCount() == 0)) break;
index += step;
```

=== `uint64_t` key ===

Chunk stride 256 B, item 16 B. `keyMatchesItem` is a `cmp`, so there is no call
in the loop and nothing is ever spilled.

Before, `322d80 .. 322ddc`, 24 instructions:

```
  322d4c:  whilelo p0.b, wzr, w9         ; governing predicate, hoisted
  322d54:  mov x12, #0x7fffffffffffffff  ; mask constant, hoisted
loop:
  322d80:  and x2, x0, x1                ; index & chunkMask
  322d84:  lsl x3, x2, #8                ;   * sizeof(Chunk) = 256
  322d88:  add x2, x18, x3               ; chunk
  322d8c:  prfm pldl1keep, [x2, #144]    ; prefetchAddr(chunk->itemAddr(8))
  322d90:  ld1b {z1.b}, p0/z, [x18, x3]  ; tags_[0..15]
  322d94:  match p1.b, p0/z, z1.b, z0.b  ; svmatch_u8 -- also sets NZCV
  322d98:  b.eq 322dcc                   ; svptest_any() == false (free)
  322d9c:  mov z1.b, p1/z, #17           ; -. 0x11 per matching lane
  322da0:  shrn v1.8b, v1.8h, #4         ;  | narrow to 4 bits/lane
  322da4:  fmov x3, d1                   ;  | predicate -> GPR, the long way
  322da8:  rbit x3, x3                   ;  |
  322dac:  clz x4, x3                    ; -' x4 = first match index * 4
  322db0:  add x5, x2, x4, lsl #2        ; item = chunk + i*16
  322db4:  ldr x6, [x5, #16]             ; keyMatchesItem
  322db8:  cmp x15, x6
  322dbc:  b.eq 322de4                   ; hit -> ItemIter{chunk, i}
  322dc0:  lsr x4, x12, x4               ; SparseMaskIter advance; needs the
  322dc4:  ands x3, x4, x3               ;   hoisted 0x7fff.. constant
  322dc8:  b.ne 322dac                   ; next tag match
  322dcc:  ldrb w2, [x2, #15]            ; outboundOverflowCount()
  322dd0:  cbz w2, 322e44                ; == 0 -> break
  322dd4:  subs x17, x17, #0x1
  322dd8:  add x0, x16, x0               ; index += step
  322ddc:  b.ne 322d80
```

After, `3229c8 .. 322a1c`, 22 instructions:

```
  322998:  whilelo p0.b, wzr, w9         ; governing predicate, hoisted
loop:
  3229c8:  and x1, x18, x0               ; index & chunkMask
  3229cc:  lsl x2, x1, #8                ;   * sizeof(Chunk) = 256
  3229d0:  add x1, x17, x2               ; chunk
  3229d4:  prfm pldl1keep, [x1, #144]    ; prefetchAddr(chunk->itemAddr(8))
  3229d8:  ld1b {z1.b}, p0/z, [x17, x2]  ; tags_[0..15]
  3229dc:  match p1.b, p0/z, z1.b, z0.b  ; svmatch_u8 -- also sets NZCV
  3229e0:  b.eq 322a0c                   ; svptest_any() == false (free)
  3229e4:  brkb p2.b, p0/z, p1.b         ; lanes strictly before first match
  3229e8:  cntp x2, p0, p2.b             ; count them = the index
  3229ec:  ubfiz x2, x2, #4, #32         ;   * 16
  3229f0:  add x2, x1, x2                ; item = chunk + i*16
  3229f4:  ldr x3, [x2, #16]             ; keyMatchesItem
  3229f8:  cmp x14, x3
  3229fc:  b.eq 322a24                   ; hit -> ItemIter{chunk, i}
  322a00:  brka p2.b, p0/z, p1.b         ; lanes up to AND INCLUDING it
  322a04:  bics p1.b, p0/z, p1.b, p2.b   ; clear it; BICS sets the flags
  322a08:  b.ne 3229e4                   ; next tag match
  322a0c:  ldrb w1, [x1, #15]            ; outboundOverflowCount()
  322a10:  cbz w1, 322a84                ; == 0 -> break
  322a14:  subs x16, x16, #0x1
  322a18:  add x18, x15, x18             ; index += step
  322a1c:  b.ne 3229c8
```

`match` to item-address goes 6 -> 4 instructions, and the loop-invariant
`0x7fffffffffffffff` that `SparseMaskIter` needs disappears, freeing a register
across the whole loop.

=== `std::string` key ===

Chunk stride 576 B, item 40 B. Here `keyMatchesItem` is a size compare plus an
out-of-line `bcmp`, and that call is what makes the two arms diverge: under the
base AAPCS64 a normal callee clobbers all of `p0`-`p15`, so any live predicate
has to go to the stack. That is what `addvl sp, sp, #-2` reserves, and what
`str p` / `ldr p` move.

LLVM clones the probe loop here — `cbnz x21, <main loop>` at the foot of the
hash block dispatches on key length, so there is a second, call-free copy for
the empty-key case (30 -> 27 instructions, never executed by this benchmark).
The 48-instruction string-hash block that precedes the loop is byte-identical
between the two arms. Only the main loop is shown.

Before, `3235e0 .. 3236c0`, 57 instructions:

```
  323508:  addvl sp, sp, #-2             ; VL-scaled SVE spill area
  3235ac:  str p1, [x29, #-1, mul vl]    ; governing predicate spilled ONCE
loop:
  3235e0:  and x8, x28, x19
  3235e4:  mul x8, x8, x6                ; * 576
  3235e8:  add x25, x26, x8
  3235ec:  prfm pldl1keep, [x25, #336]   ; prefetchAddr(chunk->itemAddr(8))
  3235f0:  ld1b {z0.b}, p1/z, [x26, x8]  ; tags_[0..15]
  3235f4:  match p0.b, p1/z, z0.b, z1.b  ; svmatch_u8
  3235f8:  b.eq 3236b0                   ; no match
  3235fc:  mov z0.b, p0/z, #17           ; -. rebuild the nibble mask
  323600:  str w23, [sp, #44]
  323604:  str z1, [x29, #-2, mul vl]    ; needle vector spilled
  323608:  stp x12, x10, [sp, #24]
  32360c:  shrn v0.8b, v0.8h, #4         ;  |
  323610:  fmov x8, d0                   ;  |
  323614:  rbit x8, x8                   ;  |
  323618:  str x8, [sp, #56]             ; GPR spill: the reversed mask
  32361c:  clz x8, x8                    ;  -' index * 4
  323620:  mov w9, #0x28
  323624:  str x8, [sp, #48]             ; GPR spill: the index * 4
  323628:  lsr x8, x8, #2
  32362c:  umaddl x24, w8, w9, x25       ; item = chunk + i*40
  323630:  ldr x8, [x24, #24]            ; keyMatchesItem: size first
  323634:  cmp x21, x8
  323638:  b.ne 323690                   ; size mismatch -> next tag match
  32363c:  ldr x1, [x24, #16]
  323640:  mov x0, x22
  323644:  mov x2, x21
  323648:  mov x23, x22                  ; shuffle to keep x30/x22 alive
  32364c:  mov x22, x30                  ;   across the call
  323650:  bl bcmp                       ; CALL
  323654:  mov x3, #0xbfd6
  323658:  mov x1, #0xacc9
  32365c:  ldr p1, [x29, #-1, mul vl]    ; predicate refill
  323660:  movk x3, #0x7d8f, lsl #16
  323664:  movk x1, #0x962e, lsl #16
  323668:  mov x30, x22                  ; undo the shuffle
  32366c:  movk x3, #0x6556, lsl #32
  323670:  movk x1, #0x4b93, lsl #32
  323674:  mov x22, x23
  323678:  mov w6, #0x240
  32367c:  mov x5, #0xffffffffffffffff
  323680:  mov w4, #0x1
  323684:  movk x3, #0x4227, lsl #48
  323688:  movk x1, #0x8bb8, lsl #48
  32368c:  cbz w0, 323898                ; bcmp == 0 -> hit
  323690:  ldp x10, x9, [sp, #48]        ; refill index*4 and mask
  323694:  mov x8, #0x7fffffffffffffff
  323698:  ldr z1, [x29, #-2, mul vl]    ; refill needle
  32369c:  ldr w23, [sp, #44]
  3236a0:  lsr x8, x8, x10
  3236a4:  ldp x12, x10, [sp, #24]
  3236a8:  and x8, x8, x9
  3236ac:  cbnz x8, 323618               ; next tag match
  3236b0:  ldrb w8, [x25, #15]           ; outboundOverflowCount()
  3236b4:  cbz w8, 3238b8                ; == 0 -> break
  3236b8:  subs x12, x12, #0x1
  3236bc:  add x28, x28, x10             ; index += step
  3236c0:  b.ne 3235e0
```

After, `323220 .. 3232d8`, 47 instructions:

```
  323148:  addvl sp, sp, #-2             ; VL-scaled SVE spill area
  3231ec:  str p2, [x29, #-1, mul vl]    ; governing predicate spilled ONCE
loop:
  323220:  and x8, x28, x19
  323224:  mul x8, x8, x6                ; * 576
  323228:  add x27, x26, x8
  32322c:  prfm pldl1keep, [x27, #336]   ; prefetchAddr(chunk->itemAddr(8))
  323230:  ld1b {z0.b}, p2/z, [x26, x8]  ; tags_[0..15]
  323234:  match p1.b, p2/z, z0.b, z1.b  ; svmatch_u8
  323238:  b.eq 3232c8                   ; no match
  32323c:  str w23, [sp, #44]
  323240:  str z1, [x29, #-2, mul vl]    ; needle vector spilled
  323244:  stp x12, x10, [sp, #24]
  323248:  brkb p0.b, p2/z, p1.b         ; lanes before the first match
  32324c:  mov w9, #0x28
  323250:  str p1, [x29, #-2, mul vl]    ; THE NEW SPILL: match predicate
  323254:  cntp x8, p2, p0.b             ; count them = the index
  323258:  umaddl x23, w8, w9, x27       ; item = chunk + i*40
  32325c:  ldr x8, [x23, #24]            ; keyMatchesItem: size first
  323260:  cmp x21, x8
  323264:  b.ne 3232ac                   ; size mismatch -> next tag match
  323268:  ldr x1, [x23, #16]
  32326c:  mov x0, x22
  323270:  mov x2, x21                   ; no x30/x22 shuffle needed
  323274:  bl bcmp                       ; CALL
  323278:  mov x3, #0xbfd6
  32327c:  mov x1, #0xacc9
  323280:  ldr p2, [x29, #-1, mul vl]    ; governing predicate refill
  323284:  movk x3, #0x7d8f, lsl #16
  323288:  movk x1, #0x962e, lsl #16
  32328c:  mov w6, #0x240
  323290:  movk x3, #0x6556, lsl #32
  323294:  movk x1, #0x4b93, lsl #32
  323298:  mov x5, #0xffffffffffffffff
  32329c:  mov w4, #0x1
  3232a0:  movk x3, #0x4227, lsl #48
  3232a4:  movk x1, #0x8bb8, lsl #48
  3232a8:  cbz w0, 32349c                ; bcmp == 0 -> hit
  3232ac:  ldr p1, [x29, #-2, mul vl]    ; match predicate refill
  3232b0:  ldr z1, [x29, #-2, mul vl]    ; needle refill
  3232b4:  ldr w23, [sp, #44]
  3232b8:  ldp x12, x10, [sp, #24]
  3232bc:  brka p0.b, p2/z, p1.b         ; lanes up to AND INCLUDING it
  3232c0:  bics p1.b, p2/z, p1.b, p0.b   ; clear it; BICS sets the flags
  3232c4:  b.ne 323248                   ; next tag match
  3232c8:  ldrb w8, [x27, #15]           ; outboundOverflowCount()
  3232cc:  cbz w8, 3234bc                ; == 0 -> break
  3232d0:  subs x12, x12, #0x1
  3232d4:  add x28, x28, x10             ; index += step
  3232d8:  b.ne 323220
```

The trade is in one place. Before spills two GPRs (`[sp, #56]` the reversed
mask, `[sp, #48]` the index) and refills them with an `ldp`; after spills one
predicate and refills it with one `ldr`. Because the predicate carries the
iteration state directly, the five-instruction mask rebuild, the
`0x7fffffffffffffff` constant, and the four `mov`s shuffling `x22`/`x23`/`x30`
around the call all go away.

`str z1, [x29, #-2, mul vl]` and `str p1, [x29, #-2, mul vl]` read like the
second stomps the first; they do not. `mul vl` scales by VL for Z registers and
by VL/8 for P registers, so at VL=128 the two slots are `x29-32 .. x29-16` and
`x29-4 .. x29-2`.

=== Counts ===

| region | before | after | delta |
| --- | --- | --- | --- |
| `uint64_t` probe loop | 24 | 22 | -2 |
| -- match -> item address | 6 | 4 | -2 |
| -- next-match advance | 3 | 3 | 0 |
| `std::string` probe loop | 57 | 47 | **-10** |
| -- match -> `bl bcmp` | 24 | 17 | -7 |
| -- `bcmp` return -> loop-back | 28 | 25 | -3 |
| `std::string` empty-key clone | 30 | 27 | -3 |

`addvl sp, sp, #-2` is unchanged in both `std::string` arms (same SVE spill
area), while the fixed frame shrinks `0x40` -> `0x30` — exactly the 16 bytes of
GPR mask spills that go away.

For a *second* tag match in the same chunk the new path is 10 instructions
(`brkb` .. `b.ne`) against the old 8 (`clz` .. `b.ne`), because `brkb`+`cntp`
are re-executed where the old code re-entered at `clz`. False tag matches are
~1/255 per key, well below the first-match saving.

Depends on D117044647, which gates the pre-existing `svmatch` sites on SVE2 —
without it an SVE1 target cannot compile this file at all.

Result on Grace (Neoverse V2), `hash_maps_bench` find, ~5-6% faster.

Reviewed By: yfeldblum

Differential Revision: D117005509

fbshipit-source-id: 30f4dda50935e9bde72dab323408560a2c43b064
meta-codesync Bot pushed a commit that referenced this pull request Aug 31, 2026
Summary:
Task-lifecycle USDT probes in `ThreadPoolExecutor::runTask()` are not symmetric
relative to the task context lifecycle and TaskObserver hooks:
* `thread_pool_executor_task_dequeued` fires before the `RequestContext` is set and before `TaskObserver::taskDequeued()`
* `thread_pool_executor_task_stats` fires before `TaskObserver::taskProcessed()` and before the `RequestContext` is unset

```
  |    RequestContext   |
    |  TaskObserver  |
|   USDT probes   |
```

The lack of strict nesting makes it awkward to correlate these events with events
emitted from the `RequestContext` code or the task observers.

There are several ways to align the nesting:
1. Probes around the `RequestContext`.
2. Probes around the `TaskObserver` hooks.
3. Probes inside the `TaskObserver` hooks.

#1 is the least appropriate because, conceptually, a task is executed **within** a `RequestContext`.
Between #2 and #3, I prefer #3 because the observed slice includes only the task duration and excludes observers' overhead. If needed, the observers' overhead can be derived from the `runTime` field.

Move the probe down so it fires after the observer loop.
Resulting nesting:
```
  |    RequestContext   |
    |  TaskObserver   |
      | USDT probes |
```

Payload values are unchanged: `waitTime`, `enqueueTime`, `requestId` and
`taskId` are all computed before the scope guard. Only the instant at which the
probe fires moves later, by the cost of the `taskDequeued()` callbacks.

Reviewed By: ot

Differential Revision: D117593428

fbshipit-source-id: cc24700cfb24382f9375f0d62e97951be04626e5
meta-codesync Bot pushed a commit that referenced this pull request Sep 4, 2026
Summary:
WARNING: Generated by Autopilot (alpha) — review carefully, verify the underlying claim before accepting.
Agent: Bugs Agent | Trajectory: https://www.internalfb.com/intern/devai/devmate/inspector/3221407f-2c63-4d42-a456-c64f8b060195/ | SC job: https://www.internalfb.com/intern/sandcastle/instance/4503602530313669/

 ---

`RequestContext::get()` returns `&defaultContext`, a function-local static, when no
ambient context is set. Because it has a non-trivial destructor, it is registered
with `__cxa_atexit` and destroyed during `exit()`. Any thread still running at that
point that reaches the default context reads memory freed by `~State()`.

`mcbigcache` hits this on every process teardown. All 274 ASAN reports collected for
this signature since 2026-08-13 are the same shape: freed on `T0` from
`__run_exit_handlers`, read on a `ti/resource` `RpcStreams::Stream::rpcThread()` that
is still issuing Thrift calls.

```
  ==388==ERROR: AddressSanitizer: heap-use-after-free
  READ of size 8 at 0x7c0bab477698 thread T947
      #1 folly::SingleWriterFixedHashMap<folly::RequestToken, folly::RequestData*>::size() const
      #6 folly::RequestContext::State::getContextData(folly::RequestToken const&) fbcode/folly/io/async/Request.cpp:466
      #8 facebook::request::SimpleRequestData<...>::get() fbcode/common/request/SimpleRequestData-inl.h:22
      #9 facebook::tracing::TClientSideSamplingHandler::postWrite(...)
  freed by thread T0 here:
      #1 folly::RequestContext::State::~State() fbcode/folly/io/async/Request.cpp:252
      #2 __run_exit_handlers
      #3 exit
```

Wrapping the static in `Indestructible` (already used for `RequestToken::getCache()`
in this file) drops the atexit registration, so late-running threads observe a live
context. Nothing is leaked from LSAN's point of view: the object stays in static
storage, so its `Combined` and `RequestData` allocations remain reachable from a root.

Anything attached to the default context is process-lifetime state by definition, so
skipping its teardown loses nothing — only `onClear()` on data set on the default
context (never on a per-request context) no longer runs at exit.

This is **not** the duplicate-key bug from T284992965. That root cause
([D113867999](https://www.internalfb.com/diff/D113867999), reverted by
[D115897136](https://www.internalfb.com/diff/D115897136)) was already gone: the
`writer_find()` guard is present in `SingleWriterFixedHashMap::insert()` at
`b57498484004`, the revision that built `fbcdn.bigcache.asan:987` — and that binary
crashed with this signature on 2026-09-02. The crash rate never moved after the
revert, holding at 5-32/day through today.

Reviewed By: yfeldblum

Differential Revision: D118542493

fbshipit-source-id: 6f4d35d29ff806e62453c5efd0d1d09fb13af9ee
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants