Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ICE: diagnostic::SpanHandler::span_bug - panic at Box<Any> #22713

Closed
mark3982 opened this issue Feb 23, 2015 · 6 comments
Closed

ICE: diagnostic::SpanHandler::span_bug - panic at Box<Any> #22713

mark3982 opened this issue Feb 23, 2015 · 6 comments
Labels
E-needs-test Call for participation: An issue has been fixed and does not reproduce, but no test has been added. I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️

Comments

@mark3982
Copy link

note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: http://doc.rust-lang.org/complement-bugreport.html
note: run with `RUST_BACKTRACE=1` for a backtrace
thread 'rustc' panicked at 'Box<Any>', /mnt/host/kmcg3413.net/rust/src/libsyntax/diagnostic.rs:129

stack backtrace:
   1:     0x7f8fc1df61c0 - sys::backtrace::write::h58461d7d0ee03fe821y
   2:     0x7f8fc1e1a5c0 - failure::on_fail::h983ff0e03bf1b1c6rcH
   3:     0x7f8fc1d78590 - rt::unwind::begin_unwind_inner::he58ce9282e8b04faMQG
   4:     0x7f8fbf14b7f0 - rt::unwind::begin_unwind::h2211373843863054340
   5:     0x7f8fbf14b780 - diagnostic::SpanHandler::span_bug::hf33669210284312an3E
   6:     0x7f8fbfc87d00 - session::Session::span_bug::hb08419bf656da62caHr
   7:     0x7f8fc0bd0bf0 - ast_util::walk_pat::walk_pat_::h12022859396464238272
   8:     0x7f8fc0aadb30 - trans::controlflow::trans_block::h8385ff59a33ae83fBde
   9:     0x7f8fc0b78ca0 - trans::base::trans_closure::h5aee682c389bb18e9du
  10:     0x7f8fc0a99300 - trans::base::trans_fn::hfef6be3a8a4134a4ppu
  11:     0x7f8fc0a94380 - trans::base::trans_item::h8b00b5f4ca3d68c1eOu
  12:     0x7f8fc0b80260 - trans::base::trans_crate::h599d9bfb3fe64a33yLv
  13:     0x7f8fc240b560 - driver::phase_4_translate_to_llvm::h7473c59213764f77wPa
  14:     0x7f8fc23e4610 - driver::compile_input::h89bfe02f11866383Eba
  15:     0x7f8fc24b5a10 - run_compiler::h08c73b096e0a052c5bc
  16:     0x7f8fc24b4070 - thunk::F.Invoke<A, R>::invoke::h6531393211258230256
  17:     0x7f8fc24b2f60 - rt::unwind::try::try_fn::h3599546013013709466
  18:     0x7f8fc1e86b10 - rust_try_inner
  19:     0x7f8fc1e86b00 - rust_try
  20:     0x7f8fc24b3210 - thunk::F.Invoke<A, R>::invoke::h10613949120532292059
  21:     0x7f8fc1e06ab0 - sys::thread::thread_start::hca42318cad6a03d0FQC
  22:     0x7f8fbbf64a80 - start_thread
  23:                0x0 - <unknown>
rustc 1.0.0-dev (e29f42025 2015-02-11 17:59:37 +0000)

The build is a little old. I am currently compiling the most recent from the repo, but I figured this might not have been solved yet. I will try with the newest version as soon as it is done building.

@mark3982
Copy link
Author

Forgot important part:

src/main.rs:201:9: 201:22 error: internal compiler error: debuginfo::create_local_var_metadata() - Referenced variable location is not an alloca!
             let activity_name = if xlibs.len() > 0 {
                 ^~~~~~~~~~~

@steveklabnik steveklabnik added the I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️ label Feb 23, 2015
@steveklabnik
Copy link
Member

Can you post the whole code?

@mark3982
Copy link
Author

#![feature(path, core, io, os, rustc_private)]

extern crate serialize;

use std::collections::HashMap;
use std::old_io::process::Command;
use std::old_io::{File, TempDir};
use std::old_io::fs;
use std::old_io::fs::PathExtensions;

fn main() {
    let (args, passthrough) = parse_arguments();

    // Find all the native shared libraries that exist in the target directory.
    let native_shared_libs = find_native_libs(&args);

    // getting the path from the ANDROID_HOME env
    let sdk_path = std::os::env().into_iter().find(|&(ref k, _)| k.as_slice() == "ANDROID_HOME")
        .map(|(_, v)| Path::new(v)).expect("Please set the ANDROID_HOME environment variable");

    // hardcoding ndk path
    let ndk_path = std::os::env().into_iter().find(|&(ref k, _)| k.as_slice() == "NDK_HOME")
        .map(|(_, v)| Path::new(v)).expect("Please set the NDK_HOME environment variable");

    // hardcoding ndk path
    let standalone_path = std::os::env().into_iter().find(|&(ref k, _)| k.as_slice() == "NDK_STANDALONE")
        .map(|(_, v)| Path::new(v)).unwrap_or(Path::new("/opt/ndk_standalone"));

    // creating the build directory that will contain all the necessary files to create the apk
    let directory = build_directory(&sdk_path, args.output.filestem_str().unwrap(), &native_shared_libs);

    // Copy the additional native libs into the libs directory.
    for (name, path) in native_shared_libs.iter() {
        fs::copy(path, &directory.path().join("libs").join("armeabi").join(name)).unwrap();
    }

    // Set the paths for the tools used in one central place. Then we also use this to not
    // only invoke the tool when needed, but also to check before first invocation in order
    // to display a nice error message to the user if the tool is missing from the path.
    let toolgccpath = standalone_path.join("bin").join("arm-linux-androideabi-gcc");
    let toolantpath = Path::new("ant");

    if !toolgccpath.exists() {
        println!("Missing Tool `{}`!", toolgccpath.display());
        std::os::set_exit_status(1);
    }
    // compiling android_native_app_glue.c
    //if Command::new(toolgccpath.clone())
    //    .arg(ndk_path.join("sources").join("android").join("native_app_glue").join("android_native_app_glue.c"))
    //    .arg("-c")
    //    .arg("-o").arg(directory.path().join("android_native_app_glue.o"))
    //    .stdout(std::old_io::process::InheritFd(1)).stderr(std::old_io::process::InheritFd(2))
    //    .status().unwrap() != std::old_io::process::ExitStatus(0)
    //{
    //    println!("Error while executing gcc");
    //    std::os::set_exit_status(1);
    //    return;
    //}

    // calling gcc to link to a shared object
    if Command::new(toolgccpath.clone())
        .args(passthrough.as_slice())
        //.arg(directory.path().join("android_native_app_glue.o"))
        .arg("-o").arg(directory.path().join("libs").join("armeabi").join("libmain.so"))
        .arg("-shared")
        .arg("-Wl,-E")
        .stdout(std::old_io::process::InheritFd(1))
        .stderr(std::old_io::process::InheritFd(2))//.cwd(directory.path())
        .status().unwrap() != std::old_io::process::ExitStatus(0)
    {
        println!("Error while executing gcc");
        std::os::set_exit_status(1);
        return;
    }

    // calling objdump to make sure that our object has `ANativeActivity_onCreate`
    // TODO: not working
    /*{
        let mut process =
            Command::new(standalone_path.join("bin").join("arm-linux-androideabi-objdump"))
            .arg("-x").arg(directory.path().join("libs").join("armeabi").join("libmain.so"))
            .stderr(std::old_io::process::InheritFd(2))
            .spawn().unwrap();

        // TODO: use UFCS instead
        fn by_ref<'a, T: Reader>(r: &'a mut T) -> std::old_io::RefReader<'a, T> { r.by_ref() };

        let stdout = process.stdout.as_mut().unwrap();
        let mut stdout = std::old_io::BufferedReader::new(by_ref(stdout));

        if stdout.lines().filter_map(|l| l.ok())
            .find(|line| line.as_slice().contains("ANativeActivity_onCreate")).is_none()
        {
            println!("Error: the output file doesn't contain ANativeActivity_onCreate");
            std::os::set_exit_status(1);
            return;
        }
    }*/

    copy_assets(&directory.path());

    // executing ant
    let antcmd = Command::new(toolantpath).arg("debug").stdout(std::old_io::process::InheritFd(1))
        .stderr(std::old_io::process::InheritFd(2)).cwd(directory.path())
        .status();
    if antcmd.is_err() || antcmd.unwrap() != std::old_io::process::ExitStatus(0)
    {
        println!("Error while executing program `ant` debug, or missing program.");
        std::os::set_exit_status(1);
        return;
    }

    // copying apk file to the requested output
    fs::copy(&directory.path().join("bin").join("rust-android-debug.apk"),
        &args.output).unwrap();
}

#[cfg(feature = "assets_hack")]
fn copy_assets(build_path: &Path) {
    use std::old_io::fs::{PathExtensions};

    let cwd = std::os::getcwd().ok()
        .expect("Can not get current working directory!");
    let assets_path = cwd.join("assets");
    if assets_path.exists() {
        fs::symlink(&assets_path, &build_path.join("assets"))
            .ok().expect("Can not create symlink to assets");
    }
}

#[cfg(not(feature = "assets_hack"))]
fn copy_assets(_: &Path) {}

struct Args {
    output: Path,
}

fn parse_arguments() -> (Args, Vec<String>) {
    let mut result_output = None;
    let mut result_passthrough = Vec::new();

    let args = std::os::args();
    let mut args = args.into_iter().skip(1);

    loop {
        let arg = match args.next() {
            None => return (
                Args {
                    output: result_output.expect("Could not find -o argument")
                },
                result_passthrough
            ),
            Some(arg) => arg
        };

        match arg.as_slice() {
            "-o" => {
                result_output = Some(Path::new(args.next().expect("-o must be followed by the output name")));
            },
            _ => result_passthrough.push(arg)
        };
    }
}

fn find_native_libs(args: &Args) -> HashMap<String, Path> {
    let base_path = args.output.dir_path().join("native");
    let mut native_shared_libs: HashMap<String, Path> = HashMap::new();

    fs::walk_dir(&base_path).and_then(|dirs| {
        for dir in dirs {
            fs::readdir(&dir).and_then(|paths| {
                for path in paths.iter() {
                    match (path.filename_str(), path.extension_str()) {
                        (Some(filename), Some(ext)) => {
                            if filename.starts_with("lib") && ext == "so" {
                                native_shared_libs.insert(filename.to_string(), path.clone());
                            }
                        }
                        _ => {}
                    }
                }
                Ok(())
            }).ok();
        }
        Ok(())
    }).ok();

    native_shared_libs
}

fn build_directory(sdk_dir: &Path, crate_name: &str, libs: &HashMap<String, Path>) -> TempDir {
    use std::old_io::fs;

    let mut xlibs: HashMap<String, Path> = HashMap::new();
    let build_directory = TempDir::new("android-rs-glue-rust-to-apk")
        .ok().expect("Could not create temporary build directory");

    panic!("HERE");
    xlibs.insert(String::from_str("Emain"), Path::new(""));

    let activity_name = if xlibs.len() > 0 {
        let src_path = build_directory.path().join("src/rust/glutin");
        fs::mkdir_recursive(&src_path, std::old_io::USER_RWX).unwrap();

        File::create(&src_path.join("MainActivity.java")).unwrap()
            .write_str(java_src(&xlibs).as_slice())
            .unwrap();

        "rust.glutin.MainActivity"
    } else {
        "android.app.NativeActivity"
    };

    File::create(&build_directory.path().join("AndroidManifest.xml")).unwrap()
        .write_str(build_manifest(crate_name, activity_name).as_slice())
        .unwrap();

    File::create(&build_directory.path().join("build.xml")).unwrap()
        .write_str(build_build_xml().as_slice())
        .unwrap();

    File::create(&build_directory.path().join("local.properties")).unwrap()
        .write_str(build_local_properties(sdk_dir).as_slice())
        .unwrap();

    File::create(&build_directory.path().join("project.properties")).unwrap()
        .write_str(build_project_properties().as_slice())
        .unwrap();

    {
        let libs_path = build_directory.path().join("libs").join("armeabi");
        fs::mkdir_recursive(&libs_path, std::old_io::USER_RWX).unwrap();
    }

    {
        // Make sure that 'src' directory is creates
        let src_path = build_directory.path().join("src");
        fs::mkdir_recursive(&src_path, std::old_io::USER_RWX).unwrap();
    }

    build_directory
}

fn java_src(libs: &HashMap<String, Path>) -> String {
    let mut libs_string = "".to_string();

    for (name, _) in libs.iter() {
        // Strip off the 'lib' prefix and ".so" suffix. This is safe since libs only get added
        // to the hash map if they start with lib.
        let line = format!("        System.loadLibrary(\"{}\");\n", name.slice(3, name.len()-3));
        libs_string.push_str(line.as_slice());
    }

    format!(r#"package rust.glutin;

public class MainActivity extends android.app.NativeActivity {{
    static {{
        {0}
    }}
}}"#, libs_string)
}

fn build_manifest(crate_name: &str, activity_name: &str) -> String {
    format!(r#"<?xml version="1.0" encoding="utf-8"?>
<!-- BEGIN_INCLUDE(manifest) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.native_activity"
        android:versionCode="1"
        android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9" />

    <uses-feature android:glEsVersion="0x00020000" android:required="true"></uses-feature>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application android:label="{0}">
        <activity android:name="{1}"
                android:label="{0}"
                android:configChanges="orientation|keyboardHidden">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest> 
<!-- END_INCLUDE(manifest) -->
"#, crate_name, activity_name)
}

fn build_build_xml() -> String {
    format!(r#"<?xml version="1.0" encoding="UTF-8"?>
<project name="rust-android" default="help">
    <property file="local.properties" />
    <loadproperties srcFile="project.properties" />
    <import file="custom_rules.xml" optional="true" />
    <import file="${{sdk.dir}}/tools/ant/build.xml" />
</project>
"#)
}

fn build_local_properties(sdk_dir: &Path) -> String {
    use std::os;
    format!(r"sdk.dir={}", os::make_absolute(sdk_dir).unwrap().display())
}

fn build_project_properties() -> String {
    format!(r"target=android-18")
}

@tamird
Copy link
Contributor

tamird commented Apr 22, 2015

This example is unfortunately quite stale:

$ rustc main.rs
main.rs:6:5: 6:34 error: unresolved import `std::old_io::process::Command`. Could not find `old_io` in `std`
main.rs:6 use std::old_io::process::Command;
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.rs:7:19: 7:23 error: unresolved import `std::old_io::File`. Could not find `old_io` in `std`
main.rs:7 use std::old_io::{File, TempDir};
                            ^~~~
main.rs:7:25: 7:32 error: unresolved import `std::old_io::TempDir`. Could not find `old_io` in `std`
main.rs:7 use std::old_io::{File, TempDir};
                                  ^~~~~~~
main.rs:8:5: 8:20 error: unresolved import `std::old_io::fs`. Could not find `old_io` in `std`
main.rs:8 use std::old_io::fs;
              ^~~~~~~~~~~~~~~
main.rs:9:5: 9:36 error: unresolved import `std::old_io::fs::PathExtensions`. Could not find `old_io` in `std`
main.rs:9 use std::old_io::fs::PathExtensions;
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.rs:192:9: 192:24 error: unresolved import `std::old_io::fs`. Could not find `old_io` in `std`
main.rs:192     use std::old_io::fs;
                    ^~~~~~~~~~~~~~~
error: aborting due to 6 previous errors

@kmcguire3413 can you update this please?

@Manishearth Manishearth added the E-needs-test Call for participation: An issue has been fixed and does not reproduce, but no test has been added. label Nov 5, 2015
@apasel422
Copy link
Contributor

If the test case here can't be reduced, we should just close this issue as is.

@apasel422
Copy link
Contributor

Closing due to inactivity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
E-needs-test Call for participation: An issue has been fixed and does not reproduce, but no test has been added. I-ICE Issue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️
Projects
None yet
Development

No branches or pull requests

7 participants