Skip to content

Commit f004258

Browse files
leogrpoiana
authored andcommitted
fix(userspace/engine): replace non-thread-safe random() with thread-local RNG
random() uses internal static state that is not thread-safe. Since should_drop_evt() can be called concurrently from per-source event processing threads, replace it with a thread_local std::mt19937 seeded by std::random_device. Remove the now-unused srandom() seed and Windows compat defines. Signed-off-by: Leonardo Grasso <me@leonardograsso.com>
1 parent 6a00de2 commit f004258

1 file changed

Lines changed: 5 additions & 10 deletions

File tree

userspace/engine/falco_engine.cpp

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,12 @@ See the License for the specific language governing permissions and
1515
limitations under the License.
1616
*/
1717

18-
#include <cstdlib>
1918
#ifndef _WIN32
2019
#include <unistd.h>
2120
#else
22-
#include <stdlib.h>
2321
#include <io.h>
24-
#define srandom srand
25-
#define random rand
2622
#endif
23+
#include <random>
2724
#include <string>
2825
#include <fstream>
2926
#include <functional>
@@ -52,7 +49,7 @@ const std::string falco_engine::s_default_ruleset = "falco-default-ruleset";
5249

5350
using namespace falco;
5451

55-
falco_engine::falco_engine(bool seed_rng):
52+
falco_engine::falco_engine(bool /* seed_rng */):
5653
m_syscall_source(NULL),
5754
m_syscall_source_idx(SIZE_MAX),
5855
m_rule_reader(std::make_shared<rule_loader::reader>()),
@@ -62,10 +59,6 @@ falco_engine::falco_engine(bool seed_rng):
6259
m_min_priority(falco_common::PRIORITY_DEBUG),
6360
m_sampling_ratio(1),
6461
m_sampling_multiplier(0) {
65-
if(seed_rng) {
66-
srandom((unsigned)getpid());
67-
}
68-
6962
m_default_ruleset_id = find_ruleset_id(s_default_ruleset);
7063

7164
fill_engine_state_funcs(m_engine_state);
@@ -1007,6 +1000,8 @@ inline bool falco_engine::should_drop_evt() const {
10071000
return false;
10081001
}
10091002

1010-
double coin = (random() * (1.0 / RAND_MAX));
1003+
thread_local std::mt19937 rng(std::random_device{}());
1004+
std::uniform_real_distribution<double> dist(0.0, 1.0);
1005+
double coin = dist(rng);
10111006
return (coin >= (1.0 / (m_sampling_multiplier * m_sampling_ratio)));
10121007
}

0 commit comments

Comments
 (0)