Skip to content

Typos corrections to Overview.md - #1

Closed
chrisaycock wants to merge 1 commit into
meta:masterfrom
chrisaycock:patch-1
Closed

chrisaycock wants to merge 1 commit into
meta:masterfrom
chrisaycock:patch-1

Conversation

@chrisaycock

Copy link
Copy Markdown
Contributor

Some typos corrections, and collapsed the two descriptions of Bits.h into one.

@ghost ghost assigned andrewjcg Jun 3, 2012
@tudor tudor closed this Jun 5, 2012
@tudor

tudor commented Jun 5, 2012

Copy link
Copy Markdown
Contributor

Merged manually, thanks!

@chrisaycock

Copy link
Copy Markdown
Contributor Author

@tudor Glad I could be of help!

unmeshvrije pushed a commit to unmeshvrije/C-- that referenced this pull request Feb 16, 2014
…o one.

Summary: meta/folly#1

Test Plan: N/A.

Reviewed By: [email protected]

FB internal diff: D485738
@WenlinWang WenlinWang mentioned this pull request Feb 3, 2015
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
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
ghost pushed a commit that referenced this pull request Apr 28, 2016
Summary:
Use tag dispatching instead of `enable_if`: it is clearer, it
sidesteps the GCC mangling bug, and more importantly the conditional
doesn't leak into the symbol, making stack traces and profiles more
readable.

Testing on a compilation unit with 1000 `Function`s from simple lambdas.
Before:
```
folly::impl::Function<int (), false>::Function<main::{lambda()#1}, {lambda()#1}>(main::{lambda()#1}&&, std::enable_if<std::integral_constant<bool, ((sizeof (std::decay<main::{lambda()#1}>::type))<=(sizeof folly::detail::function::Data::small))&&std::is_nothrow_move_constructible<std::decay<main::{lambda()#1}> >::value>::value, folly::detail::Tag>::type)::Ops::call(folly::detail::function&)
```
After:
```
folly::impl::Function<int (), false>::OpsSmall<main::{lambda()#1}>::call(folly::detail::function::Data&)
```
Note that the function type is repeated 5 times before, and only once after. This makes a large difference with long namespaces.

Binary size is almost unaffected, compile times slightly better:
Before:
GCC opt: 22.3 seconds, 4435232 bytes
Clang dev: 7.7 seconds, 5257344 bytes

After:
GCC opt: 18.6 seconds, 4493920 bytes
Clang dev: 7.2 seconds, 5469136 bytes

Reviewed By: ericniebler

Differential Revision: D3231530

