0

I am trying to write a simle rust console application that calls into WINAPI.

I will ommit the obvious use and extern crate parts of my code. Here it is:

fn win32_string(value : &str ) -> Vec<u16> {
    OsStr::new( value ).encode_wide().chain( once( 0 ) ).collect()
}

fn main() {
    println!("=====  Rust Windows experiment #1  =====");

    let module_name = win32_string("ntdll.dll");

    let h_instance: HMODULE;

    unsafe {
        h_instance = GetModuleHandleW(module_name.as_ptr());
    }

    println!("Value of h_instance: {:#?}", h_instance);
}

I am building it against the target triple:

[build]
target = "i686-pc-windows-msvc"

As you can see I am targeting to build a 32 bit application. Now the output of my program is the following:

=====  Rust Windows experiment #1  =====
Value of h_instance: 0x00007ffb61c40000

It is showing a 64 bit address. How can this happen? Am I writing the HMODULE value wrongly to the console, or what am I doing wrong?

geo10
  • 366
  • 2
  • 11
  • Are you sure your configuration is working ok? Can you confirm that the compiled EXE is actually a Win32 module and not a Win64? – rodrigo Jul 02 '20 at 13:14
  • you are actually right, the output seems to be a 64 bit exe. How can I tell the rust to build a 32 bit application then? Also, after every run of the progam, the same value is being written out. Is this because ntdll.dll gets mapped everytime to the same virtual address of the application? Thanks – geo10 Jul 02 '20 at 13:23
  • 1
    A `.cargo\config` file as you noted should work, but maybe there is a typo somewhere (`config.txt`, maybe?). You can try doing it explicitly with `cargo build --target i686-pc-windows-msvc`. About `ntdll.dll` being on the same virtual address, I think it is expected: since system libraries are preloaded their addresses are always available so they aren't even relocatable. Or that used to be before ASLR... – rodrigo Jul 02 '20 at 13:35
  • 1
    ...but take a look at https://stackoverflow.com/a/3665046/865874 – rodrigo Jul 02 '20 at 13:37
  • thanks. you shed light on the issue. I have added the build tag to my cargo.toml instead of the cargo\config file. I have added the cargo\config and now it compiles correctly to 32 bit: Value of h_instance: 0x76fc0000 – geo10 Jul 02 '20 at 14:59
  • 1
    Oh, I've been there ;-), Cargo files can be confusing at first. You fixed it, then go ahead and [answer your own question](https://stackoverflow.com/help/self-answer)! – rodrigo Jul 02 '20 at 15:31

1 Answers1

0

With help from rodrigo: The build tag is supposed to be included in the .cargo\config file instead of the cargo.toml file, in order for the compiler to pick it up. :) After changing that the issue is now fixed. :)

geo10
  • 366
  • 2
  • 11