]> git.lizzy.rs Git - rust.git/commitdiff
avoid using unchecked casts or arithmetic
authorRalf Jung <post@ralfj.de>
Tue, 17 Mar 2020 14:18:53 +0000 (15:18 +0100)
committerRalf Jung <post@ralfj.de>
Tue, 17 Mar 2020 14:21:43 +0000 (15:21 +0100)
14 files changed:
src/bin/miri.rs
src/eval.rs
src/helpers.rs
src/shims/dlsym.rs
src/shims/env.rs
src/shims/foreign_items.rs
src/shims/foreign_items/posix.rs
src/shims/foreign_items/posix/linux.rs
src/shims/foreign_items/posix/macos.rs
src/shims/foreign_items/windows.rs
src/shims/fs.rs
src/shims/intrinsics.rs
src/shims/mod.rs
src/shims/time.rs

index e40bfcf6276adcde031c8f485522277d25a90efd..4a54867c99640c4c5f75f690965405a19c63ae4a 100644 (file)
@@ -259,7 +259,6 @@ fn main() {
     rustc_driver::install_ice_hook();
     let result = rustc_driver::catch_fatal_errors(move || {
         rustc_driver::run_compiler(&rustc_args, &mut MiriCompilerCalls { miri_config }, None, None)
-    })
-    .and_then(|result| result);
+    });
     std::process::exit(result.is_err() as i32);
 }
index 2cf5a1dc444c2ab3c07f532629bbe6e1987b8ce4..64beff6eb77fe3ade2699e0db3802ddadfbd53a6 100644 (file)
@@ -1,6 +1,7 @@
 //! Main evaluator loop and setting up the initial stack frame.
 
 use std::ffi::OsStr;
+use std::convert::TryFrom;
 
 use rand::rngs::StdRng;
 use rand::SeedableRng;
@@ -101,14 +102,14 @@ pub fn create_ecx<'mir, 'tcx: 'mir>(
     // First argument: pointer to `main()`.
     let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
     // Second argument (argc): length of `config.args`.
-    let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
+    let argc = Scalar::from_uint(u64::try_from(config.args.len()).unwrap(), ecx.pointer_size());
     // Third argument (`argv`): created from `config.args`.
     let argv = {
         // Put each argument in memory, collect pointers.
         let mut argvs = Vec::<Scalar<Tag>>::new();
         for arg in config.args.iter() {
             // Make space for `0` terminator.
-            let size = arg.len() as u64 + 1;
+            let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
             let arg_type = tcx.mk_array(tcx.types.u8, size);
             let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
             ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
@@ -116,10 +117,10 @@ pub fn create_ecx<'mir, 'tcx: 'mir>(
         }
         // Make an array with all these pointers, in the Miri memory.
         let argvs_layout =
-            ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64))?;
+            ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
         let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
         for (idx, arg) in argvs.into_iter().enumerate() {
-            let place = ecx.mplace_field(argvs_place, idx as u64)?;
+            let place = ecx.mplace_field(argvs_place, u64::try_from(idx).unwrap())?;
             ecx.write_scalar(arg, place.into())?;
         }
         ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
@@ -153,13 +154,13 @@ pub fn create_ecx<'mir, 'tcx: 'mir>(
             cmd.push(std::char::from_u32(0).unwrap());
 
             let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
-            let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
+            let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
             let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
             ecx.machine.cmd_line = Some(cmd_place.ptr);
             // Store the UTF-16 string. We just allocated so we know the bounds are fine.
             let char_size = Size::from_bytes(2);
             for (idx, &c) in cmd_utf16.iter().enumerate() {
-                let place = ecx.mplace_field(cmd_place, idx as u64)?;
+                let place = ecx.mplace_field(cmd_place, u64::try_from(idx).unwrap())?;
                 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
             }
         }
index 5ff0a5671cdb5adf5d751a26614f85d3ccaad553..ecb3a5d8bce9c346fccd49daf983559e1ec60324 100644 (file)
@@ -1,5 +1,6 @@
 use std::ffi::OsStr;
 use std::{iter, mem};