fb-gh-sync-id: 6aa76e7f780a8afdbfed8a378f257ceb86dce704
fbshipit-source-id: 6aa76e7f780a8afdbfed8a378f257ceb86dce704
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
@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
@wumuzi520 wumuzi520 mentioned this pull request Feb 27, 2018
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
facebook-github-bot pushed a commit that referenced this pull request Jan 18, 2019
Summary:
This is mostly a POC. It will probably fail in some cases, but it's better than nothing.
Sample output:
  (gdb) co_bt this
  0x292d70 <zero()>
  0x293f50 <one()>
  0x295050 <two()>
  0x296150 <three()>
  0x297250 <folly::coro::TaskWithExecutor<int>::start() &&::{lambda(folly::Promise<int>, folly::coro::TaskWithExecutor<int>)#1}::operator()(folly::Promise<int>, folly::coro::TaskWithExecutor<int>) const>

Reviewed By: jwiepert

Differential Revision: D13727139

fbshipit-source-id: bff98eb4f5eb2ebd73c880d3b525172782f87511
facebook-github-bot pushed a commit that referenced this pull request Oct 23, 2019
Summary:
MemorySanitizer was failing due to uninitialized memory in the stack.

```
==596112==WARNING: MemorySanitizer: use-of-uninitialized-value
[testserver][INFO]: IOBuff received. Len = 128
    #0 0x9d4b21 in folly::SocketAddress::updateUnixAddressLength(unsigned int) xplat/folly/SocketAddress.cpp:710:7
    #1 0x9d4740 in folly::SocketAddress::setFromSockaddr(sockaddr_un const*, unsigned int) xplat/folly/SocketAddress.cpp:338:3

  Uninitialized value was created by an allocation of 'addrStorage' in the stack frame of function '_ZN5folly17AsyncServerSocket12handler
ReadyEtNS_13NetworkSocketEt'
    #0 0x7de840 in folly::AsyncServerSocket::handlerReady(unsigned short, folly::NetworkSocket, unsigned short) xplat/folly/io/async/Asyn
cServerSocket.cpp:835
```

Differential Revision: D18086738

fbshipit-source-id: f36013b157d7b34d3b29c08d4533f01be1a1a8c9
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Jul 18, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Jul 23, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Jul 30, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Aug 1, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Aug 1, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
DenisYaroshevskiy added a commit to DenisYaroshevskiy/folly that referenced this pull request Aug 2, 2024
Summary:
Pull Request resolved: meta#2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Differential Revision: D59396081
facebook-github-bot pushed a commit that referenced this pull request Aug 2, 2024
Summary:
Moving simdForEachAligning into folly/algorithm/simd.

Step 1. Just move the files.

Reviewed By: dmm-fb

Differential Revision: D59680837

fbshipit-source-id: ad04d5a881bf8dbda186d1fd5cb943dae011e7ac
facebook-github-bot pushed a commit that referenced this pull request Aug 5, 2024
Summary:
Pull Request resolved: #2249

We have a need for some common concepts that are used in many places.

This is a proposal, please let me know what you think.

Usages example:

`uncvref_same_as`:

https://www.internalfb.com/code/fbsource/[a71ce59323a15fd7559d6132c1f8e2d0256ca7cb]/fbcode/multifeed/entrepot/lib/zdb_manager/ZdbUtil.h?lines=237

`uncvref_instantiated_from`:

https://www.internalfb.com/code/fbsource/[b366209d2c108133a0545edc7943b9461323623b]/fbcode/multifeed/mfaction/MFHashSerializer.h?lines=38

Reviewed By: yfeldblum

Differential Revision: D59396081

fbshipit-source-id: 4912c2f9fe683f4d3b37fce43466c9281d03ce13
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 May 1, 2025
…tionCounterLib

Summary:
When using `ASAN_OPTIONS=strict_init_order=true` (https://github.com/google/sanitizers/wiki/AddressSanitizerInitializationOrderFiasco#strict-init-order-checking), if some other global initializer throws an exception, this leads to
```
==2675213==ERROR: AddressSanitizer: initialization-order-fiasco on address 0x000076d59040 at pc 0x00002dfbfecc bp 0x7ffc4ccb0a10 sp 0x7ffc4ccb0a08
READ of size 4 at 0x000076d59040 thread T0
SCARINESS: 8 (4-byte-read-initialization-order-fiasco)
    #0 0x2dfbfecb in (anonymous namespace)::throwHandler(void*, std::type_info*, void (**)(void*)) fbcode/third-party-buck/platform010/build/libgcc/include/c++/trunk/bits/atomic_base.h:481
    #1 0xb70bd5c in __cxa_throw fbcode/folly/debugging/exception_tracer/ExceptionTracerLib.cpp:82
...
0x000076d59040 is located 0 bytes inside of global variable '(anonymous namespace)::gExceptionStats' defined in 'fbcode/folly/debugging/exception_tracer/ExceptionCounterLib.cpp' (0x76d59040) of size 40
```

In practice this is a false-positive because this code can only be reached after `registerCxaThrowCallback(throwHandler)` has been called which requires this translation unit's globals to have already been initialized, but ASAN doesn't know about this in the strict mode.

Reviewed By: dmm-fb, Gownta, yfeldblum

Differential Revision: D73963976

fbshipit-source-id: aee9f6a16725c94b98aad16ec45dcfdb12fa1378
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 #1 in Post [Truncation of UserMetric::Time](https://fb.workplace.com/groups/560979627394613/permalink/3320975644728317/)

Our team uses [BENCHMARK_IMPL_COUNTERS](https://www.internalfb.com/code/fbsource/[f51516f2368d]/fbcode/folly/Benchmark.h?lines=379) to measure custom metrics during Folly::benchmarks execution. While working on updates to NodeAPI::SlaBenchmark in D77320464 I noticed Folly `UserMetric` accepts integer(Long) type values which works great for `UserMetric::Type::Custom` and `UserMetric::Type::Metric`, but causes issues for `UserMetric::Type::Time` values.

When [time metrics](https://www.internalfb.com/code/fbsource/[f51516f2368d8097604a13de292824a7d85d7de1]/fbcode/folly/Benchmark.cpp?lines=529) are formated for display the value is implicitly cast(`Long` -> `Double`) resulting in loss of precision. This results in any value smaller than 1s being displayed as 0.00fs due to the truncation making it impossible to display small time values.

~~This diff adds support for users to provide floating point values as input to `UserMetric` allowing precision to be retained through a new `time_value` field, while remaining backward compatible with existing usage that relies on the existing `value` field.~~ See discussion below

Reviewed By: yfeldblum

Differential Revision: D77319941

fbshipit-source-id: a4d55165b5429fa602ea357764db03a81b9ac760
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
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 22, 2026
Summary:
The result of SparseMaskIter's next is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the and is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]


By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗

Differential Revision: D94030304
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]


By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]


By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Pull Request resolved: meta#2589

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]

By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Instruction CTZ is not available on armv9a CPUs.
This implies that to compute trailing zeroes, RBIT followed by CLZ must be issued.

We are changing the mask's logic to reverse bits once nad rely on CLZ instead of CTZ.

The former instruction sequence looked like this:

  2c3e48:	fmov	x15, d1
  2c3e4c:	rbit	x16, x15
  2c3e50:	clz	x16, x16
  2c3e54:	lsl	x16, x16, meta#1
  2c3e58:	and	x16, x16, #0xf8
  2c3e5c:	ldr	w16, [x14, x16]
  2c3e60:	cbz	w16, 2c3e88 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x35c>
  2c3e64:	sub	x16, x15, #0x1
  2c3e68:	ands	x15, x16, x15
  2c3e6c:	b.ne	2c3e4c <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x320>  // b.any

The newer looks like this:

  2c3d90:	fmov	x15, d1
  2c3d94:	rbit	x15, x15
  2c3d98:	clz	x17, x15
  2c3d9c:	lsl	x18, x17, meta#1
  2c3da0:	and	x18, x18, #0xf8
  2c3da4:	ldr	w18, [x16, x18]
  2c3da8:	cbz	w18, 2c3dd0 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x364>
  2c3dac:	lsr	x17, x12, x17
  2c3db0:	ands	x15, x17, x15
  2c3db4:	b.ne	2c3d98 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x32c>  // b.any


We can observe three things:

-The final conditional branch jumps back to clz instead of rbit.
-Instruction lsr depends on the result of clz, whereas sub depends on the result of rbit; meaning the old codepath can be executed speculatively earlier.
-Assignment of 0x7FFFFFFFFFFFFFFF has been hoisted.

There are no improvements nor regressions observed on benchmarks, probably it doesn't hit the case where many matches occur within the same tag.
The added instruction of assigning 0x7FFFFFFFFFFFFFFF could potentially delay the tag memory load by 1 cycle, although it's unlikely

This change allows performance improvements on occupiedIter: D94023144

Differential Revision: D94020004
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]


