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

trans: Use LLVM's writeArchive to modify archives #26926

Merged
merged 1 commit into from
Jul 10, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mk/rustllvm.mk
Original file line number Diff line number Diff line change
@@ -24,7 +24,8 @@ LLVM_EXTRA_INCDIRS_$(1)= $$(call CFG_CC_INCLUDE_$(1),$(S)src/llvm/include) \
endif

RUSTLLVM_OBJS_CS_$(1) := $$(addprefix rustllvm/, \
ExecutionEngineWrapper.cpp RustWrapper.cpp PassWrapper.cpp)
ExecutionEngineWrapper.cpp RustWrapper.cpp PassWrapper.cpp \
ArchiveWrapper.cpp)

RUSTLLVM_INCS_$(1) = $$(LLVM_EXTRA_INCDIRS_$(1)) \
$$(call CFG_CC_INCLUDE_$(1),$$(LLVM_INCDIR_$(1))) \
1 change: 0 additions & 1 deletion src/librustc/lib.rs
Original file line number Diff line number Diff line change
@@ -99,7 +99,6 @@ pub mod diagnostics;

pub mod back {
pub use rustc_back::abi;
pub use rustc_back::archive;
pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel;
3 changes: 2 additions & 1 deletion src/librustc/metadata/loader.rs
Original file line number Diff line number Diff line change
@@ -212,7 +212,6 @@
//! no means all of the necessary details. Take a look at the rest of
//! metadata::loader or metadata::creader for all the juicy details!

use back::archive::METADATA_FILENAME;
use back::svh::Svh;
use session::Session;
use session::search_paths::PathKind;
@@ -280,6 +279,8 @@ pub struct CratePaths {
pub rlib: Option<PathBuf>
}

pub const METADATA_FILENAME: &'static str = "rust.metadata.bin";

impl CratePaths {
fn paths(&self) -> Vec<PathBuf> {
match (&self.dylib, &self.rlib) {
361 changes: 0 additions & 361 deletions src/librustc_back/archive.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/librustc_back/lib.rs
Original file line number Diff line number Diff line change
@@ -51,7 +51,6 @@ extern crate rustc_llvm;
#[macro_use] extern crate log;

pub mod abi;
pub mod archive;
pub mod tempdir;
pub mod arm;
pub mod mips;
1 change: 1 addition & 0 deletions src/librustc_back/target/linux_base.rs
Original file line number Diff line number Diff line change
@@ -29,6 +29,7 @@ pub fn opts() -> TargetOptions {
"-Wl,--as-needed".to_string(),
],
position_independent_executables: true,
archive_format: "gnu".to_string(),
.. Default::default()
}
}
6 changes: 6 additions & 0 deletions src/librustc_back/target/mod.rs
Original file line number Diff line number Diff line change
@@ -166,6 +166,11 @@ pub struct TargetOptions {
/// the functions in the executable are not randomized and can be used
/// during an exploit of a vulnerability in any code.
pub position_independent_executables: bool,
/// Format that archives should be emitted in. This affects whether we use
/// LLVM to assemble an archive or fall back to the system linker, and
/// currently only "gnu" is used to fall into LLVM. Unknown strings cause
/// the system linker to be used.
pub archive_format: String,
}

impl Default for TargetOptions {
@@ -202,6 +207,7 @@ impl Default for TargetOptions {
position_independent_executables: false,
pre_link_objects: Vec::new(),
post_link_objects: Vec::new(),
archive_format: String::new(),
}
}
}
1 change: 1 addition & 0 deletions src/librustc_back/target/windows_base.rs
Original file line number Diff line number Diff line change
@@ -25,6 +25,7 @@ pub fn opts() -> TargetOptions {
staticlib_suffix: ".lib".to_string(),
morestack: false,
is_like_windows: true,
archive_format: "gnu".to_string(),
pre_link_args: vec!(
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
65 changes: 39 additions & 26 deletions src/librustc_llvm/archive_ro.rs
Original file line number Diff line number Diff line change
@@ -13,6 +13,7 @@
use ArchiveRef;

use std::ffi::CString;
use std::marker;
use std::path::Path;
use std::slice;
use std::str;
@@ -25,8 +26,8 @@ pub struct Iter<'a> {
}

pub struct Child<'a> {
name: Option<&'a str>,
data: &'a [u8],
ptr: ::ArchiveChildRef,
_data: marker::PhantomData<&'a ArchiveRO>,
}

impl ArchiveRO {
@@ -60,6 +61,8 @@ impl ArchiveRO {
}
}

pub fn raw(&self) -> ArchiveRef { self.ptr }

pub fn iter(&self) -> Iter {
unsafe {
Iter { ptr: ::LLVMRustArchiveIteratorNew(self.ptr), archive: self }
@@ -79,28 +82,11 @@ impl<'a> Iterator for Iter<'a> {
type Item = Child<'a>;

fn next(&mut self) -> Option<Child<'a>> {
unsafe {
let ptr = ::LLVMRustArchiveIteratorCurrent(self.ptr);
if ptr.is_null() {
return None
}
let mut name_len = 0;
let name_ptr = ::LLVMRustArchiveChildName(ptr, &mut name_len);
let mut data_len = 0;
let data_ptr = ::LLVMRustArchiveChildData(ptr, &mut data_len);
let child = Child {
name: if name_ptr.is_null() {
None
} else {
let name = slice::from_raw_parts(name_ptr as *const u8,
name_len as usize);
str::from_utf8(name).ok().map(|s| s.trim())
},
data: slice::from_raw_parts(data_ptr as *const u8,
data_len as usize),
};
::LLVMRustArchiveIteratorNext(self.ptr);
Some(child)
let ptr = unsafe { ::LLVMRustArchiveIteratorNext(self.ptr) };
if ptr.is_null() {
None
} else {
Some(Child { ptr: ptr, _data: marker::PhantomData })
}
}
}
@@ -114,6 +100,33 @@ impl<'a> Drop for Iter<'a> {
}

impl<'a> Child<'a> {
pub fn name(&self) -> Option<&'a str> { self.name }
pub fn data(&self) -> &'a [u8] { self.data }
pub fn name(&self) -> Option<&'a str> {
unsafe {
let mut name_len = 0;
let name_ptr = ::LLVMRustArchiveChildName(self.ptr, &mut name_len);
if name_ptr.is_null() {
None
} else {
let name = slice::from_raw_parts(name_ptr as *const u8,
name_len as usize);
str::from_utf8(name).ok().map(|s| s.trim())
}
}
}

pub fn data(&self) -> &'a [u8] {
unsafe {
let mut data_len = 0;
let data_ptr = ::LLVMRustArchiveChildData(self.ptr, &mut data_len);
slice::from_raw_parts(data_ptr as *const u8, data_len as usize)
}
}

pub fn raw(&self) -> ::ArchiveChildRef { self.ptr }
}

impl<'a> Drop for Child<'a> {
fn drop(&mut self) {
unsafe { ::LLVMRustArchiveChildFree(self.ptr); }
}
}
16 changes: 14 additions & 2 deletions src/librustc_llvm/lib.rs
Original file line number Diff line number Diff line change
@@ -522,6 +522,9 @@ pub type DebugLocRef = *mut DebugLoc_opaque;
#[allow(missing_copy_implementations)]
pub enum SMDiagnostic_opaque {}
pub type SMDiagnosticRef = *mut SMDiagnostic_opaque;
#[allow(missing_copy_implementations)]
pub enum RustArchiveMember_opaque {}
pub type RustArchiveMemberRef = *mut RustArchiveMember_opaque;

pub type DiagnosticHandler = unsafe extern "C" fn(DiagnosticInfoRef, *mut c_void);
pub type InlineAsmDiagHandler = unsafe extern "C" fn(SMDiagnosticRef, *const c_void, c_uint);
@@ -2069,12 +2072,12 @@ extern {

pub fn LLVMRustOpenArchive(path: *const c_char) -> ArchiveRef;
pub fn LLVMRustArchiveIteratorNew(AR: ArchiveRef) -> ArchiveIteratorRef;
pub fn LLVMRustArchiveIteratorNext(AIR: ArchiveIteratorRef);
pub fn LLVMRustArchiveIteratorCurrent(AIR: ArchiveIteratorRef) -> ArchiveChildRef;
pub fn LLVMRustArchiveIteratorNext(AIR: ArchiveIteratorRef) -> ArchiveChildRef;
pub fn LLVMRustArchiveChildName(ACR: ArchiveChildRef,
size: *mut size_t) -> *const c_char;
pub fn LLVMRustArchiveChildData(ACR: ArchiveChildRef,
size: *mut size_t) -> *const c_char;
pub fn LLVMRustArchiveChildFree(ACR: ArchiveChildRef);
pub fn LLVMRustArchiveIteratorFree(AIR: ArchiveIteratorRef);
pub fn LLVMRustDestroyArchive(AR: ArchiveRef);

@@ -2111,6 +2114,15 @@ extern {
CX: *mut c_void);

pub fn LLVMWriteSMDiagnosticToString(d: SMDiagnosticRef, s: RustStringRef);

pub fn LLVMRustWriteArchive(Dst: *const c_char,
NumMembers: size_t,
Members: *const RustArchiveMemberRef,
WriteSymbtab: bool) -> c_int;
pub fn LLVMRustArchiveMemberNew(Filename: *const c_char,
Name: *const c_char,
Child: ArchiveChildRef) -> RustArchiveMemberRef;
pub fn LLVMRustArchiveMemberFree(Member: RustArchiveMemberRef);
}

// LLVM requires symbols from this library, but apparently they're not printed
504 changes: 504 additions & 0 deletions src/librustc_trans/back/archive.rs

Large diffs are not rendered by default.

96 changes: 47 additions & 49 deletions src/librustc_trans/back/link.rs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use super::archive::{Archive, ArchiveBuilder, ArchiveConfig, METADATA_FILENAME};
use super::archive::{ArchiveBuilder, ArchiveConfig};
use super::linker::{Linker, GnuLinker, MsvcLinker};
use super::rpath::RPathConfig;
use super::rpath;
@@ -20,8 +20,9 @@ use session::config::{OutputFilenames, Input, OutputTypeBitcode, OutputTypeExe,
use session::search_paths::PathKind;
use session::Session;
use metadata::common::LinkMeta;
use metadata::{encoder, cstore, filesearch, csearch, creader};
use metadata::filesearch::FileDoesntMatch;
use metadata::loader::METADATA_FILENAME;
use metadata::{encoder, cstore, filesearch, csearch, creader};
use middle::ty::{self, Ty};
use rustc::ast_map::{PathElem, PathElems, PathName};
use trans::{CrateContext, CrateTranslation, gensym_name};
@@ -513,18 +514,22 @@ fn link_binary_output(sess: &Session,
}
}

let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
match crate_type {
config::CrateTypeRlib => {
link_rlib(sess, Some(trans), &objects, &out_filename).build();
link_rlib(sess, Some(trans), &objects, &out_filename,
tmpdir.path()).build();
}
config::CrateTypeStaticlib => {
link_staticlib(sess, &objects, &out_filename);
link_staticlib(sess, &objects, &out_filename, tmpdir.path());
}
config::CrateTypeExecutable => {
link_natively(sess, trans, false, &objects, &out_filename, outputs);
link_natively(sess, trans, false, &objects, &out_filename, outputs,
tmpdir.path());
}
config::CrateTypeDylib => {
link_natively(sess, trans, true, &objects, &out_filename, outputs);
link_natively(sess, trans, true, &objects, &out_filename, outputs,
tmpdir.path());
}
}

@@ -548,13 +553,13 @@ fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
}

fn archive_config<'a>(sess: &'a Session,
output: &Path) -> ArchiveConfig<'a> {
output: &Path,
input: Option<&Path>) -> ArchiveConfig<'a> {
ArchiveConfig {
handler: &sess.diagnostic().handler,
sess: sess,
dst: output.to_path_buf(),
src: input.map(|p| p.to_path_buf()),
lib_search_paths: archive_search_paths(sess),
slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
ar_prog: get_ar_prog(sess),
command_path: command_path(sess),
}
@@ -569,11 +574,12 @@ fn archive_config<'a>(sess: &'a Session,
fn link_rlib<'a>(sess: &'a Session,
trans: Option<&CrateTranslation>, // None == no metadata/bytecode
objects: &[PathBuf],
out_filename: &Path) -> ArchiveBuilder<'a> {
out_filename: &Path,
tmpdir: &Path) -> ArchiveBuilder<'a> {
info!("preparing rlib from {:?} to {:?}", objects, out_filename);
let mut ab = ArchiveBuilder::create(archive_config(sess, out_filename));
let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
for obj in objects {
ab.add_file(obj).unwrap();
ab.add_file(obj);
}

for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
@@ -587,13 +593,12 @@ fn link_rlib<'a>(sess: &'a Session,
// symbol table of the archive.
ab.update_symbols();

