-
Notifications
You must be signed in to change notification settings - Fork 91
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement standalone executable compilation (#140)
- Loading branch information
Showing
6 changed files
with
186 additions
and
5 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
use std::{env, path::Path, process::ExitCode}; | ||
|
||
use anyhow::Result; | ||
use console::style; | ||
use mlua::Compiler as LuaCompiler; | ||
use tokio::{fs, io::AsyncWriteExt as _}; | ||
|
||
use crate::executor::MetaChunk; | ||
|
||
/** | ||
Compiles and embeds the bytecode of a given lua file to form a standalone | ||
binary, then writes it to an output file, with the required permissions. | ||
*/ | ||
#[allow(clippy::similar_names)] | ||
pub async fn build_standalone( | ||
input_path: impl AsRef<Path>, | ||
output_path: impl AsRef<Path>, | ||
source_code: impl AsRef<[u8]>, | ||
) -> Result<ExitCode> { | ||
let input_path_displayed = input_path.as_ref().display(); | ||
let output_path_displayed = output_path.as_ref().display(); | ||
|
||
// First, we read the contents of the lune interpreter as our starting point | ||
println!( | ||
"Creating standalone binary using {}", | ||
style(input_path_displayed).green() | ||
); | ||
let mut patched_bin = fs::read(env::current_exe()?).await?; | ||
|
||
// Compile luau input into bytecode | ||
let bytecode = LuaCompiler::new() | ||
.set_optimization_level(2) | ||
.set_coverage_level(0) | ||
.set_debug_level(1) | ||
.compile(source_code); | ||
|
||
// Append the bytecode / metadata to the end | ||
let meta = MetaChunk { bytecode }; | ||
patched_bin.extend_from_slice(&meta.to_bytes()); | ||
|
||
// And finally write the patched binary to the output file | ||
println!( | ||
"Writing standalone binary to {}", | ||
style(output_path_displayed).blue() | ||
); | ||
write_executable_file_to(output_path, patched_bin).await?; | ||
|
||
Ok(ExitCode::SUCCESS) | ||
} | ||
|
||
async fn write_executable_file_to(path: impl AsRef<Path>, bytes: impl AsRef<[u8]>) -> Result<()> { | ||
let mut options = fs::OpenOptions::new(); | ||
options.write(true).create(true).truncate(true); | ||
|
||
#[cfg(unix)] | ||
{ | ||
options.mode(0o755); // Read & execute for all, write for owner | ||
} | ||
|
||
let mut file = options.open(path).await?; | ||
file.write_all(bytes.as_ref()).await?; | ||
|
||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
use std::{env, process::ExitCode}; | ||
|
||
use lune::Lune; | ||
|
||
use anyhow::{bail, Result}; | ||
use tokio::fs; | ||
|
||
const MAGIC: &[u8; 8] = b"cr3sc3nt"; | ||
|
||
/** | ||
Metadata for a standalone Lune executable. Can be used to | ||
discover and load the bytecode contained in a standalone binary. | ||
*/ | ||
#[derive(Debug, Clone)] | ||
pub struct MetaChunk { | ||
pub bytecode: Vec<u8>, | ||
} | ||
|
||
impl MetaChunk { | ||
/** | ||
Tries to read a standalone binary from the given bytes. | ||
*/ | ||
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> { | ||
let bytes = bytes.as_ref(); | ||
if bytes.len() < 16 || !bytes.ends_with(MAGIC) { | ||
bail!("not a standalone binary") | ||
} | ||
|
||
// Extract bytecode size | ||
let bytecode_size_bytes = &bytes[bytes.len() - 16..bytes.len() - 8]; | ||
let bytecode_size = | ||
usize::try_from(u64::from_be_bytes(bytecode_size_bytes.try_into().unwrap()))?; | ||
|
||
// Extract bytecode | ||
let bytecode = bytes[bytes.len() - 16 - bytecode_size..].to_vec(); | ||
|
||
Ok(Self { bytecode }) | ||
} | ||
|
||
/** | ||
Writes the metadata chunk to a byte vector, to later bet read using `from_bytes`. | ||
*/ | ||
pub fn to_bytes(&self) -> Vec<u8> { | ||
let mut bytes = Vec::new(); | ||
bytes.extend_from_slice(&self.bytecode); | ||
bytes.extend_from_slice(&(self.bytecode.len() as u64).to_be_bytes()); | ||
bytes.extend_from_slice(MAGIC); | ||
bytes | ||
} | ||
} | ||
|
||
/** | ||
Returns whether or not the currently executing Lune binary | ||
is a standalone binary, and if so, the bytes of the binary. | ||
*/ | ||
pub async fn check_env() -> (bool, Vec<u8>) { | ||
let path = env::current_exe().expect("failed to get path to current running lune executable"); | ||
let contents = fs::read(path).await.unwrap_or_default(); | ||
let is_standalone = contents.ends_with(MAGIC); | ||
(is_standalone, contents) | ||
} | ||
|
||
/** | ||
Discovers, loads and executes the bytecode contained in a standalone binary. | ||
*/ | ||
pub async fn run_standalone(patched_bin: impl AsRef<[u8]>) -> Result<ExitCode> { | ||
// The first argument is the path to the current executable | ||
let args = env::args().skip(1).collect::<Vec<_>>(); | ||
let meta = MetaChunk::from_bytes(patched_bin).expect("must be a standalone binary"); | ||
|
||
let result = Lune::new() | ||
.with_args(args) | ||
.run("STANDALONE", meta.bytecode) | ||
.await; | ||
|
||
Ok(match result { | ||
Err(err) => { | ||
eprintln!("{err}"); | ||
ExitCode::FAILURE | ||
} | ||
Ok(code) => code, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters