folly.git
7 years agofolly: use std::__throw_out_of_range
Lucian Grijincu [Fri, 30 Sep 2016 19:12:32 +0000 (12:12 -0700)]
folly: use std::__throw_out_of_range

Summary:
A ton of these functions are tiny and should be inlined. `throw std::out_of_range("bla")` generates quite a lot of code.

See godbolt from {D3940968}: https://godbolt.org/g/9K36Km

  advanceNoInline(S):
          movq    %rdi, %rax
          sarq    $32, %rax
          cmpl    %eax, %edi
          jg      .L20
          leal    1(%rdi), %eax
          ret
  .L20:
          subq    $8, %rsp
          call    S::outOfRange() [clone .isra.0]

vs previous implementation

  advance(S):
          movq    %rdi, %rdx
          sarq    $32, %rdx
          cmpl    %edx, %edi
          jg      .L14
          leal    1(%rdi), %eax
          ret
  .L14:
          pushq   %rbp
          pushq   %rbx
          movl    $16, %edi
          subq    $8, %rsp
          call    __cxa_allocate_exception
          movl    $.LC0, %esi
          movq    %rax, %rdi
          movq    %rax, %rbx
          call    std::out_of_range::out_of_range(char const*)
          movl    std::out_of_range::~out_of_range(), %edx
          movl    typeinfo for std::out_of_range, %esi
          movq    %rbx, %rdi
          call    __cxa_throw
          movq    %rax, %rbp
          movq    %rbx, %rdi
          call    __cxa_free_exception
          movq    %rbp, %rdi
          call    _Unwind_Resume

This pattern is in the standard library as well:
```
      reference
      at(size_type __n)
      {
if (__n >= _Nm)
  std::__throw_out_of_range(__N("array::at"));
return _M_instance[__n];
      }
```

https://github.com/gcc-mirror/gcc/blob/edd716b6b1caa1a5cb320a8cd7f626f30198e098/libstdc%2B%2B-v3/include/tr1/array#L138

Reviewed By: yfeldblum

Differential Revision: D3947075

fbshipit-source-id: 6e174c725791762a533a534c8482ea9576460b86

7 years agoFind dwarf.h in libdwarf subdirectory
Ted Percival [Fri, 30 Sep 2016 17:40:00 +0000 (10:40 -0700)]
Find dwarf.h in libdwarf subdirectory