let mut ab = match sess.target.target.options.is_like_osx {
// For OSX/iOS, we must be careful to update symbols only when adding
// object files. We're about to start adding non-object files, so run
// `ar` now to process the object files.
true => ab.build().extend(),
false => ab,
};
// For OSX/iOS, we must be careful to update symbols only when adding
// object files. We're about to start adding non-object files, so run
// `ar` now to process the object files.
if sess.target.target.options.is_like_osx && !ab.using_llvm() {
ab.build();
}

// Note that it is important that we add all of our non-object "magical
// files" *after* all of the object files in the archive. The reason for
@@ -622,8 +627,7 @@ fn link_rlib<'a>(sess: &'a Session,
// contain the metadata in a separate file. We use a temp directory
// here so concurrent builds in the same directory don't try to use
// the same filename for metadata (stomping over one another)
let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
let metadata = tmpdir.path().join(METADATA_FILENAME);
let metadata = tmpdir.join(METADATA_FILENAME);
match fs::File::create(&metadata).and_then(|mut f| {
f.write_all(&trans.metadata)
}) {
@@ -633,8 +637,7 @@ fn link_rlib<'a>(sess: &'a Session,
metadata.display(), e));
}
}
ab.add_file(&metadata).unwrap();
remove(sess, &metadata);
ab.add_file(&metadata);

