diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index dbc3ae8cf..2d864a6da 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - directory: [alloc, profiling] + directory: [alloc, profiling, ddcommon-ffi] env: CARGO_TERM_COLOR: always steps: diff --git a/Cargo.lock b/Cargo.lock index f261acf21..4b5594f2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1193,6 +1193,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.19" @@ -1690,8 +1699,10 @@ name = "ddcommon-ffi" version = "11.0.0" dependencies = [ "anyhow", + "bolero", "build_common", "chrono", + "crossbeam-queue", "ddcommon", "hyper 0.14.28", ] diff --git a/LICENSE-3rdparty.yml b/LICENSE-3rdparty.yml index 4dc7ebacc..0ec429cc4 100644 --- a/LICENSE-3rdparty.yml +++ b/LICENSE-3rdparty.yml @@ -7716,6 +7716,42 @@ third_party_libraries: DEALINGS IN THE SOFTWARE. - license: Apache-2.0 text: " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n" +- package_name: crossbeam-queue + package_version: 0.3.11 + repository: https://github.com/crossbeam-rs/crossbeam + license: MIT OR Apache-2.0 + licenses: + - license: MIT + text: | + The MIT License (MIT) + + Copyright (c) 2019 The Crossbeam Project Developers + + Permission is hereby granted, free of charge, to any + person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the + Software without restriction, including without + limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software + is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice + shall be included in all copies or substantial portions + of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF + ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT + SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + - license: Apache-2.0 + text: " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n" - package_name: crossbeam-utils package_version: 0.8.19 repository: https://github.com/crossbeam-rs/crossbeam diff --git a/ddcommon-ffi/Cargo.toml b/ddcommon-ffi/Cargo.toml index 2c621a8ab..e9064644a 100644 --- a/ddcommon-ffi/Cargo.toml +++ b/ddcommon-ffi/Cargo.toml @@ -21,5 +21,9 @@ build_common = { path = "../build-common" } [dependencies] anyhow = "1.0" chrono = { version = "0.4.38", features = ["std"] } +crossbeam-queue = "0.3.11" ddcommon = { path = "../ddcommon" } hyper = {version = "0.14", default-features = false} + +[dev-dependencies] +bolero = "0.10.1" diff --git a/ddcommon-ffi/cbindgen.toml b/ddcommon-ffi/cbindgen.toml index b09c11abf..6652e931d 100644 --- a/ddcommon-ffi/cbindgen.toml +++ b/ddcommon-ffi/cbindgen.toml @@ -54,6 +54,12 @@ rename_types = "PascalCase" [export.rename] "ParseTagsResult" = "ddog_Vec_Tag_ParseResult" "PushTagResult" = "ddog_Vec_Tag_PushResult" +"ArrayQueueNewResult" = "ddog_ArrayQueue_NewResult" +"ArrayQueuePushResult" = "ddog_ArrayQueue_PushResult" +"ArrayQueuePopResult" = "ddog_ArrayQueue_PopResult" +"ArrayQueueBoolResult" = "ddog_ArrayQueue_BoolResult" +"ArrayQueueUsizeResult" = "ddog_ArrayQueue_UsizeResult" + [enum] prefix_with_name = true diff --git a/ddcommon-ffi/src/array_queue.rs b/ddcommon-ffi/src/array_queue.rs new file mode 100644 index 000000000..0193d8fa0 --- /dev/null +++ b/ddcommon-ffi/src/array_queue.rs @@ -0,0 +1,471 @@ +// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +use crate::Error; +use anyhow::Context; +use std::{ffi::c_void, ptr::NonNull}; + +#[derive(Debug)] +#[repr(C)] +// A simple wrapper around crossbeam_queue::ArrayQueue<*mut c_void>, which is a lock free +// bounded multi-producer and multi-consumer (MPMC) queue. +pub struct ArrayQueue { + // The actual type here should be NonNull>. + // However, cbindgen does not use the module name crossbeam_queue to generate the C header, and + // above will be generated into ArrayQueue<*void>. So we use NonNull here and cast + // it to the correct type in the FFI functions. Also, we use NonNull instead of Box to avoid + // getting into trouble with the drop implementation. + inner: NonNull, + item_delete_fn: unsafe extern "C" fn(*mut c_void) -> c_void, +} + +unsafe impl Sync for ArrayQueue {} +unsafe impl Send for ArrayQueue {} + +impl ArrayQueue { + pub fn new( + capacity: usize, + item_delete_fn: Option c_void>, + ) -> anyhow::Result { + anyhow::ensure!(capacity > 0, "capacity must be greater than 0"); + let item_delete_fn = item_delete_fn.context("item_delete_fn must be non-null")?; + + let internal_queue: crossbeam_queue::ArrayQueue<*mut c_void> = + crossbeam_queue::ArrayQueue::new(capacity); + // # Safety: internal_queue must be non-null. + // If the memory allocation had failed, the program would panic. + let inner = NonNull::new(Box::into_raw(Box::new(internal_queue)) as *mut ArrayQueue) + .context("nullptr passed to NonNull, failed to create internal_queue")?; + Ok(Self { + inner, + item_delete_fn, + }) + } +} + +impl<'a> ArrayQueue { + pub fn as_inner_ref( + queue: &'a ArrayQueue, + ) -> anyhow::Result<&'a crossbeam_queue::ArrayQueue<*mut c_void>> { + // # Safety: the inner points to a valid memory location which is a + // crossbeam_queue::ArrayQueue<*mut c_void>. + Ok(unsafe { &*(queue.inner.as_ptr() as *const crossbeam_queue::ArrayQueue<*mut c_void>) }) + } +} + +impl Drop for ArrayQueue { + fn drop(&mut self) { + // # Safety: the inner pointer is not null and points to a valid memory location + // holding an crossbeam::ArrayQueue<*mut c_void> created via ArrayQueue::new. + let queue = unsafe { + Box::from_raw(self.inner.as_ptr() as *mut crossbeam_queue::ArrayQueue<*mut c_void>) + }; + while let Some(item) = queue.pop() { + // # Safety: the item is a valid memory location that can be deallocated by the + // item_delete_fn. + unsafe { + (self.item_delete_fn)(item); + } + } + } +} + +#[allow(unused)] +#[repr(C)] +pub enum ArrayQueueNewResult { + Ok(NonNull), + Err(Error), +} + +/// Creates a new ArrayQueue with the given capacity and item_delete_fn. +/// The item_delete_fn is called when an item is dropped from the queue. +#[no_mangle] +#[must_use] +pub extern "C" fn ddog_ArrayQueue_new( + capacity: usize, + item_delete_fn: Option c_void>, +) -> ArrayQueueNewResult { + match ArrayQueue::new(capacity, item_delete_fn) { + Ok(queue) => ArrayQueueNewResult::Ok( + // # Safety: ptr is not null and points to a valid memory location holding an + // ArrayQueue + unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(queue))) }, + ), + Err(err) => ArrayQueueNewResult::Err(err.into()), + } +} + +/// Drops the ArrayQueue. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_drop(queue: *mut ArrayQueue) { + // Technically, this function has been designed so if it's double-dropped + // then it's okay, but it's not something that should be relied on. + if !queue.is_null() { + drop(Box::from_raw(queue)); + } +} + +/// Data structure for the result of the push() and force_push() functions. +/// force_push() replaces the oldest element if the queue is full, while push() returns the given +/// value if the queue is full. For push(), it's redundant to return the value since the caller +/// already has it, but it's returned for consistency with crossbeam API and with force_push(). +#[allow(unused)] +#[repr(C)] +pub enum ArrayQueuePushResult { + Ok, + Full(*mut c_void), + Err(Error), +} + +impl From, anyhow::Error>> for ArrayQueuePushResult { + fn from(result: Result, anyhow::Error>) -> Self { + match result { + Ok(value) => match value { + Ok(()) => ArrayQueuePushResult::Ok, + Err(value) => ArrayQueuePushResult::Full(value), + }, + Err(err) => ArrayQueuePushResult::Err(err.into()), + } + } +} + +/// Pushes an item into the ArrayQueue. It returns the given value if the queue is full. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. The value +/// is null or points to a valid memory location that can be deallocated by the item_delete_fn. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_push( + queue_ptr: &ArrayQueue, + value: *mut c_void, +) -> ArrayQueuePushResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.push(value)) + })() + .context("ArrayQueue_push failed") + .into() +} + +impl From, anyhow::Error>> for ArrayQueuePushResult { + fn from(result: Result, anyhow::Error>) -> Self { + match result { + Ok(value) => match value { + Some(value) => ArrayQueuePushResult::Full(value), + None => ArrayQueuePushResult::Ok, + }, + Err(err) => ArrayQueuePushResult::Err(err.into()), + } + } +} + +/// Pushes an element into the queue, replacing the oldest element if necessary. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. The value +/// is null or points to a valid memory location that can be deallocated by the item_delete_fn. +#[no_mangle] +#[must_use] +pub unsafe extern "C" fn ddog_ArrayQueue_force_push( + queue_ptr: &ArrayQueue, + value: *mut c_void, +) -> ArrayQueuePushResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.force_push(value)) + })() + .context("ArrayQueue_force_push failed") + .into() +} + +#[allow(unused)] +#[repr(C)] +pub enum ArrayQueuePopResult { + Ok(*mut c_void), + Empty, + Err(Error), +} + +impl From>> for ArrayQueuePopResult { + fn from(result: anyhow::Result>) -> Self { + match result { + Ok(value) => match value { + Some(value) => ArrayQueuePopResult::Ok(value), + None => ArrayQueuePopResult::Empty, + }, + Err(err) => ArrayQueuePopResult::Err(err.into()), + } + } +} + +/// Pops an item from the ArrayQueue. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[must_use] +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_pop(queue_ptr: &ArrayQueue) -> ArrayQueuePopResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.pop()) + })() + .context("ArrayQueue_pop failed") + .into() +} + +#[allow(unused)] +#[repr(C)] +pub enum ArrayQueueBoolResult { + Ok(bool), + Err(Error), +} + +impl From> for ArrayQueueBoolResult { + fn from(result: anyhow::Result) -> Self { + match result { + Ok(value) => ArrayQueueBoolResult::Ok(value), + Err(err) => ArrayQueueBoolResult::Err(err.into()), + } + } +} + +/// Checks if the ArrayQueue is empty. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_is_empty(queue_ptr: &ArrayQueue) -> ArrayQueueBoolResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.is_empty()) + })() + .context("ArrayQueue_is_empty failed") + .into() +} + +#[allow(unused)] +#[repr(C)] +pub enum ArrayQueueUsizeResult { + Ok(usize), + Err(Error), +} + +impl From> for ArrayQueueUsizeResult { + fn from(result: anyhow::Result) -> Self { + match result { + Ok(value) => ArrayQueueUsizeResult::Ok(value), + Err(err) => ArrayQueueUsizeResult::Err(err.into()), + } + } +} + +/// Returns the length of the ArrayQueue. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_len(queue_ptr: &ArrayQueue) -> ArrayQueueUsizeResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.len()) + })() + .context("ArrayQueue_len failed") + .into() +} + +/// Returns true if the underlying queue is full. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_is_full(queue_ptr: &ArrayQueue) -> ArrayQueueBoolResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.is_full()) + })() + .context("ArrayQueue_is_full failed") + .into() +} + +/// Returns the capacity of the ArrayQueue. +/// # Safety +/// The pointer is null or points to a valid memory location allocated by ArrayQueue_new. +#[no_mangle] +pub unsafe extern "C" fn ddog_ArrayQueue_capacity(queue_ptr: &ArrayQueue) -> ArrayQueueUsizeResult { + (|| { + let queue = ArrayQueue::as_inner_ref(queue_ptr)?; + anyhow::Ok(queue.capacity()) + })() + .context("ArrayQueue_capacity failed") + .into() +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + use bolero::TypeGenerator; + + unsafe extern "C" fn drop_item(item: *mut c_void) -> c_void { + _ = Box::from_raw(item as *mut i32); + std::mem::zeroed() + } + + #[test] + fn test_new_drop() { + let queue_new_result = ddog_ArrayQueue_new(1, Some(drop_item)); + assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_))); + let queue_ptr = match queue_new_result { + ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(), + _ => std::ptr::null_mut(), + }; + let item = Box::new(1i32); + let item_ptr = Box::into_raw(item); + let item2 = Box::new(2i32); + let item2_ptr = Box::into_raw(item2); + let item3 = Box::new(3i32); + let item3_ptr = Box::into_raw(item3); + unsafe { + let queue = &*queue_ptr; + let result = ddog_ArrayQueue_push(queue, item_ptr as *mut c_void); + assert!(matches!(result, ArrayQueuePushResult::Ok)); + let result = ddog_ArrayQueue_push(queue, item2_ptr as *mut c_void); + assert!( + matches!(result, ArrayQueuePushResult::Full(ptr) if ptr == item2_ptr as *mut c_void) + ); + let result = ddog_ArrayQueue_pop(queue); + assert!( + matches!(result, ArrayQueuePopResult::Ok(ptr) if ptr == item_ptr as *mut c_void) + ); + let item_ptr = match result { + ArrayQueuePopResult::Ok(ptr) => ptr, + _ => std::ptr::null_mut(), + }; + drop(Box::from_raw(item_ptr as *mut i32)); + let result = ddog_ArrayQueue_push(queue, item3_ptr as *mut c_void); + assert!(matches!(result, ArrayQueuePushResult::Ok)); + ddog_ArrayQueue_drop(queue_ptr); + drop(Box::from_raw(item2_ptr)); + } + } + + #[test] + fn test_capacity_zero() { + let queue_new_result = ddog_ArrayQueue_new(0, Some(drop_item)); + assert!(matches!(queue_new_result, + ArrayQueueNewResult::Err(err) if err == Error::from("capacity must be greater than 0"))); + } + + #[test] + fn test_none_delete_fn() { + let queue_new_result = ddog_ArrayQueue_new(1, None); + assert!(matches!(queue_new_result, ArrayQueueNewResult::Err(err) + if err == Error::from("item_delete_fn must be non-null"))); + } + + #[derive(Debug, TypeGenerator)] + enum Operation { + Push, + ForcePush, + Pop, + } + + fn process_ops(ops: &[Operation], queue: &ArrayQueue, cnt: &AtomicUsize) { + for op in ops { + match op { + Operation::Push => { + let item = Box::new(1i32); + let item_ptr = Box::into_raw(item); + let result = unsafe { ddog_ArrayQueue_push(queue, item_ptr as *mut c_void) }; + match result { + ArrayQueuePushResult::Ok => { + cnt.fetch_add(1, Ordering::SeqCst); + } + ArrayQueuePushResult::Full(ptr) => { + assert_eq!(ptr, item_ptr as *mut c_void); + unsafe { + drop(Box::from_raw(ptr as *mut i32)); + } + } + ArrayQueuePushResult::Err(_) => { + panic!("push failed"); + } + } + } + Operation::ForcePush => { + let item = Box::new(2i32); + let item_ptr = Box::into_raw(item); + let result = + unsafe { ddog_ArrayQueue_force_push(queue, item_ptr as *mut c_void) }; + match result { + ArrayQueuePushResult::Ok => { + cnt.fetch_add(1, Ordering::SeqCst); + } + ArrayQueuePushResult::Full(ptr) => unsafe { + drop(Box::from_raw(ptr as *mut i32)); + }, + ArrayQueuePushResult::Err(_) => { + panic!("force_push failed"); + } + } + } + Operation::Pop => { + let result = unsafe { ddog_ArrayQueue_pop(queue) }; + match result { + ArrayQueuePopResult::Ok(ptr) => { + cnt.fetch_sub(1, Ordering::SeqCst); + unsafe { + drop(Box::from_raw(ptr as *mut i32)); + } + } + ArrayQueuePopResult::Empty => { + // No guarantee that cnt is 0, but would likely be. + } + ArrayQueuePopResult::Err(_) => { + panic!("pop failed"); + } + } + } + } + } + } + + #[test] + fn fuzz_with_threads() { + let capacity_gen = 1..=32usize; + let ops_gen = Vec::::gen(); + + bolero::check!() + .with_generator((capacity_gen, ops_gen, ops_gen, ops_gen, ops_gen)) + .for_each(|(capacity, ops1, ops2, ops3, ops4)| { + let queue_new_result = ddog_ArrayQueue_new(*capacity, Some(drop_item)); + assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_))); + let queue_ptr = match queue_new_result { + ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(), + _ => std::ptr::null_mut(), + }; + let queue = unsafe { &*queue_ptr }; + + let cnt = AtomicUsize::new(0); + + std::thread::scope(|s| { + s.spawn(|| process_ops(ops1, queue, &cnt)); + s.spawn(|| process_ops(ops2, queue, &cnt)); + s.spawn(|| process_ops(ops3, queue, &cnt)); + s.spawn(|| process_ops(ops4, queue, &cnt)); + }); + + // Check the length + let result = unsafe { ddog_ArrayQueue_len(queue) }; + match result { + ArrayQueueUsizeResult::Ok(len) => { + assert_eq!(len, cnt.load(Ordering::SeqCst)); + } + ArrayQueueUsizeResult::Err(_) => { + panic!("len failed"); + } + } + + unsafe { + ddog_ArrayQueue_drop(queue_ptr); + } + }) + } +} diff --git a/ddcommon-ffi/src/lib.rs b/ddcommon-ffi/src/lib.rs index 1fdef2289..5163ca1c0 100644 --- a/ddcommon-ffi/src/lib.rs +++ b/ddcommon-ffi/src/lib.rs @@ -3,6 +3,7 @@ mod error; +pub mod array_queue; pub mod endpoint; pub mod option; pub mod slice; diff --git a/examples/ffi/.gitignore b/examples/ffi/.gitignore new file mode 100644 index 000000000..36ecc189c --- /dev/null +++ b/examples/ffi/.gitignore @@ -0,0 +1,14 @@ +CMakeFiles/ +CMakeCache.txt +cmake_install.cmake +Makefile +compile_commands.json + +array_queue +crashinfo +crashtracking +exporter +profiles +telemetry +telemetry_metrics +trace_exporter diff --git a/examples/ffi/CMakeLists.txt b/examples/ffi/CMakeLists.txt index 992d81d8e..b7b715074 100644 --- a/examples/ffi/CMakeLists.txt +++ b/examples/ffi/CMakeLists.txt @@ -4,6 +4,7 @@ project(datadog_profiling_ffi_examples LANGUAGES C CXX) find_package(Datadog REQUIRED) set(VCRUNTIME_LINK_TYPE DLL CACHE STRING "Specify the Runtime Library to use when compiling with MSVC") +set(CMAKE_EXPORT_COMPILE_COMMANDS on) function(set_vcruntime_link_type binary link_type) if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC") @@ -60,3 +61,8 @@ endif() add_executable(trace_exporter trace_exporter.c) target_link_libraries(trace_exporter PRIVATE Datadog::Profiling) set_vcruntime_link_type(trace_exporter ${VCRUNTIME_LINK_TYPE}) + +add_executable(array_queue array_queue.cpp) +target_compile_features(array_queue PRIVATE cxx_std_20) +target_link_libraries(array_queue PRIVATE Datadog::Profiling) +set_vcruntime_link_type(array_queue ${VCRUNTIME_LINK_TYPE}) diff --git a/examples/ffi/array_queue.cpp b/examples/ffi/array_queue.cpp new file mode 100644 index 000000000..07e989c13 --- /dev/null +++ b/examples/ffi/array_queue.cpp @@ -0,0 +1,100 @@ +// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +extern "C" { +#include +} +#include +#include +#include +#include +#include +#include + +struct Sample { + int x; + int y; +}; + +void delete_fn(void *sample) { delete (Sample *)sample; } + +struct Deleter { + void operator()(ddog_ArrayQueue *object) { ddog_ArrayQueue_drop(object); } +}; + +void print_error(const char *s, const ddog_Error &err) { + ddog_CharSlice charslice = ddog_Error_message(&err); + printf("%s (%.*s)\n", s, static_cast(charslice.len), charslice.ptr); +} + +int main(void) { + ddog_ArrayQueue_NewResult array_queue_new_result = ddog_ArrayQueue_new(5, delete_fn); + if (array_queue_new_result.tag != DDOG_ARRAY_QUEUE_NEW_RESULT_OK) { + print_error("Failed to create array queue", array_queue_new_result.err); + ddog_Error_drop(&array_queue_new_result.err); + return 1; + } + std::unique_ptr array_queue(array_queue_new_result.ok); + + size_t num_threads = 4; + size_t num_elements = 50; + std::vector> counts(num_elements); + for (size_t i = 0; i < num_elements; ++i) { + counts[i].store(0); + } + + auto consumer = [&array_queue, &counts, num_elements]() { + for (size_t i = 0; i < num_elements; ++i) { + while (true) { + ddog_ArrayQueue_PopResult pop_result = ddog_ArrayQueue_pop(array_queue.get()); + if (pop_result.tag == DDOG_ARRAY_QUEUE_POP_RESULT_OK) { + Sample *sample = (Sample *)pop_result.ok; + counts[sample->x].fetch_add(1, std::memory_order_seq_cst); + delete sample; + break; + } else if (pop_result.tag == DDOG_ARRAY_QUEUE_POP_RESULT_EMPTY) { + std::this_thread::yield(); + } else { + print_error("Failed to pop from array queue", pop_result.err); + ddog_Error_drop(&pop_result.err); + return; + } + } + } + }; + + auto producer = [&array_queue, num_elements]() { + for (size_t i = 0; i < num_elements; ++i) { + Sample *sample = new Sample(); + sample->x = i; + sample->y = i; + while (true) { + ddog_ArrayQueue_PushResult push_result = ddog_ArrayQueue_push(array_queue.get(), sample); + if (push_result.tag == DDOG_ARRAY_QUEUE_PUSH_RESULT_OK) { + break; + } else if (push_result.tag == DDOG_ARRAY_QUEUE_PUSH_RESULT_FULL) { + std::this_thread::yield(); + } else { + print_error("Failed to push to array queue", push_result.err); + ddog_Error_drop(&push_result.err); + delete sample; + return; + } + } + } + }; + + std::vector threads; + for (size_t i = 0; i < num_threads; ++i) { + threads.emplace_back(consumer); + threads.emplace_back(producer); + } + + for (auto &t : threads) { + t.join(); + } + + for (const auto &c : counts) { + assert(c.load(std::memory_order_seq_cst) == num_threads); + } +}