By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev pushed a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Instruction CTZ is not currently available on our aarch64 CPUs, it will be supported on the processors arriving in 2028.
This implies that to compute trailing zeroes, RBIT followed by CLZ must be issued.

We are changing the mask's logic to reverse bits once nad rely on CLZ instead of CTZ.

The former instruction sequence looked like this:

  2c3e48:	fmov	x15, d1
  2c3e4c:	rbit	x16, x15
  2c3e50:	clz	x16, x16
  2c3e54:	lsl	x16, x16, meta#1
  2c3e58:	and	x16, x16, #0xf8
  2c3e5c:	ldr	w16, [x14, x16]
  2c3e60:	cbz	w16, 2c3e88 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x35c>
  2c3e64:	sub	x16, x15, #0x1
  2c3e68:	ands	x15, x16, x15
  2c3e6c:	b.ne	2c3e4c <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x320>  // b.any

The newer looks like this:

  2c3d90:	fmov	x15, d1
  2c3d94:	rbit	x15, x15
  2c3d98:	clz	x17, x15
  2c3d9c:	lsl	x18, x17, meta#1
  2c3da0:	and	x18, x18, #0xf8
  2c3da4:	ldr	w18, [x16, x18]
  2c3da8:	cbz	w18, 2c3dd0 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x364>
  2c3dac:	lsr	x17, x12, x17
  2c3db0:	ands	x15, x17, x15
  2c3db4:	b.ne	2c3d98 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x32c>  // b.any

We can observe three things:

-The final conditional branch jumps back to clz instead of rbit.
-Instruction lsr depends on the result of clz, whereas sub depends on the result of rbit; meaning the old codepath can be executed speculatively earlier.
-Assignment of 0x7FFFFFFFFFFFFFFF has been hoisted.

There are no improvements nor regressions observed on benchmarks, probably it doesn't hit the case where many matches occur within the same tag.
The added instruction of assigning 0x7FFFFFFFFFFFFFFF could potentially delay the tag memory load by 1 cycle, although it's unlikely

This change allows performance improvements on occupiedIter: D94023144

Differential Revision: D94020004
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Pull Request resolved: meta#2589

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]

By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Instruction CTZ is not available on armv9a CPUs.
This implies that to compute trailing zeroes, RBIT followed by CLZ must be issued.

We are changing the mask's logic to reverse bits once nad rely on CLZ instead of CTZ.

The former instruction sequence looked like this:

  2c3e48:	fmov	x15, d1
  2c3e4c:	rbit	x16, x15
  2c3e50:	clz	x16, x16
  2c3e54:	lsl	x16, x16, meta#1
  2c3e58:	and	x16, x16, #0xf8
  2c3e5c:	ldr	w16, [x14, x16]
  2c3e60:	cbz	w16, 2c3e88 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x35c>
  2c3e64:	sub	x16, x15, #0x1
  2c3e68:	ands	x15, x16, x15
  2c3e6c:	b.ne	2c3e4c <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x320>  // b.any

