Skip to content

Commit 98297a6

Browse files
authored
Merge pull request #3730 from TheBlueMatt/2025-04-features-less-alloc
Store `Feature` flags in line rather than on the heap by default (without increasing their size)
2 parents b543afe + 3702472 commit 98297a6

File tree

7 files changed

+420
-43
lines changed

7 files changed

+420
-43
lines changed

fuzz/src/bin/feature_flags_target.rs

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
// This file is auto-generated by gen_target.sh based on target_template.txt
11+
// To modify it, modify target_template.txt and run gen_target.sh instead.
12+
13+
#![cfg_attr(feature = "libfuzzer_fuzz", no_main)]
14+
#![cfg_attr(rustfmt, rustfmt_skip)]
15+
16+
#[cfg(not(fuzzing))]
17+
compile_error!("Fuzz targets need cfg=fuzzing");
18+
19+
#[cfg(not(hashes_fuzz))]
20+
compile_error!("Fuzz targets need cfg=hashes_fuzz");
21+
22+
#[cfg(not(secp256k1_fuzz))]
23+
compile_error!("Fuzz targets need cfg=secp256k1_fuzz");
24+
25+
extern crate lightning_fuzz;
26+
use lightning_fuzz::feature_flags::*;
27+
28+
#[cfg(feature = "afl")]
29+
#[macro_use] extern crate afl;
30+
#[cfg(feature = "afl")]
31+
fn main() {
32+
fuzz!(|data| {
33+
feature_flags_run(data.as_ptr(), data.len());
34+
});
35+
}
36+
37+
#[cfg(feature = "honggfuzz")]
38+
#[macro_use] extern crate honggfuzz;
39+
#[cfg(feature = "honggfuzz")]
40+
fn main() {
41+
loop {
42+
fuzz!(|data| {
43+
feature_flags_run(data.as_ptr(), data.len());
44+
});
45+
}
46+
}
47+
48+
#[cfg(feature = "libfuzzer_fuzz")]
49+
#[macro_use] extern crate libfuzzer_sys;
50+
#[cfg(feature = "libfuzzer_fuzz")]
51+
fuzz_target!(|data: &[u8]| {
52+
feature_flags_run(data.as_ptr(), data.len());
53+
});
54+
55+
#[cfg(feature = "stdin_fuzz")]
56+
fn main() {
57+
use std::io::Read;
58+
59+
let mut data = Vec::with_capacity(8192);
60+
std::io::stdin().read_to_end(&mut data).unwrap();
61+
feature_flags_run(data.as_ptr(), data.len());
62+
}
63+
64+
#[test]
65+
fn run_test_cases() {
66+
use std::fs;
67+
use std::io::Read;
68+
use lightning_fuzz::utils::test_logger::StringBuffer;
69+
70+
use std::sync::{atomic, Arc};
71+
{
72+
let data: Vec<u8> = vec![0];
73+
feature_flags_run(data.as_ptr(), data.len());
74+
}
75+
let mut threads = Vec::new();
76+
let threads_running = Arc::new(atomic::AtomicUsize::new(0));
77+
if let Ok(tests) = fs::read_dir("test_cases/feature_flags") {
78+
for test in tests {
79+
let mut data: Vec<u8> = Vec::new();
80+
let path = test.unwrap().path();
81+
fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
82+
threads_running.fetch_add(1, atomic::Ordering::AcqRel);
83+
84+
let thread_count_ref = Arc::clone(&threads_running);
85+
let main_thread_ref = std::thread::current();
86+
threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
87+
std::thread::spawn(move || {
88+
let string_logger = StringBuffer::new();
89+
90+
let panic_logger = string_logger.clone();
91+
let res = if ::std::panic::catch_unwind(move || {
92+
feature_flags_test(&data, panic_logger);
93+
}).is_err() {
94+
Some(string_logger.into_string())
95+
} else { None };
96+
thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
97+
main_thread_ref.unpark();
98+
res
99+
})
100+
));
101+
while threads_running.load(atomic::Ordering::Acquire) > 32 {
102+
std::thread::park();
103+
}
104+
}
105+
}
106+
let mut failed_outputs = Vec::new();
107+
for (test, thread) in threads.drain(..) {
108+
if let Some(output) = thread.join().unwrap() {
109+
println!("\nOutput of {}:\n{}\n", test, output);
110+
failed_outputs.push(test);
111+
}
112+
}
113+
if !failed_outputs.is_empty() {
114+
println!("Test cases which failed: ");
115+
for case in failed_outputs {
116+
println!("{}", case);
117+
}
118+
panic!();
119+
}
120+
}

fuzz/src/bin/gen_target.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ GEN_TEST indexedmap
2525
GEN_TEST onion_hop_data
2626
GEN_TEST base32
2727
GEN_TEST fromstr_to_netaddress
28+
GEN_TEST feature_flags
2829

2930
GEN_TEST msg_accept_channel msg_targets::
3031
GEN_TEST msg_announcement_signatures msg_targets::

