{ "cells": [ { "cell_type": "markdown", "id": "be646ea8-f855-4899-98fa-16b5b8585e42", "metadata": {}, "source": [ "## Null Pointer Dereference" ] }, { "cell_type": "code", "execution_count": 2, "id": "ab399580-d168-46e3-9f07-1e72965e5433", "metadata": {}, "outputs": [], "source": [ "use std::process::{Command, Output, Stdio};\n", "\n", "// A helper function to execute a shell command from a Rust script\n", "fn execute_command(command: &str) -> Result<(), std::io::Error> {\n", " let status = Command::new(\"bash\")\n", " .arg(\"-c\")\n", " .arg(command)\n", " .stderr(Stdio::inherit())\n", " .status()?;\n", "\n", " if status.success() {\n", " Ok(())\n", " } else {\n", " Err(std::io::Error::from_raw_os_error(status.code().unwrap_or(1)))\n", " }\n", "}" ] }, { "cell_type": "markdown", "id": "e7989928-64c5-4796-b465-9991ef421ca0", "metadata": {}, "source": [ "### C Lang" ] }, { "cell_type": "code", "execution_count": 39, "id": "ab54cf8d-7284-442f-9e83-7c15c45f3b26", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[sudo] password for mahmoud: Sorry, try again.\n", "[sudo] password for mahmoud: \n", "sudo: no password was provided\n", "sudo: 1 incorrect password attempt\n", "Error executing command: Operation not permitted (os error 1)\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"echo 'your-password' | sudo -S ./chapter-1/1-null-pointer-dereference/c/null_pointer\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}\n", "\n", "// Replace 'your-password', and you should see something like:\n", "// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'\n", "// 64943 Segmentation fault | sudo -S ./chapter-1/1-null-pointer-dereference/c/null_pointer\n", "// Error executing command: Unknown error 139 (os error 139)" ] }, { "cell_type": "markdown", "id": "614f4135-5e3a-409f-876e-3c8590e12b9e", "metadata": {}, "source": [ "### Rust Lang" ] }, { "cell_type": "code", "execution_count": 4, "id": "3ab31da1-91da-4964-b4b8-90a616147fd1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value: 21891\n" ] } ], "source": [ "let ptr: *const i32 = std::ptr::null();\n", "let value = unsafe { *ptr };\n", "println!(\"Value: {}\", value);\n", "\n", "// Sometimes, this code may result in a segmentation fault." ] }, { "cell_type": "markdown", "id": "6d391e31-043c-42d7-857a-fbc1439c4c96", "metadata": {}, "source": [ "Let's execute a bash command." ] }, { "cell_type": "code", "execution_count": 8, "id": "064ae2fb-4d16-4cbc-9269-66d5ffd3f3ed", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[sudo] password for mahmoud: Sorry, try again.\n", "[sudo] password for mahmoud: \n", "sudo: no password was provided\n", "sudo: 1 incorrect password attempt\n", "Error executing command: Operation not permitted (os error 1)\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"echo 'your-password' | sudo -S ./chapter-1/1-null-pointer-dereference/rust/null_pointer\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}\n", "\n", "// Replace 'your-password', and you should see something like:\n", "// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'\n", "// 64579 Segmentation fault | sudo -S ./chapter-1/1-null-pointer-dereference/rust/null_pointer\n", "// Error executing command: Unknown error 139 (os error 139)" ] }, { "cell_type": "code", "execution_count": 6, "id": "618190db-c165-4728-bdea-388501b3e9b7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Popped value: 3\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let mut vec = vec![1, 2, 3];\n", "// let mut vec: Vec = vec![];\n", "let item = vec.pop();\n", "match item {\n", "\tSome(val) => println!(\"Popped value: {}\", val),\n", "\tNone => println!(\"Vector is empty\"),\n", "}" ] }, { "cell_type": "code", "execution_count": 11, "id": "b636eda4-d126-4999-a3f6-3fe6dbd828ea", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Popped value: 3\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "// Or\n", "let command = \"rustc ./chapter-1/1-null-pointer-dereference/rust/null_pointer_safe.rs && ./chapter-1/1-null-pointer-dereference/rust/null_pointer_safe\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}" ] }, { "cell_type": "markdown", "id": "4e8bce9c-fbec-4e56-8ad4-71bf741f4e88", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "4df228bb-faf3-4283-a448-05d4b63d16ae", "metadata": {}, "source": [ "## Buffer Overflow" ] }, { "cell_type": "markdown", "id": "d3ad3484-b918-43ba-b2e5-340893179c03", "metadata": {}, "source": [ "### C Lang" ] }, { "cell_type": "code", "execution_count": 9, "id": "ef8e4566-9ed0-49ef-bfe5-648aa58be366", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[sudo] password for mahmoud: Sorry, try again.\n", "[sudo] password for mahmoud: \n", "sudo: no password was provided\n", "sudo: 1 incorrect password attempt\n", "Error executing command: Operation not permitted (os error 1)\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"echo 'your-password' | sudo -S ./chapter-1/2-buffer-overflow/c/buffer_overflow\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}\n", "\n", "// Replace 'your-password', and you should see:\n", "// [sudo] password for username: bash: line 1: 64243 Done echo 'your-password'\n", "// 64244 Segmentation fault | sudo -S ./chapter-1/2-buffer-overflow/c/buffer_overflow\n", "// Error executing command: Unknown error 139 (os error 139)" ] }, { "cell_type": "markdown", "id": "aa2f7b7f-4145-4b86-9a57-6550c3ca575b", "metadata": {}, "source": [ "### Rust Lang" ] }, { "cell_type": "code", "execution_count": 11, "id": "9849348d-73e5-4303-af88-717b78e8cb03", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "[sudo] password for mahmoud: thread 'main' panicked at 'range end index 20 out of range for slice of length 5', buffer_ovreflow.rs:4:5\n", "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n", "Error executing command: Network is unreachable (os error 101)\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "// Replace 'your-password'\n", "let command = \"echo 'your-password' | sudo -S ./chapter-1/2-buffer-overflow/rust/buffer_ovreflow\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}" ] }, { "cell_type": "markdown", "id": "78694fe1-b4e2-4b2e-a12e-6b9638b4f732", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "a0140826-1bfc-4ded-84b3-7f375e981273", "metadata": {}, "source": [ "## Garbage Collector" ] }, { "cell_type": "markdown", "id": "17873337-290c-4336-8457-6ce56df3b02a", "metadata": {}, "source": [ "### C++ Lang" ] }, { "cell_type": "code", "execution_count": 13, "id": "fd294961-e8b6-486c-b0dd-f72643f48cbb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "()" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"echo 'your-password' | sudo -S ./chapter-1/3-garbage-collector/c++/gc\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}" ] }, { "cell_type": "markdown", "id": "55a08213-6835-43ee-81a3-3b4f0cfb8dec", "metadata": {}, "source": [ "### Rust Lang" ] }, { "cell_type": "code", "execution_count": 16, "id": "402f3868-520e-4ef3-8070-921f33a44de3", "metadata": {}, "outputs": [], "source": [ "struct Resource {\n", " data: Vec,\n", "}\n", "\n", "let resource = Resource {\n", " data: vec![1, 2, 3, 4, 5],\n", "};" ] }, { "cell_type": "markdown", "id": "5e2ba485-e202-4516-833f-732cf3ded505", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "98734b00-2bfa-473d-af63-093111c23ffe", "metadata": {}, "source": [ "## The Era of Multithreading and Parallelism" ] }, { "cell_type": "markdown", "id": "7ec22f5e-5784-4a9d-b07c-ec8c8be0d214", "metadata": {}, "source": [ "### Rust Lang" ] }, { "cell_type": "code", "execution_count": 21, "id": "be881022-88f6-48b7-95a2-891367e32296", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Processed: 2\n", "Processed: 4\n", "Processed: 6\n", "Processed: 8\n", "Processed: 10\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "use std::thread;\n", "\n", "let data = vec![1, 2, 3, 4, 5];\n", "let mut handles = vec![];\n", "\n", "for &item in &data {\n", " handles.push(thread::spawn(move || {\n", " println!(\"Processed: {}\", item * 2);\n", " }));\n", "}\n", "\n", "for handle in handles {\n", " handle.join().unwrap();\n", "}" ] }, { "cell_type": "code", "execution_count": 24, "id": "9c69dafe-5bb5-41e3-aff5-72a530d78d0e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Final data value: 10\n" ] } ], "source": [ "use std::sync::{Arc, Mutex};\n", "use std::thread;\n", "\n", "let data = Arc::new(Mutex::new(0));\n", "\n", "let handles: Vec<_> = (0..10)\n", "\t.map(|_| {\n", "\t\tlet data = data.clone();\n", "\t\tthread::spawn(move || {\n", "\t\t\tlet mut data = data.lock().unwrap();\n", "\t\t\t*data += 1;\n", "\t\t})\n", "\t})\n", ".collect();\n", "\n", "for handle in handles {\n", "\thandle.join().unwrap();\n", "}\n", "\n", "println!(\"Final data value: {:?}\", *data.lock().unwrap());" ] }, { "cell_type": "markdown", "id": "1237fe71-46e6-41d8-b2f5-6582ed41074c", "metadata": {}, "source": [ "### C++ Lang" ] }, { "cell_type": "code", "execution_count": 20, "id": "98a51444-1802-4095-849d-3f4452f77ed2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Processed: 2Processed: \n", "4Processed: \n", "Processed: 8\n", "Processed: 10\n", "6\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"echo 'your-password' | sudo -S ./chapter-1/4-the-era-of-multithreading-and-parallelism/c++/thread\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}" ] }, { "cell_type": "markdown", "id": "98b13b3c-61d3-42df-8aed-84964287278a", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "2a16829d-ddb4-49bd-8df7-d392126b0cfe", "metadata": {}, "source": [ "## The Power of Pattern Matching" ] }, { "cell_type": "code", "execution_count": 27, "id": "dff3d2e7-7520-43a4-abe7-0e94195af91e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3216.990877275948" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "enum Shape {\n", " Circle(f64),\n", " Rectangle(f64, f64),\n", " Triangle(f64, f64, f64),\n", "}\n", "\n", "fn area(shape: Shape) -> f64 {\n", " match shape {\n", " Shape::Circle(radius) => std::f64::consts::PI * radius * radius,\n", " Shape::Rectangle(width, height) => width * height,\n", " Shape::Triangle(a, b, c) => {\n", " let s = (a + b + c) / 2.0;\n", " (s * (s - a) * (s - b) * (s - c)).sqrt()\n", " }\n", " }\n", "}\n", "\n", "area(Shape::Circle(32.0))" ] }, { "cell_type": "markdown", "id": "730cdf83-272d-4ba0-9894-189f2960a50e", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "7c8032f3-4058-44f8-a094-03c3f6a6ea3a", "metadata": {}, "source": [ "## Lifetimes for Memory Safety" ] }, { "cell_type": "code", "execution_count": 28, "id": "467ba9d9-cb5e-4f03-acb1-9935156c0d87", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The longest common prefix is: ab\n" ] } ], "source": [ "fn longest_common_prefix<'a>(x: &'a str, y: &'a str) -> &'a str {\n", " let min_length = std::cmp::min(x.len(), y.len());\n", " let bytes_x = x.as_bytes();\n", " let bytes_y = y.as_bytes();\n", "\n", " for i in 0..min_length {\n", " if bytes_x[i] != bytes_y[i] {\n", " return &x[..i];\n", " }\n", " }\n", "\n", " &x[..min_length]\n", "}\n", "\n", "let string1 = \"abc\";\n", "let result;\n", "{\n", " let string2 = \"abdef\";\n", " result = longest_common_prefix(string1, string2);\n", "}\n", "println!(\"The longest common prefix is: {}\", result);" ] }, { "cell_type": "markdown", "id": "f63c720a-a403-40dc-a071-021a7ea4e113", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "59f0f337-4ed6-4418-8bef-834197f7ecdb", "metadata": {}, "source": [ "## Zero-Cost Abstractions for Performance" ] }, { "cell_type": "code", "execution_count": 29, "id": "17e403c8-b870-4361-9b71-1efadfb7e57d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Thread 0 Sum: 15\n", "Thread 1 Sum: 15\n", "Thread 2 Sum: 15\n", "Thread 3 Sum: 15\n", "Thread 4 Sum: 15\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "use std::thread;\n", "\n", "let data = vec![1, 2, 3, 4, 5];\n", "let shared_data = std::sync::Arc::new(data);\n", "\n", "let handles: Vec<_> = (0..5).map(|i| {\n", " let shared_data = shared_data.clone();\n", " thread::spawn(move || {\n", " let local_sum: i32 = shared_data.iter().sum();\n", " println!(\"Thread {} Sum: {}\", i, local_sum);\n", " })\n", "}).collect();\n", "\n", "for handle in handles {\n", " handle.join().unwrap();\n", "}" ] }, { "cell_type": "markdown", "id": "b61e12f9-6389-4286-a24d-a5f4a2305e23", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "e92293a4-a728-4cd8-9e71-0ba8bdd137ed", "metadata": {}, "source": [ "## Foreign Function Interface (FFI) for Integration" ] }, { "cell_type": "code", "execution_count": 31, "id": "2bb2719b-4261-41c1-8f5f-5a9f3e1dc098", "metadata": {}, "outputs": [], "source": [ "extern \"C\" {\n", " fn process_data(data: *mut u8, length: usize);\n", "}\n", "\n", "fn main() {\n", " let mut data: Vec = vec![1, 2, 3, 4, 5];\n", "\n", " unsafe {\n", " process_data(data.as_mut_ptr(), data.len());\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 32, "id": "b5391ede-4fa0-428c-9844-e0b20ef2a584", "metadata": {}, "outputs": [], "source": [ "// gcc -c external_lib.c -o external_lib.o\n", "// ar rcs libexternal_lib.a external_lib.o\n", "// rustc -L . -o main main.rs -l external_lib" ] }, { "cell_type": "code", "execution_count": 30, "id": "cb3d15e4-bcd5-4e64-9e21-676cbdc87655", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 4 5 \n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "let command = \"./chapter-1/8-foreign-function-interface/rust/main\";\n", "\n", "if let Err(err) = execute_command(command) {\n", " eprintln!(\"Error executing command: {}\", err);\n", "}" ] }, { "cell_type": "markdown", "id": "dbaca625-70db-4149-843e-9acbd797355a", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "1e9b4798-d731-4848-bf4d-d295fd3ef043", "metadata": {}, "source": [ "## Robust Error Handling with Result and Option" ] }, { "cell_type": "code", "execution_count": 37, "id": "62b6eaca-6847-4fc5-8bbb-7ced02d45b7a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "File contents:\n", "line 1\n", "line 2\n", "line 3\n", "\n" ] }, { "data": { "text/plain": [ "()" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "use std::fs::File;\n", "use std::io::{Read, Error};\n", "\n", "fn read_file_contents(filename: &str) -> Result {\n", " let mut file = File::open(filename)?;\n", " let mut contents = String::new();\n", " file.read_to_string(&mut contents)?;\n", " Ok(contents)\n", "}\n", "\n", "let filename = \"./chapter-1/9-robust-error-handling-with-result-and-option/rust/content.txt\";\n", "\n", "match read_file_contents(filename) {\n", " Ok(contents) => {\n", " println!(\"File contents:\\n{}\", contents);\n", " }\n", " Err(err) => {\n", " eprintln!(\"Error reading file: {}\", err);\n", " }\n", "}" ] }, { "cell_type": "markdown", "id": "0415d394-cbbe-42ba-95ec-cced59cebcfc", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "bba60e09-e531-4179-bca1-a2beff371885", "metadata": {}, "source": [ "## Controlled Unsafe Operations" ] }, { "cell_type": "code", "execution_count": 38, "id": "f629131c-c4ae-47b1-a9e9-641259e4806f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Modified data: [1, 2, 10, 4, 5]\n" ] } ], "source": [ "let mut data = [1, 2, 3, 4, 5];\n", "let data_ptr = data.as_mut_ptr();\n", "\n", "unsafe {\n", " *data_ptr.offset(2) = 10;\n", "}\n", "\n", "println!(\"Modified data: {:?}\", data);" ] }, { "cell_type": "markdown", "id": "a7bfc2b5-d976-4718-ac73-8c13465ada8f", "metadata": {}, "source": [ "---" ] } ], "metadata": { "kernelspec": { "display_name": "Rust", "language": "rust", "name": "rust" }, "language_info": { "codemirror_mode": "rust", "file_extension": ".rs", "mimetype": "text/rust", "name": "Rust", "pygment_lexer": "rust", "version": "" } }, "nbformat": 4, "nbformat_minor": 5 }