1
0

fuzzing.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #![cfg(not(miri))]
  2. use dioxus::prelude::*;
  3. use dioxus_core::{AttributeValue, DynamicNode, NoOpMutations, VComponent, VNode, *};
  4. use std::{
  5. cfg, collections::HashSet, default::Default, sync::atomic::AtomicUsize, sync::atomic::Ordering,
  6. };
  7. fn random_ns() -> Option<&'static str> {
  8. let namespace = rand::random::<u8>() % 2;
  9. match namespace {
  10. 0 => None,
  11. 1 => Some(Box::leak(
  12. format!("ns{}", rand::random::<usize>()).into_boxed_str(),
  13. )),
  14. _ => unreachable!(),
  15. }
  16. }
  17. fn create_random_attribute(attr_idx: &mut usize) -> TemplateAttribute {
  18. match rand::random::<u8>() % 2 {
  19. 0 => TemplateAttribute::Static {
  20. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  21. value: Box::leak(format!("value{}", rand::random::<usize>()).into_boxed_str()),
  22. namespace: random_ns(),
  23. },
  24. 1 => TemplateAttribute::Dynamic {
  25. id: {
  26. let old_idx = *attr_idx;
  27. *attr_idx += 1;
  28. old_idx
  29. },
  30. },
  31. _ => unreachable!(),
  32. }
  33. }
  34. fn create_random_template_node(
  35. dynamic_node_types: &mut Vec<DynamicNodeType>,
  36. template_idx: &mut usize,
  37. attr_idx: &mut usize,
  38. depth: usize,
  39. ) -> TemplateNode {
  40. match rand::random::<u8>() % 4 {
  41. 0 => {
  42. let attrs = {
  43. let attrs: Vec<_> = (0..(rand::random::<usize>() % 10))
  44. .map(|_| create_random_attribute(attr_idx))
  45. .collect();
  46. Box::leak(attrs.into_boxed_slice())
  47. };
  48. TemplateNode::Element {
  49. tag: Box::leak(format!("tag{}", rand::random::<usize>()).into_boxed_str()),
  50. namespace: random_ns(),
  51. attrs,
  52. children: {
  53. if depth > 4 {
  54. &[]
  55. } else {
  56. let children: Vec<_> = (0..(rand::random::<usize>() % 3))
  57. .map(|_| {
  58. create_random_template_node(
  59. dynamic_node_types,
  60. template_idx,
  61. attr_idx,
  62. depth + 1,
  63. )
  64. })
  65. .collect();
  66. Box::leak(children.into_boxed_slice())
  67. }
  68. },
  69. }
  70. }
  71. 1 => TemplateNode::Text {
  72. text: Box::leak(format!("{}", rand::random::<usize>()).into_boxed_str()),
  73. },
  74. 2 => TemplateNode::DynamicText {
  75. id: {
  76. let old_idx = *template_idx;
  77. *template_idx += 1;
  78. dynamic_node_types.push(DynamicNodeType::Text);
  79. old_idx
  80. },
  81. },
  82. 3 => TemplateNode::Dynamic {
  83. id: {
  84. let old_idx = *template_idx;
  85. *template_idx += 1;
  86. dynamic_node_types.push(DynamicNodeType::Other);
  87. old_idx
  88. },
  89. },
  90. _ => unreachable!(),
  91. }
  92. }
  93. fn generate_paths(
  94. node: &TemplateNode,
  95. current_path: &[u8],
  96. node_paths: &mut Vec<Vec<u8>>,
  97. attr_paths: &mut Vec<Vec<u8>>,
  98. ) {
  99. match node {
  100. TemplateNode::Element { children, attrs, .. } => {
  101. for attr in *attrs {
  102. match attr {
  103. TemplateAttribute::Static { .. } => {}
  104. TemplateAttribute::Dynamic { .. } => {
  105. attr_paths.push(current_path.to_vec());
  106. }
  107. }
  108. }
  109. for (i, child) in children.iter().enumerate() {
  110. let mut current_path = current_path.to_vec();
  111. current_path.push(i as u8);
  112. generate_paths(child, &current_path, node_paths, attr_paths);
  113. }
  114. }
  115. TemplateNode::Text { .. } => {}
  116. TemplateNode::DynamicText { .. } => {
  117. node_paths.push(current_path.to_vec());
  118. }
  119. TemplateNode::Dynamic { .. } => {
  120. node_paths.push(current_path.to_vec());
  121. }
  122. }
  123. }
  124. enum DynamicNodeType {
  125. Text,
  126. Other,
  127. }
  128. fn create_random_template(name: &'static str) -> (Template, Vec<DynamicNodeType>) {
  129. let mut dynamic_node_type = Vec::new();
  130. let mut template_idx = 0;
  131. let mut attr_idx = 0;
  132. let roots = (0..(1 + rand::random::<usize>() % 5))
  133. .map(|_| {
  134. create_random_template_node(&mut dynamic_node_type, &mut template_idx, &mut attr_idx, 0)
  135. })
  136. .collect::<Vec<_>>();
  137. assert!(!roots.is_empty());
  138. let roots = Box::leak(roots.into_boxed_slice());
  139. let mut node_paths = Vec::new();
  140. let mut attr_paths = Vec::new();
  141. for (i, root) in roots.iter().enumerate() {
  142. generate_paths(root, &[i as u8], &mut node_paths, &mut attr_paths);
  143. }
  144. let node_paths = Box::leak(
  145. node_paths
  146. .into_iter()
  147. .map(|v| &*Box::leak(v.into_boxed_slice()))
  148. .collect::<Vec<_>>()
  149. .into_boxed_slice(),
  150. );
  151. let attr_paths = Box::leak(
  152. attr_paths
  153. .into_iter()
  154. .map(|v| &*Box::leak(v.into_boxed_slice()))
  155. .collect::<Vec<_>>()
  156. .into_boxed_slice(),
  157. );
  158. (
  159. Template { name, roots, node_paths, attr_paths },
  160. dynamic_node_type,
  161. )
  162. }
  163. fn create_random_dynamic_node(depth: usize) -> DynamicNode {
  164. let range = if depth > 5 { 1 } else { 3 };
  165. match rand::random::<u8>() % range {
  166. 0 => DynamicNode::Placeholder(Default::default()),
  167. 1 => (0..(rand::random::<u8>() % 5))
  168. .map(|_| {
  169. VNode::new(
  170. None,
  171. Template {
  172. name: create_template_location(),
  173. roots: &[TemplateNode::Dynamic { id: 0 }],
  174. node_paths: &[&[0]],
  175. attr_paths: &[],
  176. },
  177. Box::new([DynamicNode::Component(VComponent::new(
  178. create_random_element,
  179. DepthProps { depth, root: false },
  180. "create_random_element",
  181. ))]),
  182. Box::new([]),
  183. )
  184. })
  185. .into_dyn_node(),
  186. 2 => DynamicNode::Component(VComponent::new(
  187. create_random_element,
  188. DepthProps { depth, root: false },
  189. "create_random_element",
  190. )),
  191. _ => unreachable!(),
  192. }
  193. }
  194. fn create_random_dynamic_attr() -> Attribute {
  195. let value = match rand::random::<u8>() % 7 {
  196. 0 => AttributeValue::Text(format!("{}", rand::random::<usize>())),
  197. 1 => AttributeValue::Float(rand::random()),
  198. 2 => AttributeValue::Int(rand::random()),
  199. 3 => AttributeValue::Bool(rand::random()),
  200. 4 => AttributeValue::any_value(rand::random::<usize>()),
  201. 5 => AttributeValue::None,
  202. 6 => {
  203. let value = AttributeValue::listener(|e: Event<String>| println!("{:?}", e));
  204. return Attribute::new("ondata", value, None, false);
  205. }
  206. _ => unreachable!(),
  207. };
  208. Attribute::new(
  209. Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  210. value,
  211. random_ns(),
  212. rand::random(),
  213. )
  214. }
  215. static TEMPLATE_COUNT: AtomicUsize = AtomicUsize::new(0);
  216. fn create_template_location() -> &'static str {
  217. Box::leak(
  218. format!(
  219. "{}{}",
  220. concat!(file!(), ":", line!(), ":", column!(), ":"),
  221. TEMPLATE_COUNT.fetch_add(1, Ordering::Relaxed)
  222. )
  223. .into_boxed_str(),
  224. )
  225. }
  226. #[derive(PartialEq, Props, Clone)]
  227. struct DepthProps {
  228. depth: usize,
  229. root: bool,
  230. }
  231. fn create_random_element(cx: DepthProps) -> Element {
  232. if rand::random::<usize>() % 10 == 0 {
  233. needs_update();
  234. }
  235. let range = if cx.root { 2 } else { 3 };
  236. let node = match rand::random::<usize>() % range {
  237. 0 | 1 => {
  238. let (template, dynamic_node_types) = create_random_template(create_template_location());
  239. let node = VNode::new(
  240. None,
  241. template,
  242. dynamic_node_types
  243. .iter()
  244. .map(|ty| match ty {
  245. DynamicNodeType::Text => {
  246. DynamicNode::Text(VText::new(format!("{}", rand::random::<usize>())))
  247. }
  248. DynamicNodeType::Other => create_random_dynamic_node(cx.depth + 1),
  249. })
  250. .collect(),
  251. (0..template.attr_paths.len())
  252. .map(|_| Box::new([create_random_dynamic_attr()]) as Box<[Attribute]>)
  253. .collect(),
  254. );
  255. Some(node)
  256. }
  257. _ => None,
  258. };
  259. // println!("{node:#?}");
  260. node
  261. }
  262. // test for panics when creating random nodes and templates
  263. #[test]
  264. fn create() {
  265. let repeat_count = if cfg!(miri) { 100 } else { 1000 };
  266. for _ in 0..repeat_count {
  267. let mut vdom =
  268. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  269. vdom.rebuild(&mut NoOpMutations);
  270. }
  271. }
  272. // test for panics when diffing random nodes
  273. // This test will change the template every render which is not very realistic, but it helps stress the system
  274. #[test]
  275. fn diff() {
  276. let repeat_count = if cfg!(miri) { 100 } else { 1000 };
  277. for _ in 0..repeat_count {
  278. let mut vdom =
  279. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  280. vdom.rebuild(&mut NoOpMutations);
  281. // A list of all elements that have had event listeners
  282. // This is intentionally never cleared, so that we can test that calling event listeners that are removed doesn't cause a panic
  283. let mut event_listeners = HashSet::new();
  284. for _ in 0..100 {
  285. for &id in &event_listeners {
  286. println!("firing event on {:?}", id);
  287. vdom.handle_event(
  288. "data",
  289. std::rc::Rc::new(String::from("hello world")),
  290. id,
  291. true,
  292. );
  293. }
  294. {
  295. vdom.render_immediate(&mut InsertEventListenerMutationHandler(
  296. &mut event_listeners,
  297. ));
  298. }
  299. }
  300. }
  301. }
  302. struct InsertEventListenerMutationHandler<'a>(&'a mut HashSet<ElementId>);
  303. impl WriteMutations for InsertEventListenerMutationHandler<'_> {
  304. fn register_template(&mut self, _: Template) {}
  305. fn append_children(&mut self, _: ElementId, _: usize) {}
  306. fn assign_node_id(&mut self, _: &'static [u8], _: ElementId) {}
  307. fn create_placeholder(&mut self, _: ElementId) {}
  308. fn create_text_node(&mut self, _: &str, _: ElementId) {}
  309. fn hydrate_text_node(&mut self, _: &'static [u8], _: &str, _: ElementId) {}
  310. fn load_template(&mut self, _: &'static str, _: usize, _: ElementId) {}
  311. fn replace_node_with(&mut self, _: ElementId, _: usize) {}
  312. fn replace_placeholder_with_nodes(&mut self, _: &'static [u8], _: usize) {}
  313. fn insert_nodes_after(&mut self, _: ElementId, _: usize) {}
  314. fn insert_nodes_before(&mut self, _: ElementId, _: usize) {}
  315. fn set_attribute(
  316. &mut self,
  317. _: &'static str,
  318. _: Option<&'static str>,
  319. _: &AttributeValue,
  320. _: ElementId,
  321. ) {
  322. }
  323. fn set_node_text(&mut self, _: &str, _: ElementId) {}
  324. fn create_event_listener(&mut self, name: &'static str, id: ElementId) {
  325. println!("new event listener on {:?} for {:?}", id, name);
  326. self.0.insert(id);
  327. }
  328. fn remove_event_listener(&mut self, _: &'static str, _: ElementId) {}
  329. fn remove_node(&mut self, _: ElementId) {}
  330. fn push_root(&mut self, _: ElementId) {}
  331. }