The newer looks like this:

  2c3d90:	fmov	x15, d1
  2c3d94:	rbit	x15, x15
  2c3d98:	clz	x17, x15
  2c3d9c:	lsl	x18, x17, meta#1
  2c3da0:	and	x18, x18, #0xf8
  2c3da4:	ldr	w18, [x16, x18]
  2c3da8:	cbz	w18, 2c3dd0 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x364>
  2c3dac:	lsr	x17, x12, x17
  2c3db0:	ands	x15, x17, x15
  2c3db4:	b.ne	2c3d98 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x32c>  // b.any


We can observe three things:

-The final conditional branch jumps back to clz instead of rbit.
-Instruction lsr depends on the result of clz, whereas sub depends on the result of rbit; meaning the old codepath can be executed speculatively earlier.
-Assignment of 0x7FFFFFFFFFFFFFFF has been hoisted.

There are no improvements nor regressions observed on benchmarks, probably it doesn't hit the case where many matches occur within the same tag.
The added instruction of assigning 0x7FFFFFFFFFFFFFFF could potentially delay the tag memory load by 1 cycle, although it's unlikely

This change allows performance improvements on occupiedIter: D94023144

Differential Revision: D94020004
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]


By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
Nicoshev pushed a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Instruction CTZ is not currently available on our aarch64 CPUs, it will be supported on the processors arriving in 2028.
This implies that to compute trailing zeroes, RBIT followed by CLZ must be issued.

We are changing the mask's logic to reverse bits once nad rely on CLZ instead of CTZ.

The former instruction sequence looked like this:

  2c3e48:	fmov	x15, d1
  2c3e4c:	rbit	x16, x15
  2c3e50:	clz	x16, x16
  2c3e54:	lsl	x16, x16, meta#1
  2c3e58:	and	x16, x16, #0xf8
  2c3e5c:	ldr	w16, [x14, x16]
  2c3e60:	cbz	w16, 2c3e88 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x35c>
  2c3e64:	sub	x16, x15, #0x1
  2c3e68:	ands	x15, x16, x15
  2c3e6c:	b.ne	2c3e4c <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x320>  // b.any

The newer looks like this:

  2c3d90:	fmov	x15, d1
  2c3d94:	rbit	x15, x15
  2c3d98:	clz	x17, x15
  2c3d9c:	lsl	x18, x17, meta#1
  2c3da0:	and	x18, x18, #0xf8
  2c3da4:	ldr	w18, [x16, x18]
  2c3da8:	cbz	w18, 2c3dd0 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x364>
  2c3dac:	lsr	x17, x12, x17
  2c3db0:	ands	x15, x17, x15
  2c3db4:	b.ne	2c3d98 <_ZN30F14Set_equalityRefinement_Test8TestBodyEv+0x32c>  // b.any

We can observe three things:

-The final conditional branch jumps back to clz instead of rbit.
-Instruction lsr depends on the result of clz, whereas sub depends on the result of rbit; meaning the old codepath can be executed speculatively earlier.
-Assignment of 0x7FFFFFFFFFFFFFFF has been hoisted.

There are no improvements nor regressions observed on benchmarks, probably it doesn't hit the case where many matches occur within the same tag.
The added instruction of assigning 0x7FFFFFFFFFFFFFFF could potentially delay the tag memory load by 1 cycle, although it's unlikely

This change allows performance improvements on occupiedIter: D94023144

Differential Revision: D94020004
Nicoshev added a commit to Nicoshev/folly that referenced this pull request Feb 23, 2026
Summary:
Pull Request resolved: meta#2589

The result of SparseMaskIter's next() is often used as an index on an 8-byte element array.
In this case, the index needs to be shifted left by 3 to access the desired memory position.
The return statement of the mentioned function contains i >> 2.
The compiler is simplifying the shifts by only issuing a lsl 1 while ommitting the lsr 2.
However, it then ANDs the shifted value by 0xf8, to ensure correctness when variable i is not a
multiple of 4.
We do know that variable i will always be a multiple of 4.
We add the assume clause so the compiler avoids emitting the &0xf8

Before the assembly looked like this:

  clz	x16, x16
  lsl	x16, x16, meta#1
  and	x16, x16, #0xf8
  ldr	x16, [x14, x16]

After the changes, we verified the AND is omitted:

  clz	x16, x16
  lsl	x16, x16, meta#1
  ldr	x16, [x14, x16]

By removing a pipelined instruction in the codepath, execution latency is reduced by 1 cycle 🤗
It also allows the processor to foresee proceeding instructions up to 1 cycle earlier

Differential Revision: D94030304
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.

3 participants