GithubHelp home page GithubHelp logo

Unwrap causing panic about visa-rs HOT 16 OPEN

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024
Unwrap causing panic

from visa-rs.

Comments (16)

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

I should say I am willing to do work in order to fix this. I have a workaround currently working. there are 2 problems:

  • In wrap_raw_error_in_unsafe any status code greater than 0 is considered Success but 0xBFFF0011 is not a success condition.
  • the repr for ErrorCode fails to translate 0xBFFF0011 into a valid variant even though it is valid.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

Thanks for your response, I will check this problem ASAP.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

On my PC, it returns the Error ErrorRsrcNfound (error code 0xBFFF0011) as expected, this problem might be related to your specific environment.
0xBFFF0011 is a negative number, so it should match the Error arm in the macro.
Here are codes that I tried.

use std::ffi::CString;

use visa_rs::{prelude::*, vs::ViStatus};

fn main() -> visa_rs::Result<()> {
    let res = CString::new("TCPIP0::192.168.3.1::hislip0::INSTR")
        .unwrap()
        .into();
    let r = DefaultRM::new()?.open(&res, AccessMode::NO_LOCK, TIMEOUT_IMMEDIATE);
    if let Result::Err(e) = r {
        eprintln!("Returned error in rust: `{}`", e);
        eprintln!("Error code: `{:#0X}`", e.0 as ViStatus);
    }
    Ok(())
}

Output

Returned error in rust: `Insufficient location information or the device or resource is not present in the system.`
Error code: `0xBFFF0011`

Feel free to ask if you want more help.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

Sorry for not seeing this sooner, github decided to notify me today.

So I created a new rust project, added visa-rs as a dependency, and replaced the main.rs with the code you provided above and I get

thread 'main' panicked at /home/dev/.cargo/registry/src/index.crates.io-6f17d22bba15001f/visa-rs-0.6.1/s
rc/lib.rs:391:9:
called `Result::unwrap()` on an `Err` value: TryFromPrimitiveError { number: 3221159953 }

I do want to mention we are running this on various Linux distros, but I don't know why that would matter because I wrote a proc_macro library which generates code that converts numbers into enums and it works on every system we have tried. If you have any recommendations on where I should be looking to work in a better fix. I did look around but got lost in the macros and had to get back to other priorities.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

Are you doing some cross compilation?
Can you check the size of Error and the size of ViStatus?
The repr of the Error is a proc-macro, and might cause an error if you are doing some cross compilation. The proc-macro works by checking ths size of the target repr and a legal repr ident on current platform, like this.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

I'm assuming you want the result of std::mem::size_of on those and i get 8 for both.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

I'm assuming you want the result of std::mem::size_of on those and i get 8 for both.

Then the repr is not the problem, and the number should be legal for a 8-byte-wide enum, wierd.
Can you convert the ErrorCode::ErrorRsrcNfound to a number and check its value?

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

ErrorCode::ErrorRsrcNfound as i32 = 0xBFFF0011

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

Here is my current work around https://github.com/Devlyn-Nelson/visa-rs/tree/tempfix

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

On my platform the ViStatus is 4-byte-wide, but 0xBFFF0011 as an 8-byte-wide number doesn't start with 1 (BIN), so it's a positive number. I thought it would fill with 1 at the start bits but seems it doesn't.
Can you try these codes?

use std::ffi::CString;

use visa_rs::{
    prelude::*,
    session::AsRawSs,
    vs::{self, ViStatus},
};

fn main() -> visa_rs::Result<()> {
    let res = CString::new("TCPIP0::192.168.3.1::hislip0::INSTR").unwrap();
    let rm = DefaultRM::new()?;
    let mut instr: vs::ViSession = 0;
    let s: ViStatus = unsafe {
        vs::viOpen(
            rm.as_raw_ss(),
            res.as_ptr(),
            AccessMode::NO_LOCK.bits(),
            TIMEOUT_IMMEDIATE.as_millis() as _,
            &mut instr as _,
        )
    };
    println!("{},{},{:#0X}", s > 0, s, s);
    Ok(())
}

My output

false,-1073807343,0xBFFF0011

This would be ridiculous because comparing with 0 is used in NI-VISA official examples.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

My result:

true,3221159953,0xBFFF0011

I wouldn't be surprised if the NI stuff was not the greatest. I volunteer for an FRC, which makes heavy use of NI systems, and every year I have to deal with them makes my feelings about them more and more negative.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

A easy fix would be changing the condition in the 'wrap_raw_error_in_unsafe' from 's>=0' to 's>=0&&s<=i32::MAX as _'.
Can you check this solution?
I will update the crate if it works.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

It did not work, I'm playing around with the logic there to check if there is a simple why to avoid the unwraps. I think the macro's inherent ambiguity is making it a little tricky.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

So my friend, who has asked that I get this working for him, told me that he can't get this compiling on windows at all. But what confuses me is that you say you are receiving a i32 for ViStatus and my friend says it being a i32 is want causes the compile error. So I must ask if you are using windows because according to this that would make sense. But that doesn't explain why your machine doesn't get compile errors or panics and we get a panic or a compile error depending on the system. not sure if this is the entire problem but due to the type of ViStatus being ambiguous, I have to imagine either NI or the translation is messy.

from visa-rs.

Devlyn-Nelson avatar Devlyn-Nelson commented on July 23, 2024

I redact the windows not compiling. That was my fault in the temp fix i did.

from visa-rs.

TsuITOAR avatar TsuITOAR commented on July 23, 2024

Added some unwarp info to show which arm panicked.

#[doc(hidden)]
#[macro_export]
macro_rules! wrap_raw_error_in_unsafe {
    ($s:expr) => {
        match unsafe { $s } {
            state if state >= $crate::SUCCESS && state <= i32::MAX as _ => {
                $crate::Result::<$crate::enums::status::CompletionCode>::Ok(
                    state.try_into().expect(&format!(
                        "Converting `{state}({state:#0X})` to CompletionCode failed"
                    )),
                )
            }
            e => $crate::Result::<$crate::enums::status::CompletionCode>::Err(
                e.try_into()
                    .expect(&format!("Converting `{e}({e:#0X})` to ErrorCode failed")),
            ),
        }
    };
}

And some tests to confirm the behavior of converting status codes

use crate::enums::status::{CompletionCode, ErrorCode};
    use crate::vs;

    #[test]
    fn convert_status_codes() {
        assert_eq!(
            CompletionCode::try_from(0 as vs::ViStatus).unwrap(),
            CompletionCode::Success
        );
        assert_eq!(
            ErrorCode::try_from(0xBFFF0011u32 as vs::ViStatus).unwrap(),
            ErrorCode::ErrorRsrcNfound
        );
    }

    #[test]
    #[should_panic]
    fn convert_wrong_status1() {
        CompletionCode::try_from(ErrorCode::ErrorRsrcNfound as vs::ViStatus).unwrap();
    }
    #[test]
    #[should_panic]
    fn convert_wrong_status2() {
        ErrorCode::try_from(CompletionCode::Success as vs::ViStatus).unwrap();
    }

from visa-rs.

Related Issues (8)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.