fuzz/src/feature_flags.rs

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// This file is Copyright its original authors, visible in version control
2+
// history.
3+
//
4+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5+
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7+
// You may not use this file except in accordance with one or both of these
8+
// licenses.
9+
10+
use lightning::types::features::FeatureFlags;
11+
12+
use crate::utils::test_logger;
13+
14+
use std::ops::{Deref, DerefMut};
15+
16+
/// Check various methods on [`FeatureFlags`] given `v` which should be equal to `feat` and an
17+
/// `old_v` which should be equal to `old_feat`.
18+
fn check_eq(v: &Vec<u8>, feat: &FeatureFlags, old_v: &mut Vec<u8>, old_feat: &mut FeatureFlags) {
19+
assert_eq!(v.len(), feat.len());
20+
assert_eq!(v.deref(), feat.deref());
21+
assert_eq!(old_v.deref_mut(), old_feat.deref_mut());
22+
23+
let mut feat_clone = feat.clone();
24+
assert!(feat_clone == *feat);
25+
26+
// Test iteration over the `FeatureFlags` with the base iterator
27+
let mut feat_iter = feat.iter();
28+
let mut vec_iter = v.iter();
29+
assert_eq!(feat_iter.len(), vec_iter.len());
30+
while let Some(feat) = feat_iter.next() {
31+
let v = vec_iter.next().unwrap();
32+
assert_eq!(*feat, *v);
33+
}
34+
assert!(vec_iter.next().is_none());
35+
36+
// Do the same test of iteration over the `FeatureFlags` with the mutable iterator
37+
let mut feat_iter = feat_clone.iter_mut();
38+
let mut vec_iter = v.iter();
39+
assert_eq!(feat_iter.len(), vec_iter.len());
40+
while let Some(feat) = feat_iter.next() {
41+
let v = vec_iter.next().unwrap();
42+
assert_eq!(*feat, *v);
43+
}
44+
assert!(vec_iter.next().is_none());
45+
46+
assert_eq!(v < old_v, feat < old_feat);
47+
assert_eq!(v.partial_cmp(old_v), feat.partial_cmp(old_feat));
48+
}
49+
50+
#[inline]
51+
pub fn do_test(data: &[u8]) {
52+
if data.len() % 3 != 0 {
53+
return;
54+
}
55+
let mut vec = Vec::new();
56+
let mut features = FeatureFlags::empty();
57+
58+
// For each 3-tuple in the input, interpret the first byte as a "command", the second byte as
59+
// an index within `vec`/`features` to mutate, and the third byte as a value.
60+
for step in data.windows(3) {
61+
let mut old_vec = vec.clone();
62+
let mut old_features = features.clone();
63+
match step[0] {
64+
0 => {
65+
vec.resize(step[1] as usize, step[2]);
66+
features.resize(step[1] as usize, step[2]);
67+
},
68+
1 => {
69+
if vec.len() > step[1] as usize {
70+
vec[step[1] as usize] = step[2];
71+
features[step[1] as usize] = step[2];
72+
}
73+
},
74+
2 => {
75+
if vec.len() > step[1] as usize {
76+
*vec.iter_mut().skip(step[1] as usize).next().unwrap() = step[2];
77+
*features.iter_mut().skip(step[1] as usize).next().unwrap() = step[2];
78+
}
79+
},
80+
_ => {},
81+
}
82+
// After each mutation, check that `vec` and `features` remain the same, and pass the
83+
// previous state for testing comparisons.
84+
check_eq(&vec, &features, &mut old_vec, &mut old_features);
85+
}
86+
87+
check_eq(&vec, &features, &mut vec.clone(), &mut features.clone());
88+
}
89+
90+
pub fn feature_flags_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
91+
do_test(data);
92+
}
93+
94+
#[no_mangle]
95+
pub extern "C" fn feature_flags_run(data: *const u8, datalen: usize) {
96+
do_test(unsafe { std::slice::from_raw_parts(data, datalen) });
97+
}

fuzz/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ pub mod bech32_parse;
2727
pub mod bolt11_deser;
2828
pub mod chanmon_consistency;
2929
pub mod chanmon_deser;
30+
pub mod feature_flags;
3031
pub mod fromstr_to_netaddress;
3132
pub mod full_stack;
3233
pub mod indexedmap;

fuzz/targets.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ void indexedmap_run(const unsigned char* data, size_t data_len);
1818
void onion_hop_data_run(const unsigned char* data, size_t data_len);
1919
void base32_run(const unsigned char* data, size_t data_len);
2020
void fromstr_to_netaddress_run(const unsigned char* data, size_t data_len);
21+
void feature_flags_run(const unsigned char* data, size_t data_len);
2122
void msg_accept_channel_run(const unsigned char* data, size_t data_len);
2223
void msg_announcement_signatures_run(const unsigned char* data, size_t data_len);
2324
void msg_channel_reestablish_run(const unsigned char* data, size_t data_len);

0 commit comments

Comments
 (0)