// For LTO purposes, the bytecode of this library is also inserted
// into the archive. If codegen_units > 1, we insert each of the
@@ -646,7 +649,9 @@ fn link_rlib<'a>(sess: &'a Session,
// would cause it to crash if the name of a file in an archive
// was exactly 16 bytes.
let bc_filename = obj.with_extension("bc");
let bc_deflated_filename = obj.with_extension("bytecode.deflate");
let bc_deflated_filename = tmpdir.join({
obj.with_extension("bytecode.deflate").file_name().unwrap()
});

let mut bc_data = Vec::new();
match fs::File::open(&bc_filename).and_then(|mut f| {
@@ -676,8 +681,7 @@ fn link_rlib<'a>(sess: &'a Session,
}
};

ab.add_file(&bc_deflated_filename).unwrap();
remove(sess, &bc_deflated_filename);
ab.add_file(&bc_deflated_filename);

// See the bottom of back::write::run_passes for an explanation
// of when we do and don't keep .0.bc files around.
@@ -692,7 +696,7 @@ fn link_rlib<'a>(sess: &'a Session,
// After adding all files to the archive, we need to update the
// symbol table of the archive. This currently dies on OSX (see
// #11162), and isn't necessary there anyway
if !sess.target.target.options.is_like_osx {
if !sess.target.target.options.is_like_osx || ab.using_llvm() {
ab.update_symbols();
}
}
@@ -749,12 +753,12 @@ fn write_rlib_bytecode_object_v1(writer: &mut Write,
// There's no need to include metadata in a static archive, so ensure to not
// link in the metadata object file (and also don't prepare the archive with a
// metadata file).
fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path) {
let ab = link_rlib(sess, None, objects, out_filename);
let mut ab = match sess.target.target.options.is_like_osx {
true => ab.build().extend(),
false => ab,
};
fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path,
tempdir: &Path) {
let mut ab = link_rlib(sess, None, objects, out_filename, tempdir);
if sess.target.target.options.is_like_osx && !ab.using_llvm() {
ab.build();
}
if sess.target.target.options.morestack {
ab.add_native_library("morestack").unwrap();
}
@@ -781,7 +785,7 @@ fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path) {
}