+use std::convert::TryFrom;
 
 use rustc::mir;
 use rustc::ty::{
@@ -81,7 +82,7 @@ fn local_place(&mut self, local: mir::Local) -> InterpResult<'tcx, PlaceTy<'tcx,
     }
 
     /// Generate some random bytes, and write them to `dest`.
-    fn gen_random(&mut self, ptr: Scalar<Tag>, len: usize) -> InterpResult<'tcx> {
+    fn gen_random(&mut self, ptr: Scalar<Tag>, len: u64) -> InterpResult<'tcx> {
         // Some programs pass in a null pointer and a length of 0
         // to their platform's random-generation function (e.g. getrandom())
         // on Linux. For compatibility with these programs, we don't perform
@@ -92,7 +93,7 @@ fn gen_random(&mut self, ptr: Scalar<Tag>, len: usize) -> InterpResult<'tcx> {
         }
         let this = self.eval_context_mut();
 
-        let mut data = vec![0; len];
+        let mut data = vec![0; usize::try_from(len).unwrap()];
 
         if this.machine.communicate {
             // Fill the buffer using the host's rng.
@@ -499,7 +500,7 @@ fn os_str_to_bytes<'tcx, 'a>(os_str: &'a OsStr) -> InterpResult<'tcx, &'a [u8]>
         let bytes = os_str_to_bytes(os_str)?;
         // If `size` is smaller or equal than `bytes.len()`, writing `bytes` plus the required null
         // terminator to memory using the `ptr` pointer would cause an out-of-bounds access.
-        let string_length = bytes.len() as u64;
+        let string_length = u64::try_from(bytes.len()).unwrap();
         if size <= string_length {
             return Ok((false, string_length));
         }
@@ -514,7 +515,7 @@ fn alloc_os_str_as_c_str(
         os_str: &OsStr,
         memkind: MemoryKind<MiriMemoryKind>,
     ) -> Pointer<Tag> {
-        let size = os_str.len() as u64 + 1; // Make space for `0` terminator.
+        let size = u64::try_from(os_str.len()).unwrap().checked_add(1).unwrap(); // Make space for `0` terminator.
         let this = self.eval_context_mut();
 
         let arg_type = this.tcx.mk_array(this.tcx.types.u8, size);
index 0069f8cc80870c649db70e1f1fc80c6fc8e92123..9027a97cf54e438dcab0101d56f42aec90ffc72f 100644 (file)
@@ -37,7 +37,7 @@ fn call_dlsym(
             GetEntropy => {
                 let ptr = this.read_scalar(args[0])?.not_undef()?;
                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
-                this.gen_random(ptr, len as usize)?;
+                this.gen_random(ptr, len)?;
                 this.write_null(dest)?;
             }
         }
index 7c6b6c942e5e3aee470015f4726177aa441c65cd..da634c1aeb23742b68036687e8af0a7e9bb0ffda 100644 (file)
@@ -1,5 +1,6 @@
 use std::ffi::{OsString, OsStr};
 use std::env;
+use std::convert::TryFrom;
 
 use crate::stacked_borrows::Tag;
 use crate::rustc_target::abi::LayoutOf;
@@ -58,7 +59,7 @@ fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>
         Ok(match this.machine.env_vars.map.get(name) {
             // The offset is used to strip the "{name}=" part of the string.
             Some(var_ptr) => {
-                Scalar::from(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
+                Scalar::from(var_ptr.offset(Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), this)?)
             }
             None => Scalar::ptr_null(&*this.tcx),
         })
@@ -181,10 +182,10 @@ fn update_environ(&mut self) -> InterpResult<'tcx> {
         // Make an array with all these pointers inside Miri.
         let tcx = this.tcx;
         let vars_layout =
-            this.layout_of(tcx.mk_array(tcx.types.usize, vars.len() as u64))?;
+            this.layout_of(tcx.mk_array(tcx.types.usize, u64::try_from(vars.len()).unwrap()))?;
         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Machine.into());
         for (idx, var) in vars.into_iter().enumerate() {
-            let place = this.mplace_field(vars_place, idx as u64)?;
+            let place = this.mplace_field(vars_place, u64::try_from(idx).unwrap())?;
             this.write_scalar(var, place.into())?;
         }
         this.write_scalar(
index 0183757cff0ae269e002c8c200bb36c751d54f98..deabbdd6081933a22d5daad07a3a86f228f4634c 100644 (file)
@@ -1,7 +1,7 @@
 mod windows;
 mod posix;
 
-use std::{convert::TryInto, iter};
+use std::{convert::{TryInto, TryFrom}, iter};
 
 use rustc_hir::def_id::DefId;
 use rustc::mir;
@@ -250,7 +250,7 @@ fn emulate_foreign_item_by_name(
                     MiriMemoryKind::Rust.into(),
                 );
                 // We just allocated this, the access is definitely in-bounds.
-                this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize)).unwrap();
+                this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
                 this.write_scalar(ptr, dest)?;
             }
             "__rust_dealloc" => {
@@ -350,7 +350,7 @@ fn emulate_foreign_item_by_name(
             "strlen" => {
                 let ptr = this.read_scalar(args[0])?.not_undef()?;
                 let n = this.memory.read_c_str(ptr)?.len();
-                this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
+                this.write_scalar(Scalar::from_uint(u64::try_from(n).unwrap(), dest.layout.size), dest)?;
             }
 
             // math functions
@@ -440,9 +440,9 @@ fn emulate_foreign_item_by_name(
 
                 // Saturating cast to i16. Even those are outside the valid exponent range to
                 // `scalbn` below will do its over/underflow handling.
-                let exp = if exp > i16::MAX as i32 {
+                let exp = if exp > i32::from(i16::MAX) {
                     i16::MAX
-                } else if exp < i16::MIN as i32 {
+                } else if exp < i32::from(i16::MIN) {
                     i16::MIN
                 } else {
                     exp.try_into().unwrap()
index e80908d8fa09fba6fe985c4b58ae043f23a10420..f73ec288284abd96e02352fab86b06da02048f39 100644 (file)
@@ -1,6 +1,8 @@
 mod linux;
 mod macos;
 
+use std::convert::TryFrom;
+
 use crate::*;
 use rustc::mir;
 use rustc::ty::layout::{Align, LayoutOf, Size};
@@ -84,7 +86,7 @@ fn emulate_foreign_item_by_name(
                         io::stderr().write(buf_cont)
                     };
                     match res {
-                        Ok(n) => n as i64,
+                        Ok(n) => i64::try_from(n).unwrap(),
                         Err(_) => -1,
                     }
                 } else {
index 8a1ce5594ae46050a0c22e2b9ba34e60144c9ba6..023fee4ca7b1eef68bc37bed701bb41680e52751 100644 (file)
@@ -114,7 +114,7 @@ fn getrandom<'tcx>(
     // neither of which have any effect on our current PRNG.
     let _flags = this.read_scalar(args[2])?.to_i32()?;
 
-    this.gen_random(ptr, len as usize)?;
+    this.gen_random(ptr, len)?;
     this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
     Ok(())
 }
index 0d067cc04138a6015b2ed7dc4fb10d54c913052a..34661fb2383c308ca29fa270338efcb290619904 100644 (file)
@@ -97,7 +97,7 @@ fn emulate_foreign_item_by_name(
             "SecRandomCopyBytes" => {
                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
                 let ptr = this.read_scalar(args[2])?.not_undef()?;
-                this.gen_random(ptr, len as usize)?;
+                this.gen_random(ptr, len)?;
                 this.write_null(dest)?;
             }
 
index 623b0f307b911bd05a676c29bf838e28aecb49cd..306d2f7b0e37cd8bec96a82d8fa0450fe36a1bee 100644 (file)
@@ -165,12 +165,12 @@ fn emulate_foreign_item_by_name(
                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
             }
             "TlsGetValue" => {
-                let key = this.read_scalar(args[0])?.to_u32()? as u128;
+                let key = u128::from(this.read_scalar(args[0])?.to_u32()?);
                 let ptr = this.machine.tls.load_tls(key, tcx)?;
                 this.write_scalar(ptr, dest)?;
             }
             "TlsSetValue" => {
-                let key = this.read_scalar(args[0])?.to_u32()? as u128;
+                let key = u128::from(this.read_scalar(args[0])?.to_u32()?);
                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
 
@@ -197,7 +197,7 @@ fn emulate_foreign_item_by_name(
             "SystemFunction036" => {
                 let ptr = this.read_scalar(args[0])?.not_undef()?;
                 let len = this.read_scalar(args[1])?.to_u32()?;
-                this.gen_random(ptr, len as usize)?;
+                this.gen_random(ptr, len.into())?;
                 this.write_scalar(Scalar::from_bool(true), dest)?;
             }
             // We don't support threading.
index 0ea53b16fd191132e910df53516b11529b0d32e2..7c755143f2e81407bdbce5d43b74ff58b03f0d36 100644 (file)
@@ -10,7 +10,7 @@
 
 use crate::stacked_borrows::Tag;
 use crate::*;
-use helpers::immty_from_uint_checked;
+use helpers::{immty_from_int_checked, immty_from_uint_checked};
 use shims::time::system_time_to_duration;
 
 #[derive(Debug)]
@@ -56,7 +56,7 @@ fn insert_fd_with_min_fd(&mut self, file_handle: FileHandle, min_fd: i32) -> i32
         let new_fd = candidate_new_fd.unwrap_or_else(|| {
             // find_map ran out of BTreeMap entries before finding a free fd, use one plus the
             // maximum fd in the map
-            self.handles.last_entry().map(|entry| entry.key() + 1).unwrap_or(min_fd)
+            self.handles.last_entry().map(|entry| entry.key().checked_add(1).unwrap()).unwrap_or(min_fd)
         });
 
         self.handles.insert(new_fd, file_handle).unwrap_none();
@@ -167,11 +167,11 @@ fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> Inter
         match file_type {
             Ok(file_type) => {
                 if file_type.is_dir() {
-                    Ok(this.eval_libc("DT_DIR")?.to_u8()? as i32)
+                    Ok(this.eval_libc("DT_DIR")?.to_u8()?.into())
                 } else if file_type.is_file() {
-                    Ok(this.eval_libc("DT_REG")?.to_u8()? as i32)
+                    Ok(this.eval_libc("DT_REG")?.to_u8()?.into())
                 } else if file_type.is_symlink() {
-                    Ok(this.eval_libc("DT_LNK")?.to_u8()? as i32)
+                    Ok(this.eval_libc("DT_LNK")?.to_u8()?.into())
                 } else {
                     // Certain file types are only supported when the host is a Unix system.
                     // (i.e. devices and sockets) If it is, check those cases, if not, fall back to
@@ -181,19 +181,19 @@ fn file_type_to_d_type(&mut self, file_type: std::io::Result<FileType>) -> Inter
                     {
                         use std::os::unix::fs::FileTypeExt;
                         if file_type.is_block_device() {
-                            Ok(this.eval_libc("DT_BLK")?.to_u8()? as i32)
+                            Ok(this.eval_libc("DT_BLK")?.to_u8()?.into())
                         } else if file_type.is_char_device() {
-                            Ok(this.eval_libc("DT_CHR")?.to_u8()? as i32)
+                            Ok(this.eval_libc("DT_CHR")?.to_u8()?.into())
                         } else if file_type.is_fifo() {
-                            Ok(this.eval_libc("DT_FIFO")?.to_u8()? as i32)
+                            Ok(this.eval_libc("DT_FIFO")?.to_u8()?.into())
                         } else if file_type.is_socket() {
-                            Ok(this.eval_libc("DT_SOCK")?.to_u8()? as i32)
+                            Ok(this.eval_libc("DT_SOCK")?.to_u8()?.into())
                         } else {
-                            Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()? as i32)
+                            Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
                         }
                     }
                     #[cfg(not(unix))]
-                    Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()? as i32)
+                    Ok(this.eval_libc("DT_UNKNOWN")?.to_u8()?.into())
                 }
             }
             Err(e) => return match e.raw_os_error() {
@@ -507,7 +507,7 @@ fn lseek64(
         let whence = this.read_scalar(whence_op)?.to_i32()?;
 
         let seek_from = if whence == this.eval_libc_i32("SEEK_SET")? {
-            SeekFrom::Start(offset as u64)
+            SeekFrom::Start(u64::try_from(offset).unwrap())
         } else if whence == this.eval_libc_i32("SEEK_CUR")? {
             SeekFrom::Current(offset)
         } else if whence == this.eval_libc_i32("SEEK_END")? {
@@ -519,7 +519,7 @@ fn lseek64(
         };
 
         if let Some(FileHandle { file, writable: _ }) = this.machine.file_handler.handles.get_mut(&fd) {
-            let result = file.seek(seek_from).map(|offset| offset as i64);
+            let result = file.seek(seek_from).map(|offset| i64::try_from(offset).unwrap());
             this.try_unwrap_io_result(result)
         } else {
             this.handle_not_found()
@@ -810,7 +810,7 @@ fn mkdir(
         this.check_no_isolation("mkdir")?;
 
         let _mode = if this.tcx.sess.target.target.target_os.as_str() == "macos" {
-            this.read_scalar(mode_op)?.not_undef()?.to_u16()? as u32
+            u32::from(this.read_scalar(mode_op)?.not_undef()?.to_u16()?)
         } else {
             this.read_scalar(mode_op)?.to_u32()?
         };
@@ -929,13 +929,13 @@ fn linux_readdir64_r(
                 #[cfg(not(unix))]
                 let ino = 0u64;
 
-                let file_type = this.file_type_to_d_type(dir_entry.file_type())? as u128;
+                let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
 
                 let imms = [
                     immty_from_uint_checked(ino, ino64_t_layout)?, // d_ino
                     immty_from_uint_checked(0u128, off64_t_layout)?, // d_off
                     immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
-                    immty_from_uint_checked(file_type, c_uchar_layout)?, // d_type
+                    immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
                 ];
                 this.write_packed_immediates(entry_place, &imms)?;
 
@@ -1017,14 +1017,14 @@ fn macos_readdir_r(
                 #[cfg(not(unix))]
                 let ino = 0u64;
 
-                let file_type = this.file_type_to_d_type(dir_entry.file_type())? as u128;
+                let file_type = this.file_type_to_d_type(dir_entry.file_type())?;
 
                 let imms = [
                     immty_from_uint_checked(ino, ino_t_layout)?, // d_ino
                     immty_from_uint_checked(0u128, off_t_layout)?, // d_seekoff
                     immty_from_uint_checked(0u128, c_ushort_layout)?, // d_reclen
                     immty_from_uint_checked(file_name_len, c_ushort_layout)?, // d_namlen
-                    immty_from_uint_checked(file_type, c_uchar_layout)?, // d_type
+                    immty_from_int_checked(file_type, c_uchar_layout)?, // d_type
                 ];
                 this.write_packed_immediates(entry_place, &imms)?;
 
index b91af778d9791b755bad3607659ae886c4915704..6837d45158d9774463fe710e991aa6f47963bc80 100644 (file)
@@ -1,4 +1,5 @@
 use std::iter;
+use std::convert::TryFrom;
 
 use rustc::mir;
 use rustc::mir::interpret::{InterpResult, PointerArithmetic};
@@ -48,7 +49,7 @@ fn call_intrinsic(
                 let ptr = this.read_scalar(args[0])?.not_undef()?;
 
                 let pointee_ty = substs.type_at(0);
-                let pointee_size = this.layout_of(pointee_ty)?.size.bytes() as i64;
+                let pointee_size = i64::try_from(this.layout_of(pointee_ty)?.size.bytes()).unwrap();
                 let offset = offset.overflowing_mul(pointee_size).0;
                 let result_ptr = ptr.ptr_wrapping_signed_offset(offset, this);
                 this.write_scalar(result_ptr, dest)?;
@@ -229,7 +230,7 @@ fn call_intrinsic(
                 let count = this.read_scalar(args[2])?.to_machine_usize(this)?;
                 let elem_align = elem_layout.align.abi;
 
-                let size = Size::from_bytes(count * elem_size);
+                let size = Size::from_bytes(count) * elem_size;
                 let src = this.read_scalar(args[0])?.not_undef()?;
                 let src = this.memory.check_ptr_access(src, size, elem_align)?;
                 let dest = this.read_scalar(args[1])?.not_undef()?;
@@ -419,7 +420,7 @@ fn call_intrinsic(
                 let layout = this.layout_of(ty)?;
                 let align = layout.align.pref.bytes();
                 let ptr_size = this.pointer_size();
-                let align_val = Scalar::from_uint(align as u128, ptr_size);
+                let align_val = Scalar::from_uint(align, ptr_size);
                 this.write_scalar(align_val, dest)?;
             }
 
@@ -502,7 +503,7 @@ fn call_intrinsic(
                     .size_and_align_of_mplace(mplace)?
                     .expect("size_of_val called on extern type");
                 let ptr_size = this.pointer_size();
-                this.write_scalar(Scalar::from_uint(size.bytes() as u128, ptr_size), dest)?;
+                this.write_scalar(Scalar::from_uint(size.bytes(), ptr_size), dest)?;
             }
 
             #[rustfmt::skip]
index 6adf01385855004b4477839ede404f531ea0203b..d9e4d226ecc9a6d428751be0f3b08baf3c3f71e1 100644 (file)
@@ -7,9 +7,12 @@
 pub mod time;
 pub mod tls;
 
-use crate::*;
+use std::convert::TryFrom;
+
 use rustc::{mir, ty};
 
+use crate::*;
+
 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
     fn find_mir_or_eval_fn(
@@ -54,8 +57,7 @@ fn align_offset(
         let (dest, ret) = ret.unwrap();
 
         let req_align = this
-            .force_bits(this.read_scalar(align_op)?.not_undef()?, this.pointer_size())?
-            as usize;
+            .force_bits(this.read_scalar(align_op)?.not_undef()?, this.pointer_size())?;
 
         // Stop if the alignment is not a power of two.
         if !req_align.is_power_of_two() {
@@ -69,12 +71,15 @@ fn align_offset(
         if let Ok(ptr) = this.force_ptr(ptr_scalar) {
             // Only do anything if we can identify the allocation this goes to.
             let cur_align =
-                this.memory.get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)?.1.bytes()
-                    as usize;
-            if cur_align >= req_align {
+                this.memory.get_size_and_align(ptr.alloc_id, AllocCheck::MaybeDead)?.1.bytes();
+            if u128::from(cur_align) >= req_align {
                 // If the allocation alignment is at least the required alignment we use the
-                // libcore implementation
-                result = (this.force_bits(ptr_scalar, this.pointer_size())? as *const i8).align_offset(req_align) as u128;
+                // libcore implementation.
+                // FIXME: is this correct in case of truncation?
+                result = u128::try_from(
+                    (this.force_bits(ptr_scalar, this.pointer_size())? as *const i8)
+                        .align_offset(usize::try_from(req_align).unwrap())
+                ).unwrap();
             }
         }
 
index 6adea524d2d88992a1cd1d5a9d48bd3d60652334..d761698e0d27807e17756e05eeb53389959031fe 100644 (file)
@@ -37,8 +37,8 @@ fn clock_gettime(
         let tp = this.deref_operand(tp_op)?;
 
         let duration = get_time()?;
-        let tv_sec = duration.as_secs() as i128;
-        let tv_nsec = duration.subsec_nanos() as i128;
+        let tv_sec = duration.as_secs();
+        let tv_nsec = duration.subsec_nanos();
 
         let imms = [
             immty_from_int_checked(tv_sec, this.libc_ty_layout("time_t")?)?,
@@ -69,8 +69,8 @@ fn gettimeofday(
         let tv = this.deref_operand(tv_op)?;
 
         let duration = get_time()?;
-        let tv_sec = duration.as_secs() as i128;
-        let tv_usec = duration.subsec_micros() as i128;
+        let tv_sec = duration.as_secs();
+        let tv_usec = duration.subsec_micros();
 
         let imms = [
             immty_from_int_checked(tv_sec, this.libc_ty_layout("time_t")?)?,