Summary:
libdwarf headers moved from `/usr/include` to `/usr/include/libdwarf` in [dwarfutils 20160613-2](http://metadata.ftp-master.debian.org/changelogs/main/d/dwarfutils/unstable_changelog).

Adds a check for the library as well, and fixes a tiny typo in the `libunwind` check.

No longer checks for `libdwarf.h`; only `dwarf.h` is used.
Closes https://github.com/facebook/folly/pull/480

Reviewed By: yfeldblum

Differential Revision: D3878961

Pulled By: Orvid

fbshipit-source-id: 7970d33511bf6d351cec2c8077cb07b85f2f8d33

7 years agofolly: Range: detail::throwOutOfRange -> std::__throw_out_of_range
Lucian Grijincu [Thu, 29 Sep 2016 21:40:13 +0000 (14:40 -0700)]
folly: Range: detail::throwOutOfRange -> std::__throw_out_of_range

Summary:
No need to define our own.

Generated code is similar: https://godbolt.org/g/5xWrNx (one extra move instruction).

```
.L20:
        subq    $8, %rsp
        call    S::outOfRange() [clone .isra.0]
```

```
.LC1:
        .string "out of range"
.L26:
        subq    $8, %rsp
        movl    $.LC1, %edi
        call    std::__throw_out_of_range(char const*)
```

Reviewed By: Orvid

Differential Revision: D3945578

fbshipit-source-id: c65e9dea55e8f01f51766b2695af68d2bc92c266

7 years agoFix ThreadCachedInt race condition
Dan Schatzberg [Thu, 29 Sep 2016 15:22:50 +0000 (08:22 -0700)]
Fix ThreadCachedInt race condition

Summary:
Acquire a SharedMutex at ThreadExit to ensure that after unlinking the ThreadEntry from
the list, future accessAllThreads() won't miss a destroying thread.

This is quite a dangerous fix as it changes some lock ordering semantics. ThreadLocal
elements are now destroyed while holding a lock, so if the destruction function
acquires a different lock, ordering must be consistent with other
uses of accessAllThreads().

I've made accessAllThreads() an opt-in feature via a template parameter and changed
all existing uses. I've also fixed a few lock ordering issues that arose due to this
change.

Reviewed By: andriigrynenko

Differential Revision: D3931072

fbshipit-source-id: 4d464408713184080079698df453b95873bb1a6c

7 years agoFix apple bug around TFO writes
Subodh Iyengar [Thu, 29 Sep 2016 13:42:11 +0000 (06:42 -0700)]
Fix apple bug around TFO writes

Summary:
When using connectx to do TFO, apple has a bug
where the second write after a TFO write will cause
the socket to throw an ENOTCONN error instead of an
EAGAIN. Linux handles this case fine and returns an
EAGAIN, however apple returns ENOTCONN.

We solve this by treating ENOTCONN as an EAGAIN temporarily.

Reviewed By: yfeldblum

Differential Revision: D3942681

fbshipit-source-id: ab4f0b5fd6cdcfe9c584ea00849705a2d739d65f

7 years agoAdd tfo functions for apple
Subodh Iyengar [Thu, 29 Sep 2016 13:42:10 +0000 (06:42 -0700)]
Add tfo functions for apple

Summary:
Adds TFO functions for apple devices
Also allows android as well by removing that
restriction. Newer versions of android support
TFO, so this allows us to experiment with them

Reviewed By: yfeldblum

Differential Revision: D3942664

fbshipit-source-id: faf439783b018cf7c987a2e3ade5ea6c0c02bf48

7 years agofolly: Range: outline exception throwing
Lucian Grijincu [Thu, 29 Sep 2016 05:33:39 +0000 (22:33 -0700)]
folly: Range: outline exception throwing

Summary:
Here's some godbolt: https://godbolt.org/g/9K36Km

  advanceNoInline(S):
          movq    %rdi, %rax
          sarq    $32, %rax
          cmpl    %eax, %edi
          jg      .L20
          leal    1(%rdi), %eax
          ret
  .L20:
          subq    $8, %rsp
          call    S::outOfRange() [clone .isra.0]

vs previous implementation

  advance(S):
          movq    %rdi, %rdx
          sarq    $32, %rdx
          cmpl    %edx, %edi
          jg      .L14
          leal    1(%rdi), %eax
          ret
  .L14:
          pushq   %rbp
          pushq   %rbx
          movl    $16, %edi
          subq    $8, %rsp
          call    __cxa_allocate_exception
          movl    $.LC0, %esi
          movq    %rax, %rdi
          movq    %rax, %rbx
          call    std::out_of_range::out_of_range(char const*)
          movl    std::out_of_range::~out_of_range(), %edx
          movl    typeinfo for std::out_of_range, %esi
          movq    %rbx, %rdi
          call    __cxa_throw
          movq    %rax, %rbp
          movq    %rbx, %rdi
          call    __cxa_free_exception
          movq    %rbp, %rdi
          call    _Unwind_Resume

Reviewed By: ot

Differential Revision: D3940968

fbshipit-source-id: b47a41e7cdd863fcef099ff3c21860b2979ee6e8

7 years agoAdd unchecked versions of advance(), subtract(), and subpiece() in Range
Giuseppe Ottaviano [Wed, 28 Sep 2016 22:37:33 +0000 (15:37 -0700)]
Add unchecked versions of advance(), subtract(), and subpiece() in Range

Summary:
`Range` has a somewhat inconsistent API: most methods assume
argument validity as a precondition (mirroring their STL
counterparts), others check the arguments and throw for invalid ones.

Since `Range` is intended as a zero-cost abstraction on top of
pointers/iterators, unchecked methods should be preferred. At this
point however we cannot change the semantics of `advance()` and other
methods. This diff adds new unchecked versions of these methods.

Reviewed By: luciang

Differential Revision: D3938480

fbshipit-source-id: 6952683ee0716aa1584e79584158fbf3e083b52e

7 years agoFix SUPPLY_MISSING_INT128_TRAITS
Witchakorn Kamolpornwijit [Wed, 28 Sep 2016 20:00:04 +0000 (13:00 -0700)]
Fix SUPPLY_MISSING_INT128_TRAITS

Summary:
The original code `AC_DEFINE([FOLLY_SUPPLY_MISSING_INT128_TRAITS...` resulted in defining the constant FOLLY_FOLLY_SUPPLY_MISSING_INT128_TRAITS in folly-config.h. This patch fix the name of the constant so that the name match with what appear in Traits.h.
Closes https://github.com/facebook/folly/pull/485

Reviewed By: yfeldblum

Differential Revision: D3931349

Pulled By: Orvid

fbshipit-source-id: bd7e7d3580d02134d36706bd5836822135232d26

7 years agofolly/experimental/hazptr: fix gcc 5 build
Maged Michael [Wed, 28 Sep 2016 08:36:57 +0000 (01:36 -0700)]
folly/experimental/hazptr: fix gcc 5 build

Summary: Fix includes in memory_resource.h

Reviewed By: yfeldblum

Differential Revision: D3935848

fbshipit-source-id: 713ce85ad17072779dfa1c667459e367c5e1d4b7

7 years agoSet a default value for slot in SharedMutex.h
Michael Lee [Wed, 28 Sep 2016 00:31:22 +0000 (17:31 -0700)]
Set a default value for slot in SharedMutex.h

Summary:
`SharedMutexImpl::lockSharedImpl` has a potentially uninitialized access:

  Assume state = 0
  canAlreadyDefer = (state & kMayDefer) != 0 ==> false
  aboveDeferThreshold = (state & kHasS) >= (kNumSharedToStartDeferring - 1) * kIncrHasS ==> false

  if (canAlreadyDefer || (aboveDeferThreshold && !drainInProgress)) ==> false

  line:1452: gotSlot(slot)->compare_exchange_strong(...) uses slot uninitialized

Reviewed By: Orvid

Differential Revision: D3933638

fbshipit-source-id: 0fbce5c00b8b1f34e50c302cb88def97853c5afe

7 years agoIntroducing folly::FunctionRef
Sven Over [Tue, 27 Sep 2016 14:44:32 +0000 (07:44 -0700)]
Introducing folly::FunctionRef

Summary:
This commit introduces a simple function reference type, similar to
std::reference_wrapper, but the template parameter is the function
signature type rather than the type of the referenced object.

A folly::FunctionRef is cheap to construct as it contains only a
pointer to the referenced callable and a pointer to a function which
invokes the callable.

The user of FunctionRef must be aware of the reference semantics:
storing a copy of a FunctionRef is potentially dangerous and should
be avoided unless the referenced object definitely outlives the
FunctionRef object. Thus any function that accepts a FunctionRef
parameter should only use it to invoke the referenced function and
not store a copy of it. Knowing that FunctionRef itself has reference
semantics, it is generally okay to use it to reference lambdas that
capture by reference.

Reviewed By: ericniebler

Differential Revision: D3277364

fbshipit-source-id: 0a7676919cd240da5b6e1f94cadba4289e0aca28

7 years agoSSL_SESSION wrapper
Anirudh Ramachandran [Mon, 26 Sep 2016 21:55:14 +0000 (14:55 -0700)]
SSL_SESSION wrapper

Summary:
This is a start to wrapping various SSL objects going forward so different
binaries can choose different version of OpenSSL (i.e., BoringSSL, OpenSSL
1.1.0, OpenSSL 1.0.2, etc.). There's no change to the caller - everyone just
uses 'SSLSession', but the implementation details vary

Reviewed By: siyengar

Differential Revision: D3707791

fbshipit-source-id: f895334a768cb7d43b41af40c9bc06be5307cc7f

7 years agoAsyncSSLSocket::getSSLClientCiphers using static map
Anirudh Ramachandran [Mon, 26 Sep 2016 20:14:55 +0000 (13:14 -0700)]
AsyncSSLSocket::getSSLClientCiphers using static map

Summary:
OpenSSL SSL_METHOD->get_cipher_by_char is not present in either OpenSSL
1.1.0 or BoringSSL. In addition, knekritz reports that time's being spent in
binary searching for cipher names.

Since the ciphercodes and names are (fairly) static, we store these in a static
hash map.

Reviewed By: siyengar

Differential Revision: D3275185

fbshipit-source-id: 08b36f3e73239b415b74c6ecc30ed65832d9ebd0

7 years agoMake a SharedPromise from a Future
Phil Willoughby [Mon, 26 Sep 2016 11:59:05 +0000 (04:59 -0700)]
Make a SharedPromise from a Future

Summary: Makes it easy to split a Future into multiple Futures

Reviewed By: rongrong

Differential Revision: D3885897

fbshipit-source-id: 6ac9fb22444dd828fbdebb44b06bf3d93d0f7583

7 years agoImprove documentation of MPMCQueue size and sizeGuess methods v2016.09.26.00
Eli Pozniansky [Fri, 23 Sep 2016 20:08:23 +0000 (13:08 -0700)]
Improve documentation of MPMCQueue size and sizeGuess methods

Summary: See title.

Reviewed By: nbronson

Differential Revision: D3914188

fbshipit-source-id: dd9ccd0c48911632d229ae675cc40d835ea14724

7 years agoAvoid external linkage call inside __ifunc__
Alisson Gusatti Azzolini [Fri, 23 Sep 2016 01:49:16 +0000 (18:49 -0700)]
Avoid external linkage call inside __ifunc__

Summary:
In debug mode, CpuId() ends up triggering external linkage from inside this __ifunc__.
However, in PIC, the relocation of external symbols are not ready yet, causing a segfault.

This only reproes in dynamic linking (PIC / so) and dbg mode.

Reviewed By: luciang

Differential Revision: D3895239

fbshipit-source-id: 2b7856c10abb5cfe24736d5bfac28e7e9d0e8272

7 years agoSwitch SocketAddressTest to use TemporaryFile instead of mkstemp
Michael Lee [Thu, 22 Sep 2016 18:09:57 +0000 (11:09 -0700)]
Switch SocketAddressTest to use TemporaryFile instead of mkstemp

Summary: Switch from mkstemp to the slightly more portable `folly::test::TemporaryFile`

Reviewed By: jsedgwick

Differential Revision: D3890411

fbshipit-source-id: e98d1e3a5adae92af1bb36f6213b194f633fab0f

7 years agoFix a couple comments
Giuseppe Ottaviano [Thu, 22 Sep 2016 18:06:31 +0000 (11:06 -0700)]
Fix a couple comments

Reviewed By: nbronson

Differential Revision: D3905865

fbshipit-source-id: 2743af4ae1b34adb0f8e611e672f9b6068430ec9

7 years agofix flaky TimeKeeper unit-test
Tianjiao Yin [Thu, 22 Sep 2016 08:06:15 +0000 (01:06 -0700)]
fix flaky TimeKeeper unit-test

Summary:
Sometime we have such unit-test failure

```
folly/futures/test/TimekeeperTest.cpp:134: Failure
Value of: flag
  Actual: false
Expected: true
```

This diff should make it less flaky, though I am not sure what's the best way to fix this flaky unit-test.

Reviewed By: yfeldblum

Differential Revision: D3889630

fbshipit-source-id: e7486d75fbcb3081d06724d213d4a2cf8942955d

7 years agoAdd logs for TFO succeded
Subodh Iyengar [Thu, 22 Sep 2016 08:01:42 +0000 (01:01 -0700)]
Add logs for TFO succeded

Summary:
Add logs for TFO to AsyncSocket
and wangle

Reviewed By: knekritz

Differential Revision: D3906104

fbshipit-source-id: 9a79b6f91273f8017a5e0d72fe5bdc8eff645ebc

7 years agoexperimental/observer/detail/ObserverManager.cpp missing gflags
Michael Lee [Thu, 22 Sep 2016 06:29:55 +0000 (23:29 -0700)]
experimental/observer/detail/ObserverManager.cpp missing gflags

Summary: Fix the build due to a missing gflags header

Reviewed By: yfeldblum

Differential Revision: D3905525

fbshipit-source-id: cc09189196a04741162c2d1561545d3fec417e5e

7 years agoFix compilation for libc++ 3.9
Shoaib Meenai [Wed, 21 Sep 2016 15:07:33 +0000 (08:07 -0700)]
Fix compilation for libc++ 3.9

Summary:
libc++ 3.9 and above define the __throw* functions inside stdexcept, so
defining them ourselves leads to compilation errors when compiling
against libc++ 3.9. Add appropriate preprocessor guards to avoid this.

Reviewed By: meyering

Differential Revision: D3898284

fbshipit-source-id: 435a28c2b3a83ee4d8f5af0df0343c524469011e

7 years agoFix detaching from evb
Subodh Iyengar [Tue, 20 Sep 2016 23:25:32 +0000 (16:25 -0700)]
Fix detaching from evb

Summary:
When we attach and detach from the
event base threads during connections
in the case of SSL it could result in
a crash while using TFO.

When TFO was enabled connectTimeout_
was set, which was not detached.

In the case when we would
fall back from TFO in case TFO did not
succeed, we would try and schedule a
connect timeout again. However because
we are now scheduled in a new evb thread,
this would cause the scheduleTimeout to
assert that it was not in the correct evb
thread.

This fixes the issue by attaching and detaching
connect timeouts as well.

Reviewed By: ngoyal

Differential Revision: D3892490

fbshipit-source-id: 278c0b8029022144cd59366ceb0ce83f0a60a307

7 years agouse folly::Function<void()> in folly::Executor interface
Sven Over [Tue, 20 Sep 2016 22:04:07 +0000 (15:04 -0700)]
use folly::Function<void()> in folly::Executor interface

Summary:
This diff changes the definition of `folly::Func` from `std::function<void()>`
over to `folly::Function<void()>`. This mostly affects the interface of
`folly::Executor` and derived and related classes. By using
`folly::Function<void()>`, we allow to have lambdas capturing move-only types
passed to executors. This continues an effort to get rid of the potentially
dangerous `folly::MoveWrapper` by allowing to capture move-only types in lambdas
when using `folly::Future`, `folly::EventBase` and now `folly::Executor`.

Reviewed By: yfeldblum

Differential Revision: D3706449

fbshipit-source-id: 11c2cee32cb9f0298c39b7b1695a477777eeb3aa

7 years agoDraft prototype of hazard pointers C++ template library
Maged Michael [Tue, 20 Sep 2016 20:47:17 +0000 (13:47 -0700)]
Draft prototype of hazard pointers C++ template library

Summary: Make draft of hazard pointers prototype public

Reviewed By: djwatson

Differential Revision: D3870280

fbshipit-source-id: e029efa336585055f67687059e10ae11766f8d7f

7 years agoRemove boost::barrier from AsyncUDPSocketTest.
Andrey Ignatov [Tue, 20 Sep 2016 19:14:33 +0000 (12:14 -0700)]
Remove boost::barrier from AsyncUDPSocketTest.

Summary:
`EventBase` has its own methods to wait till it's ready so we can avoid using
barriers and remove boost dependency.

Reviewed By: mzlee

Differential Revision: D3894408

fbshipit-source-id: f050a982c98c4f672cf295845115686c95fc7919

7 years agoFix fibers asan integration for new asan APIs
Igor Sugak [Tue, 20 Sep 2016 07:51:26 +0000 (00:51 -0700)]
Fix fibers asan integration for new asan APIs

Summary:
Updating fibers code to use https://github.com/llvm-mirror/compiler-rt/commit/b0477747dfa8a9706f2c902e877e616aca51e06f

Patch by andriigrynenko!

Reviewed By: andrewcox

Differential Revision: D3500482

fbshipit-source-id: f51f4bb4ebf0d95a898eb1d4098459aa691acd61

7 years agofix ZSTD support
Philip Pronin [Tue, 20 Sep 2016 03:52:08 +0000 (20:52 -0700)]
fix ZSTD support

Summary:
Existing logic is broken (unable to correctly handle chained `IOBuf`
in case of both `compress` and `uncompress`) and has unnecessarly strict
`needsUncompressedLength() == true` requirement.

This diff switches `ZSTDCodec` to use streaming to handle chained `IOBuf`,
drops `needsUncompressedLength() == true`.

Reviewed By: luciang

Differential Revision: D3827579

fbshipit-source-id: 0ef6a9ea664ef585d0e181bff6ca17166b28efc2

7 years agoTry using the last Deferred reader slot first
Qi Wang [Mon, 19 Sep 2016 23:48:17 +0000 (16:48 -0700)]
Try using the last Deferred reader slot first

Summary:
When trying to find an empty deferred reader slot, getting the current CPU can
take quite a few cycles, e.g. >1% CPU on SMC (https://fburl.com/434646643).

Let's track the last slot used by this thread and try that slot first before reading
CPU id and doing the search.

u-benchmark results seem to be improving generally (though a bit noisy and not
sure how much to trust). Results w/ this diff on left side:
P56648675

Reviewed By: nbronson

Differential Revision: D3857793

fbshipit-source-id: 8b1c005362c82e748a663100f889b0b99dc257fe

7 years agomove `shellQuote` to implementation file v2016.09.19.00
Dominik Gabi [Fri, 16 Sep 2016 22:00:45 +0000 (15:00 -0700)]
move `shellQuote` to implementation file

Summary: Fixing ODR violations...

Reviewed By: simpkins, yfeldblum

Differential Revision: D3875667

fbshipit-source-id: 0d8ec0b48e14fffb7e3e60c0e68e2576b2f58d1e

7 years agoescape `{` in cmd for deprecated `Substring(std::string...)`
Dominik Gabi [Fri, 16 Sep 2016 22:00:43 +0000 (15:00 -0700)]
escape `{` in cmd for deprecated `Substring(std::string...)`

Summary:
Since `shellify` interprets the command as a format string we need to escape
`{` and `}`.

Reviewed By: ldemailly, simpkins

Differential Revision: D3874605

fbshipit-source-id: f47db387c3a44a3ba1c0c1d4726b7212fcb5ef3e

7 years agoupdate stats APIs to use TimePoint vs Duration correctly
Adam Simpkins [Fri, 16 Sep 2016 19:23:41 +0000 (12:23 -0700)]
update stats APIs to use TimePoint vs Duration correctly

Summary:
Update the stats APIs to correcly distinguish between TimePoint and Duration
types.

This does leave addValue() and update() APIs in place that accept Duration
values, for backwards compatibility.  These should eventually be removed once
all code has been converted to call the new APIs.

Reviewed By: yfeldblum

Differential Revision: D3808805

fbshipit-source-id: 36d6574ba4a09db7eb9f1a35e47addd3e07f8461

7 years agoReturn rvalue references from &&-qualified members of dynamic
Tom Jackson [Fri, 16 Sep 2016 17:09:32 +0000 (10:09 -0700)]
Return rvalue references from &&-qualified members of dynamic

Summary: Let the caller do a move, don't force one.

Reviewed By: yfeldblum

Differential Revision: D3873129

fbshipit-source-id: 40c6bf564bcbf794830c99ea1248a9c1bb30e9b0

7 years agoReduce footprint of ScribeClient
Vladimir Slaykovskiy [Fri, 16 Sep 2016 09:53:58 +0000 (02:53 -0700)]
Reduce footprint of ScribeClient

Summary:
I've found all code paths that contributed to the number of threads in new ScribeClient. Here's a list of flags that reduce the number of thread:
  --default_tls_thread_count=1 # was 32
  --sr2_event_base_pool_size=1
  --has_thrift_dispatcher_reporter=0 # creates a thrift server with a few extra threads
  --observer_manager_pool_size=1 # default is 4

Optimizations in this diff:
- Don't initialize OBCClient object if it is not used
- Added FLAG_observer_manager_pool_size to control size of the pool in ObserverManager

Currently OBC counters are switched off globally in ScribeCliean, it means that new code path that creates SR instances is disabled, but eventually we plan to switch it on. Clients that don't use SR and want to keep their RSS/threads profile low, should pass flags listed above. I'll announce this in ScribeUsers group as well.

Differential Revision: D3870704

fbshipit-source-id: 0efad6b3dc43c072ab11cac7e9461c09532ea11c

7 years agowork around LLVM#30305 in folly::Expected, use unified initialization syntax for...
Eric Niebler [Fri, 16 Sep 2016 00:00:30 +0000 (17:00 -0700)]
work around LLVM#30305 in folly::Expected, use unified initialization syntax for extra goodness

Summary: The behavior of inheriting constructors changed in clang 3.9 (see https://llvm.org/bugs/show_bug.cgi?id=30305), and folly::Expected needs to change accordingly. As a drive-by improvement, change all invocations of default constructors to use unified initialization syntax.

Reviewed By: igorsugak

Differential Revision: D3872994

fbshipit-source-id: fdaea8b35980df21b8522e2c3d5a8c3be1d84efa

7 years agofolly/.../ExceptionTracerLib.cpp: provide less DOF fodder (avoid heap use-after-free)
Jim Meyering [Thu, 15 Sep 2016 23:26:34 +0000 (16:26 -0700)]
folly/.../ExceptionTracerLib.cpp: provide less DOF fodder (avoid heap use-after-free)

Summary:
Before this change, an application would fail consistently with a shutdown-time heap use-after-free (i.e., destructor-order-fiasco when one of the following symbols was used after its static-destruction-triggered free):

  DECLARE_CALLBACK(CxaThrow);
  DECLARE_CALLBACK(CxaBeginCatch);
  DECLARE_CALLBACK(CxaRethrow);
  DECLARE_CALLBACK(CxaEndCatch);
  DECLARE_CALLBACK(RethrowException);

Each of those would define a classic meyers singleton.
Since each destructor is trivial, we can fix this by making each a pseudo-leaky (indestructible) meyers singleton instead. Since each static value is never destroyed,
it can never cause a DOF error again.

Differential Revision: D3870740

fbshipit-source-id: 625f5d5268768ca0e4125bed72bc66c53618be29

7 years agoKill unneeded dependency on portability/Memory.h
Christopher Dykes [Thu, 15 Sep 2016 20:00:46 +0000 (13:00 -0700)]
Kill unneeded dependency on portability/Memory.h

Summary: This dependency was added but isn't actually needed, so get rid of it.

Reviewed By: mzlee

Differential Revision: D3863923

fbshipit-source-id: 407d2b3db759e30c37d876dde133fc962daeaeae

7 years agoAdd flag to indicate a session resumption attempt
Neel Goyal [Thu, 15 Sep 2016 19:00:17 +0000 (12:00 -0700)]
Add flag to indicate a session resumption attempt

Summary: Track when session resumption was attempted during connect

Reviewed By: shamdor-fb

Differential Revision: D3861028

fbshipit-source-id: 26ca41084faeeb64666b6833896b9510ef2b4c25

7 years agoa simple first step towards using clocks properly in the stats code
Adam Simpkins [Thu, 15 Sep 2016 18:02:47 +0000 (11:02 -0700)]
a simple first step towards using clocks properly in the stats code

Summary:
Update the timeseries and histogram classes to accept a clock parameter as a
template parameter, instead of a time duration type.

This is a first step towards transitioning the code to correctly distinguishing
between time_point and duration types.  This defines TimePoint and Duration
type aliases, but does not start using them yet.

In upcoming diffs I will start converting more APIs to correctly use TimePoint
instead of just Duration.

For now the default clock type is folly::LegacyStatsClock, which still uses
std::chrono::seconds as the default duration.  At the moment the stats code is
optimized for second granularity--the addValue() code has a fast path when
called in the same second as the last update.  When using finer granularity
durations this fast path can't be used as often.  I will also send out
subsequent diffs to make the code optimized for updates within the same bucket,
rather than just updates with the exact same time value.

Reviewed By: yfeldblum

Differential Revision: D3807715

fbshipit-source-id: 77696c4f44a8d85e4d6ff84d7656fe7a9709797c

7 years agoignore `$SHELL` in `shellify`
Dominik Gabi [Thu, 15 Sep 2016 14:57:15 +0000 (07:57 -0700)]
ignore `$SHELL` in `shellify`

Summary:
Why `$SHELL` is a bad idea:

- getenv() is not thread safe. (In practice it should work if other threads aren't calling setenv(), but still seems undesirable if we can avoid it.)
- It seems confusing for the program to have different behavior for different developers.
- Other shells besides /bin/sh may have different quoting behaviors. For instance, I don't think csh allows unescaped newlines inside single quotes.
- SHELL might be set to other non-shell-like programs in some cases. (Say, if this gets run from inside a git or mercurial hook it might end up being set to the restricted git or hg shell that only lets you run specific commands.)
Anyway, this isn't related to your diff, so nothing needs to be done for now,
but I would vote for changing this to always use /bin/sh in a future diff.

Both the C system() call and python's subprocess module appear to
always use /bin/sh and ignore $SHELL.

Reviewed By: simpkins

Differential Revision: D3867047

fbshipit-source-id: dab0e6afbe1c20ff13d9a52f212df95af425dd77

7 years agoformatting support for `Subprocess::shellify`
Dominik Gabi [Thu, 15 Sep 2016 14:57:14 +0000 (07:57 -0700)]
formatting support for `Subprocess::shellify`

Summary:
Adding formatting support with automatic escaping of parameters. Will
subsequentyl try and make it harder for people to use non-statically determined
format strings for this.

Reviewed By: simpkins

Differential Revision: D3866174

fbshipit-source-id: 80bb5886386692643876116fbf338ca0d6986e6a

7 years agodeprecate `folly::Subprocess(std::string, ...)`
Dominik Gabi [Thu, 15 Sep 2016 14:57:13 +0000 (07:57 -0700)]
deprecate `folly::Subprocess(std::string, ...)`

Summary:
introducing `Subprocess::shellify` to get around this. Still thinking
about how to make sure people escape arguments passing into that function. I'd
like to have something along the lines of Phabricator's `csprintf` here.

Reviewed By: yfeldblum

Differential Revision: D3857827

fbshipit-source-id: 8afbc9f1c62c62e0fc91782e11b808145b370933

7 years agoMake ElfCache follow .gnu_debuglink
Mark Williams [Wed, 14 Sep 2016 22:48:52 +0000 (15:48 -0700)]
Make ElfCache follow .gnu_debuglink

Summary:
If you split out debug info into a separate file, folly::Symbolizer
didn't find it, and failed to include file and line number info in
backtraces.

This adds a new open mode which follows the .gnu_debuginfo link, and
uses it from ElfCache and SignalSafeElfCache.

Reviewed By: meyering, luciang

Differential Revision: D3852311

fbshipit-source-id: fec9e57378ae59fa1b82d41a163bb9cfcf9ca23c

7 years agoSwap a newly added include of gtest.h with portability/GTest.h
Christopher Dykes [Wed, 14 Sep 2016 21:12:21 +0000 (14:12 -0700)]
Swap a newly added include of gtest.h with portability/GTest.h

Summary: Because it's needed with the way the portability layer works.

Reviewed By: yfeldblum

Differential Revision: D3863954

fbshipit-source-id: 3b682dcc2d2799f17c61fe16a4391fc9f0c2b127

7 years agoTest for folly::SingletonThreadLocal
Phil Willoughby [Wed, 14 Sep 2016 08:53:09 +0000 (01:53 -0700)]
Test for folly::SingletonThreadLocal

Summary: Validates that we create a distinct singleton for each thread and that each such singleton is destroyed at its owning-thread's exit.

Reviewed By: yfeldblum

Differential Revision: D3849146

fbshipit-source-id: af878b32ecfc6c82b866d7a805e1385d74a8a5f5

7 years agoRemove Benchmark.h dependency in SpookyHash tests
Michael Lee [Tue, 13 Sep 2016 23:02:19 +0000 (16:02 -0700)]
Remove Benchmark.h dependency in SpookyHash tests

Summary: It would seem the folly/Benchmark.h dependency was to pull in glog/logging.h. Include what you use.

Reviewed By: yfeldblum

Differential Revision: D3857112

fbshipit-source-id: 8d5bd105e10eee8f5b6e5d377d58ae84d908ed57

7 years agoOptimize toJson() Performance
Milo Yip [Tue, 13 Sep 2016 18:24:35 +0000 (11:24 -0700)]
Optimize toJson() Performance

Summary:
Removing string::reserve() which causes O(n^2) penalty.

Fixes #477
Closes https://github.com/facebook/folly/pull/478

Reviewed By: yfeldblum

Differential Revision: D3850509

Pulled By: Orvid

fbshipit-source-id: ecf44c35b2aedadc5385d23c325cacab1abfd02d

7 years agoFix recordStack feature in FiberManager
Stepan Palamarchuk [Tue, 13 Sep 2016 02:49:22 +0000 (19:49 -0700)]
Fix recordStack feature in FiberManager

Summary:
It appears that a feature of recording exact stack usage on fibers is broken for a long time.
This diff brings it back.

Reviewed By: andriigrynenko

Differential Revision: D3847035

fbshipit-source-id: d9cf532774204b6ac2f40e1b39fd98ea06c08f55

7 years agoFix a bug in ObserverManager destructor
Andrii Grynenko [Tue, 13 Sep 2016 00:53:52 +0000 (17:53 -0700)]
Fix a bug in ObserverManager destructor

Summary: facepaw

Reviewed By: ckwalsh

Differential Revision: D3853363

fbshipit-source-id: f863a3e3ae830256f5cff6c56f23254ff6fdee2a

7 years agoFix TLObserver copy constructor
Andrii Grynenko [Tue, 13 Sep 2016 00:53:09 +0000 (17:53 -0700)]
Fix TLObserver copy constructor

Reviewed By: yfeldblum

Differential Revision: D3853494

fbshipit-source-id: 23f5cadcb55a9307fb2a825fe4c53a03c5978d12

7 years agoDo not mess with NDEBUG in fbstring
Giuseppe Ottaviano [Mon, 12 Sep 2016 21:00:40 +0000 (14:00 -0700)]
Do not mess with NDEBUG in fbstring

Summary: Temporarily overriding `NDEBUG` can have unexpected side-effects depending on the implementation of `<assert.h>`. Better use an explicit macro for `assert()` that we can explicitly disable.

Reviewed By: Gownta

Differential Revision: D3850717

fbshipit-source-id: b1e7fce89ab4120b0224e9c6bf668d983b3d2d31

7 years agoUse the GTest portability headers v2016.09.12.00 v2016.09.12.01
Christopher Dykes [Sat, 10 Sep 2016 00:44:01 +0000 (17:44 -0700)]
Use the GTest portability headers

Summary:
Switch all of the uses of `<gtest/gtest.h>` to `<folly/portability/GTest.h>`.

This is painful but necessary to get the tests to compile nicely under MSVC.

Reviewed By: yfeldblum

Differential Revision: D3837300

fbshipit-source-id: 7ae43a5d5ba94c8c24fa23a485f18546416e7191

7 years agoUse the GMock portability header
Christopher Dykes [Sat, 10 Sep 2016 00:44:00 +0000 (17:44 -0700)]
Use the GMock portability header

Summary:
Switch all of the uses of <gmock/gmock.h> to <folly/portability/GMock.h>.

This is painful but necessary to get the tests to compile nicely under MSVC.

Reviewed By: yfeldblum

Differential Revision: D3837529

fbshipit-source-id: 7221dfea8f2a880919690b5b0601ca91642991ae

7 years agoAdd portability headers for GTest and GMock
Christopher Dykes [Sat, 10 Sep 2016 00:43:59 +0000 (17:43 -0700)]
Add portability headers for GTest and GMock

Summary:
Both the gtest and gmock headers include `<io.h>` on Windows, which conflicts with how the portability headers include it, so a specific include order is required before either of those headers can be included. As that's brittle and messy, create a pair of portability headers for them instead, so that those can be included instead.

This only adds the headers. The switch to using them will be done in a later pair of diffs.

Reviewed By: mzlee

Differential Revision: D3837221

fbshipit-source-id: 82a273485cdd4536f1153d958c171bfe3ec32e0b

7 years agoRefactor basic_fbstring
Eric Niebler [Fri, 9 Sep 2016 23:19:15 +0000 (16:19 -0700)]
Refactor basic_fbstring

Summary: Move fbstring_core and basic_fbstring member functions from in-situ to out-of-class inlines and refactor for readability. Remove superfluous dependence on scope_guard.

Reviewed By: ot, luciang

Differential Revision: D3795250

fbshipit-source-id: f6edca25d4771181faff9e0a4339bbaffd71a370

7 years agoNomenclature in Synchronized - prefer read to shared
Yedidya Feldblum [Fri, 9 Sep 2016 21:44:11 +0000 (14:44 -0700)]
Nomenclature in Synchronized - prefer read to shared

Summary:
[Folly] Nomenclature in `Synchronized` - prefer `read` to `shared`.

`folly::Synchronized` is a higher-level abstraction, so it will use higher-level nomenclature than will lower-level tools like `std::mutex` and `folly::LockTraits`. `shared` describes the lock state, and is used in the C++ libraries. `read` describes the class of operations that calling code is permitted to perform.

Reviewed By: simpkins

Differential Revision: D3840060

fbshipit-source-id: 4b23eaa391cb59d1eca2bfacf72db89d3c7c591e

7 years agoAdd forwarding gather() function to IOBufQueue
Daniel Sommermann [Fri, 9 Sep 2016 20:50:08 +0000 (13:50 -0700)]
Add forwarding gather() function to IOBufQueue

Summary:
I'm working with a parser that requires a certain number of
contiguous bytes to be able to make forward progress. I'm also using
IOBufQueue to receive data from an AsyncReader::ReadCallback with
pre/postallocate. So, I need to call gather() to ensure that the queue's
front IOBuf has the right number of contiguous bytes available.

Reviewed By: djwatson

Differential Revision: D3838079

fbshipit-source-id: 9f1ec5c86895eb1b2b109f9f145ca42d2dbba4c6

7 years agoMake folly::PasswordCollector::getPassword const
Anirudh Ramachandran [Fri, 9 Sep 2016 17:23:15 +0000 (10:23 -0700)]
Make folly::PasswordCollector::getPassword const

Summary: As in title

Reviewed By: siyengar

Differential Revision: D3794648

fbshipit-source-id: f0b7052f34ecce65cf4e21d546d08c7a6b0a8ee3

7 years ago#if FOLLY_HAVE_INT128_T rather than #ifdef
Michael Lee [Fri, 9 Sep 2016 00:02:37 +0000 (17:02 -0700)]
#if FOLLY_HAVE_INT128_T rather than #ifdef

Summary: Switch from #ifdef to #if so the configuration can define the macro to 0

Reviewed By: yfeldblum, Orvid

Differential Revision: D3838748

fbshipit-source-id: e287b07f0fdfdc86c882538e96f2078795b85bfd

7 years agomove AsyncSSLSocket logging level for errors to vlog
Denis Samoylov [Thu, 8 Sep 2016 20:50:13 +0000 (13:50 -0700)]
move AsyncSSLSocket logging level for errors to vlog

Summary: current log entries ("E0906 AsyncSSLSocket.cpp:117] TCP connect failed: AsyncSocketException: connect failed, type = Socket not open, errno = 111 (Connection refused)") are not very helpful to debug due lack of details and can spam logs of application that uses async library without ability to disable logging

Reviewed By: djwatson

Differential Revision: D3825048

fbshipit-source-id: 1c97f14e1ea3f1b276d04bb12483d42372a0d186

7 years agoDynamic expansion of folly MPMC queue
Maged Michael [Thu, 8 Sep 2016 17:43:23 +0000 (10:43 -0700)]
Dynamic expansion of folly MPMC queue

Summary:
This diff allows queues to start with small capacity and expand as needed up to the specified capacity.
The main additions and changes:
- Extra template parameter `Dynamic` that enables dynamic expansion (`default 'false').
- `ClosedArray` type.
- Extra members:
  -- `dstate_`: a packed 64 bit unsigned int that contains a seqlock (which implicitly indicates the number of expansions and the lowest ticket for the current `dslots_/dcapacity_/dstride_` configuration.
 -- `dcapacity_`: current dynamic capacity.
 -- `dslots_`: current dynamic slots array. (in anonymous union with `slots_`)
 -- `dstride_`: current dynamic stride. (in anonymous union with `stride_`)
 -- `closed_` a logarithmic-sized array of ClosedArray to hold information about earlier smaller queue arrays for use by lagging consumers.

Design sketch:
- Reallocate a new larger array on expansion
- Expansion uses a seqlock. The common case critical path includes a seqlock read-only section.
- Lagging consumers and lagging blocking producers use a logarithmic-sized array for info about closed arrays
- Tickets are adjusted by an offset (to accounts for the tickets associated with earlier closed arrays) in order to calculate appropriate index and turn.
- The synching of `pushTicket_` with the ticket offset packed in `dstate_` is tricky. `pushTicket_` is accessed outside `dstate_`'s seqlock.

Reviewed By: djwatson

Differential Revision: D3462592

fbshipit-source-id: d442a7694190cca3c33753409ffac941d7463f83

7 years agoRemove runAfterDrain()
Andrii Grynenko [Thu, 8 Sep 2016 17:29:01 +0000 (10:29 -0700)]
Remove runAfterDrain()

Reviewed By: djwatson

Differential Revision: D3832835

fbshipit-source-id: b5cabc00758fd80b314424e4224458e2d50ddb5c

7 years agoExplicitly include <random> to use std::mt19937 in MathBenchmark.
Zonr Chang [Thu, 8 Sep 2016 13:18:44 +0000 (06:18 -0700)]
Explicitly include <random> to use std::mt19937 in MathBenchmark.

Summary:
This fixes build with Clang.
Closes https://github.com/facebook/folly/pull/470

Differential Revision: D3834865

Pulled By: nbronson

fbshipit-source-id: 02c1ca192c6b6af2cc0a8fdaa0a854510cb0bca4

7 years agoprvalues from get_ref_default()'s default functor
Tom Jackson [Thu, 8 Sep 2016 09:36:58 +0000 (02:36 -0700)]
prvalues from get_ref_default()'s default functor

Summary: This previously allowed `get_ref_default(map, 4, []{ return 6; })`, even though this would form a reference to a temporary, then **use that invalid reference**.

Reviewed By: yfeldblum

Differential Revision: D3802707

fbshipit-source-id: 384d965f69c9d7b6bd3f011c8eff7fe55be7023a

7 years agoMove the alignment attribute in TokenBucket to a place where MSVC supports it
Christopher Dykes [Thu, 8 Sep 2016 01:44:32 +0000 (18:44 -0700)]
Move the alignment attribute in TokenBucket to a place where MSVC supports it

Summary: MSVC doesn't support the aligment attribute being after the field name.

Reviewed By: yfeldblum

Differential Revision: D3832314

fbshipit-source-id: 6a56db245e01922ede6b9b93eb1c8aecc835e2bf

7 years agointeger division with controlled rounding in Math.h
Nathan Bronson [Wed, 7 Sep 2016 22:50:38 +0000 (15:50 -0700)]
integer division with controlled rounding in Math.h

Summary:
C++'s integer division performs truncation, but it is fairly
common that people actually want to round up.  There are actually
four rounding modes that make some sense: toward negative infinity
(floor), toward positive infinity (ceil), toward zero (truncation),
and away from zero (?).  It is pretty common that code that wants ceil
actually writes (a + b - 1) / b, which doesn't work at all for negative
values (and has a potential overflow issue).  This diff adds 4 templated
functions for performing integer division: divFloor, divCeil, divTrunc,
and divRoundAway.  They are not subject to unnecessary internal underflow
or overflow, and they work correctly across their entire input domain.

I did a bit of benchmarking across x86_64, arm64, and 32-bit ARM.
Only 32-bit ARM was different.  That's not surprising since it doesn't
have an integer division instruction, and the function that implements
integer division doesn't produce the remainder for free.  On 32-bit ARM
a branchful version that doesn't need the modulus is used.

Reviewed By: yfeldblum

Differential Revision: D3806743

fbshipit-source-id: c14c56717e96f135321920e64acbfe9dcb1fe039

7 years agoExpand DSched interface for managing auxiliary functions
Maged Michael [Wed, 7 Sep 2016 15:31:10 +0000 (08:31 -0700)]
Expand DSched interface for managing auxiliary functions

Summary:
Changed DSched interface for managing auxiliary functions to allow separate auxiliary functions for single actions (applicable to the next shared access by a specific thread) and repeating actions (applicable to all subsequent shared accesses).

[Note: I have a dependent diff that depends on both this diff and the diff for dynamic MPMCQueue (/D3462592). I don't think I can submit a diff that depends on multiple diffs that haven't landed yet. So, I'll wait until this one lands.]

Reviewed By: djwatson

Differential Revision: D3792669

fbshipit-source-id: 52654fffda2dc905b19ff91f4459f15da11f7735

7 years agoRework the de-allocation guard on the munmap implementation
Christopher Dykes [Tue, 6 Sep 2016 23:22:33 +0000 (16:22 -0700)]
Rework the de-allocation guard on the munmap implementation

Summary:
The previous version assumed that `RegionSize` would always be the full size of the allocation done by `VirtualAlloc`. However, `RegionSize` actually only includes the following pages that have the same attributes, so, if you change the access permissions via `mprotect`, the `RegionSize` would exclude that region, which is not what was intended.
This instead stores the length and a dummy magic value after the end of the requested allocation.

Reviewed By: yfeldblum

Differential Revision: D3812949

fbshipit-source-id: 53bbbcc371accbed08adaffa82fc082ec44f316f

7 years agoEliminate a string allocation in folly::SocketAddr and bug in char[] conversion
Chip Turner [Tue, 6 Sep 2016 18:27:41 +0000 (11:27 -0700)]
Eliminate a string allocation in folly::SocketAddr and bug in char[] conversion

Summary:
We were doing an unnecessary and wasteful string conversion in the
SocketAddr codepath.  This eliminates it.  I also noticed we had an off-by-one
in the "convert string to char buffer" code path, so I added a test to confirm
the bug and fixed it.

Reviewed By: yfeldblum, meyering

Differential Revision: D3817959

fbshipit-source-id: 51fed8331ab23c0888a3d1f9e0cc9cea5ea8329b

7 years agoImplement more of the sockets API
Christopher Dykes [Tue, 6 Sep 2016 17:07:44 +0000 (10:07 -0700)]
Implement more of the sockets API

Summary:
This gets the socket portability layer functional enough that most of the socket tests are passing, the few that are left are depending on specific error messages.
This also switches all of the additional overloads for some of the socket functions to forward to a single implementation, to make adjustments to these functions easier in the future. (most of the functions already needed adjustments and would have had to change regardless)

Reviewed By: yfeldblum

Differential Revision: D3814011

fbshipit-source-id: c6793ee74a91d9e164775a2d52c96f54b28b9f24

7 years agodelete const rvalue reference ctor of folly::Function v2016.09.05.00
Philip Pronin [Fri, 2 Sep 2016 16:51:19 +0000 (09:51 -0700)]
delete const rvalue reference ctor of folly::Function

Summary:
This code compiles and is causing stack overflow at runtime:

```
using F = folly::Function<void()>;
void foo(F);

F bar;
auto baz = [bar = std::move(bar)] {
  foo(std::move(bar));
};
baz();
```

The bug there is that `baz` is missing `mutable` keyword, so when
constructing argument for `foo`, `F(const F&&)` is called, which is selecting
`template <typename Fun> F(Fun&&)` (where `Fun = F const`) and we end up in
an infinite `F<Fun>(Fun&&) <-> F<Fun>(Fun&&, SmallTag|HeapTag)` cycle.

This diff transforms this easy-to-make-bug into compile-time error.

Reviewed By: yfeldblum

Differential Revision: D3810269

fbshipit-source-id: f80a18ab02bd0715d692cf67c3c8943f557c2982

7 years agozstd is no longer in beta -- s/ZSTD_BETA/ZSTD/g
Chip Turner [Thu, 1 Sep 2016 23:40:08 +0000 (16:40 -0700)]
zstd is no longer in beta -- s/ZSTD_BETA/ZSTD/g

Summary:
itshappening

Need to override unit test failures after repeated landing failures unrelated
to the change.

Reviewed By: yfeldblum

Differential Revision: D3803301

fbshipit-source-id: b6581e3d2ff6baba57eb0f61b890a61107118bf7

7 years agoFix folly conversions for Clang with GCC5's libstdc++
Phil Willoughby [Thu, 1 Sep 2016 20:09:24 +0000 (13:09 -0700)]
Fix folly conversions for Clang with GCC5's libstdc++

Summary: Now builds correctly

Reviewed By: meyering

Differential Revision: D3763879

fbshipit-source-id: e272fbcc28a74fcf36b63a0135534c5063a7c4ee

7 years agoAdd ScopeGuard.h include in places where it is needed.
Eric Niebler [Thu, 1 Sep 2016 18:06:06 +0000 (11:06 -0700)]
Add ScopeGuard.h include in places where it is needed.

Summary: Fix code that is transitively including ScopeGuard.h via FBString.h.

Reviewed By: yfeldblum

Differential Revision: D3801328

fbshipit-source-id: 7e1dc37cd6dd3aa691dd1baf31385d3a8c51eed0

7 years agoProperly report observable returning nullptr
Andrii Grynenko [Wed, 31 Aug 2016 21:12:57 +0000 (14:12 -0700)]
Properly report observable returning nullptr

Summary: Make sure exception is propagated to caller (especially when Observer is just created).

Reviewed By: yfeldblum

Differential Revision: D3798991

fbshipit-source-id: cee8452cfd40dcfbaf0e2ae2c2ee628af0362c6e

7 years agoUpdate FBVector.md
Colin Ni [Wed, 31 Aug 2016 19:59:54 +0000 (12:59 -0700)]
Update FBVector.md

Summary:
Minor changes. Simplified the memory-handling explanation; also fixed some grammar issues and re-worded some confusing paragraphs. (I suggest reading the edited and unedited versions separately.)
Closes https://github.com/facebook/folly/pull/459

Reviewed By: simpkins

Differential Revision: D3779296

Pulled By: Orvid

fbshipit-source-id: 24b086cbd0b67e4c592731aeec6a7ffc14ff0319

7 years agoupdate TimeseriesHistogram::rate to return a template type
Adam Simpkins [Wed, 31 Aug 2016 19:21:13 +0000 (12:21 -0700)]
update TimeseriesHistogram::rate to return a template type

Summary:
Update TimeseriesHistogram::rate(int level) to have a configurable return type,
similar to the rate(TimeType start, TimeType end) function, as well as the
avg() functions.  I believe it was simply an oversight initially that this
version of rate did not have a configurable return type.

Since rate() and avg() are template methods, their full definitions should
really be available in TimeseriesHistogram.h rather than
TimeseriesHistogram-defs.h.  This also fixes that problem.  Most of the logic
in these functions isn't actually dependent on the return type, so that was
split out into separate non-template helper functions that are still in
TimeseriesHistogram-defs.h

Reviewed By: yfeldblum

Differential Revision: D3776017

fbshipit-source-id: 7deebf5b9ea1be143b5d772a15246706cb0cae80

7 years agoConsolidate namespace for using GFlags.
Zonr Chang [Wed, 31 Aug 2016 18:37:58 +0000 (11:37 -0700)]
Consolidate namespace for using GFlags.

Summary:
Default namespace for GFlags has been changed from "google" to "gflags".

See: https://github.com/gflags/gflags/commit/d9d06b9.
Closes https://github.com/facebook/folly/pull/466

Reviewed By: yfeldblum

Differential Revision: D3787144

Pulled By: Orvid

fbshipit-source-id: db7bcaf4e2bcd46b022a48b17b50ef155570f296

7 years agoReverted commit D3755446
Philip Pronin [Wed, 31 Aug 2016 12:10:43 +0000 (05:10 -0700)]
Reverted commit D3755446

Summary:
Move ThreadLocal object destruction to occur under the lock to avoid races.
This causes a few cascading changes - the Tag lock needs to be a recursive_mutex so
constructing a new object while destroying another st. Also, forking requires
a new mutex to avoid deadlocking on accessing a recursive_mutex across a fork()

Reviewed By: andriigrynenko

Differential Revision: D3755446

fbshipit-source-id: f1f1f92175eb39e77aaa2add6915e5c9bb68d0fb

7 years agoFix folly::SocketAddress::reset
Naizhi Li [Wed, 31 Aug 2016 05:56:57 +0000 (22:56 -0700)]
Fix folly::SocketAddress::reset

Summary:
Currently reset does not actually reset it. This change
make sure it does the job.

Reviewed By: yfeldblum

Differential Revision: D3788869

fbshipit-source-id: 771a641e31bb3cf307e5bebb979b81a3d3feea55

7 years agoExpose SSL key materials to debug SSL
Gabriel Grise [Wed, 31 Aug 2016 02:55:12 +0000 (19:55 -0700)]
Expose SSL key materials to debug SSL

Summary: Adding two methods to export the parameters used to generate the key material   (key_block). These parameter can be used to decrypt a TLS session from a packet capture.

Reviewed By: anirudhvr

Differential Revision: D3687099

fbshipit-source-id: 04137f34dd32c387a1b7aec04b3ed6066f123a8e

7 years agoUse a normal variable if thread local is not available.
Michael Lee [Wed, 31 Aug 2016 02:29:59 +0000 (19:29 -0700)]
Use a normal variable if thread local is not available.

Summary: This should not affect correctness, but it means SharedMutex would need to share the variable across threads.

Reviewed By: yfeldblum

Differential Revision: D3621227

fbshipit-source-id: dc1baa7c47cd2d459cd0ef89451bcd7fd4d553aa

7 years agoFix joining threads twice when exiting EventBaseTest.RunInThread normally
Zonr Chang [Tue, 30 Aug 2016 22:46:50 +0000 (15:46 -0700)]
Fix joining threads twice when exiting EventBaseTest.RunInThread normally

Summary:
10e9cd3 set up SCOPE_EXIT to join threads (wait for them to exit) on
exceptions. However, it is also called on normal exit. Remove the
original code at the end for joining threads.

This fixes EventBaseTest regression.
Closes https://github.com/facebook/folly/pull/468

Reviewed By: yfeldblum

Differential Revision: D3792977

Pulled By: Orvid

fbshipit-source-id: e4b12202ae3e35fd942ad2ca1d8d405cf1a28f68

7 years agoDefine "__STDC_FORMAT_MACROS" for using PRI{u,x}64 in C++.
Zonr Chang [Tue, 30 Aug 2016 20:41:51 +0000 (13:41 -0700)]
Define "__STDC_FORMAT_MACROS" for using PRI{u,x}64 in C++.

Summary: Closes https://github.com/facebook/folly/pull/467

Reviewed By: yfeldblum

Differential Revision: D3787151

Pulled By: Orvid

fbshipit-source-id: e255c9daea9917082f684e52e27984770c9f08b1

7 years agoMake type conversion from Expected<> to bool explicitly.
Zonr Chang [Tue, 30 Aug 2016 20:37:29 +0000 (13:37 -0700)]
Make type conversion from Expected<> to bool explicitly.

Summary: Closes https://github.com/facebook/folly/pull/465

Reviewed By: yfeldblum

Differential Revision: D3787146

Pulled By: Orvid

fbshipit-source-id: 17433a256338bd107eec41e69af3eef58de3339b

7 years agoAdded a better check for openssl
Bruno Goncalves [Tue, 30 Aug 2016 20:37:13 +0000 (13:37 -0700)]
Added a better check for openssl

Summary:
For some systems like my Fedora 23 is missing -lcrypto library to be together with -lssl

The following error ocurr running 'make check':
avoid undefined reference to symbol 'EVP_DigestInit_ex
Closes https://github.com/facebook/folly/pull/428

Reviewed By: yfeldblum

Differential Revision: D3787160

Pulled By: Orvid

fbshipit-source-id: 8ff69d00c9c752d0a005d2a5e8d68e65347cc43b

7 years agoModified ref-qualifiers return type for Optional::value() and Optional::operator*
Anand Mazumdar [Tue, 30 Aug 2016 06:21:40 +0000 (23:21 -0700)]
Modified ref-qualifiers return type for Optional::value() and Optional::operator*

Summary:
Optional::value() returns a temporary object when the object is an rvalue. This is different in semantics then what boost::optional/std::optional do.

The decision to make the copy or not should be up to the user and not the library. Consider an example:

```
void F(Optional<T> &&opt) {
  T&& t = std::move(opt).get();
  // I know `opt` is alive in this scope, I should be able to keep a rvalue ref to the internals
}
// if we were to return a `T`, that would actually return a new temporary.
```

```
void G(T&& t);
G(std::move(opt).get()); // This could have surprising behavior too !
```

This change modified the return type to be `T&&` and also introduces an extra overload for `const T&&`. Also, deleted two test-cases that assume the lifetime to be extended. This is a breaking change but this brings folly::Optional on parity with other siblings.
Closes https://github.com/facebook/folly/pull/353

Reviewed By: ddrcoder

Differential Revision: D3714962

Pulled By: yfeldblum

fbshipit-source-id: 1794d51590062db4ad02fc8688cb28a06712c076

7 years agoFix ThreadCachedInt race condition
Dan Schatzberg [Mon, 29 Aug 2016 23:42:44 +0000 (16:42 -0700)]
Fix ThreadCachedInt race condition

Summary:
Move ThreadLocal object destruction to occur under the lock to avoid races.
This causes a few cascading changes - the Tag lock needs to be a recursive_mutex so
constructing a new object while destroying another st. Also, forking requires
a new mutex to avoid deadlocking on accessing a recursive_mutex across a fork()

Reviewed By: andriigrynenko

Differential Revision: D3755446

fbshipit-source-id: bb4c4f29bab98d763490df29b460066f124303e0

7 years agoResolve fibers-futures dependency
Andrii Grynenko [Mon, 29 Aug 2016 23:02:38 +0000 (16:02 -0700)]
Resolve fibers-futures dependency

Reviewed By: mzlee

Differential Revision: D3780312

fbshipit-source-id: c42c8f0a06b82520ee1b46f105a2a85ad524c442

7 years agogen::dereference should perfectly-forward unwrapped values
Yedidya Feldblum [Mon, 29 Aug 2016 21:57:05 +0000 (14:57 -0700)]
gen::dereference should perfectly-forward unwrapped values

Summary:
[Folly] `gen::dereference` should perfectly-forward unwrapped values.

The problem comes in when the wrapped value is not actually a pointer, but is actually an rvalue-ref to some other kind of wrapper type with `Inner&& operator*() &&`. In such cases, the compiler emits a type mismatch error that it cannot cast `Inner` to `Inner&&`, with the errors originating in `Dereference::foreach` and `Dereference::apply`.

Fixes a couple other missing-forwarding and extra-forwarding bugs.

Reviewed By: ddrcoder

Differential Revision: D3776617

fbshipit-source-id: 6926fc18244a572846b22d428bd407d37fb20aa1

7 years agoUse Synchronized in RequestContext
Yedidya Feldblum [Mon, 29 Aug 2016 21:01:15 +0000 (14:01 -0700)]
Use Synchronized in RequestContext

Summary:
[Folly] Use `Synchronized` in `RequestContext`.

Because we can. And it makes the code a tad simpler and also enforces access correctness a tad.

Also use `folly::make_unique` in `RequestContextTest` to keep balance between the explicit `new` and `delete` ops.

Reviewed By: markisaa

Differential Revision: D3781115

fbshipit-source-id: 63b41ddd8009e9546e3be5f89bdd23a4d791105c

7 years agoAdd default constructor to folly::IOBuf::Iterator.
Nick Terrell [Mon, 29 Aug 2016 16:50:36 +0000 (09:50 -0700)]
Add default constructor to folly::IOBuf::Iterator.

Summary:
Iterators must be default constructible.
folly::IOBuf can now be used as a range in ranges-v3.

Reviewed By: yfeldblum

Differential Revision: D3782536

fbshipit-source-id: 854813b4e3336aba50048649e6ae7b375d49e382

7 years agoFix up TokenBucket.h in Makefile headers
Jon Maltiel Swenson [Mon, 29 Aug 2016 16:30:52 +0000 (09:30 -0700)]
Fix up TokenBucket.h in Makefile headers

Summary: Title.

Reviewed By: andreazevedo

Differential Revision: D3785212

fbshipit-source-id: c551e0367196cbc68cf39a5d40f2b324883fcdf4

7 years agoGeneralized and polished folly::TokenBucket v2016.08.29.00
Philipp Unterbrunner [Mon, 29 Aug 2016 13:27:23 +0000 (06:27 -0700)]
Generalized and polished folly::TokenBucket

Summary: Added support for user-defined clock classes, improved comments, and removed part of the std::atomics use that had no effect on thread-safety.

Reviewed By: yfeldblum

Differential Revision: D3708378

fbshipit-source-id: 1a933c3707c12311584a3b33afd773ee91577167

7 years agoAdded fiber-compatible semaphore.
Lee Howes [Fri, 26 Aug 2016 22:58:45 +0000 (15:58 -0700)]
Added fiber-compatible semaphore.

Summary: Adds a standard semaphore type with signal and wait methods that is safe to use in both multi-threaded contexts and from fibers.

Reviewed By: andriigrynenko

Differential Revision: D3778943

fbshipit-source-id: 6997f1fb870739e07f982399dbebfd8b3e45daa2

7 years agoUse folly::Random and ensure M_PI is defined
Christopher Dykes [Fri, 26 Aug 2016 20:11:03 +0000 (13:11 -0700)]
Use folly::Random and ensure M_PI is defined

Summary: Because MSVC doesn't have `random()` and `M_PI` is guarded by a pre-processor macro.

Reviewed By: yfeldblum

Differential Revision: D3767159

fbshipit-source-id: fcb1c41cd75925455c76efad38423cd52bd98aeb

7 years agocollectOne
Yunqiao Zhang [Fri, 26 Aug 2016 19:53:24 +0000 (12:53 -0700)]
collectOne

Summary:
The resultant future of collectOne will be fulfilled when the first one of
the future in the list completes without exception. If all input futures throws
exception, the resultant future will get the last exception that was thrown.

Reviewed By: andriigrynenko

Differential Revision: D3764760

fbshipit-source-id: 76484254e35182eddc8266865853d65c28170f82

7 years agoAdd CachelinePadded<T> to folly.
David Goldblatt [Fri, 26 Aug 2016 19:40:58 +0000 (12:40 -0700)]
Add CachelinePadded<T> to folly.

Summary:
This class allows easy insertion of padding bytes after an object to ensure
that two cacheline-padded elements of an array don't engage in false sharing.

Reviewed By: yfeldblum

Differential Revision: D3485144

fbshipit-source-id: a3ece1e34566b20f94ff9f66532b2386ab19a9b1

7 years agoRemove now-useless FOLLY_MALLOC_H_
Nicholas Ormrod [Fri, 26 Aug 2016 18:41:38 +0000 (11:41 -0700)]
Remove now-useless FOLLY_MALLOC_H_

Summary:
Malloc.h is intentionally included multiple times, once from folly and once from libstdc++. The current ###pragma once## implicitly allows this to happen. FBString.h has an undef for Malloc.h's include guard, which originally accomplished this goal.

The undefing code is presently moot, since its functionality has been replaced by ###pragma once##. Remove it.

I noticed this when ott was copying FBString over to libstdc++ in D3757853.
The diff that switched the include guards to pragmas was a codemod, and was not specific to fbstring. D3054492

Reviewed By: ot

Differential Revision: D3758119

fbshipit-source-id: e796d039a031d5f842ed39bf55a6b1aeb2686bc4