ab.update_symbols();
let _ = ab.build();
ab.build();

if !all_native_libs.is_empty() {
sess.note("link against the following native artifacts when linking against \
@@ -806,10 +810,10 @@ fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path) {
// links to all upstream files as well.
fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
objects: &[PathBuf], out_filename: &Path,
outputs: &OutputFilenames) {
outputs: &OutputFilenames,
tmpdir: &Path) {
info!("preparing dylib? ({}) from {:?} to {:?}", dylib, objects,
out_filename);
let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");

// The invocations of cc share some flags across platforms
let (pname, mut cmd) = get_linker(sess);
@@ -827,7 +831,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
} else {
Box::new(GnuLinker { cmd: &mut cmd, sess: &sess }) as Box<Linker>
};
link_args(&mut *linker, sess, dylib, tmpdir.path(),
link_args(&mut *linker, sess, dylib, tmpdir,
trans, objects, out_filename, outputs);
if !sess.target.target.options.no_compiler_rt {
linker.link_staticlib("compiler-rt");
@@ -1185,20 +1189,13 @@ fn add_upstream_rust_crates(cmd: &mut Linker, sess: &Session,
let name = &name[3..name.len() - 5]; // chop off lib/.rlib

time(sess.time_passes(), &format!("altering {}.rlib", name), (), |()| {
let err = (|| {
io::copy(&mut try!(fs::File::open(&cratepath)),
&mut try!(fs::File::create(&dst)))
})();
if let Err(e) = err {
sess.fatal(&format!("failed to copy {} to {}: {}",
cratepath.display(), dst.display(), e));
}

let mut archive = Archive::open(archive_config(sess, &dst));
let cfg = archive_config(sess, &dst, Some(cratepath));
let mut archive = ArchiveBuilder::new(cfg);
archive.remove_file(METADATA_FILENAME);
archive.update_symbols();

let mut any_objects = false;
for f in archive.files() {
for f in archive.src_files() {
if f.ends_with("bytecode.deflate") {
archive.remove_file(&f);
continue
@@ -1217,6 +1214,7 @@ fn add_upstream_rust_crates(cmd: &mut Linker, sess: &Session,
}

if any_objects {
archive.build();
cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
}
});
8 changes: 2 additions & 6 deletions src/librustc_trans/back/linker.rs
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::fs;

use rustc_back::archive;
use back::archive;
use session::Session;
use session::config;

@@ -88,11 +88,7 @@ impl<'a> Linker for GnuLinker<'a> {
// -force_load is the OSX equivalent of --whole-archive, but it
// involves passing the full path to the library to link.
let mut v = OsString::from("-Wl,-force_load,");
v.push(&archive::find_library(lib,
&target.options.staticlib_prefix,
&target.options.staticlib_suffix,
search_path,
&self.sess.diagnostic().handler));
v.push(&archive::find_library(lib, search_path, &self.sess));
self.cmd.arg(&v);
}
}
4 changes: 2 additions & 2 deletions src/librustc_trans/lib.rs
Original file line number Diff line number Diff line change
@@ -53,8 +53,8 @@ extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate serialize;
extern crate rustc_llvm as llvm;
extern crate serialize;

#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
@@ -68,7 +68,6 @@ pub use rustc::util;

pub mod back {
pub use rustc_back::abi;
pub use rustc_back::archive;
pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel;
@@ -78,6 +77,7 @@ pub mod back {
pub use rustc_back::x86;
pub use rustc_back::x86_64;

pub mod archive;
pub mod linker;
pub mod link;
pub mod lto;
168 changes: 168 additions & 0 deletions src/rustllvm/ArchiveWrapper.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#include "rustllvm.h"

#include "llvm/Object/Archive.h"

#if LLVM_VERSION_MINOR >= 7
#include "llvm/Object/ArchiveWriter.h"
#endif

using namespace llvm;
using namespace llvm::object;

struct LLVMRustArchiveMember {
const char *filename;
const char *name;
Archive::Child child;

LLVMRustArchiveMember(): filename(NULL), name(NULL), child(NULL, NULL) {}
~LLVMRustArchiveMember() {}
};

#if LLVM_VERSION_MINOR >= 6
typedef OwningBinary<Archive> RustArchive;
#define GET_ARCHIVE(a) ((a)->getBinary())
#else
typedef Archive RustArchive;
#define GET_ARCHIVE(a) (a)
#endif

extern "C" void*
LLVMRustOpenArchive(char *path) {
ErrorOr<std::unique_ptr<MemoryBuffer>> buf_or = MemoryBuffer::getFile(path,
-1,
false);
if (!buf_or) {
LLVMRustSetLastError(buf_or.getError().message().c_str());
return nullptr;
}

#if LLVM_VERSION_MINOR >= 6
ErrorOr<std::unique_ptr<Archive>> archive_or =
Archive::create(buf_or.get()->getMemBufferRef());

if (!archive_or) {
LLVMRustSetLastError(archive_or.getError().message().c_str());
return nullptr;
}

OwningBinary<Archive> *ret = new OwningBinary<Archive>(
std::move(archive_or.get()), std::move(buf_or.get()));
#else
std::error_code err;
Archive *ret = new Archive(std::move(buf_or.get()), err);
if (err) {
LLVMRustSetLastError(err.message().c_str());
return nullptr;
}
#endif

return ret;
}

extern "C" void
LLVMRustDestroyArchive(RustArchive *ar) {
delete ar;
}

struct RustArchiveIterator {
Archive::child_iterator cur;
Archive::child_iterator end;
};

extern "C" RustArchiveIterator*
LLVMRustArchiveIteratorNew(RustArchive *ra) {
Archive *ar = GET_ARCHIVE(ra);
RustArchiveIterator *rai = new RustArchiveIterator();
rai->cur = ar->child_begin();
rai->end = ar->child_end();
return rai;
}

extern "C" const Archive::Child*
LLVMRustArchiveIteratorNext(RustArchiveIterator *rai) {
if (rai->cur == rai->end)
return NULL;
const Archive::Child *cur = rai->cur.operator->();
Archive::Child *ret = new Archive::Child(*cur);
++rai->cur;
return ret;
}

extern "C" void
LLVMRustArchiveChildFree(Archive::Child *child) {
delete child;
}

extern "C" void
LLVMRustArchiveIteratorFree(RustArchiveIterator *rai) {
delete rai;
}

extern "C" const char*
LLVMRustArchiveChildName(const Archive::Child *child, size_t *size) {
ErrorOr<StringRef> name_or_err = child->getName();
if (name_or_err.getError())
return NULL;
StringRef name = name_or_err.get();
*size = name.size();
return name.data();
}

extern "C" const char*
LLVMRustArchiveChildData(Archive::Child *child, size_t *size) {
StringRef buf = child->getBuffer();
*size = buf.size();
return buf.data();
}

extern "C" LLVMRustArchiveMember*
LLVMRustArchiveMemberNew(char *Filename, char *Name, Archive::Child *child) {
LLVMRustArchiveMember *Member = new LLVMRustArchiveMember;
Member->filename = Filename;
Member->name = Name;
if (child)
Member->child = *child;
return Member;
}

extern "C" void
LLVMRustArchiveMemberFree(LLVMRustArchiveMember *Member) {
delete Member;
}

extern "C" int
LLVMRustWriteArchive(char *Dst,
size_t NumMembers,
const LLVMRustArchiveMember **NewMembers,
bool WriteSymbtab) {
#if LLVM_VERSION_MINOR >= 7
std::vector<NewArchiveIterator> Members;

for (size_t i = 0; i < NumMembers; i++) {
auto Member = NewMembers[i];
assert(Member->name);
if (Member->filename) {
Members.push_back(NewArchiveIterator(Member->filename, Member->name));
} else {
Members.push_back(NewArchiveIterator(Member->child, Member->name));
}
}
auto pair = writeArchive(Dst, Members, WriteSymbtab);
if (!pair.second)
return 0;
LLVMRustSetLastError(pair.second.message().c_str());
#else
LLVMRustSetLastError("writing archives not supported with this LLVM version");
#endif
return -1;
}
101 changes: 0 additions & 101 deletions src/rustllvm/RustWrapper.cpp
Original file line number Diff line number Diff line change
@@ -825,107 +825,6 @@ LLVMRustLinkInExternalBitcode(LLVMModuleRef dst, char *bc, size_t len) {
return true;
}

extern "C" void*
LLVMRustOpenArchive(char *path) {
ErrorOr<std::unique_ptr<MemoryBuffer>> buf_or = MemoryBuffer::getFile(path,
-1,
false);
if (!buf_or) {
LLVMRustSetLastError(buf_or.getError().message().c_str());
return nullptr;
}

#if LLVM_VERSION_MINOR >= 6
ErrorOr<std::unique_ptr<Archive>> archive_or =
Archive::create(buf_or.get()->getMemBufferRef());

if (!archive_or) {
LLVMRustSetLastError(archive_or.getError().message().c_str());
return nullptr;
}

OwningBinary<Archive> *ret = new OwningBinary<Archive>(
std::move(archive_or.get()), std::move(buf_or.get()));
#else
std::error_code err;
Archive *ret = new Archive(std::move(buf_or.get()), err);
if (err) {
LLVMRustSetLastError(err.message().c_str());
return nullptr;
}
#endif

return ret;
}

#if LLVM_VERSION_MINOR >= 6
typedef OwningBinary<Archive> RustArchive;
#define GET_ARCHIVE(a) ((a)->getBinary())
#else
typedef Archive RustArchive;
#define GET_ARCHIVE(a) (a)
#endif

extern "C" void
LLVMRustDestroyArchive(RustArchive *ar) {
delete ar;
}

struct RustArchiveIterator {
Archive::child_iterator cur;
Archive::child_iterator end;
};

extern "C" RustArchiveIterator*
LLVMRustArchiveIteratorNew(RustArchive *ra) {
Archive *ar = GET_ARCHIVE(ra);
RustArchiveIterator *rai = new RustArchiveIterator();
rai->cur = ar->child_begin();
rai->end = ar->child_end();
return rai;
}

extern "C" const Archive::Child*
LLVMRustArchiveIteratorCurrent(RustArchiveIterator *rai) {
if (rai->cur == rai->end)
return NULL;
#if LLVM_VERSION_MINOR >= 6
const Archive::Child &ret = *rai->cur;
return &ret;
#else
return rai->cur.operator->();
#endif
}

extern "C" void
LLVMRustArchiveIteratorNext(RustArchiveIterator *rai) {
if (rai->cur == rai->end)
return;
++rai->cur;
}

extern "C" void
LLVMRustArchiveIteratorFree(RustArchiveIterator *rai) {
delete rai;
}

extern "C" const char*
LLVMRustArchiveChildName(const Archive::Child *child, size_t *size) {
ErrorOr<StringRef> name_or_err = child->getName();
if (name_or_err.getError())
return NULL;
StringRef name = name_or_err.get();
*size = name.size();
return name.data();
}

extern "C" const char*
LLVMRustArchiveChildData(Archive::Child *child, size_t *size) {
StringRef buf = child->getBuffer();
*size = buf.size();
return buf.data();
}

extern "C" void
LLVMRustSetDLLStorageClass(LLVMValueRef Value,
GlobalValue::DLLStorageClassTypes Class) {