1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
//! A generic shared memory region to be used by any functions (queues or feedbacks
//! too.)
#[cfg(feature = "alloc")]
use alloc::{rc::Rc, string::ToString};
#[cfg(feature = "alloc")]
use core::fmt::Display;
#[cfg(feature = "alloc")]
use core::{cell::RefCell, fmt, mem::ManuallyDrop};
use core::{fmt::Debug, mem};
#[cfg(feature = "std")]
use std::env;
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
use std::io::Read;
#[cfg(all(feature = "std", not(target_os = "haiku")))]
use std::io::Write;
use serde::{Deserialize, Serialize};
#[cfg(all(
feature = "std",
unix,
not(any(target_os = "android", target_os = "haiku"))
))]
pub use unix_shmem::{MmapShMem, MmapShMemProvider};
#[cfg(all(feature = "std", unix, not(target_os = "haiku")))]
pub use unix_shmem::{UnixShMem, UnixShMemProvider};
#[cfg(all(windows, feature = "std"))]
pub use win32_shmem::{Win32ShMem, Win32ShMemProvider};
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
use crate::os::pipes::Pipe;
#[cfg(all(feature = "std", unix, not(target_os = "haiku")))]
pub use crate::os::unix_shmem_server::{ServedShMemProvider, ShMemService};
use crate::{AsMutSlice, AsSlice, Error};
/// The standard sharedmem provider
#[cfg(all(windows, feature = "std"))]
pub type StdShMemProvider = Win32ShMemProvider;
/// The standard sharedmem provider
#[cfg(all(target_os = "android", feature = "std"))]
pub type StdShMemProvider =
RcShMemProvider<ServedShMemProvider<unix_shmem::ashmem::AshmemShMemProvider>>;
/// The standard sharedmem service
#[cfg(all(target_os = "android", feature = "std"))]
pub type StdShMemService = ShMemService<unix_shmem::ashmem::AshmemShMemProvider>;
/// The standard sharedmem provider
#[cfg(all(feature = "std", target_vendor = "apple"))]
pub type StdShMemProvider = RcShMemProvider<ServedShMemProvider<MmapShMemProvider>>;
#[cfg(all(feature = "std", target_vendor = "apple"))]
/// The standard sharedmem service
pub type StdShMemService = ShMemService<MmapShMemProvider>;
/// The default [`ShMemProvider`] for this os.
#[cfg(all(
feature = "std",
unix,
not(any(target_os = "android", target_vendor = "apple", target_os = "haiku"))
))]
pub type StdShMemProvider = UnixShMemProvider;
/// The standard sharedmem service
#[cfg(any(
not(any(target_os = "android", target_vendor = "apple", target_os = "haiku")),
not(feature = "std")
))]
pub type StdShMemService = DummyShMemService;
// for unix only
/// The standard served shmem provider
#[cfg(all(target_os = "android", feature = "std"))]
pub type StdServedShMemProvider =
RcShMemProvider<ServedShMemProvider<unix_shmem::ashmem::AshmemShMemProvider>>;
/// The standard served shmem provider
#[cfg(all(feature = "std", target_vendor = "apple"))]
pub type StdServedShMemProvider = RcShMemProvider<ServedShMemProvider<MmapShMemProvider>>;
/// The standard served shmem provider
#[cfg(all(
feature = "std",
unix,
not(any(target_os = "android", target_vendor = "apple", target_os = "haiku"))
))]
pub type StdServedShMemProvider = RcShMemProvider<ServedShMemProvider<MmapShMemProvider>>;
/// Description of a shared map.
/// May be used to restore the map by id.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct ShMemDescription {
/// Size of this map
pub size: usize,
/// Id of this map
pub id: ShMemId,
}
impl ShMemDescription {
/// Create a description from a `id_str` and a `size`.
#[must_use]
pub fn from_string_and_size(id_str: &str, size: usize) -> Self {
Self {
size,
id: ShMemId::from_string(id_str),
}
}
}
/// An id associated with a given shared memory mapping ([`ShMem`]), which can be used to
/// establish shared-mappings between proccesses.
/// Id is a file descriptor if you use `MmapShMem` or `AshmemShMem`.
/// That means you have to use shmem server to access to the shmem segment from other processes in these cases.
/// On the other hand, id is a unique identifier if you use `CommonUnixShMem` or `Win32ShMem`.
/// In these two cases, you can use shmat(id) or `OpenFileMappingA`(id) to gain access to the shmem
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
pub struct ShMemId {
id: [u8; 20],
}
impl ShMemId {
/// Create a new id from a fixed-size string/bytes array
/// It should contain a valid cstring.
#[must_use]
pub fn from_array(array: &[u8; 20]) -> Self {
Self { id: *array }
}
/// Try to create a new id from a bytes string.
/// The slice must have a length of at least 20 bytes and contain a valid cstring.
pub fn try_from_slice(slice: &[u8]) -> Result<Self, Error> {
Ok(Self::from_array(&slice[0..20].try_into()?))
}
/// Create a new id from an int
#[cfg(feature = "alloc")]
#[must_use]
pub fn from_int(val: i32) -> Self {
Self::from_string(&val.to_string())
}
/// Create a new id from a string
#[must_use]
pub fn from_string(val: &str) -> Self {
let mut slice: [u8; 20] = [0; 20];
for (i, val) in val.as_bytes().iter().enumerate() {
slice[i] = *val;
}
Self { id: slice }
}
/// Returns `true` if this `ShMemId` has an empty backing slice.
/// If this is the case something went wrong, and this `ShMemId` may not be read from.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.id[0] == 0
}
/// Get the id as a fixed-length slice
#[must_use]
pub const fn as_array(&self) -> &[u8; 20] {
&self.id
}
/// Returns the first null-byte in or the end of the buffer
#[must_use]
pub fn null_pos(&self) -> usize {
self.id.iter().position(|&c| c == 0).unwrap()
}
/// Returns a `str` representation of this [`ShMemId`]
#[cfg(feature = "alloc")]
#[must_use]
pub fn as_str(&self) -> &str {
alloc::str::from_utf8(&self.id[..self.null_pos()]).unwrap()
}
}
impl AsSlice for ShMemId {
type Entry = u8;
fn as_slice(&self) -> &[u8] {
&self.id
}
}
#[cfg(feature = "alloc")]
impl From<ShMemId> for i32 {
fn from(id: ShMemId) -> i32 {
id.as_str().parse().unwrap()
}
}
#[cfg(feature = "alloc")]
impl Display for ShMemId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
/// A [`ShMem`] is an interface to shared maps.
/// They are the backbone of [`crate::llmp`] for inter-process communication.
/// All you need for scaling on a new target is to implement this interface, as well as the respective [`ShMemProvider`].
pub trait ShMem: Sized + Debug + Clone + AsSlice<Entry = u8> + AsMutSlice<Entry = u8> {
/// Get the id of this shared memory mapping
fn id(&self) -> ShMemId;
/// Get the size of this mapping
fn len(&self) -> usize;
/// Check if the mapping is empty
fn is_empty(&self) -> bool {
self.len() == 0
}
/// Convert to a ptr of a given type, checking the size.
/// If the map is too small, returns `None`
fn as_ptr_of<T: Sized>(&self) -> Option<*const T> {
if self.len() >= mem::size_of::<T>() {
Some(self.as_slice().as_ptr() as *const T)
} else {
None
}
}
/// Convert to a mut ptr of a given type, checking the size.
/// If the map is too small, returns `None`
fn as_mut_ptr_of<T: Sized>(&mut self) -> Option<*mut T> {
if self.len() >= mem::size_of::<T>() {
Some(self.as_mut_slice().as_mut_ptr() as *mut T)
} else {
None
}
}
/// Get the description of the shared memory mapping
fn description(&self) -> ShMemDescription {
ShMemDescription {
size: self.len(),
id: self.id(),
}
}
/// Write this map's config to env
#[cfg(feature = "std")]
fn write_to_env(&self, env_name: &str) -> Result<(), Error> {
let map_size = self.len();
let map_size_env = format!("{env_name}_SIZE");
env::set_var(env_name, self.id().to_string());
env::set_var(map_size_env, format!("{map_size}"));
Ok(())
}
}
/// A [`ShMemProvider`] provides access to shared maps.
/// They are the backbone of [`crate::llmp`] for inter-process communication.
/// All you need for scaling on a new target is to implement this interface, as well as the respective [`ShMem`].
pub trait ShMemProvider: Clone + Default + Debug {
/// The actual shared map handed out by this [`ShMemProvider`].
type ShMem: ShMem;
/// Create a new instance of the provider
fn new() -> Result<Self, Error>;
/// Create a new shared memory mapping
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error>;
/// Get a mapping given its id and size
fn shmem_from_id_and_size(&mut self, id: ShMemId, size: usize) -> Result<Self::ShMem, Error>;
/// Create a new shared memory mapping to hold an object of the given type, and initializes it with the given value.
fn new_on_shmem<T: Sized + 'static>(&mut self, value: T) -> Result<Self::ShMem, Error> {
self.uninit_on_shmem::<T>().map(|mut shmem| {
// # Safety
// The map has been created at this point in time, and is large enough.
// The map is fresh from the OS and, hence, the pointer should be properly aligned for any object.
unsafe { shmem.as_mut_ptr_of::<T>().unwrap().write_volatile(value) };
shmem
})
}
/// Create a new shared memory mapping to hold an object of the given type, and initializes it with the given value.
fn uninit_on_shmem<T: Sized + 'static>(&mut self) -> Result<Self::ShMem, Error> {
self.new_shmem(mem::size_of::<T>())
}
/// Get a mapping given a description
fn shmem_from_description(
&mut self,
description: ShMemDescription,
) -> Result<Self::ShMem, Error> {
self.shmem_from_id_and_size(description.id, description.size)
}
/// Create a new sharedmap reference from an existing `id` and `len`
fn clone_ref(&mut self, mapping: &Self::ShMem) -> Result<Self::ShMem, Error> {
self.shmem_from_id_and_size(mapping.id(), mapping.len())
}
/// Reads an existing map config from env vars, then maps it
#[cfg(feature = "std")]
fn existing_from_env(&mut self, env_name: &str) -> Result<Self::ShMem, Error> {
let map_shm_str = env::var(env_name)?;
let map_size = str::parse::<usize>(&env::var(format!("{env_name}_SIZE"))?)?;
self.shmem_from_description(ShMemDescription::from_string_and_size(
&map_shm_str,
map_size,
))
}
/// This method should be called before a fork or a thread creation event, allowing the [`ShMemProvider`] to
/// get ready for a potential reset of thread specific info, and for potential reconnects.
/// Make sure to call [`Self::post_fork()`] after threading!
fn pre_fork(&mut self) -> Result<(), Error> {
// do nothing
Ok(())
}
/// This method should be called after a fork or after cloning/a thread creation event, allowing the [`ShMemProvider`] to
/// reset thread specific info, and potentially reconnect.
/// Make sure to call [`Self::pre_fork()`] before threading!
fn post_fork(&mut self, _is_child: bool) -> Result<(), Error> {
// do nothing
Ok(())
}
/// Release the resources associated with the given [`ShMem`]
fn release_shmem(&mut self, _shmem: &mut Self::ShMem) {
// do nothing
}
}
/// A Reference Counted shared map,
/// that can use internal mutability.
/// Useful if the `ShMemProvider` needs to keep local state.
#[cfg(feature = "alloc")]
#[derive(Debug, Clone)]
pub struct RcShMem<T: ShMemProvider> {
internal: ManuallyDrop<T::ShMem>,
provider: Rc<RefCell<T>>,
}
#[cfg(feature = "alloc")]
impl<T> ShMem for RcShMem<T>
where
T: ShMemProvider + Debug,
{
fn id(&self) -> ShMemId {
self.internal.id()
}
fn len(&self) -> usize {
self.internal.len()
}
}
#[cfg(feature = "alloc")]
impl<T> AsSlice for RcShMem<T>
where
T: ShMemProvider + Debug,
{
type Entry = u8;
fn as_slice(&self) -> &[u8] {
self.internal.as_slice()
}
}
#[cfg(feature = "alloc")]
impl<T> AsMutSlice for RcShMem<T>
where
T: ShMemProvider + Debug,
{
type Entry = u8;
fn as_mut_slice(&mut self) -> &mut [u8] {
self.internal.as_mut_slice()
}
}
#[cfg(feature = "alloc")]
impl<T: ShMemProvider> Drop for RcShMem<T> {
fn drop(&mut self) {
self.provider.borrow_mut().release_shmem(&mut self.internal);
}
}
/// A Reference Counted `ShMemProvider`,
/// that can use internal mutability.
/// Useful if the `ShMemProvider` needs to keep local state.
#[derive(Debug, Clone)]
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
pub struct RcShMemProvider<SP>
where
SP: ShMemProvider,
{
/// The wrapped [`ShMemProvider`].
internal: Rc<RefCell<SP>>,
/// A pipe the child uses to communicate progress to the parent after fork.
/// This prevents a potential race condition when using the [`ShMemService`].
#[cfg(unix)]
child_parent_pipe: Option<Pipe>,
#[cfg(unix)]
/// A pipe the parent uses to communicate progress to the child after fork.
/// This prevents a potential race condition when using the [`ShMemService`].
parent_child_pipe: Option<Pipe>,
}
//#[cfg(all(unix, feature = "std"))]
//unsafe impl<SP: ShMemProvider> Send for RcShMemProvider<SP> {}
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
impl<SP> ShMemProvider for RcShMemProvider<SP>
where
SP: ShMemProvider + Debug,
{
type ShMem = RcShMem<SP>;
fn new() -> Result<Self, Error> {
Ok(Self {
internal: Rc::new(RefCell::new(SP::new()?)),
child_parent_pipe: None,
parent_child_pipe: None,
})
}
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error> {
Ok(Self::ShMem {
internal: ManuallyDrop::new(self.internal.borrow_mut().new_shmem(map_size)?),
provider: self.internal.clone(),
})
}
fn shmem_from_id_and_size(&mut self, id: ShMemId, size: usize) -> Result<Self::ShMem, Error> {
Ok(Self::ShMem {
internal: ManuallyDrop::new(
self.internal
.borrow_mut()
.shmem_from_id_and_size(id, size)?,
),
provider: self.internal.clone(),
})
}
fn release_shmem(&mut self, map: &mut Self::ShMem) {
self.internal.borrow_mut().release_shmem(&mut map.internal);
}
fn clone_ref(&mut self, mapping: &Self::ShMem) -> Result<Self::ShMem, Error> {
Ok(Self::ShMem {
internal: ManuallyDrop::new(self.internal.borrow_mut().clone_ref(&mapping.internal)?),
provider: self.internal.clone(),
})
}
/// This method should be called before a fork or a thread creation event, allowing the [`ShMemProvider`] to
/// get ready for a potential reset of thread specific info, and for potential reconnects.
fn pre_fork(&mut self) -> Result<(), Error> {
// Set up the pipes to communicate progress over, later.
self.child_parent_pipe = Some(Pipe::new()?);
self.parent_child_pipe = Some(Pipe::new()?);
self.internal.borrow_mut().pre_fork()
}
/// After fork, make sure everything gets set up correctly internally.
fn post_fork(&mut self, is_child: bool) -> Result<(), Error> {
if is_child {
self.await_parent_done()?;
//let child_shmem = self.internal.borrow_mut().clone();
//self.internal = Rc::new(RefCell::new(child_shmem));
}
self.internal.borrow_mut().post_fork(is_child)?;
if is_child {
self.set_child_done()?;
} else {
self.set_parent_done()?;
self.await_child_done()?;
}
self.parent_child_pipe = None;
self.child_parent_pipe = None;
Ok(())
}
}
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
impl<SP> RcShMemProvider<SP>
where
SP: ShMemProvider,
{
/// "set" the "latch"
/// (we abuse `pipes` as `semaphores`, as they don't need an additional shared mem region.)
fn pipe_set(pipe: &mut Option<Pipe>) -> Result<(), Error> {
match pipe {
Some(pipe) => {
let ok = [0_u8; 4];
pipe.write_all(&ok)?;
Ok(())
}
None => Err(Error::illegal_state(
"Unexpected `None` Pipe in RcShMemProvider! Missing post_fork()?".to_string(),
)),
}
}
/// "await" the "latch"
fn pipe_await(pipe: &mut Option<Pipe>) -> Result<(), Error> {
match pipe {
Some(pipe) => {
let ok = [0_u8; 4];
let mut ret = ok;
pipe.read_exact(&mut ret)?;
if ret == ok {
Ok(())
} else {
Err(Error::unknown(format!(
"Wrong result read from pipe! Expected 0, got {ret:?}"
)))
}
}
None => Err(Error::illegal_state(
"Unexpected `None` Pipe in RcShMemProvider! Missing post_fork()?".to_string(),
)),
}
}
/// After fork, wait for the parent to write to our pipe :)
fn await_parent_done(&mut self) -> Result<(), Error> {
Self::pipe_await(&mut self.parent_child_pipe)
}
/// After fork, inform the new child we're done
fn set_parent_done(&mut self) -> Result<(), Error> {
Self::pipe_set(&mut self.parent_child_pipe)
}
/// After fork, wait for the child to write to our pipe :)
fn await_child_done(&mut self) -> Result<(), Error> {
Self::pipe_await(&mut self.child_parent_pipe)
}
/// After fork, inform the new child we're done
fn set_child_done(&mut self) -> Result<(), Error> {
Self::pipe_set(&mut self.child_parent_pipe)
}
}
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
impl<SP> Default for RcShMemProvider<SP>
where
SP: ShMemProvider + Debug,
{
fn default() -> Self {
Self::new().unwrap()
}
}
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
impl<SP> RcShMemProvider<ServedShMemProvider<SP>>
where
SP: ShMemProvider + Debug,
{
/// Forward to `ServedShMemProvider::on_restart`
pub fn on_restart(&mut self) {
self.internal.borrow_mut().on_restart();
}
}
/// A Unix sharedmem implementation.
///
/// On Android, this is partially reused to wrap [`unix_shmem::ashmem::AshmemShMem`],
/// Although for an [`ServedShMemProvider`] using a unix domain socket
/// Is needed on top.
#[cfg(all(unix, feature = "std", not(target_os = "haiku")))]
pub mod unix_shmem {
#[cfg(doc)]
use crate::shmem::{ShMem, ShMemProvider};
/// Shared memory provider for Android, allocating and forwarding maps over unix domain sockets.
#[cfg(target_os = "android")]
pub type UnixShMemProvider = ashmem::AshmemShMemProvider;
/// Shared memory for Android
#[cfg(target_os = "android")]
pub type UnixShMem = ashmem::AshmemShMem;
/// Shared memory Provider for Unix
#[cfg(not(target_os = "android"))]
pub type UnixShMemProvider = default::CommonUnixShMemProvider;
/// Shared memory for Unix
#[cfg(not(target_os = "android"))]
pub type UnixShMem = default::CommonUnixShMem;
/// Mmap [`ShMem`] for Unix
#[cfg(not(target_os = "android"))]
pub use default::MmapShMem;
/// Mmap [`ShMemProvider`] for Unix
#[cfg(not(target_os = "android"))]
pub use default::MmapShMemProvider;
#[cfg(all(unix, feature = "std", not(target_os = "android")))]
mod default {
use alloc::string::ToString;
use core::{ptr, slice};
use std::{io::Write, process};
use libc::{
c_int, c_uchar, close, ftruncate, mmap, munmap, shm_open, shm_unlink, shmat, shmctl,
shmdt, shmget,
};
use crate::{
rands::{Rand, RandomSeed, StdRand},
shmem::{ShMem, ShMemId, ShMemProvider},
AsMutSlice, AsSlice, Error,
};
// This is macOS's limit
// https://stackoverflow.com/questions/38049068/osx-shm-open-returns-enametoolong
#[cfg(target_vendor = "apple")]
const MAX_MMAP_FILENAME_LEN: usize = 31;
#[cfg(not(target_vendor = "apple"))]
const MAX_MMAP_FILENAME_LEN: usize = 256;
/// Mmap-based The sharedmap impl for unix using [`shm_open`] and [`mmap`].
/// Default on `MacOS` and `iOS`, where we need a central point to unmap
/// shared mem segments for dubious Mach kernel reasons.
#[derive(Clone, Debug)]
pub struct MmapShMem {
/// The path of this shared memory segment.
/// None in case we didn't [`shm_open`] this ourselves, but someone sent us the FD.
filename_path: Option<[u8; MAX_MMAP_FILENAME_LEN]>,
/// The size of this map
map_size: usize,
/// The map ptr
map: *mut u8,
/// The shmem id, containing the file descriptor and size, to send over the wire
id: ShMemId,
/// The file descriptor of the shmem
shm_fd: c_int,
}
impl MmapShMem {
/// Create a new [`MmapShMem`]
pub fn new(map_size: usize, rand_id: u32) -> Result<Self, Error> {
unsafe {
let mut filename_path = [0_u8; MAX_MMAP_FILENAME_LEN];
write!(
&mut filename_path[..MAX_MMAP_FILENAME_LEN - 1],
"/libafl_{}_{}",
process::id(),
rand_id
)?;
/* create the shared memory segment as if it was a file */
let shm_fd = shm_open(
filename_path.as_ptr() as *const _,
libc::O_CREAT | libc::O_RDWR | libc::O_EXCL,
0o600,
);
if shm_fd == -1 {
return Err(Error::last_os_error(format!(
"Failed to shm_open map with id {filename_path:?}",
)));
}
/* configure the size of the shared memory segment */
if ftruncate(shm_fd, map_size.try_into()?) != 0 {
shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::last_os_error(format!(
"setup_shm(): ftruncate() failed for map with id {filename_path:?}",
)));
}
/* map the shared memory segment to the address space of the process */
let map = mmap(
ptr::null_mut(),
map_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
shm_fd,
0,
);
if map == libc::MAP_FAILED || map.is_null() {
close(shm_fd);
shm_unlink(filename_path.as_ptr() as *const _);
return Err(Error::last_os_error(format!(
"mmap() failed for map with id {filename_path:?}",
)));
}
Ok(Self {
filename_path: Some(filename_path),
map: map as *mut u8,
map_size,
shm_fd,
id: ShMemId::from_string(&format!("{shm_fd}")),
})
}
}
fn shmem_from_id_and_size(id: ShMemId, map_size: usize) -> Result<Self, Error> {
unsafe {
let shm_fd: i32 = id.to_string().parse().unwrap();
/* map the shared memory segment to the address space of the process */
let map = mmap(
ptr::null_mut(),
map_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
shm_fd,
0,
);
if map == libc::MAP_FAILED || map.is_null() {
close(shm_fd);
return Err(Error::last_os_error(format!(
"mmap() failed for map with fd {shm_fd:?}"
)));
}
Ok(Self {
filename_path: None,
map: map as *mut u8,
map_size,
shm_fd,
id: ShMemId::from_string(&format!("{shm_fd}")),
})
}
}
/// Get `filename_path`
#[must_use]
pub fn filename_path(&self) -> &Option<[u8; MAX_MMAP_FILENAME_LEN]> {
&self.filename_path
}
}
/// A [`ShMemProvider`] which uses [`shm_open`] and [`mmap`] to provide shared memory mappings.
#[cfg(unix)]
#[derive(Clone, Debug)]
pub struct MmapShMemProvider {
rand: StdRand,
}
unsafe impl Send for MmapShMemProvider {}
#[cfg(unix)]
impl Default for MmapShMemProvider {
fn default() -> Self {
Self::new().unwrap()
}
}
/// Implement [`ShMemProvider`] for [`MmapShMemProvider`].
#[cfg(unix)]
impl ShMemProvider for MmapShMemProvider {
type ShMem = MmapShMem;
fn new() -> Result<Self, Error> {
Ok(Self {
rand: StdRand::new(),
})
}
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error> {
let id = self.rand.next() as u32;
MmapShMem::new(map_size, id)
}
fn shmem_from_id_and_size(
&mut self,
id: ShMemId,
size: usize,
) -> Result<Self::ShMem, Error> {
MmapShMem::shmem_from_id_and_size(id, size)
}
}
impl ShMem for MmapShMem {
fn id(&self) -> ShMemId {
self.id
}
fn len(&self) -> usize {
self.map_size
}
}
impl AsSlice for MmapShMem {
type Entry = u8;
fn as_slice(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.map, self.map_size) }
}
}
impl AsMutSlice for MmapShMem {
type Entry = u8;
fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.map, self.map_size) }
}
}
impl Drop for MmapShMem {
fn drop(&mut self) {
unsafe {
assert!(
!self.map.is_null(),
"Map should never be null for MmapShMem (on Drop)"
);
munmap(self.map as *mut _, self.map_size);
self.map = ptr::null_mut();
assert!(
self.shm_fd != -1,
"FD should never be -1 for MmapShMem (on Drop)"
);
// None in case we didn't [`shm_open`] this ourselves, but someone sent us the FD.
if let Some(filename_path) = self.filename_path {
shm_unlink(filename_path.as_ptr() as *const _);
}
}
}
}
/// The default sharedmap impl for unix using shmctl & shmget
#[derive(Clone, Debug)]
pub struct CommonUnixShMem {
id: ShMemId,
map: *mut u8,
map_size: usize,
}
impl CommonUnixShMem {
/// Create a new shared memory mapping, using shmget/shmat
#[allow(unused_qualifications)]
pub fn new(map_size: usize) -> Result<Self, Error> {
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
const SHM_R: libc::c_int = 0o400;
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
const SHM_R: libc::c_int = libc::SHM_R;
#[cfg(any(target_os = "solaris", target_os = "illumos"))]
const SHM_W: libc::c_int = 0o200;
#[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
const SHM_W: libc::c_int = libc::SHM_W;
unsafe {
let os_id = shmget(
libc::IPC_PRIVATE,
map_size,
libc::IPC_CREAT | libc::IPC_EXCL | SHM_R | SHM_W,
);
if os_id < 0_i32 {
return Err(Error::unknown(format!("Failed to allocate a shared mapping of size {map_size} - check OS limits (i.e shmall, shmmax)")));
}
let map = shmat(os_id, ptr::null(), 0) as *mut c_uchar;
if map as c_int == -1 || map.is_null() {
return Err(Error::last_os_error("Failed to map the shared mapping"));
}
Ok(Self {
id: ShMemId::from_int(os_id),
map,
map_size,
})
}
}
/// Get a [`UnixShMem`] of the existing shared memory mapping identified by id
pub fn shmem_from_id_and_size(id: ShMemId, map_size: usize) -> Result<Self, Error> {
unsafe {
let id_int: i32 = id.into();
let map = shmat(id_int, ptr::null(), 0) as *mut c_uchar;
if map.is_null() || map == ptr::null_mut::<c_uchar>().wrapping_sub(1) {
return Err(Error::last_os_error(format!(
"Failed to map the shared mapping with id {id_int}"
)));
}
Ok(Self { id, map, map_size })
}
}
}
#[cfg(unix)]
impl ShMem for CommonUnixShMem {
fn id(&self) -> ShMemId {
self.id
}
fn len(&self) -> usize {
self.map_size
}
}
impl AsSlice for CommonUnixShMem {
type Entry = u8;
fn as_slice(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.map, self.map_size) }
}
}
impl AsMutSlice for CommonUnixShMem {
type Entry = u8;
fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.map, self.map_size) }
}
}
/// [`Drop`] implementation for [`UnixShMem`], which detaches the memory and cleans up the mapping.
#[cfg(unix)]
impl Drop for CommonUnixShMem {
fn drop(&mut self) {
unsafe {
let id_int: i32 = self.id.into();
shmctl(id_int, libc::IPC_RMID, ptr::null_mut());
shmdt(self.map as *mut _);
}
}
}
/// A [`ShMemProvider`] which uses `shmget`/`shmat`/`shmctl` to provide shared memory mappings.
#[cfg(unix)]
#[derive(Clone, Debug)]
pub struct CommonUnixShMemProvider {}
unsafe impl Send for CommonUnixShMemProvider {}
#[cfg(unix)]
impl Default for CommonUnixShMemProvider {
fn default() -> Self {
Self::new().unwrap()
}
}
/// Implement [`ShMemProvider`] for [`UnixShMemProvider`].
#[cfg(unix)]
impl ShMemProvider for CommonUnixShMemProvider {
type ShMem = CommonUnixShMem;
fn new() -> Result<Self, Error> {
Ok(Self {})
}
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error> {
CommonUnixShMem::new(map_size)
}
fn shmem_from_id_and_size(
&mut self,
id: ShMemId,
size: usize,
) -> Result<Self::ShMem, Error> {
CommonUnixShMem::shmem_from_id_and_size(id, size)
}
}
}
/// Module containing `ashmem` shared memory support, commonly used on Android.
#[cfg(all(unix, feature = "std"))]
pub mod ashmem {
use alloc::string::ToString;
use core::{ptr, slice};
use std::ffi::CString;
use libc::{
c_uint, c_ulong, c_void, close, ioctl, mmap, open, MAP_SHARED, O_RDWR, PROT_READ,
PROT_WRITE,
};
use crate::{
shmem::{ShMem, ShMemId, ShMemProvider},
AsMutSlice, AsSlice, Error,
};
/// An ashmem based impl for linux/android
#[cfg(unix)]
#[derive(Clone, Debug)]
pub struct AshmemShMem {
id: ShMemId,
map: *mut u8,
map_size: usize,
}
#[derive(Copy, Clone)]
#[repr(C)]
struct ashmem_pin {
pub offset: c_uint,
pub len: c_uint,
}
const ASHMEM_GET_SIZE: c_ulong = 0x00007704;
const ASHMEM_UNPIN: c_ulong = 0x40087708;
//const ASHMEM_SET_NAME: c_long = 0x41007701;
const ASHMEM_SET_SIZE: c_ulong = 0x40087703;
impl AshmemShMem {
/// Create a new shared memory mapping, using shmget/shmat
pub fn new(map_size: usize) -> Result<Self, Error> {
unsafe {
let device_path = CString::new(
if let Ok(boot_id) =
std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
{
let path_str = format!("/dev/ashmem{boot_id}").trim().to_string();
if std::path::Path::new(&path_str).exists() {
path_str
} else {
"/dev/ashmem".to_string()
}
} else {
"/dev/ashmem".to_string()
},
)
.unwrap();
let fd = open(device_path.as_ptr(), O_RDWR);
if fd == -1 {
return Err(Error::unknown(format!(
"Failed to open the ashmem device at {device_path:?}"
)));
}
//if ioctl(fd, ASHMEM_SET_NAME, name) != 0 {
//close(fd);
//return Err(Error::unknown("Failed to set the ashmem mapping's name".to_string()));
//};
#[allow(trivial_numeric_casts)]
if ioctl(fd, ASHMEM_SET_SIZE as _, map_size) != 0 {
close(fd);
return Err(Error::unknown(
"Failed to set the ashmem mapping's size".to_string(),
));
};
let map = mmap(
ptr::null_mut(),
map_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
0,
);
if map == usize::MAX as *mut c_void {
close(fd);
return Err(Error::unknown(
"Failed to map the ashmem mapping".to_string(),
));
}
Ok(Self {
id: ShMemId::from_string(&format!("{fd}")),
map: map as *mut u8,
map_size,
})
}
}
/// Get a [`crate::shmem::unix_shmem::UnixShMem`] of the existing [`ShMem`] mapping identified by id.
pub fn shmem_from_id_and_size(id: ShMemId, map_size: usize) -> Result<Self, Error> {
unsafe {
let fd: i32 = id.to_string().parse().unwrap();
#[allow(trivial_numeric_casts, clippy::cast_sign_loss)]
if ioctl(fd, ASHMEM_GET_SIZE as _) as u32 as usize != map_size {
return Err(Error::unknown(
"The mapping's size differs from the requested size".to_string(),
));
};
let map = mmap(
ptr::null_mut(),
map_size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
0,
);
if map == usize::MAX as *mut c_void {
close(fd);
return Err(Error::unknown(
"Failed to map the ashmem mapping".to_string(),
));
}
Ok(Self {
id,
map: map as *mut u8,
map_size,
})
}
}
}
#[cfg(unix)]
impl ShMem for AshmemShMem {
fn id(&self) -> ShMemId {
self.id
}
fn len(&self) -> usize {
self.map_size
}
}
impl AsSlice for AshmemShMem {
type Entry = u8;
fn as_slice(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.map, self.map_size) }
}
}
impl AsMutSlice for AshmemShMem {
type Entry = u8;
fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.map, self.map_size) }
}
}
/// [`Drop`] implementation for [`AshmemShMem`], which cleans up the mapping.
#[cfg(unix)]
impl Drop for AshmemShMem {
#[allow(trivial_numeric_casts)]
fn drop(&mut self) {
unsafe {
let fd: i32 = self.id.to_string().parse().unwrap();
#[allow(trivial_numeric_casts)]
#[allow(clippy::cast_sign_loss)]
let length = ioctl(fd, ASHMEM_GET_SIZE as _) as u32;
let ap = ashmem_pin {
offset: 0,
len: length,
};
ioctl(fd, ASHMEM_UNPIN as _, &ap);
close(fd);
}
}
}
/// A [`ShMemProvider`] which uses ashmem to provide shared memory mappings.
#[cfg(unix)]
#[derive(Clone, Debug)]
pub struct AshmemShMemProvider {}
unsafe impl Send for AshmemShMemProvider {}
#[cfg(unix)]
impl Default for AshmemShMemProvider {
fn default() -> Self {
Self::new().unwrap()
}
}
/// Implement [`ShMemProvider`] for [`AshmemShMemProvider`], for the Android `ShMem`.
#[cfg(unix)]
impl ShMemProvider for AshmemShMemProvider {
type ShMem = AshmemShMem;
fn new() -> Result<Self, Error> {
Ok(Self {})
}
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error> {
let mapping = AshmemShMem::new(map_size)?;
Ok(mapping)
}
fn shmem_from_id_and_size(
&mut self,
id: ShMemId,
size: usize,
) -> Result<Self::ShMem, Error> {
AshmemShMem::shmem_from_id_and_size(id, size)
}
}
}
}
/// Then `win32` implementation for shared memory.
#[cfg(all(feature = "std", windows))]
pub mod win32_shmem {
use alloc::string::String;
use core::{
ffi::c_void,
fmt::{self, Debug, Formatter},
slice,
};
use uuid::Uuid;
use crate::{
shmem::{ShMem, ShMemId, ShMemProvider},
AsMutSlice, AsSlice, Error,
};
const INVALID_HANDLE_VALUE: isize = -1;
use windows::{
core::PCSTR,
Win32::{
Foundation::{CloseHandle, BOOL, HANDLE},
System::Memory::{
CreateFileMappingA, MapViewOfFile, OpenFileMappingA, UnmapViewOfFile,
FILE_MAP_ALL_ACCESS, MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READWRITE,
},
},
};
/// The default [`ShMem`] impl for Windows using `shmctl` & `shmget`
#[derive(Clone)]
pub struct Win32ShMem {
id: ShMemId,
handle: HANDLE,
map: *mut u8,
map_size: usize,
}
impl Debug for Win32ShMem {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Win32ShMem")
.field("id", &self.id)
.field("handle", &self.handle.0)
.field("map", &self.map)
.field("map_size", &self.map_size)
.finish()
}
}
impl Win32ShMem {
fn new_shmem(map_size: usize) -> Result<Self, Error> {
unsafe {
let uuid = Uuid::new_v4();
let mut map_str = format!("libafl_{}", uuid.simple());
let map_str_bytes = map_str.as_mut_vec();
map_str_bytes[19] = 0; // Trucate to size 20
let handle = CreateFileMappingA(
HANDLE(INVALID_HANDLE_VALUE),
None,
PAGE_READWRITE,
0,
map_size as u32,
PCSTR(map_str_bytes.as_mut_ptr()),
)?;
let map =
MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, map_size).Value as *mut u8;
if map.is_null() {
return Err(Error::unknown(format!(
"Cannot map shared memory {}",
String::from_utf8_lossy(map_str_bytes)
)));
}
Ok(Self {
id: ShMemId::try_from_slice(map_str_bytes).unwrap(),
handle,
map,
map_size,
})
}
}
fn shmem_from_id_and_size(id: ShMemId, map_size: usize) -> Result<Self, Error> {
unsafe {
let map_str_bytes = id.id;
// Unlike MapViewOfFile this one needs u32
let handle = OpenFileMappingA(
FILE_MAP_ALL_ACCESS.0,
BOOL(0),
PCSTR(map_str_bytes.as_ptr() as *mut _),
)?;
let map =
MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, map_size).Value as *mut u8;
if map.is_null() {
return Err(Error::unknown(format!(
"Cannot map shared memory {}",
String::from_utf8_lossy(&map_str_bytes)
)));
}
Ok(Self {
id,
handle,
map,
map_size,
})
}
}
}
impl ShMem for Win32ShMem {
fn id(&self) -> ShMemId {
self.id
}
fn len(&self) -> usize {
self.map_size
}
}
impl AsSlice for Win32ShMem {
type Entry = u8;
fn as_slice(&self) -> &[u8] {
unsafe { slice::from_raw_parts(self.map, self.map_size) }
}
}
impl AsMutSlice for Win32ShMem {
type Entry = u8;
fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe { slice::from_raw_parts_mut(self.map, self.map_size) }
}
}
/// Deinit sharedmaps on [`Drop`]
impl Drop for Win32ShMem {
fn drop(&mut self) {
unsafe {
let res = UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
Value: self.map as *mut c_void,
});
if let Err(err) = res {
// ignore result: nothing we can do if this goes wrong..
log::warn!("Failed to unmap memory at {:?}: {err}", self.map);
}
let res = CloseHandle(self.handle);
if let Err(err) = res {
// ignore result: nothing we can do if this goes wrong..
log::warn!("Failed to close mem handle {:?}: {err}", self.handle);
}
}
}
}
/// A [`ShMemProvider`] which uses `win32` functions to provide shared memory mappings.
#[derive(Clone, Debug)]
pub struct Win32ShMemProvider {}
impl Default for Win32ShMemProvider {
fn default() -> Self {
Self::new().unwrap()
}
}
/// Implement [`ShMemProvider`] for [`Win32ShMemProvider`]
impl ShMemProvider for Win32ShMemProvider {
type ShMem = Win32ShMem;
fn new() -> Result<Self, Error> {
Ok(Self {})
}
fn new_shmem(&mut self, map_size: usize) -> Result<Self::ShMem, Error> {
Win32ShMem::new_shmem(map_size)
}
fn shmem_from_id_and_size(
&mut self,
id: ShMemId,
size: usize,
) -> Result<Self::ShMem, Error> {
Win32ShMem::shmem_from_id_and_size(id, size)
}
}
}
/// A `ShMemService` dummy, that does nothing on start.
/// Drop in for targets that don't need a server for ref counting and page creation.
#[derive(Debug)]
pub struct DummyShMemService;
impl DummyShMemService {
/// Create a new [`DummyShMemService`] that does nothing.
/// Useful only to have the same API for [`StdShMemService`] on Operating Systems that don't need it.
#[inline]
pub fn start() -> Result<Self, Error> {
Ok(Self {})
}
}
/// A cursor around [`ShMem`] that immitates [`std::io::Cursor`]. Notably, this implements [`Write`] for [`ShMem`] in std environments.
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct ShMemCursor<T: ShMem> {
inner: T,
pos: usize,
}
#[cfg(all(feature = "std", not(target_os = "haiku")))]
impl<T: ShMem> ShMemCursor<T> {
/// Create a new [`ShMemCursor`] around [`ShMem`]
pub fn new(shmem: T) -> Self {
Self {
inner: shmem,
pos: 0,
}
}
/// Slice from the current location on this map to the end, mutable
fn empty_slice_mut(&mut self) -> &mut [u8] {
&mut (self.inner.as_mut_slice()[self.pos..])
}
}
#[cfg(all(feature = "std", not(target_os = "haiku")))]
impl<T: ShMem> Write for ShMemCursor<T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self.empty_slice_mut().write(buf) {
Ok(w) => {
self.pos += w;
Ok(w)
}
Err(e) => Err(e),
}
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
match self.empty_slice_mut().write_vectored(bufs) {
Ok(w) => {
self.pos += w;
Ok(w)
}
Err(e) => Err(e),
}
}
fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
match self.empty_slice_mut().write_all(buf) {
Ok(w) => {
self.pos += buf.len();
Ok(w)
}
Err(e) => Err(e),
}
}
}
#[cfg(feature = "std")]
impl<T: ShMem> std::io::Seek for ShMemCursor<T> {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
let effective_new_pos = match pos {
std::io::SeekFrom::Start(s) => s,
std::io::SeekFrom::End(offset) => {
let map_len = self.inner.as_slice().len();
let signed_pos = i64::try_from(map_len).unwrap();
let effective = signed_pos.checked_add(offset).unwrap();
assert!(effective >= 0);
effective.try_into().unwrap()
}
std::io::SeekFrom::Current(offset) => {
let current_pos = self.pos;
i64::try_from(current_pos).unwrap();
let signed_pos = i64::try_from(current_pos).unwrap();
let effective = signed_pos.checked_add(offset).unwrap();
assert!(effective >= 0);
effective.try_into().unwrap()
}
};
usize::try_from(effective_new_pos).unwrap();
self.pos = effective_new_pos as usize;
Ok(effective_new_pos)
}
}
#[cfg(all(feature = "std", not(target_os = "haiku")))]
#[cfg(test)]
mod tests {
use serial_test::serial;
use crate::{
shmem::{ShMemProvider, StdShMemProvider},
AsMutSlice, AsSlice,
};
#[test]
#[serial]
#[cfg_attr(miri, ignore)]
fn test_shmem_service() {
let mut provider = StdShMemProvider::new().unwrap();
let mut map = provider.new_shmem(1024).unwrap();
map.as_mut_slice()[0] = 1;
assert!(map.as_slice()[0] == 1);
}
}