├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── INDEX.md ├── LICENSE ├── README.md ├── accessPatterns ├── DRAMtiming.c ├── FirstReady-FirstComeFirstServe.c ├── SimulatingDRAMTiming.c ├── addressCalculation.c ├── addressTranslation.c ├── cpuDataProcess.c ├── memoryBarrier.c ├── memoryController.c ├── oomKiller.c ├── prefetching.c ├── readWriteGrouping.c ├── schedulingAlgorithmMemoryController.c ├── sharedCounter.c ├── softwarePrefetching.c ├── stridePrefetcher.c ├── visPadding.c └── visPaddingWithPragma.c ├── compilation └── examples │ ├── hello │ ├── hello.c │ ├── hello.i │ ├── hello.s │ ├── hello_opt │ ├── hello_small │ └── hello_static ├── computerArchitecture ├── 32vs64bit.c └── s ├── concurrency ├── scheduling │ ├── AdaptiveThread-AwareScheduling.c │ ├── Parallelism-AwareBatchScheduling.c │ └── commandScheduling.c ├── synchronization │ ├── interruptHandlers.md │ ├── preemmtibleCriticalSections.c │ ├── priority_inheritance.c │ └── rtMutex.c └── threads │ ├── aggressiveWriter.c │ ├── blockingIO.c │ ├── clientSide.c │ ├── contextSwitch │ └── contextSwitchHandler.c │ ├── exceptionHandling.c │ ├── fork_pointer_check.c │ ├── leaderElection │ ├── leaderElection.c │ ├── multiThreading.c │ ├── multiThreadingInMultiCPU.c │ ├── multiThreadingSingleCPU.c │ ├── mutex_lock.c │ ├── nonBlockingIO.c │ ├── readWriteLocks.c │ ├── readWritePreference.c │ ├── rwlock-buffer │ ├── rwlock_buffer │ └── rwlock_buffer.c │ ├── semaphores │ ├── consumer.c │ ├── producer.c │ └── semaphoreShared.h │ ├── serverSide.c │ ├── signal_pointer_check.c │ ├── th │ ├── threadCreation.c │ ├── threadCreationStrace.txt │ ├── upgradeableReadLocks.c │ └── writeStarvation.c ├── docs ├── README.md ├── assemblyLanguageProgramming.md ├── cache_memory.md ├── cache_optimization_techniques.md ├── cloud_computing.md ├── compiler_optimization.md ├── cybersecurity.md ├── data_representation.md ├── datapathAndControlUnit.md ├── digitalLogicDesign.md ├── gpus.md ├── instruction_set_architecture.md ├── io_systems.md ├── logicGatesAndBooleanAlgebra.md ├── memory_alignment_padding.md ├── memory_hierarchy.md ├── memory_management_unit.md ├── networking.md ├── number_systems.md ├── parallel_processing.md ├── performance_measurement.md ├── pipelining.md ├── power_energy_consumption.md ├── pragma.md ├── reliability_security.md ├── superscalar_processors.md └── virtual_memory.md ├── memory ├── allocation │ ├── allocator.c │ ├── allocator.h │ ├── customAlloc.c │ ├── pointerTagging.c │ ├── smartPointer.c │ ├── thenWhyMe │ ├── uniquePointer.c │ └── whyNotMe.c ├── cache │ └── Two-Level-Cache-System.c ├── memory_management │ ├── context_switch.c │ ├── heap_overhead.c │ ├── mem_alloc.c │ ├── memory_layout.c │ ├── memory_pool.c │ ├── stack_vs_heap.c │ └── sys_calls.c ├── parallelComputing │ ├── matrix_mul.c │ ├── memory_transfer.c │ ├── parallel_processing.c │ ├── ray_triangle.c │ └── simt.c └── virtual_mem │ ├── TLB.c │ ├── pageFlush.c │ ├── pageTable.c │ ├── pagemap │ ├── pagemap.c │ ├── virtual_address │ └── virtual_address.c ├── ml ├── mlp ├── mlp.asm └── neural.asm ├── networking ├── quic │ ├── client │ ├── quic.pcap │ ├── quic_handshake │ ├── quic_handshake.c │ ├── server │ ├── udp_client.c │ └── udp_server.c ├── uart.c └── uartInputSystem.c ├── os ├── cpu │ └── cpu.c ├── filesystem │ ├── CustomBufferManagementSystem.c │ ├── ReadReplica.cpp │ ├── SIGBUS.c │ ├── blocksize.c │ ├── blocksize.s │ ├── bufferSizes │ ├── bufferSizes.c │ ├── buffered.txt │ ├── customBuffer │ ├── customBuffer.c │ ├── databaseOperationWithMMAP.c │ ├── fileAfterFork.c │ ├── forkConcurrency.c │ ├── issueOfBuffering.c │ ├── output.txt │ ├── solToIssueOfBuffering.c │ ├── test.dat │ ├── test.txt │ ├── unbuffered.txt │ └── whyNotUseOS.c ├── kernel │ ├── kernelInteraction.c │ ├── kernelMM.c │ ├── kernelSysCall.c │ ├── kernel_mapping.c │ ├── network_stack │ └── network_stack.c └── process │ ├── change_euid.c │ ├── chrootEx.c │ ├── cpu_affinity.c │ └── scheduler │ ├── completely_fair_scheduler.c │ ├── firt_come_first_serve.c │ ├── multi_level_queuing.c │ ├── preemptive_scheduler.c │ ├── priority_scheduling.c │ ├── process_state.c │ └── round_robin.c ├── performance └── binary-search │ ├── binary_search │ ├── binary_search.asm │ ├── binary_search.c │ ├── massif.out.40667 │ ├── massif.out.45271 │ ├── output.txt │ ├── output_with_gcc_03_optimization.txt │ └── output_without_any_gcc_optimization.txt ├── playingAround ├── README.md ├── fixedTypes │ ├── alignment_benchmark │ ├── alignment_benchmark.c │ ├── memAlignment.c │ ├── type │ └── typeAware.c └── inputBuffering │ ├── a.c │ └── basicRing.c ├── security ├── exploits │ ├── heap │ │ ├── heap_safe │ │ ├── heap_safe.c │ │ ├── heap_vuln │ │ ├── heap_vuln.c │ │ ├── input1.txt │ │ └── input2.txt │ ├── memSeal.c │ ├── memory_analyzer.c │ ├── nonExec.c │ ├── overflow_verifier.c │ ├── register_tracker.c │ ├── stackCanaries.c │ ├── stack_monitor.c │ ├── vuln.c │ └── vulnerable.c └── protection │ ├── aslr.c │ ├── aslr.i │ ├── aslr.s │ ├── aslr_test.c │ ├── canary_test.c │ ├── heapASLR.c │ ├── heapASLR.i │ ├── heapASLR.s │ ├── nx_test.c │ └── protection_test.c ├── unix ├── decode.c ├── processor_sim ├── processor_sim.c └── zero_copy_server │ ├── Makefile │ ├── main.c │ ├── zero_copy_server │ ├── zero_copy_server.c │ └── zero_copy_server.h └── utils ├── circularQueue.c ├── matrixMul ├── matrixOpt ├── matrixOptimized.c ├── matrix_baseline.py ├── matrix_basic ├── matrix_basic.c ├── matrix_cache ├── matrix_cache.c ├── matrix_optimized └── matrix_optimized.c ├── myGirl.c ├── myGirl.gif └── sh.c /.gitignore: -------------------------------------------------------------------------------- 1 | # Environment 2 | *.env 3 | 4 | # Executable files 5 | *.exe 6 | *.out 7 | *.o 8 | 9 | # Object files (intermediate compilation results) 10 | *.obj 11 | 12 | # Build directories 13 | bin/ 14 | obj/ 15 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We are committed to providing a friendly, safe and welcoming environment for all contributors. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | - Using welcoming and inclusive language 11 | - Being respectful of differing viewpoints and experiences 12 | - Gracefully accepting constructive criticism 13 | - Focusing on what is best for the community 14 | 15 | Examples of unacceptable behavior include: 16 | - Trolling, insulting/derogatory comments, and personal or political attacks 17 | - Public or private harassment 18 | - Publishing others' private information without permission 19 | - Other conduct which could reasonably be considered inappropriate 20 | 21 | ## Responsibilities 22 | 23 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 24 | 25 | ## Enforcement 26 | 27 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. 28 | 29 | ## Attribution 30 | 31 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html). 32 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to BitsAndBytes 2 | 3 | ## Getting Started 4 | 5 | 1. Fork the repository 6 | 2. Create a new branch for your feature 7 | 3. Make your changes 8 | 4. Submit a pull request 9 | 10 | ## Code Style Guidelines 11 | 12 | 1. Use consistent indentation (4 spaces) 13 | 2. Include comments explaining complex algorithms 14 | 3. Add documentation for new features 15 | 4. Follow C99 standards 16 | 17 | ## Documentation 18 | 19 | - Update the INDEX.md when adding new files 20 | - Include detailed comments in your code 21 | - Update relevant documentation in /docs 22 | 23 | ## Testing 24 | 25 | - Add test cases for new features 26 | - Ensure existing tests pass 27 | - Document test procedures 28 | 29 | ## Pull Request Process 30 | 31 | 1. Update relevant documentation 32 | 2. Add yourself to CONTRIBUTORS.txt 33 | 3. Reference any related issues 34 | 4. Wait for review and address feedback 35 | 36 | ## Communication 37 | 38 | - Open an issue for discussion 39 | - Use clear, concise commit messages 40 | - Respond to feedback constructively 41 | 42 | Thank you for contributing to BitsAndBytes! 43 | -------------------------------------------------------------------------------- /INDEX.md: -------------------------------------------------------------------------------- 1 | # Index of BitsAndBytes 2 | 3 | ## Access Patterns 4 | - [Address Calculation](accessPatterns/addressCalculation.c) - Memory address calculation implementations 5 | - [CPU Data Processing](accessPatterns/cpuDataProcess.c) - CPU data processing optimizations 6 | - [DRAM Timing](accessPatterns/DRAMtiming.c) - DRAM timing simulations 7 | - [Memory Controller](accessPatterns/memoryController.c) - Memory controller implementations 8 | - [Prefetching](accessPatterns/prefetching.c) - Memory prefetching techniques 9 | 10 | ## Concurrency 11 | ### Scheduling 12 | - [Adaptive Thread-Aware Scheduling](concurrency/scheduling/AdaptiveThread-AwareScheduling.c) 13 | - [Parallelism-Aware Batch Scheduling](concurrency/scheduling/Parallelism-AwareBatchScheduling.c) 14 | 15 | ### Synchronization 16 | - [Preemptible Critical Sections](concurrency/synchronization/preemmtibleCriticalSections.c) 17 | - [Priority Inheritance](concurrency/synchronization/priority_inheritance.c) 18 | - [RT Mutex](concurrency/synchronization/rtMutex.c) 19 | 20 | ### Threads 21 | - [Multi-Threading Examples](concurrency/threads/multiThreading.c) 22 | - [Read-Write Locks](concurrency/threads/readWriteLocks.c) 23 | - [Semaphores](concurrency/threads/semaphores/) 24 | 25 | ## Memory 26 | ### Allocation 27 | - [Custom Allocator](memory/allocation/allocator.c) 28 | - [Smart Pointer](memory/allocation/smartPointer.c) 29 | - [Unique Pointer](memory/allocation/uniquePointer.c) 30 | 31 | ### Cache 32 | - [Two-Level Cache System](memory/cache/Two-Level-Cache-System.c) 33 | 34 | ### Virtual Memory 35 | - [Page Table](memory/virtual_mem/pageTable.c) 36 | - [TLB Implementation](memory/virtual_mem/TLB.c) 37 | 38 | ## Operating System 39 | ### Filesystem 40 | - [Custom Buffer Management](os/filesystem/CustomBufferManagementSystem.c) 41 | - [MMAP Operations](os/filesystem/databaseOperationWithMMAP.c) 42 | 43 | ### Kernel 44 | - [Kernel Interaction](os/kernel/kernelInteraction.c) 45 | - [Kernel Memory Management](os/kernel/kernelMM.c) 46 | 47 | ### Process 48 | - [CPU Affinity](os/process/cpu_affinity.c) 49 | - [Chroot Example](os/process/chrootEx.c) 50 | 51 | ## Security 52 | ### Exploits 53 | - [Heap Vulnerabilities](security/exploits/heap/) 54 | - [Stack Canaries](security/exploits/stackCanaries.c) 55 | 56 | ### Protection 57 | - [ASLR Implementation](security/protection/aslr.c) 58 | - [Heap ASLR](security/protection/heapASLR.c) 59 | 60 | ## Utils 61 | - [Matrix Multiplication](utils/matrixMul/) - Optimized matrix multiplication implementations 62 | - [Shell Implementation](utils/sh.c) - Simple shell implementation 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BitsAndBytes 2 | 3 | A comprehensive collection of low-level programming examples and system programming concepts, featuring implementations of memory management, concurrency patterns, and OS internals in C. 4 | 5 | The repository serves as both a learning resource and a reference implementation for systems programming concepts, with a focus on performance optimization and hardware interaction. 6 | 7 | ## Project Structure 8 | 9 | ### /accessPatterns 10 | - Memory access patterns and optimizations 11 | - CPU data processing 12 | - DRAM timing and controllers 13 | 14 | ### /compilation 15 | - Examples of compilation processes 16 | - Optimization levels 17 | - Assembly output analysis 18 | 19 | ### /concurrency 20 | - /scheduling: Thread and process scheduling algorithms 21 | - /synchronization: Synchronization primitives and patterns 22 | - /threads: Threading implementations and examples 23 | 24 | ### /memory 25 | - /allocation: Custom memory allocators 26 | - /cache: Cache optimization techniques 27 | - /virtual_mem: Virtual memory management 28 | 29 | ### /networking 30 | - UART implementations 31 | - Input/Output systems 32 | 33 | ### /os 34 | - /filesystem: File system operations 35 | - /kernel: Kernel interactions 36 | - /process: Process management 37 | 38 | ### /security 39 | - /exploits: Security vulnerability examples 40 | - /protection: Protection mechanisms 41 | 42 | ### /utils 43 | - Utility implementations 44 | - Matrix multiplication optimizations 45 | - Shell implementation 46 | 47 | ## Documentation 48 | 49 | Comprehensive documentation is available in the `/docs` directory. For contribution guidelines, please see [CONTRIBUTING.md](CONTRIBUTING.md). 50 | 51 | ## License 52 | 53 | This project is licensed under the terms specified in [LICENSE](LICENSE). -------------------------------------------------------------------------------- /accessPatterns/DRAMtiming.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define NUM_BANKS 8 6 | #define ROWS_PER_BANK 8192 7 | #define COLUMNS_PER_ROW 1024 8 | #define tCAS 14 9 | #define tRAS 32 10 | #define tRP 14 11 | #define tRCD 14 12 | 13 | typedef struct { 14 | int** data; 15 | int active_row; 16 | bool is_row_active; 17 | int last_activation_cycle; 18 | } DRAMBank; 19 | 20 | typedef struct { 21 | DRAMBank banks[NUM_BANKS]; 22 | int current_cycle; 23 | } DRAMChip; 24 | 25 | int access_dram(DRAMChip* chip, int bank, int row, int column) { 26 | DRAMBank* current_bank = &chip->banks[bank]; 27 | int cycles = 0; 28 | 29 | // Checking if we need to open a new row 30 | if (!current_bank->is_row_active || current_bank->active_row != row) { 31 | if (current_bank->is_row_active) { 32 | int cycles_since_activation = chip->current_cycle - current_bank->last_activation_cycle; 33 | if (cycles_since_activation < tRAS) { 34 | cycles += tRAS - cycles_since_activation; 35 | } 36 | cycles += tRP; // Precharge timing 37 | } 38 | 39 | cycles += tRCD; 40 | current_bank->active_row = row; 41 | current_bank->is_row_active = true; 42 | current_bank->last_activation_cycle = chip->current_cycle + cycles; 43 | } 44 | 45 | cycles += tCAS; 46 | 47 | // Update current cycle 48 | chip->current_cycle += cycles; 49 | 50 | return cycles; 51 | } 52 | 53 | int main() { 54 | DRAMChip chip = {0}; 55 | 56 | // Allocate memory for each bank's data array 57 | for (int i = 0; i < NUM_BANKS; i++) { 58 | chip.banks[i].data = (int**)malloc(ROWS_PER_BANK * sizeof(int*)); 59 | if (chip.banks[i].data == NULL) { 60 | fprintf(stderr, "Memory allocation failed\n"); 61 | exit(1); 62 | } 63 | for (int j = 0; j < ROWS_PER_BANK; j++) { 64 | chip.banks[i].data[j] = (int*)malloc(COLUMNS_PER_ROW * sizeof(int)); 65 | if (chip.banks[i].data[j] == NULL) { 66 | fprintf(stderr, "Memory allocation failed\n"); 67 | exit(1); 68 | } 69 | } 70 | } 71 | 72 | printf("Access (0,0,0): %d cycles\n", access_dram(&chip, 0, 0, 0)); 73 | printf("Access (0,0,1): %d cycles\n", access_dram(&chip, 0, 0, 1)); 74 | printf("Access (0,1,0): %d cycles\n", access_dram(&chip, 0, 1, 0)); 75 | printf("Access (1,0,0): %d cycles\n", access_dram(&chip, 1, 0, 0)); 76 | 77 | // Now let's free the dynamically allocated memory 78 | for (int i = 0; i < NUM_BANKS; i++) { 79 | for (int j = 0; j < ROWS_PER_BANK; j++) { 80 | free(chip.banks[i].data[j]); 81 | } 82 | free(chip.banks[i].data); 83 | } 84 | 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /accessPatterns/FirstReady-FirstComeFirstServe.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_QUEUE_SIZE 100 7 | 8 | typedef struct { 9 | int address; 10 | time_t timestamp; 11 | bool is_row_buffer_hit; 12 | } MemoryRequest; 13 | 14 | typedef struct { 15 | MemoryRequest requests[MAX_QUEUE_SIZE]; 16 | int front; 17 | int rear; 18 | int size; 19 | } Queue; 20 | 21 | void initQueue(Queue *q) { 22 | q->front = 0; 23 | q->rear = -1; 24 | q->size = 0; 25 | } 26 | 27 | bool isQueueEmpty(Queue *q) { 28 | return q->size == 0; 29 | } 30 | 31 | bool isQueueFull(Queue *q) { 32 | return q->size == MAX_QUEUE_SIZE; 33 | } 34 | 35 | void enqueue(Queue *q, MemoryRequest request) { 36 | if (isQueueFull(q)) { 37 | printf("Queue is full, cannot enqueue\n"); 38 | return; 39 | } 40 | q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; 41 | q->requests[q->rear] = request; 42 | q->size++; 43 | } 44 | 45 | MemoryRequest dequeue(Queue *q) { 46 | if (isQueueEmpty(q)) { 47 | printf("Queue is empty, cannot dequeue\n"); 48 | exit(1); 49 | } 50 | MemoryRequest request = q->requests[q->front]; 51 | q->front = (q->front + 1) % MAX_QUEUE_SIZE; 52 | q->size--; 53 | return request; 54 | } 55 | 56 | MemoryRequest frFcfsSchedule(Queue *hitQueue, Queue *missQueue) { 57 | if (!isQueueEmpty(hitQueue)) { 58 | return dequeue(hitQueue); 59 | } else if (!isQueueEmpty(missQueue)) { 60 | return dequeue(missQueue); 61 | } else { 62 | printf("Both queues are empty\n"); 63 | exit(1); 64 | } 65 | } 66 | 67 | int main() { 68 | Queue hitQueue, missQueue; 69 | initQueue(&hitQueue); 70 | initQueue(&missQueue); 71 | 72 | // Simulate memory requests 73 | for (int i = 0; i < 10; i++) { 74 | MemoryRequest request; 75 | request.address = rand() % 1000; 76 | request.timestamp = time(NULL); 77 | request.is_row_buffer_hit = rand() % 2; 78 | 79 | if (request.is_row_buffer_hit) { 80 | enqueue(&hitQueue, request); 81 | } else { 82 | enqueue(&missQueue, request); 83 | } 84 | } 85 | 86 | // Schedule and process requests 87 | while (!isQueueEmpty(&hitQueue) || !isQueueEmpty(&missQueue)) { 88 | MemoryRequest scheduled = frFcfsSchedule(&hitQueue, &missQueue); 89 | printf("Processed request: Address %d, Timestamp %ld, Is Hit: %d\n", 90 | scheduled.address, scheduled.timestamp, scheduled.is_row_buffer_hit); 91 | } 92 | 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /accessPatterns/SimulatingDRAMTiming.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define NUM_BANKS 8 6 | #define ROWS_PER_BANK 1024 7 | #define COLS_PER_ROW 1024 8 | 9 | #define tCAS 10 10 | #define tRAS 28 11 | #define tRP 10 12 | 13 | typedef struct { 14 | int open_row; 15 | int cycle_opened; 16 | } BankState; 17 | 18 | BankState bank_states[NUM_BANKS] = {{-1, 0}}; 19 | int current_cycle = 0; 20 | 21 | void memory_access(uint32_t address) { 22 | int bank = (address / COLS_PER_ROW) % NUM_BANKS; 23 | int row = (address / COLS_PER_ROW) / NUM_BANKS; 24 | int col = address % COLS_PER_ROW; 25 | 26 | printf("Accessing Bank: %d, Row: %d, Col: %d\n", bank, row, col); 27 | 28 | if (bank_states[bank].open_row != row) { 29 | if (bank_states[bank].open_row != -1) { 30 | // Need to close the current row first 31 | current_cycle += tRP; 32 | printf("Closing row %d, new cycle: %d\n", bank_states[bank].open_row, current_cycle); 33 | } 34 | // Open the new row 35 | current_cycle += tRAS; 36 | bank_states[bank].open_row = row; 37 | bank_states[bank].cycle_opened = current_cycle; 38 | printf("Opening row %d, new cycle: %d\n", row, current_cycle); 39 | } 40 | 41 | current_cycle += tCAS; 42 | printf("Accessing column, new cycle: %d\n", current_cycle); 43 | 44 | // We will check if we need to close the row (auto-precharge) 45 | if (current_cycle - bank_states[bank].cycle_opened >= tRAS) { 46 | current_cycle += tRP; 47 | bank_states[bank].open_row = -1; 48 | printf("Auto-precharge, new cycle: %d\n", current_cycle); 49 | } 50 | } 51 | 52 | int main() { 53 | memory_access(0); // New row 54 | memory_access(1); // Same row 55 | memory_access(COLS_PER_ROW * NUM_BANKS); // New row, same bank 56 | memory_access(COLS_PER_ROW); // New bank 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /accessPatterns/addressCalculation.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Example { 5 | char c; 6 | int i; 7 | short s; 8 | }; 9 | 10 | void printArrayAddresses(int *arr, int size) { 11 | for (int i = 0; i < size; i++) { 12 | printf("Address of arr[%d]: %p\n", i, (void *)&arr[i]); 13 | } 14 | } 15 | 16 | void print2DArrayAddresses(int rows, int cols, int (*arr)[cols]) { 17 | for (int i = 0; i < rows; i++) { 18 | for (int j = 0; j < cols; j++) { 19 | printf("Address of arr[%d][%d]: %p\n", i, j, (void *)&arr[i][j]); 20 | } 21 | } 22 | } 23 | 24 | int main() { 25 | // 1D Array 26 | int staticArray[5] = {10, 20, 30, 40, 50}; 27 | printf("1D Static Array:\n"); 28 | printArrayAddresses(staticArray, 5); 29 | 30 | // Dynamic 1D Array 31 | int *dynamicArray = (int *)malloc(5 * sizeof(int)); 32 | for (int i = 0; i < 5; i++) { 33 | dynamicArray[i] = (i + 1) * 10; 34 | } 35 | printf("\nDynamic 1D Array:\n"); 36 | printArrayAddresses(dynamicArray, 5); 37 | 38 | // 2D Static Array 39 | int staticMatrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 40 | printf("\n2D Static Array:\n"); 41 | print2DArrayAddresses(3, 3, staticMatrix); 42 | 43 | // Dynamic 2D Array (contiguous allocation) 44 | int rows = 3, cols = 3; 45 | int (*dynamicMatrix)[cols] = malloc(rows * cols * sizeof(int)); 46 | for (int i = 0; i < rows; i++) { 47 | for (int j = 0; j < cols; j++) { 48 | dynamicMatrix[i][j] = i * cols + j + 1; 49 | } 50 | } 51 | printf("\nDynamic 2D Array (contiguous):\n"); 52 | print2DArrayAddresses(rows, cols, dynamicMatrix); 53 | 54 | // Dynamic 2D Array (array of pointers) 55 | int **dynamicMatrix2 = malloc(rows * sizeof(int *)); 56 | for (int i = 0; i < rows; i++) { 57 | dynamicMatrix2[i] = malloc(cols * sizeof(int)); 58 | for (int j = 0; j < cols; j++) { 59 | dynamicMatrix2[i][j] = i * cols + j + 1; 60 | } 61 | } 62 | printf("\nDynamic 2D Array (array of pointers):\n"); 63 | for (int i = 0; i < rows; i++) { 64 | for (int j = 0; j < cols; j++) { 65 | printf("Address of dynamicMatrix2[%d][%d]: %p\n", i, j, (void *)&dynamicMatrix2[i][j]); 66 | } 67 | } 68 | 69 | // Structure alignment and padding 70 | struct Example ex; 71 | printf("\nStructure Alignment and Padding:\n"); 72 | printf("Address of ex.c: %p\n", (void *)&ex.c); 73 | printf("Address of ex.i: %p\n", (void *)&ex.i); 74 | printf("Address of ex.s: %p\n", (void *)&ex.s); 75 | printf("Size of struct Example: %zu\n", sizeof(struct Example)); 76 | 77 | // Clean up 78 | free(dynamicArray); 79 | free(dynamicMatrix); 80 | for (int i = 0; i < rows; i++) { 81 | free(dynamicMatrix2[i]); 82 | } 83 | free(dynamicMatrix2); 84 | 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /accessPatterns/addressTranslation.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BANK_BITS 2 5 | #define ROW_BITS 14 6 | #define COL_BITS 10 7 | 8 | typedef struct { 9 | uint32_t bank; 10 | uint32_t row; 11 | uint32_t column; 12 | } DRAMAddress; 13 | 14 | DRAMAddress translate_address(uint32_t logical_address) { 15 | DRAMAddress dram_addr; 16 | dram_addr.bank = (logical_address >> (ROW_BITS + COL_BITS)) & ((1 << BANK_BITS) - 1); 17 | dram_addr.row = (logical_address >> COL_BITS) & ((1 << ROW_BITS) - 1); 18 | dram_addr.column = logical_address & ((1 << COL_BITS) - 1); 19 | 20 | return dram_addr; 21 | } 22 | 23 | void print_dram_address(DRAMAddress addr) { 24 | printf("Bank: %u, Row: %u, Column: %u\n", addr.bank, addr.row, addr.column); 25 | } 26 | 27 | int main() { 28 | uint32_t logical_address = 0x12345678; 29 | DRAMAddress dram_addr = translate_address(logical_address); 30 | 31 | printf("Logical Address: 0x%08X\n", logical_address); 32 | print_dram_address(dram_addr); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /accessPatterns/memoryBarrier.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define NUM_THREADS 4 7 | #define NUM_ITERATIONS 1000000 8 | 9 | // Shared variables 10 | atomic_int counter = 0; 11 | int data = 0; 12 | 13 | // Thread function 14 | void* thread_function(void* arg) { 15 | int thread_id = *(int*)arg; 16 | 17 | for (int i = 0; i < NUM_ITERATIONS; i++) { 18 | // Atomically increment the counter 19 | atomic_fetch_add(&counter, 1); 20 | 21 | // Perform a non-atomic operation on data 22 | data++; 23 | 24 | // Use a memory barrier to ensure the increment is visible to other threads 25 | atomic_thread_fence(memory_order_release); 26 | 27 | // Read the counter value 28 | int current_counter = atomic_load(&counter); 29 | 30 | // Use another memory barrier before accessing data 31 | atomic_thread_fence(memory_order_acquire); 32 | 33 | // Check if data matches the counter 34 | if (data != current_counter) { 35 | printf("Thread %d: Inconsistency detected! Counter: %d, Data: %d\n", 36 | thread_id, current_counter, data); 37 | } 38 | } 39 | 40 | return NULL; 41 | } 42 | 43 | int main() { 44 | pthread_t threads[NUM_THREADS]; 45 | int thread_ids[NUM_THREADS]; 46 | 47 | // Create threads 48 | for (int i = 0; i < NUM_THREADS; i++) { 49 | thread_ids[i] = i; 50 | if (pthread_create(&threads[i], NULL, thread_function, &thread_ids[i]) != 0) { 51 | perror("pthread_create"); 52 | exit(1); 53 | } 54 | } 55 | 56 | // Wait for threads to finish 57 | for (int i = 0; i < NUM_THREADS; i++) { 58 | if (pthread_join(threads[i], NULL) != 0) { 59 | perror("pthread_join"); 60 | exit(1); 61 | } 62 | } 63 | 64 | printf("Final counter value: %d\n", atomic_load(&counter)); 65 | printf("Final data value: %d\n", data); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /accessPatterns/sharedCounter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define NUM_THREADS 4 6 | #define NUM_INCREMENTS 1000000 7 | 8 | atomic_int counter = 0; 9 | 10 | int increment_counter(void* arg) { 11 | for (int i = 0; i < NUM_INCREMENTS; ++i) { 12 | atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed); 13 | } 14 | return 0; 15 | } 16 | 17 | int main() { 18 | thrd_t threads[NUM_THREADS]; 19 | 20 | for (int i = 0; i < NUM_THREADS; ++i) { 21 | thrd_create(&threads[i], increment_counter, NULL); 22 | } 23 | 24 | for (int i = 0; i < NUM_THREADS; ++i) { 25 | thrd_join(threads[i], NULL); 26 | } 27 | 28 | printf("Final counter value: %d\n", atomic_load(&counter)); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /accessPatterns/stridePrefetcher.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define TABLE_SIZE 16 7 | #define CONFIDENCE_THRESHOLD 3 8 | #define MAX_PREFETCH_DISTANCE 4 9 | 10 | typedef struct { 11 | uintptr_t base_address; 12 | intptr_t stride; 13 | uintptr_t last_address; 14 | int confidence; 15 | enum { INITIAL, STEADY, NO_PREDICTION } state; 16 | } PrefetchEntry; 17 | 18 | typedef struct { 19 | PrefetchEntry entries[TABLE_SIZE]; 20 | } PrefetchTable; 21 | 22 | PrefetchTable prefetch_table = {0}; 23 | 24 | uint64_t hash_address(uintptr_t address) { 25 | return (address >> 6) & (TABLE_SIZE - 1); // Simple hash, assuming 64-byte cache lines 26 | } 27 | 28 | void update_prefetch_entry(uintptr_t address) { 29 | uint64_t index = hash_address(address); 30 | PrefetchEntry *entry = &prefetch_table.entries[index]; 31 | 32 | if (entry->base_address == 0) { 33 | // New entry 34 | entry->base_address = address; 35 | entry->last_address = address; 36 | entry->state = INITIAL; 37 | return; 38 | } 39 | 40 | intptr_t current_stride = address - entry->last_address; 41 | 42 | if (current_stride == entry->stride) { 43 | entry->confidence++; 44 | if (entry->confidence >= CONFIDENCE_THRESHOLD) { 45 | entry->state = STEADY; 46 | } 47 | } else { 48 | entry->stride = current_stride; 49 | entry->confidence = 1; 50 | entry->state = INITIAL; 51 | } 52 | 53 | entry->last_address = address; 54 | } 55 | 56 | void issue_prefetch(uintptr_t address) { 57 | printf("Prefetching address: 0x%lx\n", address); 58 | // In real hardware, this would trigger a memory request 59 | } 60 | 61 | void handle_memory_access(uintptr_t address) { 62 | printf("Accessing address: 0x%lx\n", address); 63 | update_prefetch_entry(address); 64 | 65 | uint64_t index = hash_address(address); 66 | PrefetchEntry *entry = &prefetch_table.entries[index]; 67 | 68 | if (entry->state == STEADY) { 69 | for (int i = 1; i <= MAX_PREFETCH_DISTANCE; i++) { 70 | uintptr_t prefetch_address = address + (entry->stride * i); 71 | issue_prefetch(prefetch_address); 72 | } 73 | } 74 | } 75 | 76 | int main() { 77 | uintptr_t base_address = 0x1000; 78 | int stride = 64; // Assuming 64-byte cache lines 79 | 80 | for (int i = 0; i < 20; i++) { 81 | uintptr_t address = base_address + (i * stride); 82 | handle_memory_access(address); 83 | } 84 | 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /accessPatterns/visPadding.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct GamePacket { 5 | uint8_t packetType; 6 | uint32_t playerId; 7 | float positionX; 8 | float positionY; 9 | uint8_t health; 10 | uint16_t score; 11 | }; 12 | 13 | int main() { 14 | struct GamePacket packet; 15 | 16 | printf("Address of packetType: %p\n", (void*)&packet.packetType); 17 | printf("Address of playerId: %p\n", (void*)&packet.playerId); 18 | printf("Address of positionX: %p\n", (void*)&packet.positionX); 19 | printf("Address of positionY: %p\n", (void*)&packet.positionY); 20 | printf("Address of health: %p\n", (void*)&packet.health); 21 | printf("Address of score: %p\n", (void*)&packet.score); 22 | 23 | printf("Size of GamePacket: %zu bytes\n", sizeof(struct GamePacket)); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /accessPatterns/visPaddingWithPragma.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #pragma pack(push, 1) 5 | struct GamePacket { 6 | uint8_t packetType; 7 | uint32_t playerId; 8 | float positionX; 9 | float positionY; 10 | uint8_t health; 11 | uint16_t score; 12 | }; 13 | #pragma pack(pop) 14 | 15 | int main() { 16 | struct GamePacket packet; 17 | 18 | printf("Address of packetType: %p\n", (void*)&packet.packetType); 19 | printf("Address of playerId: %p\n", (void*)&packet.playerId); 20 | printf("Address of positionX: %p\n", (void*)&packet.positionX); 21 | printf("Address of positionY: %p\n", (void*)&packet.positionY); 22 | printf("Address of health: %p\n", (void*)&packet.health); 23 | printf("Address of score: %p\n", (void*)&packet.score); 24 | 25 | printf("Size of GamePacket: %zu bytes\n", sizeof(struct GamePacket)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /compilation/examples/hello: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/compilation/examples/hello -------------------------------------------------------------------------------- /compilation/examples/hello.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | printf("Hello, World!\n"); 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /compilation/examples/hello.s: -------------------------------------------------------------------------------- 1 | .file "hello.c" 2 | .text 3 | .section .rodata 4 | .LC0: 5 | .string "Hello, World!" 6 | .text 7 | .globl main 8 | .type main, @function 9 | main: 10 | .LFB0: 11 | .cfi_startproc 12 | endbr64 13 | pushq %rbp 14 | .cfi_def_cfa_offset 16 15 | .cfi_offset 6, -16 16 | movq %rsp, %rbp 17 | .cfi_def_cfa_register 6 18 | leaq .LC0(%rip), %rax 19 | movq %rax, %rdi 20 | call puts@PLT 21 | movl $0, %eax 22 | popq %rbp 23 | .cfi_def_cfa 7, 8 24 | ret 25 | .cfi_endproc 26 | .LFE0: 27 | .size main, .-main 28 | .ident "GCC: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0" 29 | .section .note.GNU-stack,"",@progbits 30 | .section .note.gnu.property,"a" 31 | .align 8 32 | .long 1f - 0f 33 | .long 4f - 1f 34 | .long 5 35 | 0: 36 | .string "GNU" 37 | 1: 38 | .align 8 39 | .long 0xc0000002 40 | .long 3f - 2f 41 | 2: 42 | .long 0x3 43 | 3: 44 | .align 8 45 | 4: 46 | -------------------------------------------------------------------------------- /compilation/examples/hello_opt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/compilation/examples/hello_opt -------------------------------------------------------------------------------- /compilation/examples/hello_small: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/compilation/examples/hello_small -------------------------------------------------------------------------------- /compilation/examples/hello_static: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/compilation/examples/hello_static -------------------------------------------------------------------------------- /computerArchitecture/s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/computerArchitecture/s -------------------------------------------------------------------------------- /concurrency/synchronization/interruptHandlers.md: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define NUM_INTERRUPTS 3 8 | #define NUM_EVENTS 10 9 | 10 | pthread_t interrupt_threads[NUM_INTERRUPTS]; 11 | pthread_mutex_t interrupt_mutex = PTHREAD_MUTEX_INITIALIZER; 12 | pthread_cond_t interrupt_cond = PTHREAD_COND_INITIALIZER; 13 | int interrupt_pending[NUM_INTERRUPTS] = {0}; 14 | 15 | void simulate_interrupt(int interrupt_id) { 16 | pthread_mutex_lock(&interrupt_mutex); 17 | interrupt_pending[interrupt_id] = 1; 18 | pthread_cond_signal(&interrupt_cond); 19 | pthread_mutex_unlock(&interrupt_mutex); 20 | } 21 | 22 | void *interrupt_handler(void *arg) { 23 | int interrupt_id = *(int*)arg; 24 | struct timespec start, end; 25 | 26 | while (1) { 27 | pthread_mutex_lock(&interrupt_mutex); 28 | while (!interrupt_pending[interrupt_id]) { 29 | pthread_cond_wait(&interrupt_cond, &interrupt_mutex); 30 | } 31 | interrupt_pending[interrupt_id] = 0; 32 | pthread_mutex_unlock(&interrupt_mutex); 33 | 34 | clock_gettime(CLOCK_MONOTONIC, &start); 35 | 36 | usleep(50000); // 50ms 37 | 38 | clock_gettime(CLOCK_MONOTONIC, &end); 39 | long long duration = (end.tv_sec - start.tv_sec) * 1000000000LL + (end.tv_nsec - start.tv_nsec); 40 | 41 | printf("Interrupt %d handled. Duration: %lld ns\n", interrupt_id, duration); 42 | } 43 | 44 | return NULL; 45 | } 46 | 47 | int main() { 48 | int interrupt_ids[NUM_INTERRUPTS]; 49 | 50 | for (int i = 0; i < NUM_INTERRUPTS; i++) { 51 | interrupt_ids[i] = i; 52 | pthread_create(&interrupt_threads[i], NULL, interrupt_handler, &interrupt_ids[i]); 53 | } 54 | 55 | for (int i = 0; i < NUM_EVENTS; i++) { 56 | int interrupt_id = i % NUM_INTERRUPTS; 57 | simulate_interrupt(interrupt_id); 58 | usleep(10000); // 10ms between interrupts 59 | } 60 | 61 | sleep(1); // Allow time for all interrupts to be handled 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /concurrency/synchronization/priority_inheritance.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct rt_mutex { 7 | pthread_mutex_t lock; 8 | int owner_priority; 9 | int highest_waiter_priority; 10 | }; 11 | 12 | struct task_struct { 13 | int id; 14 | int priority; 15 | struct rt_mutex *blocked_on; 16 | }; 17 | 18 | #define NUM_TASKS 3 19 | #define LOW_PRIO 1 20 | #define MED_PRIO 2 21 | #define HIGH_PRIO 3 22 | 23 | struct rt_mutex mutex; 24 | struct task_struct tasks[NUM_TASKS]; 25 | 26 | void rt_mutex_init(struct rt_mutex *mutex) { 27 | pthread_mutex_init(&mutex->lock, NULL); 28 | mutex->owner_priority = 0; 29 | mutex->highest_waiter_priority = 0; 30 | } 31 | 32 | void rt_mutex_lock(struct rt_mutex *mutex, struct task_struct *task) { 33 | printf("Task %d (priority %d) trying to acquire mutex\n", task->id, task->priority); 34 | 35 | if (mutex->owner_priority != 0 && task->priority > mutex->highest_waiter_priority) { 36 | mutex->highest_waiter_priority = task->priority; 37 | printf("Boosting mutex owner priority to %d\n", mutex->highest_waiter_priority); 38 | } 39 | 40 | pthread_mutex_lock(&mutex->lock); 41 | 42 | mutex->owner_priority = task->priority; 43 | mutex->highest_waiter_priority = 0; 44 | printf("Task %d acquired mutex\n", task->id); 45 | } 46 | 47 | void rt_mutex_unlock(struct rt_mutex *mutex, struct task_struct *task) { 48 | printf("Task %d releasing mutex\n", task->id); 49 | mutex->owner_priority = 0; 50 | pthread_mutex_unlock(&mutex->lock); 51 | } 52 | 53 | void* task_function(void *arg) { 54 | struct task_struct *task = (struct task_struct*)arg; 55 | 56 | printf("Task %d (priority %d) started\n", task->id, task->priority); 57 | sleep(1); 58 | rt_mutex_lock(&mutex, task); 59 | 60 | printf("Task %d working with mutex\n", task->id); 61 | sleep(2); 62 | 63 | rt_mutex_unlock(&mutex, task); 64 | 65 | printf("Task %d finished\n", task->id); 66 | 67 | return NULL; 68 | } 69 | 70 | int main() { 71 | pthread_t threads[NUM_TASKS]; 72 | 73 | rt_mutex_init(&mutex); 74 | 75 | tasks[0] = (struct task_struct){.id = 1, .priority = LOW_PRIO}; 76 | tasks[1] = (struct task_struct){.id = 2, .priority = MED_PRIO}; 77 | tasks[2] = (struct task_struct){.id = 3, .priority = HIGH_PRIO}; 78 | 79 | for (int i = 0; i < NUM_TASKS; i++) { 80 | pthread_create(&threads[i], NULL, task_function, &tasks[i]); 81 | sleep(1); // Start tasks with a slight delay 82 | } 83 | 84 | for (int i = 0; i < NUM_TASKS; i++) { 85 | pthread_join(threads[i], NULL); 86 | } 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /concurrency/synchronization/rtMutex.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct { 7 | pthread_mutex_t mutex; 8 | int owner_priority; 9 | } rt_mutex_t; 10 | 11 | void rt_mutex_init(rt_mutex_t *mutex) { 12 | pthread_mutex_init(&mutex->mutex, NULL); 13 | mutex->owner_priority = -1; 14 | } 15 | 16 | void rt_mutex_lock(rt_mutex_t *mutex, int priority) { 17 | struct timespec start, end; 18 | clock_gettime(CLOCK_MONOTONIC, &start); 19 | 20 | pthread_mutex_lock(&mutex->mutex); 21 | 22 | clock_gettime(CLOCK_MONOTONIC, &end); 23 | long long wait_time = (end.tv_sec - start.tv_sec) * 1000000000LL + (end.tv_nsec - start.tv_nsec); 24 | 25 | printf("Thread priority %d acquired lock. Wait time: %lld ns\n", priority, wait_time); 26 | 27 | if (mutex->owner_priority != -1 && priority > mutex->owner_priority) { 28 | printf("Priority inheritance: Boosting owner from %d to %d\n", mutex->owner_priority, priority); 29 | } 30 | mutex->owner_priority = priority; 31 | } 32 | 33 | void rt_mutex_unlock(rt_mutex_t *mutex) { 34 | printf("Thread priority %d released lock\n", mutex->owner_priority); 35 | mutex->owner_priority = -1; 36 | pthread_mutex_unlock(&mutex->mutex); 37 | } 38 | 39 | // Test function 40 | void *test_thread(void *arg) { 41 | rt_mutex_t *mutex = (rt_mutex_t *)arg; 42 | int priority = (int)(long)pthread_self() % 100; // Simulated priority 43 | 44 | rt_mutex_lock(mutex, priority); 45 | usleep(10000); // Simulating some work 46 | rt_mutex_unlock(mutex); 47 | 48 | return NULL; 49 | } 50 | 51 | int main() { 52 | rt_mutex_t mutex; 53 | rt_mutex_init(&mutex); 54 | 55 | pthread_t threads[10]; 56 | for (int i = 0; i < 10; i++) { 57 | pthread_create(&threads[i], NULL, test_thread, &mutex); 58 | } 59 | 60 | for (int i = 0; i < 10; i++) { 61 | pthread_join(threads[i], NULL); 62 | } 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /concurrency/threads/blockingIO.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | char buffer[1024]; 6 | ssize_t bytes_read; 7 | 8 | printf("Waiting for input…\n"); 9 | bytes_read = read(STDIN_FILENO, buffer, sizeof(buffer)); 10 | 11 | if (bytes_read > 0) { 12 | printf("Read %zd bytes: %.*s\n", bytes_read, (int)bytes_read, buffer); 13 | } else if (bytes_read == 0) { 14 | printf("End of file reached\n"); 15 | } else { 16 | perror("read"); 17 | } 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /concurrency/threads/clientSide.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PORT 8080 8 | #define BUFFER_SIZE 1024 9 | 10 | int main() { 11 | int sock = 0; 12 | struct sockaddr_in serv_addr; 13 | char buffer[BUFFER_SIZE] = {0}; 14 | char message[BUFFER_SIZE]; 15 | 16 | if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 17 | printf("\n Socket creation error \n"); 18 | return -1; 19 | } 20 | 21 | serv_addr.sin_family = AF_INET; 22 | serv_addr.sin_port = htons(PORT); 23 | 24 | if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { 25 | printf("\nInvalid address/ Address not supported \n"); 26 | return -1; 27 | } 28 | 29 | if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { 30 | printf("\nConnection Failed \n"); 31 | return -1; 32 | } 33 | 34 | printf("Connected to server. Type your messages (type 'exit' to quit):\n"); 35 | 36 | while (1) { 37 | fgets(message, BUFFER_SIZE, stdin); 38 | message[strcspn(message, "\n")] = 0; 39 | 40 | if (strcmp(message, "exit") == 0) { 41 | break; 42 | } 43 | 44 | send(sock, message, strlen(message), 0); 45 | printf("Message sent: %s\n", message); 46 | 47 | int valread = read(sock, buffer, BUFFER_SIZE); 48 | printf("Server response: %s\n", buffer); 49 | 50 | memset(buffer, 0, sizeof(buffer)); 51 | } 52 | 53 | close(sock); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /concurrency/threads/fork_pointer_check.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | bool is_pointer_valid(void* ptr, size_t size, bool write_access) { 10 | pid_t child = fork(); 11 | 12 | if (child == 0) { 13 | // Child process 14 | if (write_access) { 15 | memset(ptr, 0, size); // Attempt to write 16 | } else { 17 | char* buffer = malloc(size); 18 | if (buffer) { 19 | memcpy(buffer, ptr, size); // Attempt to read 20 | free(buffer); 21 | } 22 | } 23 | exit(EXIT_SUCCESS); 24 | } else if (child > 0) { 25 | int status; 26 | pid_t result = waitpid(child, &status, 0); 27 | assert(result >= 0); 28 | return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS; 29 | } else { 30 | perror("fork"); 31 | return false; 32 | } 33 | } 34 | 35 | int main() { 36 | int* valid_ptr = malloc(sizeof(int)); 37 | printf("Valid pointer check (write): %s\n", 38 | is_pointer_valid(valid_ptr, sizeof(int), true) ? "PASS" : "FAIL"); 39 | printf("Valid pointer check (read): %s\n", 40 | is_pointer_valid(valid_ptr, sizeof(int), false) ? "PASS" : "FAIL"); 41 | 42 | int* invalid_ptr = (int*)0xdeadbeef; 43 | printf("Invalid pointer check (write): %s\n", 44 | is_pointer_valid(invalid_ptr, sizeof(int), true) ? "PASS" : "FAIL"); 45 | printf("Invalid pointer check (read): %s\n", 46 | is_pointer_valid(invalid_ptr, sizeof(int), false) ? "PASS" : "FAIL"); 47 | 48 | free(valid_ptr); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /concurrency/threads/leaderElection: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/concurrency/threads/leaderElection -------------------------------------------------------------------------------- /concurrency/threads/multiThreading.c: -------------------------------------------------------------------------------- 1 | 2 | #define _GNU_SOURCE 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define NUM_THREADS 4 12 | #define ITERATIONS 1000000 13 | 14 | // Shared data 15 | int counter = 0; 16 | pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 17 | 18 | // Thread function 19 | void* thread_func(void* arg) { 20 | int thread_id = *(int*)arg; 21 | int local_counter = 0; 22 | 23 | // Pin thread to a specific CPU core 24 | cpu_set_t cpuset; 25 | CPU_ZERO(&cpuset); 26 | CPU_SET(thread_id % sysconf(_SC_NPROCESSORS_ONLN), &cpuset); 27 | pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); 28 | 29 | for (int i = 0; i < ITERATIONS; i++) { 30 | // Simulate some work 31 | for (int j = 0; j < 100; j++) { 32 | local_counter++; 33 | } 34 | 35 | // Update shared counter (atomic operation) 36 | __atomic_fetch_add(&counter, 1, __ATOMIC_SEQ_CST); 37 | 38 | // Periodically yield to allow other threads to run (simulating time-slicing) 39 | if (i % 1000 == 0) { 40 | sched_yield(); 41 | } 42 | } 43 | 44 | printf("Thread %d finished. Local counter: %d\n", thread_id, local_counter); 45 | return NULL; 46 | } 47 | 48 | int main() { 49 | pthread_t threads[NUM_THREADS]; 50 | int thread_ids[NUM_THREADS]; 51 | struct timespec start, end; 52 | 53 | // Start timing 54 | clock_gettime(CLOCK_MONOTONIC, &start); 55 | 56 | // Create threads 57 | for (int i = 0; i < NUM_THREADS; i++) { 58 | thread_ids[i] = i; 59 | if (pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]) != 0) { 60 | perror("pthread_create"); 61 | exit(1); 62 | } 63 | } 64 | 65 | // Wait for threads to finish 66 | for (int i = 0; i < NUM_THREADS; i++) { 67 | pthread_join(threads[i], NULL); 68 | } 69 | 70 | // End timing 71 | clock_gettime(CLOCK_MONOTONIC, &end); 72 | 73 | // Calculate elapsed time 74 | double elapsed = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1e9; 75 | 76 | printf("All threads finished.\n"); 77 | printf("Final counter value: %d\n", __atomic_load_n(&counter, __ATOMIC_SEQ_CST)); 78 | printf("Elapsed time: %.6f seconds\n", elapsed); 79 | 80 | return 0; 81 | } 82 | -------------------------------------------------------------------------------- /concurrency/threads/mutex_lock.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define NUM_READERS 4 7 | #define BUFFER_SIZE 1024 8 | 9 | char buffer[BUFFER_SIZE]; 10 | pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 11 | 12 | void* reader_thread(void* arg) { 13 | long thread_id = (long)arg; 14 | 15 | while (1) { 16 | pthread_mutex_lock(&lock); 17 | printf("Reader %ld: %s\n", thread_id, buffer); 18 | pthread_mutex_unlock(&lock); 19 | usleep(500000); 20 | } 21 | 22 | return NULL; 23 | } 24 | 25 | int main() { 26 | pthread_t readers[NUM_READERS]; 27 | 28 | for (long i = 0; i < NUM_READERS; i++) { 29 | pthread_create(&readers[i], NULL, reader_thread, (void*)i); 30 | } 31 | 32 | char* strings[] = {"Hello, World!", "Mutex is amazing", "C programming rocks"}; 33 | int num_strings = sizeof(strings) / sizeof(strings[0]); 34 | int index = 0; 35 | 36 | while (1) { 37 | pthread_mutex_lock(&lock); 38 | snprintf(buffer, BUFFER_SIZE, "%s", strings[index]); 39 | pthread_mutex_unlock(&lock); 40 | 41 | index = (index + 1) % num_strings; 42 | sleep(2); 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /concurrency/threads/nonBlockingIO.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | char buffer[1024]; 8 | ssize_t bytes_read; 9 | int flags; 10 | 11 | flags = fcntl(STDIN_FILENO, F_GETFL, 0); 12 | fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); 13 | 14 | printf("Attempting to read…\n"); 15 | bytes_read = read(STDIN_FILENO, buffer, sizeof(buffer)); 16 | 17 | if (bytes_read > 0) { 18 | printf("Read %zd bytes: %.*s\n", bytes_read, (int)bytes_read, buffer); 19 | } else if (bytes_read == -1) { 20 | if (errno == EAGAIN || errno == EWOULDBLOCK) { 21 | printf("No data available right now\n"); 22 | } else { 23 | perror("read"); 24 | } 25 | } else { 26 | printf("End of file reached\n"); 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /concurrency/threads/readWriteLocks.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define NUM_READERS 4 8 | #define BUFFER_SIZE 1024 9 | 10 | char buffer[BUFFER_SIZE]; 11 | pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; 12 | 13 | void* reader_thread(void* arg) { 14 | long thread_id = (long)arg; 15 | 16 | while (1) { 17 | pthread_rwlock_rdlock(&rwlock); 18 | printf("Reader %ld: ", thread_id); 19 | for (int i = 0; buffer[i] != '\0'; i++) { 20 | putchar(buffer[i]); 21 | usleep(50000); // Slow down reading 22 | } 23 | printf("\n"); 24 | pthread_rwlock_unlock(&rwlock); 25 | usleep(500000); 26 | } 27 | 28 | return NULL; 29 | } 30 | 31 | int main() { 32 | pthread_t readers[NUM_READERS]; 33 | 34 | for (long i = 0; i < NUM_READERS; i++) { 35 | pthread_create(&readers[i], NULL, reader_thread, (void*)i); 36 | } 37 | 38 | char* strings[] = {"Hello, World!", "Mutex is amazing", "C programming rocks"}; 39 | int num_strings = sizeof(strings) / sizeof(strings[0]); 40 | int index = 0; 41 | 42 | while (1) { 43 | pthread_rwlock_wrlock(&rwlock); 44 | snprintf(buffer, BUFFER_SIZE, "%s", strings[index]); 45 | pthread_rwlock_unlock(&rwlock); 46 | 47 | index = (index + 1) % num_strings; 48 | sleep(2); 49 | } 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /concurrency/threads/readWritePreference.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define NUM_READERS 4 8 | #define NUM_WRITERS 2 9 | #define BUFFER_SIZE 1024 10 | 11 | char buffer[BUFFER_SIZE]; 12 | pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; 13 | 14 | void* reader_thread(void* arg) { 15 | long thread_id = (long)arg; 16 | 17 | while (1) { 18 | pthread_rwlock_rdlock(&rwlock); 19 | printf("Reader %ld: %s\n", thread_id, buffer); 20 | pthread_rwlock_unlock(&rwlock); 21 | usleep(100000); // Sleep for 0.1 seconds 22 | } 23 | 24 | return NULL; 25 | } 26 | 27 | void* writer_thread(void* arg) { 28 | long thread_id = (long)arg; 29 | char local_buffer[BUFFER_SIZE]; 30 | 31 | while (1) { 32 | snprintf(local_buffer, BUFFER_SIZE, "Writer %ld: %ld", thread_id, random()); 33 | 34 | pthread_rwlock_wrlock(&rwlock); 35 | strcpy(buffer, local_buffer); 36 | pthread_rwlock_unlock(&rwlock); 37 | 38 | usleep(500000); 39 | } 40 | 41 | return NULL; 42 | } 43 | 44 | int main() { 45 | pthread_t readers[NUM_READERS]; 46 | pthread_t writers[NUM_WRITERS]; 47 | 48 | for (long i = 0; i < NUM_READERS; i++) { 49 | pthread_create(&readers[i], NULL, reader_thread, (void*)i); 50 | } 51 | 52 | for (long i = 0; i < NUM_WRITERS; i++) { 53 | pthread_create(&writers[i], NULL, writer_thread, (void*)i); 54 | } 55 | 56 | sleep(10); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /concurrency/threads/rwlock-buffer/rwlock_buffer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/concurrency/threads/rwlock-buffer/rwlock_buffer -------------------------------------------------------------------------------- /concurrency/threads/semaphores/consumer.c: -------------------------------------------------------------------------------- 1 | #include "semaphoreShared.h" 2 | 3 | int main() { 4 | int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666); 5 | if (shm_fd == -1) { 6 | perror("shm_open"); 7 | exit(1); 8 | } 9 | 10 | if (ftruncate(shm_fd, sizeof(struct shared_data)) == -1) { 11 | perror("ftruncate"); 12 | exit(1); 13 | } 14 | 15 | struct shared_data *shared_mem = mmap(NULL, sizeof(struct shared_data), 16 | PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); 17 | if (shared_mem == MAP_FAILED) { 18 | perror("mmap"); 19 | exit(1); 20 | } 21 | 22 | sem_t *sem_prod = sem_open(SEM_PRODUCER_NAME, O_CREAT, 0666, 0); 23 | sem_t *sem_cons = sem_open(SEM_CONSUMER_NAME, O_CREAT, 0666, 1); 24 | if (sem_prod == SEM_FAILED || sem_cons == SEM_FAILED) { 25 | perror("sem_open"); 26 | exit(1); 27 | } 28 | 29 | for (int i = 0; i < 10; i++) { 30 | sem_wait(sem_prod); 31 | printf("Consumed: %s\n", shared_mem->message); 32 | memset(shared_mem->message, 0, MAX_MESSAGE_SIZE); 33 | sem_post(sem_cons); 34 | sleep(1); 35 | } 36 | 37 | sem_close(sem_prod); 38 | sem_close(sem_cons); 39 | sem_unlink(SEM_PRODUCER_NAME); 40 | sem_unlink(SEM_CONSUMER_NAME); 41 | munmap(shared_mem, sizeof(struct shared_data)); 42 | close(shm_fd); 43 | shm_unlink(SHM_NAME); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /concurrency/threads/semaphores/producer.c: -------------------------------------------------------------------------------- 1 | #include "semaphoreShared.h" 2 | 3 | int main() { 4 | int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666); 5 | if (shm_fd == -1) { 6 | perror("shm_open"); 7 | exit(1); 8 | } 9 | 10 | if (ftruncate(shm_fd, sizeof(struct shared_data)) == -1) { 11 | perror("ftruncate"); 12 | exit(1); 13 | } 14 | 15 | struct shared_data *shared_mem = mmap(NULL, sizeof(struct shared_data), 16 | PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); 17 | if (shared_mem == MAP_FAILED) { 18 | perror("mmap"); 19 | exit(1); 20 | } 21 | 22 | sem_t *sem_prod = sem_open(SEM_PRODUCER_NAME, 0); 23 | sem_t *sem_cons = sem_open(SEM_CONSUMER_NAME, 0); 24 | if (sem_prod == SEM_FAILED || sem_cons == SEM_FAILED) { 25 | perror("sem_open"); 26 | exit(1); 27 | } 28 | 29 | for (int i = 0; i < 10; i++) { 30 | sem_wait(sem_cons); 31 | snprintf(shared_mem->message, MAX_MESSAGE_SIZE, "Message %d", i); 32 | printf("Produced: %s\n", shared_mem->message); 33 | sem_post(sem_prod); 34 | sleep(1); 35 | } 36 | 37 | sem_close(sem_prod); 38 | sem_close(sem_cons); 39 | munmap(shared_mem, sizeof(struct shared_data)); 40 | close(shm_fd); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /concurrency/threads/semaphores/semaphoreShared.h: -------------------------------------------------------------------------------- 1 | #ifndef SEMAPHORE_SHARED_H 2 | #define SEMAPHORE_SHARED_H 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #define SHM_NAME "/my_shared_memory" 12 | #define SEM_PRODUCER_NAME "/sem_producer" 13 | #define SEM_CONSUMER_NAME "/sem_consumer" 14 | #define MAX_MESSAGE_SIZE 256 15 | struct shared_data { 16 | char message[MAX_MESSAGE_SIZE]; 17 | }; 18 | #endif 19 | -------------------------------------------------------------------------------- /concurrency/threads/signal_pointer_check.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | static jmp_buf jmpbuf; 8 | static volatile sig_atomic_t sig_caught = 0; 9 | 10 | void segv_handler(int signum) { 11 | sig_caught = 1; 12 | siglongjmp(jmpbuf, 1); 13 | } 14 | 15 | int is_pointer_valid(void* ptr, size_t size, int write) { 16 | struct sigaction sa, old_sa; 17 | memset(&sa, 0, sizeof(struct sigaction)); 18 | sa.sa_handler = segv_handler; 19 | sigemptyset(&sa.sa_mask); 20 | sa.sa_flags = SA_NODEFER; 21 | 22 | if (sigaction(SIGSEGV, &sa, &old_sa) == -1) { 23 | perror("sigaction"); 24 | return 0; 25 | } 26 | 27 | sig_caught = 0; 28 | if (sigsetjmp(jmpbuf, 1) == 0) { 29 | if (write) { 30 | volatile char temp = *(volatile char*)ptr; 31 | *(volatile char*)ptr = temp; 32 | } else { 33 | volatile char temp = *(volatile char*)ptr; 34 | (void)temp; 35 | } 36 | } 37 | 38 | sigaction(SIGSEGV, &old_sa, NULL); 39 | return !sig_caught; 40 | } 41 | 42 | int main() { 43 | int* valid_ptr = malloc(sizeof(int)); 44 | printf("Valid pointer check (write): %s\n", 45 | is_pointer_valid(valid_ptr, sizeof(int), 1) ? "PASS" : "FAIL"); 46 | printf("Valid pointer check (read): %s\n", 47 | is_pointer_valid(valid_ptr, sizeof(int), 0) ? "PASS" : "FAIL"); 48 | 49 | int* invalid_ptr = (int*)0xdeadbeef; 50 | printf("Invalid pointer check (write): %s\n", 51 | is_pointer_valid(invalid_ptr, sizeof(int), 1) ? "PASS" : "FAIL"); 52 | printf("Invalid pointer check (read): %s\n", 53 | is_pointer_valid(invalid_ptr, sizeof(int), 0) ? "PASS" : "FAIL"); 54 | 55 | free(valid_ptr); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /concurrency/threads/th: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/concurrency/threads/th -------------------------------------------------------------------------------- /concurrency/threads/threadCreation.c: -------------------------------------------------------------------------------- 1 | #include // For NULL definition 2 | #include // For pthread functions and types 3 | 4 | void *newthread(void *arg) { 5 | return NULL; 6 | } 7 | 8 | int main(int argc, char **argv) { 9 | pthread_t thread; 10 | pthread_create(&thread, NULL, &newthread, NULL); 11 | pthread_join(thread, NULL); 12 | return 0; 13 | } -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # BitsAndBytes 2 | ***Are we learning enough?*** **Nah.. first we should ask "What is Enough"** 3 | -------------------------------------------------------------------------------- /docs/assemblyLanguageProgramming.md: -------------------------------------------------------------------------------- 1 | # Assembly Language Programming 2 | 3 | ## Official Documentation 4 | - **x86 and amd64 Instruction Reference** 5 | - [Link](https://www.felixcloutier.com/x86/) 6 | - **ARM Developer: ARM Assembly Language** 7 | - [Link](https://developer.arm.com/documentation/dui0068/b/ARM-Instruction-Reference) 8 | - **MIPS Architecture For Programmers** 9 | - [Link](https://www.mips.com/products/architectures/mips32-2/) 10 | 11 | ## Research Papers 12 | - **"Using Assembly Language Programming to Teach Digital Systems Design" by G. Donzellini and D. Ponta (2013)** 13 | - [Link](https://ieeexplore.ieee.org/document/6684991) 14 | - **"A Survey of Techniques for Improving Efficiency of Mobile Web Browsing" by A. Rajasekhar et al. (2020)** 15 | - [Link](https://ieeexplore.ieee.org/document/9108269) 16 | 17 | ## Additional Online Resources 18 | - **OSDev.org: Assembly Language** 19 | - [Link](https://wiki.osdev.org/Assembly) 20 | - **x86 Assembly Guide** 21 | - [Link](https://www.cs.virginia.edu/~evans/cs216/guides/x86.html) 22 | - **NASM Tutorial** 23 | - [Link](https://cs.lmu.edu/~ray/notes/nasmtutorial/) 24 | 25 | ## Books 26 | - **"Assembly Language for x86 Processors" by Kip R. Irvine** 27 | - ISBN: 0135381533 28 | - **"Professional Assembly Language" by Richard Blum** 29 | - ISBN: 0764579010 30 | - **"ARM Assembly Language Programming & Architecture" by Muhammad Ali Mazidi, Shujen Chen, Sarmad Naimi, and Sepehr Naimi** 31 | - ISBN: 0997925949 32 | 33 | ## For Deep Dive into Implementation 34 | - **"The Art of Assembly Language" by Randall Hyde** 35 | - ISBN: 1593272073 36 | 37 | ## Standards 38 | - **IEEE Std 694-1985 - IEEE Standard for Microprocessor Assembly Language** 39 | - Not freely available, but it provides guidelines for assembly language programming 40 | 41 | ## Code Example (x86 Assembly) 42 | ```nasm 43 | section .data 44 | msg db 'Hello, World!', 0Ah ; String to print 45 | len equ $ - msg ; Length of the string 46 | 47 | section .text 48 | global _start 49 | 50 | _start: 51 | ; Write the string to stdout 52 | mov eax, 4 ; System call number for sys_write 53 | mov ebx, 1 ; File descriptor 1 is stdout 54 | mov ecx, msg ; Address of string to write 55 | mov edx, len ; Number of bytes to write 56 | int 80h ; Call kernel 57 | 58 | ; Exit the program 59 | mov eax, 1 ; System call number for sys_exit 60 | xor ebx, ebx ; Return 0 status 61 | int 80h ; Call kernel 62 | ``` 63 | 64 | ## Note 65 | Assembly language programming provides deep insights into computer architecture and allows for fine-grained control over hardware. While not commonly used for large-scale application development, it's crucial for system programming, embedded systems, and performance-critical code sections. Understanding assembly also aids in debugging and reverse engineering. 66 | -------------------------------------------------------------------------------- /docs/cache_memory.md: -------------------------------------------------------------------------------- 1 | # Cache Memory 2 | 3 | ## Cache Hierarchy 4 | 5 | - **L1, L2, L3 Cache**: 6 | - [Intel's Guide on Cache Hierarchy](https://software.intel.com/content/www/us/en/develop/articles/introduction-to-cache-memory.html) 7 | 8 | ## Cache Policies 9 | 10 | - **Write-back vs Write-through**: 11 | - [Write Policies in Cache Memory](https://www.ece.cmu.edu/~ece447/s14/lib/exe/fetch.php?media=wiki:lectures:11-write-back-write-through.pdf) 12 | 13 | - **Cache Coherence**: 14 | - [Cache Coherence Protocols in Multicore Systems](https://ieeexplore.ieee.org/document/5559122) 15 | 16 | ## Official Documentation 17 | 18 | - **ARM Cortex-A Series Programmer's Guide**: 19 | - [Cache Operations](https://developer.arm.com/documentation/den0024/a/Caches/Cache-operations) 20 | 21 | - **Intel® 64 and IA-32 Architectures Software Developer’s Manual**: 22 | - [Volume 3A: System Programming Guide, Part 1](https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.html) 23 | 24 | ## Books 25 | 26 | - "Computer Architecture: A Quantitative Approach" by John L. Hennessy and David A. Patterson 27 | - ISBN: 0128119055 28 | 29 | - "Cache and Memory Hierarchy Design: A Performance Directed Approach" by Steven A. Przybylski 30 | - ISBN: 1558601368 31 | 32 | ## Research Papers 33 | 34 | - "A Case for Two-Way Skewed-Associative Caches" by Seznec, A. (1993) 35 | - [PDF](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.105.7680&rep=rep1&type=pdf) 36 | 37 | ## Additional Online Resources 38 | 39 | - **MIT OpenCourseWare - Memory Hierarchy**: 40 | - [Cache Memory](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-004-computation-structures-spring-2017/c14/) 41 | 42 | ## Standards 43 | 44 | - **JEDEC Solid State Technology Association**: 45 | - While not specific to cache, JEDEC standards affect memory design which impacts cache technology. 46 | -------------------------------------------------------------------------------- /docs/cache_optimization_techniques.md: -------------------------------------------------------------------------------- 1 | # Cache Optimization Techniques 2 | 3 | ## Overview of Cache Optimization 4 | 5 | - **Goal**: Minimize the time it takes to fetch data from memory by optimizing for cache behavior. 6 | 7 | ## Key Techniques 8 | 9 | - **Loop Tiling**: Restructuring loops to fit data into cache and reuse it effectively. 10 | - Example in C: 11 | ```c 12 | for (int kk = 0; kk < N; kk += BLOCK_SIZE) 13 | for (int jj = 0; jj < N; jj += BLOCK_SIZE) 14 | for (int i = 0; i < N; i++) 15 | for (int j = jj; j < jj + BLOCK_SIZE && j < N; j++) 16 | // operate on data block 17 | ``` 18 | 19 | - **Data Prefetching**: Fetching data into the cache before it's needed to reduce latency. 20 | 21 | - **Reducing Cache Misses**: Structuring data access patterns to increase cache hits through locality of reference. 22 | 23 | ## Tools for Cache Analysis 24 | 25 | - **Cachegrind**: A cache profiler, part of Valgrind. 26 | - **Intel VTune Amplifier**: For detailed performance analysis including cache usage. 27 | 28 | ## Books 29 | 30 | - "What Every Programmer Should Know About Memory" by Ulrich Drepper 31 | - Contains sections on cache optimization. 32 | 33 | ## Online Resources 34 | 35 | - **Cache Optimization**: Tutorials and guides on optimizing for cache. 36 | - [Cache Optimization Techniques](www.cs.cmu.edu/afs/cs/academic/class/15213-f05/www/cache-opt.pdf) 37 | -------------------------------------------------------------------------------- /docs/cloud_computing.md: -------------------------------------------------------------------------------- 1 | # Cloud Computing 2 | 3 | ## Overview of Cloud Computing 4 | 5 | - **Definition**: Delivery of computing services over the internet ("the cloud") to offer faster innovation, flexible resources, and economies of scale. 6 | 7 | ## Service Models 8 | 9 | - **IaaS (Infrastructure as a Service)**: Provides virtualized computing resources over the internet. 10 | - **PaaS (Platform as a Service)**: A platform allowing customers to develop, run, and manage applications without the complexity of building and maintaining the infrastructure. 11 | - **SaaS (Software as a Service)**: Software distribution model where applications are hosted by a vendor or service provider and made available to customers over the internet. 12 | 13 | ## Deployment Models 14 | 15 | - **Public Cloud**: Services are offered over the public internet and available to anyone who wants to purchase them. 16 | - **Private Cloud**: Infrastructure is operated solely for a single organization. 17 | - **Hybrid Cloud**: Combines public and private clouds, bound together by technology that allows data and applications to be shared between them. 18 | 19 | ## Recent Sentiment on Cloud Computing on X 20 | 21 | - There's a mix of enthusiasm for the scalability and flexibility of cloud services with concerns about data security, privacy, and the environmental impact of data centers. 22 | 23 | ## Tools and Platforms 24 | 25 | - **AWS**, **Microsoft Azure**, **Google Cloud**: Leading cloud service providers. 26 | 27 | ## Books 28 | 29 | - "Cloud Computing: Concepts, Technology & Architecture" by Thomas Erl 30 | - ISBN: 978-0133387520 31 | 32 | ## Standards 33 | 34 | - **NIST**: National Institute of Standards and Technology has guidelines on cloud computing. 35 | -------------------------------------------------------------------------------- /docs/compiler_optimization.md: -------------------------------------------------------------------------------- 1 | # Compiler Optimization 2 | 3 | ## Introduction to Compiler Optimization 4 | 5 | - **Definition**: Techniques used by compilers to improve the performance or efficiency of the executable code. 6 | 7 | ## Common Optimization Techniques 8 | 9 | - **Loop Unrolling**: Increases the program's speed by reducing loop overhead. 10 | - **Dead Code Elimination**: Removes code that does not affect the program results. 11 | - **Register Allocation**: Efficient use of registers to minimize memory access. 12 | 13 | ## Architecture-Specific Optimizations 14 | 15 | - **Vectorization**: Utilizing SIMD instructions (like SSE, AVX on x86) for parallel operations. 16 | - **Instruction Scheduling**: Reordering instructions to reduce latency and improve pipeline efficiency. 17 | 18 | ## Books 19 | 20 | - "Compilers: Principles, Techniques, and Tools" by Alfred V. Aho, Monica S. Lam, Ravi Sethi, and Jeffrey D. Ullman 21 | - ISBN: 978-0321486813 22 | 23 | ## Tools 24 | 25 | - **GCC**: GNU Compiler Collection with various optimization flags. 26 | - **Clang/LLVM**: Provides detailed diagnostics and optimization capabilities. 27 | 28 | ## Online Resources 29 | 30 | - **Compiler Explorer**: An interactive compiler allowing to see how code is optimized. 31 | - [Godbolt's Compiler Explorer](godbolt.org) 32 | -------------------------------------------------------------------------------- /docs/cybersecurity.md: -------------------------------------------------------------------------------- 1 | # Cybersecurity 2 | 3 | ## Introduction to Cybersecurity 4 | 5 | - **Cybersecurity**: The practice of protecting digital devices, networks, and sensitive information from unauthorized access and attack. 6 | 7 | ## Core Concepts 8 | 9 | - **Confidentiality**: Ensuring information is not disclosed to unauthorized individuals. 10 | - **Integrity**: Maintaining and assuring the accuracy and consistency of data over its entire lifecycle. 11 | - **Availability**: Ensuring that authorized users have uninterrupted access to the data and resources they need. 12 | 13 | ## Common Threats 14 | 15 | - **Malware**: Software designed to harm or exploit any computing device or network. 16 | - **Phishing**: Attempting to deceive individuals into revealing sensitive information. 17 | 18 | ## Recent Sentiment on Cybersecurity on X 19 | 20 | - Heightened discussions on the need for better cybersecurity measures, especially with the rise of remote work, IoT devices, and high-profile cyber attacks. 21 | 22 | ## Tools for Cybersecurity 23 | 24 | - **Firewalls**: Network security systems that monitor and control incoming and outgoing network traffic. 25 | - **Antivirus Software**: Programs designed to detect and destroy computer viruses. 26 | 27 | ## Books 28 | 29 | - "The Art of Invisibility" by Kevin Mitnick 30 | - ISBN: 978-0316380508 31 | 32 | ## Standards and Frameworks 33 | 34 | - **ISO/IEC 27001**: International standard for managing information security. 35 | - **NIST Cybersecurity Framework**: Provides a policy framework of computer security guidance for organizations. 36 | -------------------------------------------------------------------------------- /docs/data_representation.md: -------------------------------------------------------------------------------- 1 | # Data Representation 2 | 3 | ## Official Documentation 4 | - **IEEE 754-2019 - IEEE Standard for Floating-Point Arithmetic** 5 | - [Link](https://ieeexplore.ieee.org/document/8766229) 6 | - **The Unicode® Standard Version 15.0** 7 | - [Link](https://www.unicode.org/versions/Unicode15.0.0/) 8 | 9 | ## Research Papers 10 | - **"A Survey of Techniques for Dynamic Branch Prediction" by S. Mittal (2019)** 11 | - [Link](https://ieeexplore.ieee.org/document/8444667) 12 | - **"A Survey of Architectural Techniques for Near-Threshold Computing" by U. R. Karpuzcu et al. (2015)** 13 | - [Link](https://dl.acm.org/doi/10.1145/2677091) 14 | 15 | ## Additional Online Resources 16 | - **Computerphile: Floating Point Numbers** 17 | - [Link](https://www.youtube.com/watch?v=PZRI1IfStY0) 18 | - **GeeksforGeeks: Data Types in C** 19 | - [Link](https://www.geeksforgeeks.org/data-types-in-c/) 20 | - **IBM Knowledge Center: Character Data Representation** 21 | - [Link](https://www.ibm.com/docs/en/i/7.4?topic=concepts-character-data-representation) 22 | 23 | ## Books 24 | - **"Structured Computer Organization" by Andrew S. Tanenbaum and Todd Austin** 25 | - ISBN: 0132916525 26 | - **"Computer Organization and Architecture: Designing for Performance" by William Stallings** 27 | - ISBN: 0134101618 28 | - **"Digital Design and Computer Architecture: ARM Edition" by Sarah Harris and David Harris** 29 | - ISBN: 0128000562 30 | 31 | ## For Deep Dive into Implementation 32 | - **"Computer Architecture: A Quantitative Approach" by John L. Hennessy and David A. Patterson** 33 | - ISBN: 0128119055 34 | 35 | ## Standards 36 | - **ISO/IEC 10646:2020 Information technology — Universal Coded Character Set (UCS)** 37 | - Not freely available, but it's the international standard for character encoding 38 | 39 | ## Code Example 40 | ```c 41 | #include 42 | #include 43 | #include 44 | 45 | int main() { 46 | printf("Signed int: %d to %d\n", INT_MIN, INT_MAX); 47 | printf("Unsigned int: 0 to %u\n", UINT_MAX); 48 | printf("Float: %e to %e\n", FLT_MIN, FLT_MAX); 49 | 50 | char c = 'A'; 51 | printf("Character '%c' has ASCII value %d\n", c, c); 52 | 53 | return 0; 54 | } 55 | ``` 56 | 57 | ## Note 58 | Understanding data representation is crucial for efficient programming and optimizing memory usage. It's important to be aware of the limitations and precision of different data types, especially when working with floating-point arithmetic or character encoding in international contexts. 59 | -------------------------------------------------------------------------------- /docs/datapathAndControlUnit.md: -------------------------------------------------------------------------------- 1 | # Datapath & Control Unit 2 | 3 | ## Official Documentation 4 | - **MIPS Architecture for Programmers Volume II-A: The MIPS32 Instruction Set** 5 | - [Link](https://www.mips.com/downloads/MIPS32_Architecture_Volume_II-A_MD00086-2B-MIPS32BIS-AFP-6.06.pdf) 6 | 7 | ## Research Papers 8 | - **"A Survey of Techniques for Improving Energy Efficiency in Embedded Computing Systems" by M. A. Al Faruque and J. Henkel (2011)** 9 | - [Link](https://ieeexplore.ieee.org/document/5738666) 10 | - **"A Survey of Techniques for Designing and Managing CPU Resource in Multicore Systems" by A. Sarkar et al. (2019)** 11 | - [Link](https://ieeexplore.ieee.org/document/8691754) 12 | 13 | ## Additional Online Resources 14 | - **Neso Academy: Computer Organization and Architecture Playlist** 15 | - [Link](https://www.youtube.com/playlist?list=PLBlnK6fEyqRgLLlzdgiTUKULKJPYc0A4q) 16 | - **MIT OpenCourseWare: Computation Structures** 17 | - [Link](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) 18 | - **Carnegie Mellon: 18-447 Introduction to Computer Architecture** 19 | - [Link](http://www.ece.cmu.edu/~ece447/s15/doku.php?id=schedule) 20 | 21 | ## Books 22 | - **"Computer Organization and Design: The Hardware/Software Interface" by David A. Patterson and John L. Hennessy** 23 | - ISBN: 0124077269 24 | - **"Digital Design and Computer Architecture" by David Harris and Sarah Harris** 25 | - ISBN: 0123944244 26 | - **"Computer Architecture: A Quantitative Approach" by John L. Hennessy and David A. Patterson** 27 | - ISBN: 0128119055 28 | - **"Structured Computer Organization" by Andrew S. Tanenbaum and Todd Austin** 29 | - ISBN: 0132916525 30 | - **"Computer Organization and Architecture: Designing for Performance" by William Stallings** 31 | - ISBN: 0134101618 32 | 33 | ## For Deep Dive into Implementation 34 | - **"CMOS VLSI Design: A Circuits and Systems Perspective" by Neil H. E. Weste and David M. Harris** 35 | - ISBN: 0321547748 36 | - **"Parallel Computer Organization and Design" by Michel Dubois, Murali Annavaram, and Per Stenström** 37 | - ISBN: 0521886759 38 | 39 | ## Standards 40 | - **IEEE 1800-2017 - IEEE Standard for SystemVerilog--Unified Hardware Design, Specification, and Verification Language** 41 | - Not freely available, but it's relevant for hardware description and verification of datapaths and control units 42 | 43 | ## Note 44 | Understanding the datapath and control unit is fundamental to computer architecture. The datapath performs the actual operations on data, while the control unit manages the flow of data and instructions through the processor. This topic forms the basis for understanding more advanced concepts in processor design and optimization. 45 | -------------------------------------------------------------------------------- /docs/digitalLogicDesign.md: -------------------------------------------------------------------------------- 1 | # Digital Logic Design 2 | 3 | ## Official Documentation 4 | - **IEEE Standard for SystemVerilog—Unified Hardware Design, Specification, and Verification Language** 5 | - [Link](https://ieeexplore.ieee.org/document/8299595) 6 | 7 | ## Research Papers 8 | - **"A Survey of Digital Logic Simulators" by R. B. Jones and V. H. Allan (1990)** 9 | - [Link](https://ieeexplore.ieee.org/document/55686) 10 | - **"A Survey of High-Level Synthesis Techniques for Area Minimization" by S. Ahuja et al. (2018)** 11 | - [Link](https://ieeexplore.ieee.org/document/8481667) 12 | 13 | ## Additional Online Resources 14 | - **Neso Academy: Digital Electronics** 15 | - [Link](https://www.youtube.com/playlist?list=PLBlnK6fEyqRjMH3mWf6kwqiTbT798eAOm) 16 | - **All About Circuits: Digital Logic** 17 | - [Link](https://www.allaboutcircuits.com/textbook/digital/) 18 | - **MIT OpenCourseWare: 6.004 Computation Structures** 19 | - [Link](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) 20 | 21 | ## Books 22 | - **"Digital Design: With an Introduction to the Verilog HDL" by M. Morris Mano and Michael D. Ciletti** 23 | - ISBN: 0134549899 24 | - **"Digital Design and Computer Architecture" by David Harris and Sarah Harris** 25 | - ISBN: 0123944244 26 | - **"Fundamentals of Digital Logic with Verilog Design" by Stephen Brown and Zvonko Vranesic** 27 | - ISBN: 0073380547 28 | 29 | ## For Deep Dive into Implementation 30 | - **"FPGA Prototyping by Verilog Examples: Xilinx Spartan-3 Version" by Pong P. Chu** 31 | - ISBN: 0470185325 32 | 33 | ## Standards 34 | - **IEEE 1364-2005 - IEEE Standard for Verilog Hardware Description Language** 35 | - Not freely available, but it's the standard for Verilog HDL 36 | 37 | ## Code Example (Verilog) 38 | ```verilog 39 | module d_flip_flop ( 40 | input clk, 41 | input d, 42 | output reg q 43 | ); 44 | 45 | always @(posedge clk) begin 46 | q <= d; 47 | end 48 | 49 | endmodule 50 | 51 | module counter ( 52 | input clk, 53 | input reset, 54 | output reg [3:0] count 55 | ); 56 | 57 | always @(posedge clk or posedge reset) begin 58 | if (reset) 59 | count <= 4'b0000; 60 | else 61 | count <= count + 1; 62 | end 63 | 64 | endmodule 65 | ``` 66 | 67 | ## Note 68 | Digital Logic Design is fundamental to understanding how modern digital systems work. It covers both combinational and sequential circuits, which form the building blocks of more complex digital systems like processors and memory units. 69 | -------------------------------------------------------------------------------- /docs/gpus.md: -------------------------------------------------------------------------------- 1 | # Graphics Processing Units (GPUs) 2 | 3 | ## GPU Architecture Overview 4 | 5 | - **Cores**: Hundreds to thousands of smaller, more efficient cores designed for parallel workload. 6 | - **Memory**: High-bandwidth memory (like GDDR6 or HBM) to handle large data sets. 7 | 8 | ## GPU Programming 9 | 10 | - **CUDA**: NVIDIA's parallel computing platform. 11 | - [CUDA Zone](developer.nvidia.com/cuda-zone) 12 | 13 | - **OpenCL**: An open standard for cross-platform parallel programming. 14 | - [Khronos OpenCL Registry](khronos.org/registry/OpenCL/) 15 | 16 | ## Applications 17 | 18 | - **Gaming**: Rendering complex graphics in real-time. 19 | - **Machine Learning**: Training and inference tasks on large neural networks. 20 | - **Scientific Computing**: Simulations, molecular modeling, and more. 21 | 22 | ## Performance Metrics for GPUs 23 | 24 | - **FLOPS**: Floating Point Operations Per Second, measuring computational power. 25 | - **Memory Bandwidth**: How fast data can be read from or written to memory. 26 | 27 | ## GPU vs. LPU for AI 28 | 29 | - **GPU**: General-purpose computing with strong parallel processing, better for training models. 30 | - **LPU (Language Processing Unit)**: Specialized for NLP tasks, potentially offering better efficiency for inference in language models. 31 | 32 | ## Sentiment on X 33 | 34 | - There's a growing interest in GPUs not just for gaming but for their role in AI acceleration, with discussions around new architectures like NVIDIA's Hopper series and alternatives like Groq's LPU for NLP tasks. 35 | 36 | ## Books 37 | 38 | - "GPU Gems" by NVIDIA Corporation (a series) 39 | - Available online at [developer.nvidia.com/gpugems](developer.nvidia.com/gpugems) 40 | 41 | ## Research Papers 42 | 43 | - "A Study on GPU vs. LPU Efficiency for Deep Learning Inference," (Hypothetical Title) published in recent AI conference proceedings. 44 | -------------------------------------------------------------------------------- /docs/instruction_set_architecture.md: -------------------------------------------------------------------------------- 1 | # Instruction Set Architecture (ISA) 2 | 3 | ## Official Documentation 4 | - **ARM Architecture Reference Manual** 5 | - [Link](https://developer.arm.com/documentation/ddi0487/latest) 6 | - **Intel® 64 and IA-32 Architectures Software Developer's Manual** 7 | - [Link](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html) 8 | - **RISC-V Specifications** 9 | - [Link](https://riscv.org/technical/specifications/) 10 | 11 | ## Research Papers 12 | - **"A Survey of Instruction Set Architecture Heterogeneity in University Computer Architecture Courses" by D. Franklin et al. (2019)** 13 | - [Link](https://ieeexplore.ieee.org/document/8812897) 14 | - **"A Survey of Techniques for Architectural Support of Data Analytics" by M. Ahmadi et al. (2021)** 15 | - [Link](https://dl.acm.org/doi/10.1145/3456727) 16 | 17 | ## Additional Online Resources 18 | - **Computerphile: Instruction Set Architectures** 19 | - [Link](https://www.youtube.com/watch?v=vqa9TVketPY) 20 | - **MIT OpenCourseWare: 6.004 Computation Structures** 21 | - [Link](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) 22 | - **Stanford CS107: Computer Organization & Systems** 23 | - [Link](https://web.stanford.edu/class/cs107/) 24 | 25 | ## Books 26 | - **"Computer Organization and Design RISC-V Edition" by David A. Patterson and John L. Hennessy** 27 | - ISBN: 0128203315 28 | - **"Computer Architecture: A Quantitative Approach" by John L. Hennessy and David A. Patterson** 29 | - ISBN: 0128119055 30 | - **"Structured Computer Organization" by Andrew S. Tanenbaum and Todd Austin** 31 | - ISBN: 0134997190 32 | 33 | ## For Deep Dive into Implementation 34 | - **"Modern Processor Design: Fundamentals of Superscalar Processors" by John Paul Shen and Mikko H. Lipasti** 35 | - ISBN: 1478627425 36 | 37 | ## Standards 38 | - **IEEE 1754-1994 - IEEE Standard for a 32-Bit Microprocessor Architecture** 39 | - Not freely available, but it's an example of a standardized ISA 40 | 41 | ## Code Example (RISC-V Assembly) 42 | ```assembly 43 | # Simple RISC-V assembly program to add two numbers 44 | .global _start 45 | 46 | .text 47 | _start: 48 | li a0, 10 # Load immediate value 10 into register a0 49 | li a1, 20 # Load immediate value 20 into register a1 50 | add a2, a0, a1 # Add a0 and a1, store result in a2 51 | 52 | # Exit program 53 | li a7, 93 # System call number for exit 54 | ecall # Make system call 55 | ``` 56 | 57 | ## Note 58 | Understanding ISA is crucial for both hardware designers and software developers. It defines the interface between hardware and software, influencing aspects such as performance, power efficiency, and programming complexity. Different ISAs (like RISC and CISC) have their own design philosophies and trade-offs. 59 | -------------------------------------------------------------------------------- /docs/io_systems.md: -------------------------------------------------------------------------------- 1 | # Input/Output (I/O) Systems 2 | 3 | ## I/O Techniques 4 | 5 | - **Programmed I/O**: 6 | - [Programmed I/O](https://en.wikipedia.org/wiki/Programmed_input/output) 7 | 8 | - **Interrupt-driven I/O**: 9 | - [Interrupt-driven I/O](https://cs.stackexchange.com/questions/62018/how-do-interrupts-work-in-multi-core-system) 10 | 11 | - **DMA (Direct Memory Access)**: 12 | - [DMA Explained](https://www.allaboutcircuits.com/technical-articles/direct-memory-access-DMA-and-the-importance-of-dma-engines/) 13 | 14 | ## Buses 15 | 16 | - **PCIe (Peripheral Component Interconnect Express)**: 17 | - [PCIe Basics](https://www.pcworld.com/article/171969/article.html) 18 | 19 | - **SATA (Serial ATA)**: 20 | - [SATA Overview](https://www.lifewire.com/serial-ata-sata-830619) 21 | 22 | ## Official Documentation 23 | 24 | - **PCI-SIG Specifications**: 25 | - [PCI Express Base Specification](https://pcisig.com/specifications) 26 | 27 | - **USB Implementers Forum**: 28 | - [USB 3.2 Specification](https://usb.org/document-library/usb-32-specification-released-september-22-2017-and-ecns) 29 | 30 | ## Books 31 | 32 | - "Computer Organization and Design" by David A. Patterson and John L. Hennessy 33 | - ISBN: 978-0124077263 34 | 35 | ## Research Papers 36 | 37 | - "I/O System Design for High-Performance Computing" by Y. Kim et al. (2023) 38 | - [Journal of Parallel and Distributed Computing](https://www.sciencedirect.com/science/article/abs/pii/S0743731523000364) 39 | 40 | ## Standards 41 | 42 | - **IEEE 1284**: Standard for parallel interfaces. 43 | 44 | ## Additional Online Resources 45 | - **I/O Subsystems**: Understanding I/O in computers. 46 | - [I/O Subsystem](https://www.tutorialspoint.com/computer_organization/computer_organization_input_output_subsystem.htm) 47 | -------------------------------------------------------------------------------- /docs/logicGatesAndBooleanAlgebra.md: -------------------------------------------------------------------------------- 1 | # Logic Gates and Boolean Algebra 2 | 3 | ## Official Documentation 4 | - **IEEE Standard for Logic Circuit Diagrams (ANSI/IEEE Std 991-1986)** 5 | - [Link](https://ieeexplore.ieee.org/document/26638) 6 | 7 | ## Research Papers 8 | - **"A Survey of Boolean Concepts" by J.D. Rutledge (1954)** 9 | - [Link](https://ieeexplore.ieee.org/document/5059133) 10 | - **"A Survey of Reversible Logic Synthesis Methods" by R. Wille and R. Drechsler (2010)** 11 | - [Link](https://ieeexplore.ieee.org/document/5429132) 12 | 13 | ## Additional Online Resources 14 | - **Neso Academy: Digital Electronics** 15 | - [Link](https://www.youtube.com/playlist?list=PLBlnK6fEyqRjMH3mWf6kwqiTbT798eAOm) 16 | - **MIT OpenCourseWare: Computation Structures** 17 | - [Link](https://ocw.mit.edu/courses/6-004-computation-structures-spring-2017/) 18 | - **Stanford University: CS107 - Computer Organization & Systems** 19 | - [Link](https://web.stanford.edu/class/cs107/) 20 | 21 | ## Books 22 | - **"Digital Design" by M. Morris Mano and Michael D. Ciletti** 23 | - ISBN: 0134549899 24 | - **"Fundamentals of Logic Design" by Charles H. Roth Jr. and Larry L. Kinney** 25 | - ISBN: 1133628478 26 | - **"Digital Logic Design: A Rigorous Approach" by Guy Even and Moti Medina** 27 | - ISBN: 1107156394 28 | 29 | ## For Deep Dive into Implementation 30 | - **"CMOS VLSI Design: A Circuits and Systems Perspective" by Neil H. E. Weste and David Harris** 31 | - ISBN: 0321547748 32 | 33 | ## Standards 34 | - **IEC 60617-12:1997 Graphical symbols for diagrams - Part 12: Binary logic elements** 35 | - Not freely available, but it's the international standard for logic gate symbols 36 | 37 | ## Code Example (Python implementation of basic logic gates) 38 | ```python 39 | def AND(a, b): 40 | return a and b 41 | 42 | def OR(a, b): 43 | return a or b 44 | 45 | def NOT(a): 46 | return not a 47 | 48 | def XOR(a, b): 49 | return a ^ b 50 | 51 | def NAND(a, b): 52 | return not (a and b) 53 | 54 | def NOR(a, b): 55 | return not (a or b) 56 | 57 | # Example usage 58 | print(f"AND(1, 0) = {AND(1, 0)}") 59 | print(f"OR(1, 0) = {OR(1, 0)}") 60 | print(f"NOT(1) = {NOT(1)}") 61 | print(f"XOR(1, 1) = {XOR(1, 1)}") 62 | print(f"NAND(1, 1) = {NAND(1, 1)}") 63 | print(f"NOR(0, 0) = {NOR(0, 0)}") 64 | ``` 65 | 66 | ## Note 67 | Understanding logic gates and Boolean algebra is crucial for designing digital circuits and understanding the fundamental operations of computers. These concepts form the basis of all digital systems and are essential for further study in computer architecture and digital design. 68 | -------------------------------------------------------------------------------- /docs/memory_alignment_padding.md: -------------------------------------------------------------------------------- 1 | # Memory Alignment & Padding 2 | 3 | ## Basics of Memory Alignment 4 | 5 | - **Memory Alignment**: The practice of aligning data in memory to start at addresses that are multiples of some power of two, optimizing access speed. 6 | 7 | - **Padding**: Adding bytes to align data structures, which can lead to wasted space but improved performance. 8 | 9 | ## Implications 10 | 11 | - **Performance**: Misaligned memory access can lead to performance penalties or even crashes on some architectures. 12 | - **Struct Packing**: How compilers pack structures in memory to minimize padding or align for speed. 13 | 14 | ## Techniques for Alignment 15 | 16 | - **Compiler Directives**: Using attributes or pragmas to control alignment. 17 | ```c 18 | struct __attribute__((aligned(16))) myStruct { 19 | int a; 20 | char b; 21 | }; 22 | - Manual Padding: Adding extra fields to manually align data. 23 | 24 | ## Books 25 | - "Computer Organization and Design" by David A. Patterson and John L. Hennessy 26 | - ISBN: 978-0128017333 (Discusses memory systems including alignment) 27 | 28 | ## Online Resources 29 | - **Memory Alignment**: Detailed explanation on how and why memory alignment matters. 30 | - **Memory Alignment** (www.geeksforgeeks.org/memory-alignment-in-c-struct-members-alignment-padding/) 31 | 32 | -------------------------------------------------------------------------------- /docs/memory_hierarchy.md: -------------------------------------------------------------------------------- 1 | # Memory Hierarchy 2 | 3 | ## SRAM 4 | 5 | - **SRAM Basics**: 6 | - [Static RAM Overview](https://www.allaboutcircuits.com/technical-articles/sram-static-ram-overview/) 7 | 8 | ## DRAM 9 | 10 | - **DRAM Technology**: 11 | - [Dynamic RAM](https://www.edn.com/electronics-blogs/all-aboard-/4423229/DRAM--What-it-is-and-how-it-works) 12 | 13 | ## ROM 14 | 15 | - **ROM Types**: 16 | - [Types of ROM](https://www.geeksforgeeks.org/types-of-roms/) 17 | 18 | ## Access Times, Latency, Bandwidth 19 | 20 | - **Memory Metrics**: 21 | - [Understanding Latency and Bandwidth](https://www.cs.cornell.edu/courses/cs3410/2013sp/lecture/14-memhier-i.pdf) 22 | 23 | ## Official Documentation 24 | 25 | - **JEDEC Memory Standards**: 26 | - [ JEDEC DDR5 & NVDIMM-P Standards](https://www.jedec.org/standards-documents/focus/memory-module-standards) 27 | 28 | ## Books 29 | 30 | - "Memory Systems: Cache, DRAM, Disk" by Bruce Jacob, Spencer Ng, David Wang 31 | - ISBN: 0123797519 32 | 33 | ## Research Papers 34 | 35 | - "A Survey of Techniques for Architecting and Managing Asymmetric Memory" by S. Mittal et al. (2017) 36 | - [IEEE Access](https://ieeexplore.ieee.org/document/7866854) 37 | 38 | ## Additional Online Resources 39 | 40 | - **Memory Hierarchy Lecture** by MIT OpenCourseWare: 41 | - [Memory Hierarchy](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-004-computation-structures-spring-2009/lecture-notes/MIT6_004s09_lec14.pdf) 42 | 43 | ## Standards 44 | 45 | - **JEDEC Solid State Technology Association**: 46 | - Standards for memory technologies like DDR SDRAM. 47 | -------------------------------------------------------------------------------- /docs/memory_management_unit.md: -------------------------------------------------------------------------------- 1 | # Memory Management Unit (MMU) 2 | 3 | ## Overview 4 | 5 | - **Functionality**: 6 | - Address translation from virtual to physical addresses. 7 | - Memory protection, cache control, bus arbitration, and in simpler computer architectures, bank switching. 8 | 9 | ## Key Concepts 10 | 11 | - **Virtual Memory**: 12 | - [Virtual Memory Concept](https://en.wikipedia.org/wiki/Virtual_memory) 13 | 14 | - **Paging**: 15 | - [Paging in MMU](https://www.geeksforgeeks.org/paging-in-operating-system/) 16 | 17 | ## Official Documentation & Standards 18 | 19 | - **Intel 64 and IA-32 Architectures Software Developer's Manual**: 20 | - [Volume 3A: System Programming Guide, Part 1 - Memory Management](https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.html) 21 | 22 | - **ARM Architecture Reference Manual**: 23 | - [Memory Management Unit](https://developer.arm.com/documentation/ddi0487/latest) 24 | 25 | ## Books 26 | 27 | - "Operating System Concepts" by Abraham Silberschatz, Peter B. Galvin, Greg Gagne 28 | - ISBN: 978-1119320913 29 | 30 | ## Research Papers 31 | 32 | - "A Study on Memory Management Units for Heterogeneous Systems" by J. Lee et al. (2022) 33 | - [IEEE Transactions on Computers](https://ieeexplore.ieee.org/document/9673667) 34 | 35 | ## Additional Online Resources 36 | 37 | - **Memory Management in Operating Systems** - GeeksforGeeks 38 | - [Memory Management](https://www.geeksforgeeks.org/memory-management-in-operating-system/) 39 | 40 | - **PIM-MMU: A Memory Management Unit for Processing-In-Memory Systems** 41 | - [Papers with Code](paperswithcode.com/paper/pim-mmu-a-memory-management-unit-for) 42 | 43 | ## Recent Developments 44 | 45 | - Discussion on X about hardware acceleration for data transfers in PIM systems. 46 | 47 | ## Tools & Implementations 48 | 49 | - **Linux MMU**: Understanding how Linux handles memory management. 50 | - [Linux Memory Management](http://duartes.org/gustavo/blog/post/how-the-kernel-manages-your-memory/) 51 | -------------------------------------------------------------------------------- /docs/networking.md: -------------------------------------------------------------------------------- 1 | # Networking Fundamentals 2 | 3 | ## Introduction to Networking 4 | 5 | - **Network**: A collection of interconnected devices for sharing data and resources. 6 | - **Protocols**: Rules that govern how data is sent from one computer to another. 7 | 8 | ## Key Networking Concepts 9 | 10 | - **OSI Model**: A reference model for how applications communicate over a network. 11 | - **TCP/IP**: Core protocols for internet communication. 12 | 13 | ## Network Topologies 14 | 15 | - **Star**: All nodes connect to a central device. 16 | - **Bus**: All nodes are connected to a common backbone. 17 | - **Ring**: Each node connects to exactly two other nodes. 18 | 19 | ## Recent Sentiment on Networking on X 20 | 21 | - Discussions often revolve around the advancements in wireless technology, the rollout of 5G, and concerns over network security in an increasingly connected world. 22 | 23 | ## Tools and Software 24 | 25 | - **Wireshark**: For network protocol analysis. 26 | - **Ping and Traceroute**: Basic tools for network testing. 27 | 28 | ## Books 29 | 30 | - "Computer Networks" by Andrew S. Tanenbaum and David J. Wetherall 31 | - ISBN: 978-0132126953 32 | 33 | ## Standards 34 | 35 | - **IEEE 802**: Standards for local and metropolitan area networks, with the most known being 802.11 for Wi-Fi. 36 | -------------------------------------------------------------------------------- /docs/number_systems.md: -------------------------------------------------------------------------------- 1 | # Number Systems 2 | 3 | ## Official Documentation 4 | - **IEEE Standard for Floating-Point Arithmetic (IEEE 754)** 5 | - [Link](https://ieeexplore.ieee.org/document/4610935) 6 | 7 | ## Research Papers 8 | - **"A Survey of Techniques for Improving Efficiency of Decimal Computations" by M. F. Cowlishaw (2015)** 9 | - [Link](https://ieeexplore.ieee.org/document/7348140) 10 | 11 | ## Additional Online Resources 12 | - **Khan Academy: Number Systems** 13 | - [Link](https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction) 14 | - **Tutorials Point: Number System** 15 | - [Link](https://www.tutorialspoint.com/computer_logical_organization/number_system.htm) 16 | - **GeeksforGeeks: Number System** 17 | - [Link](https://www.geeksforgeeks.org/number-system-and-base-conversions/) 18 | 19 | ## Books 20 | - **"Computer Organization and Design: The Hardware/Software Interface" by David A. Patterson and John L. Hennessy** 21 | - ISBN: 0128017333 22 | - **"Digital Design and Computer Architecture" by David Harris and Sarah Harris** 23 | - ISBN: 0123944244 24 | - **"Digital Logic Design" by Brian Holdsworth and Clive Woods** 25 | - ISBN: 0750645822 26 | 27 | ## For Deep Dive into Implementation 28 | - **"Computer Arithmetic: Algorithms and Hardware Designs" by Behrooz Parhami** 29 | - ISBN: 0195328485 30 | 31 | ## Standards 32 | - **ISO/IEC/IEEE 60559:2011 - Information technology -- Microprocessor Systems -- Floating-Point arithmetic** 33 | - Not freely available, but it's the international standard for binary floating-point arithmetic 34 | 35 | ## Code Example 36 | ```python 37 | # Binary to Decimal conversion 38 | binary = "1010" 39 | decimal = int(binary, 2) 40 | print(f"Binary {binary} is equal to Decimal {decimal}") 41 | 42 | # Decimal to Hexadecimal conversion 43 | decimal = 42 44 | hexadecimal = hex(decimal) 45 | print(f"Decimal {decimal} is equal to Hexadecimal {hexadecimal}") 46 | ``` 47 | 48 | ## Note 49 | Understanding number systems is fundamental to computer science and forms the basis for data representation in digital systems. It's crucial to master conversions between different bases and arithmetic operations in various number systems. 50 | -------------------------------------------------------------------------------- /docs/parallel_processing.md: -------------------------------------------------------------------------------- 1 | # Parallel Processing 2 | 3 | ## Introduction to Parallel Processing 4 | 5 | - **Definition**: Parallel processing involves the simultaneous use of more than one CPU or processor core to execute a program or multiple computational threads. 6 | 7 | ## Types of Parallelism 8 | 9 | - **Data Parallelism**: Same operation performed on different data elements simultaneously. 10 | - **Task Parallelism**: Different operations or tasks executed on different processors. 11 | 12 | ## Architectures 13 | 14 | - **Symmetric Multiprocessing (SMP)**: Multiple identical processors share memory and connect via a bus. 15 | - **Massively Parallel Processors (MPP)**: Many processors with their own memory and an interconnect network. 16 | 17 | ## Challenges 18 | 19 | - **Synchronization**: Coordinating between parallel processes/threads. 20 | - **Load Balancing**: Ensuring all processors are equally utilized. 21 | - **Scalability**: How well performance increases with more processors. 22 | 23 | ## Parallel Programming Models 24 | 25 | - **MPI (Message Passing Interface)**: Standard for distributed memory systems. 26 | - [MPI on Wikipedia](en.wikipedia.org/wiki/Message_Passing_Interface) 27 | 28 | - **OpenMP**: For shared memory multiprocessing. 29 | - [OpenMP Official Site](openmp.org) 30 | 31 | - **CUDA**: For GPU parallel computing developed by NVIDIA. 32 | - [CUDA Documentation](docs.nvidia.com/cuda/) 33 | 34 | ## Recent Sentiment on X about Parallel Processing 35 | 36 | - Discussions often focus on the advancements in GPU technologies enhancing parallel computing capabilities for AI and scientific computing. There's enthusiasm about how parallel processing can handle large datasets more efficiently, making real-time analytics possible. 37 | 38 | ## Books 39 | 40 | - "An Introduction to Parallel Programming" by Peter Pacheco 41 | - ISBN: 978-0123742605 42 | 43 | ## Research and Developments 44 | 45 | - Recent papers explore the integration of quantum computing elements with classical parallel processing to solve complex optimization problems. 46 | 47 | ## Standards 48 | 49 | - **IEEE P2418.2**: Standard for Quantum Computing Definitions. 50 | -------------------------------------------------------------------------------- /docs/performance_measurement.md: -------------------------------------------------------------------------------- 1 | # Performance Measurement 2 | 3 | ## Introduction to Performance Metrics 4 | 5 | - **Throughput**: Number of processes completed per unit time. 6 | - **Latency**: Time taken to respond to a request or complete a task. 7 | 8 | ## Tools for Measurement 9 | 10 | - **Benchmarking Tools**: Synthetic tests like SPEC, Geekbench. 11 | - **Profiling Tools**: gprof, perf, VTune for detailed analysis of CPU usage. 12 | 13 | ## Key Performance Indicators (KPIs) 14 | 15 | - **CPU Usage**: Percentage of time CPU spends on non-idle tasks. 16 | - **Memory Usage**: Amount of memory used versus available memory. 17 | - **Disk I/O**: Read/write speeds, IOPS (Input/Output Operations Per Second). 18 | 19 | ## Recent Sentiment on X about Performance Tools 20 | 21 | - Discussion on the effectiveness of modern benchmarking tools in capturing real-world performance, especially with newer, more complex workloads like AI training. 22 | 23 | ## Books 24 | 25 | - "Computer Architecture: A Quantitative Approach" by John L. Hennessy and David A. Patterson 26 | - ISBN: 978-0128119051 27 | 28 | ## Standards 29 | 30 | - **Standard Performance Evaluation Corporation (SPEC)**: Provides benchmarks for CPU, graphics, power, etc. 31 | 32 | ## Online Resources 33 | 34 | - **Performance Analysis 101**: Basics of system performance evaluation. 35 | - [Performance Analysis](www.brendangregg.com/performance.html) 36 | -------------------------------------------------------------------------------- /docs/power_energy_consumption.md: -------------------------------------------------------------------------------- 1 | # Power & Energy Consumption 2 | 3 | ## Understanding Power Consumption in Computing 4 | 5 | - **Dynamic Power**: Power consumed by switching activity in circuits. 6 | - **Static Power**: Due to leakage currents in transistors. 7 | 8 | ## Strategies for Reducing Power Consumption 9 | 10 | - **Dynamic Voltage and Frequency Scaling (DVFS)**: Adjusts power based on demand. 11 | - **Power Gating**: Shutting off parts of the chip not in use. 12 | 13 | ## Tools for Measuring Energy Use 14 | 15 | - **Powerstat**: Tool for Ubuntu to measure power usage. 16 | - **Intel Power Gadget**: For real-time energy monitoring on Intel processors. 17 | 18 | ## Recent X posts on Green Computing 19 | 20 | - Interest in how blockchain and data centers could be made more energy-efficient, reflecting a push towards sustainable computing practices. 21 | 22 | ## Books 23 | 24 | - "Energy-Efficient Computing and Electronics: Devices to Systems" by Santosh K. Kurinec and Krzysztof Iniewski 25 | - ISBN: 978-1138542758 26 | 27 | ## Research Papers 28 | 29 | - "Energy Efficient Cloud Computing: Where are we heading?" by A. Beloglazov et al. (2023) 30 | - [Journal of Network and Computer Applications](www.sciencedirect.com/science/article/pii/S1084804523000552) 31 | 32 | ## Standards 33 | 34 | - **Energy Star**: For energy efficiency in consumer products. 35 | - **80 PLUS**: Certification for power supplies with high efficiency. 36 | -------------------------------------------------------------------------------- /docs/reliability_security.md: -------------------------------------------------------------------------------- 1 | # Reliability & Security in Computing 2 | 3 | ## Fundamentals of System Reliability 4 | 5 | - **Mean Time Between Failures (MTBF)**: Average time between system failures. 6 | - **Availability**: Measure of the system uptime relative to total time. 7 | 8 | ## Security Principles 9 | 10 | - **Confidentiality, Integrity, Availability (CIA)**: Core principles of information security. 11 | 12 | ## Techniques for Enhancing Reliability & Security 13 | 14 | - **Redundancy**: Duplication of critical components to increase reliability. 15 | - **Encryption**: Protecting data both at rest and in transit. 16 | 17 | ## Recent Sentiment on X regarding Security 18 | 19 | - Discussions often revolve around the balance between user convenience and security measures, with new breaches prompting calls for stronger encryption and decentralized security solutions. 20 | 21 | ## Books 22 | 23 | - "Security in Computing" by Charles P. Pfleeger, Shari Lawrence Pfleeger 24 | - ISBN: 978-0134085043 25 | 26 | ## Standards and Protocols 27 | 28 | - **ISO/IEC 27001**: International standard for managing information security. 29 | - **TLS/SSL**: Protocols for secure communication over a computer network. 30 | 31 | ## Online Resources 32 | 33 | - **OWASP Top Ten**: Project listing the most critical web application security risks. 34 | - [OWASP](owasp.org/www-project-top-ten/) 35 | -------------------------------------------------------------------------------- /docs/virtual_memory.md: -------------------------------------------------------------------------------- 1 | # Virtual Memory 2 | 3 | ## Paging 4 | 5 | - **Understanding Paging**: 6 | - [Virtual Memory Paging](https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/9_VirtualMemory.html) 7 | 8 | ## Segmentation 9 | 10 | - **Segmentation Explained**: 11 | - [Memory Segmentation](https://en.wikipedia.org/wiki/Memory_segmentation) 12 | 13 | ## Translation Lookaside Buffer (TLB) 14 | 15 | - **TLB Overview**: 16 | - [Translation Lookaside Buffer](https://pages.cs.wisc.edu/~remzi/OSTEP/vm-tlbs.pdf) 17 | 18 | ## Official Documentation 19 | 20 | - **Intel® 64 and IA-32 Architectures Software Developer’s Manual**: 21 | - [Volume 3A: System Programming Guide, Part 1 - Virtual Memory](https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.html) 22 | 23 | ## Books 24 | 25 | - "Operating System Concepts" by Abraham Silberschatz, Peter B. Galvin, Greg Gagne 26 | - ISBN: 1119320910 27 | 28 | ## Research Papers 29 | 30 | - "An Analysis of Effective Paging Strategies for Virtual Memory Systems" by Peter J. Denning (1970) 31 | 32 | ## Additional Online Resources 33 | 34 | - **Linux Documentation Project - Virtual Memory**: 35 | - [Understanding Virtual Memory](http://www.tldp.org/LDP/tlk/mm/memory.html) 36 | 37 | ## Standards 38 | 39 | - **IEEE Standard for Floating-Point Arithmetic**: 40 | - Although not directly about virtual memory, it impacts how memory is managed in certain computations. 41 | -------------------------------------------------------------------------------- /memory/allocation/allocator.h: -------------------------------------------------------------------------------- 1 | #ifndef ALLOCATOR_H 2 | #define ALLOCATOR_H 3 | 4 | #include 5 | 6 | void m_init(size_t size); 7 | void *m_malloc(size_t size); 8 | void m_free(void *ptr); 9 | void *is_ptr(void *p); 10 | void gc(); 11 | void print_heap(); 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /memory/allocation/customAlloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_ALLOCATIONS 1000 6 | 7 | typedef struct { 8 | void* ptr; 9 | size_t size; 10 | const char* file; 11 | int line; 12 | } AllocationInfo; 13 | 14 | AllocationInfo allocations[MAX_ALLOCATIONS]; 15 | int allocation_count = 0; 16 | 17 | void* debug_malloc(size_t size, const char* file, int line) { 18 | void* ptr = malloc(size); 19 | if (ptr) { 20 | allocations[allocation_count].ptr = ptr; 21 | allocations[allocation_count].size = size; 22 | allocations[allocation_count].file = file; 23 | allocations[allocation_count].line = line; 24 | allocation_count++; 25 | } 26 | printf("Allocated %zu bytes at %p (%s:%d)\n", size, ptr, file, line); 27 | return ptr; 28 | } 29 | 30 | void debug_free(void* ptr, const char* file, int line) { 31 | for (int i = 0; i < allocation_count; i++) { 32 | if (allocations[i].ptr == ptr) { 33 | printf("Freed %zu bytes at %p (%s:%d)\n", allocations[i].size, ptr, file, line); 34 | free(ptr); 35 | allocations[i] = allocations[allocation_count - 1]; 36 | allocation_count--; 37 | return; 38 | } 39 | } 40 | printf("Attempt to free unallocated pointer %p (%s:%d)\n", ptr, file, line); 41 | } 42 | 43 | #define malloc(size) debug_malloc(size, __FILE__, __LINE__) 44 | #define free(ptr) debug_free(ptr, __FILE__, __LINE__) 45 | 46 | int main() { 47 | int* numbers = (int*)malloc(5 * sizeof(int)); 48 | free(numbers); 49 | free(numbers); // Double free 50 | int* unallocated = (int*)malloc(10 * sizeof(int)); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /memory/allocation/smartPointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define DEFINE_SHARED_PTR(T) \ 7 | typedef struct { \ 8 | T* data; \ 9 | _Atomic size_t* ref_count; \ 10 | void (*deleter)(T*); \ 11 | pthread_mutex_t mutex; \ 12 | } shared_ptr_##T; \ 13 | \ 14 | shared_ptr_##T* create_shared_##T(T value, void (*custom_deleter)(T*)) { \ 15 | shared_ptr_##T* ptr = (shared_ptr_##T*)malloc(sizeof(shared_ptr_##T)); \ 16 | if (!ptr) return NULL; \ 17 | \ 18 | ptr->data = (T*)malloc(sizeof(T)); \ 19 | if (!ptr->data) { \ 20 | free(ptr); \ 21 | return NULL; \ 22 | } \ 23 | *ptr->data = value; \ 24 | \ 25 | ptr->ref_count = (_Atomic size_t*)malloc(sizeof(_Atomic size_t)); \ 26 | if (!ptr->ref_count) { \ 27 | free(ptr->data); \ 28 | free(ptr); \ 29 | return NULL; \ 30 | } \ 31 | atomic_init(ptr->ref_count, 1); \ 32 | \ 33 | ptr->deleter = custom_deleter ? custom_deleter : (void (*)(T*))free; \ 34 | \ 35 | if (pthread_mutex_init(&ptr->mutex, NULL) != 0) { \ 36 | free(ptr->ref_count); \ 37 | free(ptr->data); \ 38 | free(ptr); \ 39 | return NULL; \ 40 | } \ 41 | \ 42 | return ptr; \ 43 | } \ 44 | \ 45 | void shared_ptr_inc_ref_##T(shared_ptr_##T* ptr) { \ 46 | if (ptr && ptr->ref_count) { \ 47 | pthread_mutex_lock(&ptr->mutex); \ 48 | atomic_fetch_add(ptr->ref_count, 1); \ 49 | pthread_mutex_unlock(&ptr->mutex); \ 50 | } \ 51 | } \ 52 | \ 53 | void shared_ptr_dec_ref_##T(shared_ptr_##T* ptr) { \ 54 | if (ptr && ptr->ref_count) { \ 55 | pthread_mutex_lock(&ptr->mutex); \ 56 | if (atomic_fetch_sub(ptr->ref_count, 1) == 1) { \ 57 | pthread_mutex_unlock(&ptr->mutex); \ 58 | ptr->deleter(ptr->data); \ 59 | free(ptr->ref_count); \ 60 | pthread_mutex_destroy(&ptr->mutex); \ 61 | free(ptr); \ 62 | } else { \ 63 | pthread_mutex_unlock(&ptr->mutex); \ 64 | } \ 65 | } \ 66 | } \ 67 | \ 68 | T* shared_ptr_get_##T(shared_ptr_##T* ptr) { \ 69 | return ptr ? ptr->data : NULL; \ 70 | } 71 | 72 | DEFINE_SHARED_PTR(int) 73 | 74 | void custom_int_deleter(int* ptr) { 75 | printf("Custom deleter called for int: %d\n", *ptr); 76 | free(ptr); 77 | } 78 | 79 | int main() { 80 | shared_ptr_int* ptr1 = create_shared_int(42, custom_int_deleter); 81 | shared_ptr_int* ptr2 = create_shared_int(10, NULL); 82 | 83 | printf("ptr1 value: %d\n", *shared_ptr_get_int(ptr1)); 84 | printf("ptr2 value: %d\n", *shared_ptr_get_int(ptr2)); 85 | 86 | shared_ptr_inc_ref_int(ptr1); 87 | shared_ptr_dec_ref_int(ptr1); 88 | shared_ptr_dec_ref_int(ptr1); 89 | shared_ptr_dec_ref_int(ptr2); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /memory/allocation/thenWhyMe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/memory/allocation/thenWhyMe -------------------------------------------------------------------------------- /memory/allocation/uniquePointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define DEFINE_UNIQUE_PTR(T) \ 7 | typedef struct { \ 8 | T* ptr; \ 9 | void (*deleter)(T*); \ 10 | _Atomic bool is_owned; \ 11 | } unique_ptr_##T; \ 12 | \ 13 | unique_ptr_##T unique_ptr_create_##T(T* p, void (*d)(T*)) { \ 14 | unique_ptr_##T up; \ 15 | up.ptr = p; \ 16 | up.deleter = d ? d : (void (*)(T*))free; \ 17 | atomic_init(&up.is_owned, true); \ 18 | return up; \ 19 | } \ 20 | \ 21 | void unique_ptr_destroy_##T(unique_ptr_##T* up) { \ 22 | if (atomic_exchange(&up->is_owned, false)) { \ 23 | if (up->ptr) { \ 24 | up->deleter(up->ptr); \ 25 | up->ptr = NULL; \ 26 | } \ 27 | } \ 28 | } \ 29 | \ 30 | T* unique_ptr_get_##T(unique_ptr_##T* up) { \ 31 | return up->ptr; \ 32 | } \ 33 | \ 34 | T* unique_ptr_release_##T(unique_ptr_##T* up) { \ 35 | T* tmp = up->ptr; \ 36 | if (atomic_exchange(&up->is_owned, false)) { \ 37 | up->ptr = NULL; \ 38 | } else { \ 39 | tmp = NULL; \ 40 | } \ 41 | return tmp; \ 42 | } \ 43 | \ 44 | void unique_ptr_reset_##T(unique_ptr_##T* up, T* p) { \ 45 | if (atomic_load(&up->is_owned)) { \ 46 | T* old = atomic_exchange(&up->ptr, p); \ 47 | if (old) { \ 48 | up->deleter(old); \ 49 | } \ 50 | } \ 51 | } \ 52 | \ 53 | unique_ptr_##T unique_ptr_move_##T(unique_ptr_##T* up) { \ 54 | unique_ptr_##T new_up = *up; \ 55 | if (atomic_exchange(&up->is_owned, false)) { \ 56 | up->ptr = NULL; \ 57 | } else { \ 58 | new_up.ptr = NULL; \ 59 | atomic_store(&new_up.is_owned, false); \ 60 | } \ 61 | return new_up; \ 62 | } 63 | 64 | DEFINE_UNIQUE_PTR(int) 65 | 66 | void custom_int_deleter(int* ptr) { 67 | printf("Custom deleter called for int: %d\n", *ptr); 68 | free(ptr); 69 | } 70 | 71 | int main() { 72 | int* raw_ptr = malloc(sizeof(int)); 73 | *raw_ptr = 42; 74 | 75 | unique_ptr_int up1 = unique_ptr_create_int(raw_ptr, custom_int_deleter); 76 | printf("up1 value: %d\n", *unique_ptr_get_int(&up1)); 77 | 78 | unique_ptr_int up2 = unique_ptr_move_int(&up1); 79 | printf("up2 value: %d\n", *unique_ptr_get_int(&up2)); 80 | 81 | if (unique_ptr_get_int(&up1) == NULL) { 82 | printf("up1 is now empty\n"); 83 | } 84 | 85 | unique_ptr_destroy_int(&up1); 86 | unique_ptr_destroy_int(&up2); 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /memory/allocation/whyNotMe.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "allocator.h" 4 | 5 | void malloc_and_print(const char *label, size_t size, char fill) { 6 | void *ptr = m_malloc(size); 7 | if (ptr == NULL) { 8 | printf("%s: allocation failed\n", label); 9 | return; 10 | } 11 | memset(ptr, fill, size); 12 | printf("%s: %p\n", label, ptr); 13 | } 14 | 15 | int main() { 16 | m_init(20*1024*1024); // Initialize with 20MB 17 | 18 | printf("Initial heap state:\n"); 19 | print_heap(); 20 | 21 | malloc_and_print("A", 16, 'A'); 22 | malloc_and_print("B", 20, 'B'); 23 | malloc_and_print("C", 24, 'C'); 24 | 25 | printf("\nHeap state after allocations:\n"); 26 | print_heap(); 27 | 28 | void *ptr = m_malloc(20); 29 | printf("Freeing %p\n", ptr); 30 | m_free(ptr); 31 | 32 | printf("\nHeap state after free:\n"); 33 | print_heap(); 34 | 35 | malloc_and_print("D", 8, 'D'); 36 | 37 | printf("\nFinal heap state:\n"); 38 | print_heap(); 39 | 40 | printf("\nRunning garbage collection...\n"); 41 | gc(); 42 | 43 | printf("\nHeap state after garbage collection:\n"); 44 | print_heap(); 45 | 46 | return 0; 47 | } 48 | 49 | -------------------------------------------------------------------------------- /memory/memory_management/context_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define NUM_ITERATIONS 1000 8 | 9 | double measure_context_switch() { 10 | int pipefd[2]; 11 | struct timeval start, end; 12 | char byte = 1; 13 | 14 | if(pipe(pipefd) == -1) { 15 | perror("pipe"); 16 | exit(1); 17 | } 18 | 19 | gettimeofday(&start, NULL); 20 | 21 | for(int i = 0; i < NUM_ITERATIONS; i++) { 22 | // Force context switch through pipe I/O 23 | write(pipefd[1], &byte, 1); 24 | read(pipefd[0], &byte, 1); 25 | } 26 | 27 | gettimeofday(&end, NULL); 28 | 29 | close(pipefd[0]); 30 | close(pipefd[1]); 31 | 32 | return ((end.tv_sec - start.tv_sec) * 1000000.0 + 33 | (end.tv_usec - start.tv_usec)) / NUM_ITERATIONS; 34 | } 35 | 36 | int main() { 37 | printf("Measuring context switch overhead...\n"); 38 | double avg_time = measure_context_switch(); 39 | printf("Average context switch time: %.2f microseconds\n", avg_time); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /memory/memory_management/memory_layout.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Data segment 5 | int global_initialized = 42; 6 | 7 | // BSS segment 8 | int global_uninitialized; 9 | 10 | // Function to print address information 11 | void print_address_info(void* ptr, const char* description) { 12 | printf("%s at address: %p\n", description, ptr); 13 | } 14 | 15 | int main() { 16 | // Stack variables 17 | int stack_var = 10; 18 | 19 | // Heap allocation 20 | int* heap_var = (int*)malloc(sizeof(int)); 21 | *heap_var = 20; 22 | 23 | // Print addresses of variables in different segments 24 | print_address_info(&global_initialized, "Global initialized variable"); 25 | print_address_info(&global_uninitialized, "Global uninitialized variable"); 26 | print_address_info(&stack_var, "Stack variable"); 27 | print_address_info(heap_var, "Heap variable"); 28 | print_address_info((void*)main, "Program code (text)"); 29 | 30 | free(heap_var); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /memory/memory_management/memory_pool.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define POOL_SIZE 1024 * 1024 8 | #define BLOCK_SIZE 256 9 | #define NUM_BLOCKS (POOL_SIZE / BLOCK_SIZE) 10 | 11 | typedef struct { 12 | char memory[POOL_SIZE]; 13 | char used[NUM_BLOCKS]; 14 | size_t num_allocations; 15 | size_t num_frees; 16 | } MemoryPool; 17 | 18 | MemoryPool* create_pool() { 19 | MemoryPool* pool = malloc(sizeof(MemoryPool)); 20 | memset(pool->used, 0, NUM_BLOCKS); 21 | pool->num_allocations = 0; 22 | pool->num_frees = 0; 23 | return pool; 24 | } 25 | 26 | void* pool_alloc(MemoryPool* pool) { 27 | for(int i = 0; i < NUM_BLOCKS; i++) { 28 | if(!pool->used[i]) { 29 | pool->used[i] = 1; 30 | pool->num_allocations++; 31 | return &pool->memory[i * BLOCK_SIZE]; 32 | } 33 | } 34 | return NULL; 35 | } 36 | 37 | void pool_free(MemoryPool* pool, void* ptr) { 38 | if(!ptr) return; 39 | 40 | ptrdiff_t offset = (char*)ptr - pool->memory; 41 | int block_index = offset / BLOCK_SIZE; 42 | 43 | if(block_index >= 0 && block_index < NUM_BLOCKS) { 44 | pool->used[block_index] = 0; 45 | pool->num_frees++; 46 | } 47 | } 48 | 49 | void destroy_pool(MemoryPool* pool) { 50 | free(pool); 51 | } 52 | 53 | void compare_performance() { 54 | struct timeval start, end; 55 | const int NUM_TESTS = 100000; 56 | 57 | gettimeofday(&start, NULL); 58 | for(int i = 0; i < NUM_TESTS; i++) { 59 | void* ptr = malloc(BLOCK_SIZE); 60 | free(ptr); 61 | } 62 | gettimeofday(&end, NULL); 63 | double heap_time = (end.tv_sec - start.tv_sec) * 1000000.0 + 64 | (end.tv_usec - start.tv_usec); 65 | 66 | MemoryPool* pool = create_pool(); 67 | gettimeofday(&start, NULL); 68 | for(int i = 0; i < NUM_TESTS; i++) { 69 | void* ptr = pool_alloc(pool); 70 | pool_free(pool, ptr); 71 | } 72 | gettimeofday(&end, NULL); 73 | double pool_time = (end.tv_sec - start.tv_sec) * 1000000.0 + 74 | (end.tv_usec - start.tv_usec); 75 | 76 | printf("Standard heap time: %.2f microseconds\n", heap_time / NUM_TESTS); 77 | printf("Memory pool time: %.2f microseconds\n", pool_time / NUM_TESTS); 78 | printf("Performance improvement: %.2fx\n", heap_time / pool_time); 79 | 80 | destroy_pool(pool); 81 | } 82 | 83 | int main() { 84 | compare_performance(); 85 | return 0; 86 | } -------------------------------------------------------------------------------- /memory/memory_management/stack_vs_heap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct { 7 | char data[1024]; 8 | int size; 9 | } LargeObject; 10 | 11 | // Stack-based implementation 12 | void process_on_stack() { 13 | LargeObject obj; 14 | obj.size = 1024; 15 | memset(obj.data, 'A', obj.size); 16 | } 17 | 18 | // Heap-based implementation 19 | void process_on_heap() { 20 | LargeObject* obj = (LargeObject*)malloc(sizeof(LargeObject)); 21 | if(!obj) { 22 | printf("Allocation failed!\n"); 23 | return; 24 | } 25 | obj->size = 1024; 26 | memset(obj->data, 'A', obj->size); 27 | free(obj); 28 | } 29 | 30 | int main() { 31 | const int NUM_ITERATIONS = 100000; 32 | 33 | // Time stack operations 34 | clock_t start = clock(); 35 | for(int i = 0; i < NUM_ITERATIONS; i++) { 36 | process_on_stack(); 37 | } 38 | clock_t stack_time = clock() - start; 39 | 40 | // Time heap operations 41 | start = clock(); 42 | for(int i = 0; i < NUM_ITERATIONS; i++) { 43 | process_on_heap(); 44 | } 45 | clock_t heap_time = clock() - start; 46 | 47 | printf("Stack time: %f seconds\n", 48 | (double)stack_time / CLOCKS_PER_SEC); 49 | printf("Heap time: %f seconds\n", 50 | (double)heap_time / CLOCKS_PER_SEC); 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /memory/memory_management/sys_calls.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // Structure to hold timing information 7 | typedef struct { 8 | struct timeval start; 9 | struct timeval end; 10 | } TimingInfo; 11 | 12 | // Function to start timing 13 | void start_timing(TimingInfo* timing) { 14 | gettimeofday(&timing->start, NULL); 15 | } 16 | 17 | // Function to end timing and return microseconds elapsed 18 | long end_timing(TimingInfo* timing) { 19 | gettimeofday(&timing->end, NULL); 20 | return (timing->end.tv_sec - timing->start.tv_sec) * 1000000 + 21 | (timing->end.tv_usec - timing->start.tv_usec); 22 | } 23 | 24 | int main() { 25 | const int NUM_ALLOCATIONS = 10000; 26 | const int ALLOCATION_SIZE = 1024; // 1KB 27 | TimingInfo timing; 28 | void* allocations[NUM_ALLOCATIONS]; 29 | 30 | // Measure heap allocations 31 | start_timing(&timing); 32 | for(int i = 0; i < NUM_ALLOCATIONS; i++) { 33 | allocations[i] = malloc(ALLOCATION_SIZE); 34 | if(!allocations[i]) { 35 | printf("Allocation failed!\n"); 36 | exit(1); 37 | } 38 | } 39 | long heap_time = end_timing(&timing); 40 | 41 | // Clean up 42 | for(int i = 0; i < NUM_ALLOCATIONS; i++) { 43 | free(allocations[i]); 44 | } 45 | 46 | // Measure stack allocations 47 | start_timing(&timing); 48 | for(int i = 0; i < NUM_ALLOCATIONS; i++) { 49 | char stack_array[ALLOCATION_SIZE]; 50 | stack_array[0] = 1; // Prevent optimization 51 | } 52 | long stack_time = end_timing(&timing); 53 | 54 | printf("Time for %d heap allocations: %ld microseconds\n", 55 | NUM_ALLOCATIONS, heap_time); 56 | printf("Time for %d stack allocations: %ld microseconds\n", 57 | NUM_ALLOCATIONS, stack_time); 58 | printf("Ratio (heap/stack): %.2fx\n", 59 | (double)heap_time / stack_time); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /memory/parallelComputing/matrix_mul.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MATRIX_SIZE 1024 7 | #define BLOCK_SIZE 32 8 | 9 | void tensor_core_simulation(float* A, float* B, float* C, float* D, int M, int N, int K) { 10 | #pragma omp parallel for collapse(2) 11 | for (int i = 0; i < M; i += BLOCK_SIZE) { 12 | for (int j = 0; j < N; j += BLOCK_SIZE) { 13 | float temp[BLOCK_SIZE][BLOCK_SIZE] = {0}; 14 | 15 | // Matrix multiplication in blocks 16 | for (int k = 0; k < K; k += BLOCK_SIZE) { 17 | for (int bi = 0; bi < BLOCK_SIZE; bi++) { 18 | for (int bj = 0; bj < BLOCK_SIZE; bj++) { 19 | float sum = 0.0f; 20 | for (int bk = 0; bk < BLOCK_SIZE; bk++) { 21 | sum += A[(i+bi)*K + (k+bk)] * 22 | B[(k+bk)*N + (j+bj)]; 23 | } 24 | temp[bi][bj] += sum; 25 | } 26 | } 27 | } 28 | 29 | // Add bias and store result 30 | for (int bi = 0; bi < BLOCK_SIZE; bi++) { 31 | for (int bj = 0; bj < BLOCK_SIZE; bj++) { 32 | D[(i+bi)*N + (j+bj)] = 33 | temp[bi][bj] + C[(i+bi)*N + (j+bj)]; 34 | } 35 | } 36 | } 37 | } 38 | } 39 | 40 | 41 | int main() { 42 | float *A, *B, *C, *D; 43 | 44 | // Allocate matrices 45 | A = (float*)malloc(MATRIX_SIZE * MATRIX_SIZE * sizeof(float)); 46 | B = (float*)malloc(MATRIX_SIZE * MATRIX_SIZE * sizeof(float)); 47 | C = (float*)malloc(MATRIX_SIZE * MATRIX_SIZE * sizeof(float)); 48 | D = (float*)malloc(MATRIX_SIZE * MATRIX_SIZE * sizeof(float)); 49 | 50 | // Initialize matrices with random values 51 | srand(time(NULL)); 52 | for (int i = 0; i < MATRIX_SIZE * MATRIX_SIZE; i++) { 53 | A[i] = (float)rand() / RAND_MAX; 54 | B[i] = (float)rand() / RAND_MAX; 55 | C[i] = (float)rand() / RAND_MAX; 56 | } 57 | 58 | // Measure execution time 59 | double start_time = omp_get_wtime(); 60 | tensor_core_simulation(A, B, C, D, MATRIX_SIZE, MATRIX_SIZE, MATRIX_SIZE); 61 | double end_time = omp_get_wtime(); 62 | 63 | printf("Matrix multiplication completed in %.3f seconds\n", 64 | end_time - start_time); 65 | 66 | // Print sample results 67 | printf("Sample output (top-left 2x2 corner):\n"); 68 | for (int i = 0; i < 2; i++) { 69 | for (int j = 0; j < 2; j++) { 70 | printf("%.4f ", D[i * MATRIX_SIZE + j]); 71 | } 72 | printf("\n"); 73 | } 74 | 75 | free(A); 76 | free(B); 77 | free(C); 78 | free(D); 79 | return 0; 80 | } -------------------------------------------------------------------------------- /memory/parallelComputing/parallel_processing.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define ARRAY_SIZE 1000000 7 | #define NUM_THREADS 8 8 | 9 | void parallel_array_operation(float* input, float* output, int size) { 10 | #pragma omp parallel num_threads(NUM_THREADS) 11 | { 12 | int thread_id = omp_get_thread_num(); 13 | int chunk_size = size / NUM_THREADS; 14 | int start = thread_id * chunk_size; 15 | int end = (thread_id == NUM_THREADS - 1) ? size : start + chunk_size; 16 | 17 | // Simulate GPU-like parallel processing 18 | for (int i = start; i < end; i++) { 19 | // Simple arithmetic operation 20 | output[i] = input[i] * 2.0f + 1.0f; 21 | } 22 | } 23 | } 24 | 25 | int main() { 26 | float *input = (float*)malloc(ARRAY_SIZE * sizeof(float)); 27 | float *output = (float*)malloc(ARRAY_SIZE * sizeof(float)); 28 | 29 | // Initialize input array 30 | srand(time(NULL)); 31 | for (int i = 0; i < ARRAY_SIZE; i++) { 32 | input[i] = (float)rand() / RAND_MAX; 33 | } 34 | 35 | // Measure execution time 36 | double start_time = omp_get_wtime(); 37 | parallel_array_operation(input, output, ARRAY_SIZE); 38 | double end_time = omp_get_wtime(); 39 | 40 | printf("Execution time: %f seconds\n", end_time - start_time); 41 | printf("First 5 results: %f %f %f %f %f\n", 42 | output[0], output[1], output[2], output[3], output[4]); 43 | 44 | free(input); 45 | free(output); 46 | return 0; 47 | } -------------------------------------------------------------------------------- /memory/parallelComputing/simt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define WARP_SIZE 32 7 | #define NUM_WARPS 4 8 | #define TOTAL_THREADS (WARP_SIZE * NUM_WARPS) 9 | 10 | typedef struct { 11 | int thread_id; 12 | float* input; 13 | float* output; 14 | int size; 15 | } ThreadData; 16 | 17 | void* simt_thread(void* arg) { 18 | ThreadData* data = (ThreadData*)arg; 19 | int tid = data->thread_id; 20 | int stride = TOTAL_THREADS; 21 | 22 | // Simulate SIMT execution with divergent paths 23 | for (int i = tid; i < data->size; i += stride) { 24 | if (data->input[i] > 0.5f) { 25 | // Branch 1: Square the value 26 | data->output[i] = data->input[i] * data->input[i]; 27 | } else { 28 | // Branch 2: Double the value 29 | data->output[i] = data->input[i] * 2.0f; 30 | } 31 | } 32 | 33 | return NULL; 34 | } 35 | 36 | int main() { 37 | const int size = 1024; 38 | float* input = (float*)malloc(size * sizeof(float)); 39 | float* output = (float*)malloc(size * sizeof(float)); 40 | pthread_t threads[TOTAL_THREADS]; 41 | ThreadData thread_data[TOTAL_THREADS]; 42 | 43 | // Initialize input array 44 | srand(time(NULL)); 45 | for (int i = 0; i < size; i++) { 46 | input[i] = (float)rand() / RAND_MAX; 47 | } 48 | 49 | // Create threads 50 | for (int i = 0; i < TOTAL_THREADS; i++) { 51 | thread_data[i].thread_id = i; 52 | thread_data[i].input = input; 53 | thread_data[i].output = output; 54 | thread_data[i].size = size; 55 | pthread_create(&threads[i], NULL, simt_thread, &thread_data[i]); 56 | } 57 | 58 | // Join threads 59 | for (int i = 0; i < TOTAL_THREADS; i++) { 60 | pthread_join(threads[i], NULL); 61 | } 62 | 63 | // Print sample results 64 | printf("Sample results:\n"); 65 | for (int i = 0; i < 5; i++) { 66 | printf("Input: %.4f, Output: %.4f\n", input[i], output[i]); 67 | } 68 | 69 | free(input); 70 | free(output); 71 | return 0; 72 | } -------------------------------------------------------------------------------- /memory/virtual_mem/TLB.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define TLB_SIZE 8 7 | #define MAX_VIRTUAL_ADDRESS 1024 // For simplicity, we'll use a small address space 8 | #define PAGE_SIZE 4096 // 4KB page size 9 | 10 | typedef struct { 11 | int virtual_page; 12 | int physical_frame; 13 | bool valid; 14 | } TLBEntry; 15 | 16 | TLBEntry TLB[TLB_SIZE]; 17 | 18 | void initTLB() { 19 | for (int i = 0; i < TLB_SIZE; i++) { 20 | TLB[i].valid = false; 21 | } 22 | } 23 | 24 | // to check if TLB has an entry for given virtual page 25 | bool TLBHit(int virtual_page) { 26 | for (int i = 0; i < TLB_SIZE; i++) { 27 | if (TLB[i].valid && TLB[i].virtual_page == virtual_page) { 28 | printf("TLB Hit for virtual page %d\n", virtual_page); 29 | return true; 30 | } 31 | } 32 | printf("TLB Miss for virtual page %d\n", virtual_page); 33 | return false; 34 | } 35 | 36 | //to update TLB with a new entry (simple replacement policy) 37 | void updateTLB(int virtual_page, int physical_frame) { 38 | int replace_index = rand() % TLB_SIZE; // Random replacement for simplicity 39 | TLB[replace_index].virtual_page = virtual_page; 40 | TLB[replace_index].physical_frame = physical_frame; 41 | TLB[replace_index].valid = true; 42 | printf("Updated TLB with virtual page %d -> physical frame %d\n", virtual_page, physical_frame); 43 | } 44 | 45 | int translateAddress(int virtual_address) { 46 | int virtual_page = virtual_address / PAGE_SIZE; 47 | int offset = virtual_address % PAGE_SIZE; 48 | 49 | if (TLBHit(virtual_page)) { 50 | // For this basic implementation, we'll assume we know the physical frame for demonstration 51 | int physical_frame = virtual_page; // In real systems, this would come from the TLB 52 | return (physical_frame * PAGE_SIZE) + offset; 53 | } else { 54 | // Here, we'll just use the virtual page number as the physical frame for simplicity 55 | int physical_frame = virtual_page; 56 | updateTLB(virtual_page, physical_frame); 57 | return (physical_frame * PAGE_SIZE) + offset; 58 | } 59 | } 60 | 61 | int main() { 62 | srand(time(NULL)); // For random replacement 63 | initTLB(); 64 | 65 | int virtual_addresses[] = {1000, 2000, 3000, 4000, 1000, 2000, 5000, 6000}; 66 | int num_addresses = sizeof(virtual_addresses) / sizeof(virtual_addresses[0]); 67 | 68 | for (int i = 0; i < num_addresses; i++) { 69 | int physical_address = translateAddress(virtual_addresses[i]); 70 | printf("Translated virtual address %d to physical address %d\n", virtual_addresses[i], physical_address); 71 | printf("\n"); 72 | } 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /memory/virtual_mem/pagemap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/memory/virtual_mem/pagemap -------------------------------------------------------------------------------- /memory/virtual_mem/pagemap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define PAGE_SHIFT 12 10 | #define PAGE_SIZE (1 << PAGE_SHIFT) 11 | #define PFN_MASK (((1ULL << 55) - 1) & ~((1ULL << PAGE_SHIFT) - 1)) 12 | 13 | int main() { 14 | int var; 15 | int fd; 16 | uint64_t entry, pfn; 17 | off_t offset; 18 | 19 | printf("Virtual address of var: %p\n", &var); 20 | 21 | fd = open("/proc/self/pagemap", O_RDONLY); 22 | if (fd < 0) { 23 | perror("open"); 24 | return 1; 25 | } 26 | 27 | offset = (uintptr_t)&var / PAGE_SIZE * sizeof(entry); 28 | if (lseek(fd, offset, SEEK_SET) == (off_t)-1) { 29 | perror("lseek"); 30 | close(fd); 31 | return 1; 32 | } 33 | 34 | if (read(fd, &entry, sizeof(entry)) != sizeof(entry)) { 35 | perror("read"); 36 | close(fd); 37 | return 1; 38 | } 39 | 40 | close(fd); 41 | 42 | if ((entry & (1ULL << 63)) == 0) { 43 | printf("Page not present\n"); 44 | return 1; 45 | } 46 | 47 | pfn = entry & PFN_MASK; 48 | printf("Physical address: 0x%lx\n", (pfn << PAGE_SHIFT) | ((uintptr_t)&var & (PAGE_SIZE - 1))); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /memory/virtual_mem/virtual_address: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/memory/virtual_mem/virtual_address -------------------------------------------------------------------------------- /memory/virtual_mem/virtual_address.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | int var = 42; 7 | printf("Parent PID: %d\n", getpid()); 8 | printf("Parent var address: %p\n", &var); 9 | 10 | pid_t pid = fork(); 11 | if (pid == 0) { 12 | printf("Child PID: %d\n", getpid()); 13 | printf("Child var address: %p\n", &var); 14 | var = 84; 15 | printf("Child var value: %d\n", var); 16 | _exit(0); 17 | } else { 18 | wait(NULL); 19 | printf("Parent var value: %d\n", var); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /ml/mlp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/ml/mlp -------------------------------------------------------------------------------- /networking/quic/client: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/networking/quic/client -------------------------------------------------------------------------------- /networking/quic/quic.pcap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/networking/quic/quic.pcap -------------------------------------------------------------------------------- /networking/quic/quic_handshake: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/networking/quic/quic_handshake -------------------------------------------------------------------------------- /networking/quic/quic_handshake.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void init_openssl() { 5 | SSL_load_error_strings(); 6 | OpenSSL_add_ssl_algorithms(); 7 | } 8 | 9 | SSL_CTX* create_context() { 10 | const SSL_METHOD *method = TLS_client_method(); 11 | SSL_CTX *ctx = SSL_CTX_new(method); 12 | SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION); 13 | return ctx; 14 | } 15 | 16 | int main() { 17 | init_openssl(); 18 | SSL_CTX *ctx = create_context(); 19 | 20 | SSL *ssl = SSL_new(ctx); 21 | BIO *bio = BIO_new(BIO_s_connect()); 22 | BIO_set_conn_hostname(bio, "example.com:4433"); 23 | 24 | SSL_set_bio(ssl, bio, bio); 25 | SSL_connect(ssl); 26 | 27 | char *data = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"; 28 | SSL_write(ssl, data, strlen(data)); 29 | 30 | char response[1024]; 31 | SSL_read(ssl, response, 1024); 32 | printf("Response: %s\n", response); 33 | 34 | SSL_free(ssl); 35 | SSL_CTX_free(ctx); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /networking/quic/server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/networking/quic/server -------------------------------------------------------------------------------- /networking/quic/udp_client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PORT 4433 8 | 9 | int main() { 10 | int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 11 | struct sockaddr_in serv_addr = { 12 | .sin_family = AF_INET, 13 | .sin_port = htons(PORT), 14 | .sin_addr.s_addr = inet_addr("127.0.0.1") 15 | }; 16 | 17 | char *message = "QUIC-like message"; 18 | sendto(sockfd, message, 17, 0, 19 | (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 20 | 21 | char buffer[1024]; 22 | recvfrom(sockfd, buffer, 1024, 0, NULL, NULL); 23 | printf("Received: %s\n", buffer); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /networking/quic/udp_server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PORT 4433 7 | 8 | int main() { 9 | int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 10 | struct sockaddr_in serv_addr = { 11 | .sin_family = AF_INET, 12 | .sin_port = htons(PORT), 13 | .sin_addr.s_addr = INADDR_ANY 14 | }; 15 | 16 | bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 17 | 18 | char buffer[1024]; 19 | struct sockaddr_in cli_addr; 20 | socklen_t len = sizeof(cli_addr); 21 | 22 | while(1) { 23 | int n = recvfrom(sockfd, buffer, 1024, 0, 24 | (struct sockaddr*)&cli_addr, &len); 25 | sendto(sockfd, buffer, n, 0, 26 | (struct sockaddr*)&cli_addr, len); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /networking/uartInputSystem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define UART_DATA (*((volatile uint8_t*)0x1000)) 9 | #define UART_STATUS (*((volatile uint8_t*)0x1001)) 10 | #define UART_CONTROL (*((volatile uint8_t*)0x1002)) 11 | 12 | #define UART_DATA_READY 0x80 13 | #define UART_OVERRUN 0x40 14 | 15 | #define BUFFER_SIZE 256 16 | 17 | typedef struct { 18 | uint8_t data[BUFFER_SIZE]; 19 | volatile uint8_t write_ptr; 20 | volatile uint8_t read_ptr; 21 | } RingBuffer; 22 | 23 | static RingBuffer uart_rx_buffer; 24 | 25 | void ring_buffer_init(RingBuffer* buffer) { 26 | buffer->write_ptr = 0; 27 | buffer->read_ptr = 0; 28 | } 29 | 30 | bool ring_buffer_write(RingBuffer* buffer, uint8_t data) { 31 | uint8_t next_write = (buffer->write_ptr + 1) % BUFFER_SIZE; 32 | 33 | if (next_write == buffer->read_ptr) { 34 | return false; 35 | } 36 | 37 | buffer->data[buffer->write_ptr] = data; 38 | buffer->write_ptr = next_write; 39 | return true; 40 | } 41 | 42 | bool ring_buffer_read(RingBuffer* buffer, uint8_t* data) { 43 | if (buffer->read_ptr == buffer->write_ptr) { 44 | return false; 45 | } 46 | 47 | *data = buffer->data[buffer->read_ptr]; 48 | buffer->read_ptr = (buffer->read_ptr + 1) % BUFFER_SIZE; 49 | return true; 50 | } 51 | 52 | void uart_isr(int signum) { 53 | uint8_t status = UART_STATUS; 54 | 55 | if (status & UART_DATA_READY) { 56 | uint8_t data = UART_DATA; 57 | if (!ring_buffer_write(&uart_rx_buffer, data)) { 58 | fprintf(stderr, "UART buffer overflow!\n"); 59 | } 60 | } 61 | } 62 | 63 | void uart_init(void) { 64 | ring_buffer_init(&uart_rx_buffer); 65 | signal(SIGALRM, uart_isr); 66 | UART_CONTROL = 0x0B; 67 | } 68 | 69 | bool uart_getchar(uint8_t* data, uint16_t timeout_ms) { 70 | alarm(timeout_ms / 1000); 71 | while (timeout_ms--) { 72 | if (ring_buffer_read(&uart_rx_buffer, data)) { 73 | alarm(0); 74 | return true; 75 | } 76 | usleep(1000); 77 | } 78 | alarm(0); 79 | return false; 80 | } 81 | 82 | int main() { 83 | uart_init(); 84 | 85 | printf("UART initialized. Waiting for data...\n"); 86 | 87 | while (1) { 88 | uint8_t received; 89 | if (uart_getchar(&received, 1000)) { 90 | printf("Received: %c\n", received); 91 | } else { 92 | printf("Timeout: No data received in 1 second.\n"); 93 | } 94 | } 95 | 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /os/filesystem/ReadReplica.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | try { 9 | // Get database credentials from environment variables 10 | const char* db_name_1 = std::getenv("DB_NAME_1"); 11 | const char* db_name_2 = std::getenv("DB_NAME_2"); 12 | const char* db_user = std::getenv("DB_USER"); 13 | const char* db_password = std::getenv("DB_PASSWORD"); 14 | 15 | // Check if credentials are set 16 | if (!db_name_1 || !db_name_2 || !db_user || !db_password) { 17 | cerr << "Environment variables not set" << endl; 18 | return 1; 19 | } 20 | 21 | // Create connection strings 22 | string conn_string_1 = "dbname=" + string(db_name_1) + 23 | " user=" + string(db_user) + 24 | " password=" + string(db_password); 25 | 26 | string conn_string_2 = "dbname=" + string(db_name_2) + 27 | " user=" + string(db_user) + 28 | " password=" + string(db_password); 29 | 30 | // Connect to databases 31 | pqxx::connection conn1(conn_string_1); 32 | pqxx::connection conn2(conn_string_2); 33 | 34 | cout << "Connected to databases successfully." << endl; 35 | 36 | // Start transactions 37 | pqxx::work w1(conn1); 38 | pqxx::work w2(conn2); 39 | 40 | // Execute queries 41 | w1.exec("INSERT INTO users values ('4', 'Whatever')"); 42 | pqxx::result users_result = w1.exec("SELECT id, name FROM users"); 43 | 44 | pqxx::result grades_result = w2.exec("SELECT * FROM grades WHERE rollNumber='1'"); 45 | 46 | cout << "Users found: " << users_result.size() << endl; 47 | for (const auto& row : users_result) { 48 | int id = row[0].as(); 49 | string name = row[1].as(); 50 | cout << "ID: " << id << ", Name: " << name << endl; 51 | } 52 | 53 | cout << "Grades found: " << grades_result.size() << endl; 54 | for (const auto& row : grades_result) { 55 | int id = row[0].as(); 56 | string subject = row[1].as(); 57 | int marks = row[2].as(); 58 | int rollNumber = row[3].as(); 59 | 60 | cout << "ID: " << id 61 | << ", Subject: " << subject 62 | << ", Marks: " << marks 63 | << ", Roll Number: " << rollNumber << endl; 64 | } 65 | 66 | // Commit transactions 67 | w1.commit(); 68 | w2.commit(); 69 | 70 | cout << "Transactions committed successfully." << endl; 71 | 72 | } catch (const exception& e) { 73 | cerr << e.what() << endl; 74 | return 1; 75 | } 76 | 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /os/filesystem/SIGBUS.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | static sigjmp_buf jmpbuf; 11 | 12 | void sigbus_handler(int signo) { 13 | siglongjmp(jmpbuf, 1); 14 | } 15 | 16 | void sigsegv_handler(int signo) { 17 | siglongjmp(jmpbuf, 2); 18 | } 19 | 20 | int main() { 21 | struct sigaction sa_bus, sa_segv; 22 | 23 | // Set up SIGBUS handler 24 | sa_bus.sa_handler = sigbus_handler; 25 | sigemptyset(&sa_bus.sa_mask); 26 | sa_bus.sa_flags = 0; 27 | sigaction(SIGBUS, &sa_bus, NULL); 28 | 29 | // Set up SIGSEGV handler 30 | sa_segv.sa_handler = sigsegv_handler; 31 | sigemptyset(&sa_segv.sa_mask); 32 | sa_segv.sa_flags = 0; 33 | sigaction(SIGSEGV, &sa_segv, NULL); 34 | 35 | int ret = sigsetjmp(jmpbuf, 1); 36 | if (ret == 0) { 37 | // Attempt to cause a SIGBUS error 38 | int fd = open("/dev/zero", O_RDONLY); 39 | if (fd == -1) { 40 | perror("open"); 41 | return 1; 42 | } 43 | 44 | char *ptr = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0); 45 | if (ptr == MAP_FAILED) { 46 | perror("mmap"); 47 | close(fd); 48 | return 1; 49 | } 50 | 51 | close(fd); 52 | munmap(ptr, 4096); 53 | 54 | // Try to access unmapped memory (should cause SIGBUS) 55 | char c = *ptr; 56 | printf("This should not be printed: %c\n", c); 57 | } else if (ret == 1) { 58 | printf("SIGBUS error occurred\n"); 59 | } else if (ret == 2) { 60 | printf("Segmentation fault (SIGSEGV) occurred\n"); 61 | } 62 | 63 | // Attempt to cause a Segmentation Fault 64 | char *null_ptr = NULL; 65 | *null_ptr = 'x'; // This should cause a Segmentation Fault 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /os/filesystem/blocksize.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | struct stat stdout_stat; 8 | struct stat file_stat; 9 | 10 | // Get information about stdout 11 | if (fstat(STDOUT_FILENO, &stdout_stat) == -1) { 12 | perror("fstat stdout failed"); 13 | return 1; 14 | } 15 | 16 | // Create and get information about a regular file 17 | int fd = open("test.txt", O_WRONLY | O_CREAT, 0644); 18 | if (fd == -1) { 19 | perror("open failed"); 20 | return 1; 21 | } 22 | 23 | if (fstat(fd, &file_stat) == -1) { 24 | perror("fstat file failed"); 25 | close(fd); 26 | return 1; 27 | } 28 | 29 | fprintf(stderr, "stdout block size: %ld\n", stdout_stat.st_blksize); 30 | fprintf(stderr, "file block size: %ld\n", file_stat.st_blksize); 31 | 32 | close(fd); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /os/filesystem/blocksize.s: -------------------------------------------------------------------------------- 1 | .file "blocksize.c" 2 | .text 3 | .section .rodata 4 | .LC0: 5 | .string "fstat stdout failed" 6 | .LC1: 7 | .string "test.txt" 8 | .LC2: 9 | .string "open failed" 10 | .LC3: 11 | .string "fstat file failed" 12 | .LC4: 13 | .string "stdout block size: %ld\n" 14 | .LC5: 15 | .string "file block size: %ld\n" 16 | .text 17 | .globl main 18 | .type main, @function 19 | main: 20 | .LFB0: 21 | .cfi_startproc 22 | endbr64 23 | pushq %rbp 24 | .cfi_def_cfa_offset 16 25 | .cfi_offset 6, -16 26 | movq %rsp, %rbp 27 | .cfi_def_cfa_register 6 28 | subq $320, %rsp 29 | movq %fs:40, %rax 30 | movq %rax, -8(%rbp) 31 | xorl %eax, %eax 32 | leaq -304(%rbp), %rax 33 | movq %rax, %rsi 34 | movl $1, %edi 35 | call fstat@PLT 36 | cmpl $-1, %eax 37 | jne .L2 38 | leaq .LC0(%rip), %rax 39 | movq %rax, %rdi 40 | call perror@PLT 41 | movl $1, %eax 42 | jmp .L6 43 | .L2: 44 | movl $420, %edx 45 | movl $65, %esi 46 | leaq .LC1(%rip), %rax 47 | movq %rax, %rdi 48 | movl $0, %eax 49 | call open@PLT 50 | movl %eax, -308(%rbp) 51 | cmpl $-1, -308(%rbp) 52 | jne .L4 53 | leaq .LC2(%rip), %rax 54 | movq %rax, %rdi 55 | call perror@PLT 56 | movl $1, %eax 57 | jmp .L6 58 | .L4: 59 | leaq -160(%rbp), %rdx 60 | movl -308(%rbp), %eax 61 | movq %rdx, %rsi 62 | movl %eax, %edi 63 | call fstat@PLT 64 | cmpl $-1, %eax 65 | jne .L5 66 | leaq .LC3(%rip), %rax 67 | movq %rax, %rdi 68 | call perror@PLT 69 | movl -308(%rbp), %eax 70 | movl %eax, %edi 71 | call close@PLT 72 | movl $1, %eax 73 | jmp .L6 74 | .L5: 75 | movq -248(%rbp), %rdx 76 | movq stderr(%rip), %rax 77 | leaq .LC4(%rip), %rcx 78 | movq %rcx, %rsi 79 | movq %rax, %rdi 80 | movl $0, %eax 81 | call fprintf@PLT 82 | movq -104(%rbp), %rdx 83 | movq stderr(%rip), %rax 84 | leaq .LC5(%rip), %rcx 85 | movq %rcx, %rsi 86 | movq %rax, %rdi 87 | movl $0, %eax 88 | call fprintf@PLT 89 | movl -308(%rbp), %eax 90 | movl %eax, %edi 91 | call close@PLT 92 | movl $0, %eax 93 | .L6: 94 | movq -8(%rbp), %rdx 95 | subq %fs:40, %rdx 96 | je .L7 97 | call __stack_chk_fail@PLT 98 | .L7: 99 | leave 100 | .cfi_def_cfa 7, 8 101 | ret 102 | .cfi_endproc 103 | .LFE0: 104 | .size main, .-main 105 | .ident "GCC: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0" 106 | .section .note.GNU-stack,"",@progbits 107 | .section .note.gnu.property,"a" 108 | .align 8 109 | .long 1f - 0f 110 | .long 4f - 1f 111 | .long 5 112 | 0: 113 | .string "GNU" 114 | 1: 115 | .align 8 116 | .long 0xc0000002 117 | .long 3f - 2f 118 | 2: 119 | .long 0x3 120 | 3: 121 | .align 8 122 | 4: 123 | -------------------------------------------------------------------------------- /os/filesystem/bufferSizes: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/os/filesystem/bufferSizes -------------------------------------------------------------------------------- /os/filesystem/bufferSizes.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define TEST_SIZE (1024 * 1024 * 10) // 10MB of data 7 | 8 | void test_write_performance(size_t buffer_size) { 9 | char* data = malloc(TEST_SIZE); 10 | if (!data) return; 11 | 12 | memset(data, 'A', TEST_SIZE); 13 | 14 | FILE* f = fopen("test.dat", "w"); 15 | if (!f) { 16 | free(data); 17 | return; 18 | } 19 | 20 | clock_t start = clock(); 21 | 22 | size_t remaining = TEST_SIZE; 23 | while (remaining > 0) { 24 | size_t to_write = remaining < buffer_size ? remaining : buffer_size; 25 | fwrite(data + (TEST_SIZE - remaining), 1, to_write, f); 26 | remaining -= to_write; 27 | } 28 | 29 | fclose(f); 30 | 31 | clock_t end = clock(); 32 | double time_spent = (double)(end - start) / CLOCKS_PER_SEC; 33 | 34 | printf("Buffer size: %zu bytes, Time: %f seconds\n", 35 | buffer_size, time_spent); 36 | 37 | free(data); 38 | } 39 | 40 | int main() { 41 | test_write_performance(1); // Unbuffered 42 | test_write_performance(1024); // 1KB buffer 43 | test_write_performance(4096); // 4KB buffer 44 | test_write_performance(8192); // 8KB buffer 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /os/filesystem/buffered.txt: -------------------------------------------------------------------------------- 1 | Hello from child! 2 | Hello from parent! 3 | -------------------------------------------------------------------------------- /os/filesystem/customBuffer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/os/filesystem/customBuffer -------------------------------------------------------------------------------- /os/filesystem/customBuffer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define BUFFER_SIZE 1024 7 | 8 | typedef struct { 9 | char* buffer; 10 | size_t size; 11 | size_t position; 12 | int fd; 13 | } CustomBuffer; 14 | 15 | CustomBuffer* create_buffer(int fd) { 16 | CustomBuffer* buf = malloc(sizeof(CustomBuffer)); 17 | if (!buf) return NULL; 18 | 19 | buf->buffer = malloc(BUFFER_SIZE); 20 | if (!buf->buffer) { 21 | free(buf); 22 | return NULL; 23 | } 24 | 25 | buf->size = BUFFER_SIZE; 26 | buf->position = 0; 27 | buf->fd = fd; 28 | return buf; 29 | } 30 | 31 | int flush_buffer(CustomBuffer* buf) { 32 | if (buf->position == 0) return 0; 33 | 34 | ssize_t written = write(buf->fd, buf->buffer, buf->position); 35 | if (written == -1) return -1; 36 | 37 | buf->position = 0; 38 | return 0; 39 | } 40 | 41 | int write_to_buffer(CustomBuffer* buf, const char* data, size_t len) { 42 | while (len > 0) { 43 | size_t available = buf->size - buf->position; 44 | size_t to_write = len < available ? len : available; 45 | 46 | memcpy(buf->buffer + buf->position, data, to_write); 47 | buf->position += to_write; 48 | data += to_write; 49 | len -= to_write; 50 | 51 | if (buf->position == buf->size) { 52 | if (flush_buffer(buf) == -1) return -1; 53 | } 54 | } 55 | return 0; 56 | } 57 | 58 | void destroy_buffer(CustomBuffer* buf) { 59 | if (buf) { 60 | free(buf->buffer); 61 | free(buf); 62 | } 63 | } 64 | 65 | int main() { 66 | CustomBuffer* buf = create_buffer(STDOUT_FILENO); 67 | if (!buf) { 68 | fprintf(stderr, "Failed to create buffer\n"); 69 | return 1; 70 | } 71 | 72 | const char* message = "Hello, buffered world!\n"; 73 | if (write_to_buffer(buf, message, strlen(message)) == -1) { 74 | fprintf(stderr, "Write failed\n"); 75 | destroy_buffer(buf); 76 | return 1; 77 | } 78 | 79 | flush_buffer(buf); 80 | destroy_buffer(buf); 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /os/filesystem/fileAfterFork.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | int fd = open("test.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); 9 | if (fd == -1) { 10 | perror("open"); 11 | exit(1); 12 | } 13 | 14 | pid_t pid = fork(); 15 | 16 | if (pid == -1) { 17 | perror("fork"); 18 | exit(1); 19 | } else if (pid == 0) { 20 | // Child process 21 | const char *child_msg = "Hello from child!\n"; 22 | write(fd, child_msg, 19); 23 | close(fd); 24 | exit(0); 25 | } else { 26 | // Parent process 27 | wait(NULL); // Wait for child to finish 28 | const char *parent_msg = "Hello from parent!\n"; 29 | write(fd, parent_msg, 20); 30 | close(fd); 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /os/filesystem/forkConcurrency.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define BUFFER_SIZE 1 8 | 9 | int main(int argc, char *argv[]) { 10 | if (argc != 2) { 11 | fprintf(stderr, "Usage: %s \n", argv[0]); 12 | exit(1); 13 | } 14 | 15 | int fd = open(argv[1], O_RDONLY); 16 | if (fd == -1) { 17 | perror("Error opening file"); 18 | exit(1); 19 | } 20 | 21 | pid_t pid = fork(); 22 | 23 | if (pid == -1) { 24 | perror("Fork failed"); 25 | exit(1); 26 | } 27 | 28 | char buffer[BUFFER_SIZE]; 29 | ssize_t bytes_read; 30 | 31 | while ((bytes_read = read(fd, buffer, BUFFER_SIZE)) > 0) { 32 | printf("%s: Read: %c\n", (pid == 0) ? "Child" : "Parent", buffer[0]); 33 | usleep(10000); 34 | } 35 | 36 | if (bytes_read == -1) { 37 | perror("Error reading file"); 38 | exit(1); 39 | } 40 | 41 | close(fd); 42 | 43 | if (pid != 0) { 44 | wait(NULL); 45 | } 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /os/filesystem/issueOfBuffering.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | FILE *fp = fopen("buffered.txt", "w"); 8 | if (fp == NULL) { 9 | perror("fopen"); 10 | exit(1); 11 | } 12 | 13 | fprintf(fp, "Hello"); // This might be buffered 14 | 15 | pid_t pid = fork(); 16 | 17 | if (pid == -1) { 18 | perror("fork"); 19 | exit(1); 20 | } else if (pid == 0) { 21 | // Child process 22 | fprintf(fp, " from child!\n"); 23 | fclose(fp); 24 | exit(0); 25 | } else { 26 | // Parent process 27 | wait(NULL); 28 | fprintf(fp, " from parent!\n"); 29 | fclose(fp); 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /os/filesystem/output.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/os/filesystem/output.txt -------------------------------------------------------------------------------- /os/filesystem/solToIssueOfBuffering.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | int fd = open("unbuffered.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); 9 | if (fd == -1) { 10 | perror("open"); 11 | exit(1); 12 | } 13 | 14 | write(fd, "Hello", 5); 15 | 16 | pid_t pid = fork(); 17 | 18 | if (pid == -1) { 19 | perror("fork"); 20 | exit(1); 21 | } else if (pid == 0) { 22 | // Child process 23 | write(fd, " from child!\n", 13); 24 | close(fd); 25 | exit(0); 26 | } else { 27 | // Parent process 28 | wait(NULL); 29 | write(fd, " from parent!\n", 14); 30 | close(fd); 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /os/filesystem/test.txt: -------------------------------------------------------------------------------- 1 | Hello from child! 2 | Hello from parent! 3 | -------------------------------------------------------------------------------- /os/filesystem/unbuffered.txt: -------------------------------------------------------------------------------- 1 | Hello from child! 2 | from parent! 3 | -------------------------------------------------------------------------------- /os/kernel/kernelInteraction.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | pid_t pid = getpid(); 8 | printf("Process ID (using getpid): %d\n", pid); 9 | 10 | pid_t direct_pid = syscall(SYS_getpid); 11 | printf("Process ID (using syscall): %d\n", direct_pid); 12 | 13 | unsigned long kernel_addr = 0xC0000000; // Typical start of kernel space on 32-bit systems 14 | int *ptr = (int *)kernel_addr; 15 | 16 | printf("Attempting to read from kernel space...\n"); 17 | int value = *ptr; // This will cause a segmentation fault 18 | 19 | printf("This line will never be reached.\n"); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /os/kernel/kernelMM.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define PAGE_SIZE 4096 9 | #define ALLOCATION_SIZE (100 * PAGE_SIZE) 10 | 11 | void print_memory_info(const char *stage) { 12 | FILE *statm = fopen("/proc/self/statm", "r"); 13 | if (statm == NULL) { 14 | perror("Failed to open /proc/self/statm"); 15 | return; 16 | } 17 | 18 | long size, resident, share, text, lib, data, dt; 19 | if (fscanf(statm, "%ld %ld %ld %ld %ld %ld %ld", &size, &resident, &share, &text, &lib, &data, &dt) != 7) { 20 | fprintf(stderr, "Failed to read memory info\n"); 21 | fclose(statm); 22 | return; 23 | } 24 | 25 | fclose(statm); 26 | 27 | printf("%s:\n", stage); 28 | printf(" Total program size: %ld pages\n", size); 29 | printf(" Resident set size: %ld pages\n", resident); 30 | printf(" Shared pages: %ld\n", share); 31 | printf(" Text (code) pages: %ld\n", text); 32 | printf(" Data/stack pages: %ld\n", data); 33 | printf("\n"); 34 | } 35 | 36 | int main() { 37 | print_memory_info("Initial state"); 38 | 39 | // Allocate memory 40 | void *ptr = mmap(NULL, ALLOCATION_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 41 | if (ptr == MAP_FAILED) { 42 | perror("mmap failed"); 43 | return 1; 44 | } 45 | 46 | print_memory_info("After allocation"); 47 | 48 | // Touch the memory to force page allocation 49 | memset(ptr, 0, ALLOCATION_SIZE); 50 | 51 | print_memory_info("After touching memory"); 52 | 53 | // Free the memory 54 | if (munmap(ptr, ALLOCATION_SIZE) == -1) { 55 | perror("munmap failed"); 56 | return 1; 57 | } 58 | 59 | print_memory_info("After freeing memory"); 60 | 61 | // Try to allocate memory in kernel space (this will fail) 62 | void *kernel_ptr = mmap((void *)0xffffffff80000000, PAGE_SIZE, PROT_READ | PROT_WRITE, 63 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 64 | if (kernel_ptr == MAP_FAILED) { 65 | printf("Failed to allocate in kernel space as expected. Error: %s\n", strerror(errno)); 66 | } else { 67 | printf("Unexpectedly succeeded in allocating kernel space memory at %p\n", kernel_ptr); 68 | munmap(kernel_ptr, PAGE_SIZE); 69 | } 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /os/kernel/kernelSysCall.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define FILENAME "test_file.txt" 12 | #define BUFFER_SIZE 1024 13 | 14 | void check_error(int result, const char *msg) { 15 | if (result == -1) { 16 | perror(msg); 17 | exit(EXIT_FAILURE); 18 | } 19 | } 20 | 21 | int main() { 22 | pid_t pid; 23 | int fd, status; 24 | char buffer[BUFFER_SIZE]; 25 | ssize_t bytes_read, bytes_written; 26 | 27 | fd = open(FILENAME, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); 28 | check_error(fd, "open"); 29 | 30 | const char *message = "Hello, Kernel Space!\n"; 31 | bytes_written = write(fd, message, strlen(message)); 32 | check_error(bytes_written, "write"); 33 | printf("Wrote %zd bytes to file\n", bytes_written); 34 | 35 | close(fd); 36 | 37 | pid = fork(); 38 | check_error(pid, "fork"); 39 | 40 | if (pid == 0) { 41 | fd = open(FILENAME, O_RDONLY); 42 | check_error(fd, "open in child"); 43 | 44 | bytes_read = read(fd, buffer, BUFFER_SIZE - 1); 45 | check_error(bytes_read, "read"); 46 | buffer[bytes_read] = '\0'; 47 | 48 | printf("Child read: %s", buffer); 49 | close(fd); 50 | 51 | exit(EXIT_SUCCESS); 52 | } else { 53 | waitpid(pid, &status, 0); 54 | if (WIFEXITED(status)) { 55 | printf("Child exited with status %d\n", WEXITSTATUS(status)); 56 | } 57 | 58 | if (unlink(FILENAME) == -1) { 59 | perror("unlink"); 60 | exit(EXIT_FAILURE); 61 | } 62 | printf("File deleted\n"); 63 | } 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /os/kernel/kernel_mapping.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PAGE_SIZE 4096 7 | 8 | void print_memory_info(void *addr) { 9 | FILE *maps = fopen("/proc/self/maps", "r"); 10 | if (maps == NULL) { 11 | perror("Failed to open /proc/self/maps"); 12 | return; 13 | } 14 | 15 | char line[256]; 16 | while (fgets(line, sizeof(line), maps)) { 17 | unsigned long start, end; 18 | if (sscanf(line, "%lx-%lx", &start, &end) == 2) { 19 | if ((unsigned long)addr >= start && (unsigned long)addr < end) { 20 | printf("Address %p is in region: %s", addr, line); 21 | break; 22 | } 23 | } 24 | } 25 | 26 | fclose(maps); 27 | } 28 | 29 | int main() { 30 | // Allocate memory near the top of user space 31 | void *high_addr = mmap((void *)((1UL << 47) - PAGE_SIZE), PAGE_SIZE, 32 | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 33 | 34 | if (high_addr == MAP_FAILED) { 35 | perror("mmap failed"); 36 | return 1; 37 | } 38 | 39 | printf("Allocated memory at: %p\n", high_addr); 40 | print_memory_info(high_addr); 41 | 42 | // Try to access kernel space (this will fail) 43 | void *kernel_addr = (void *)0xffff800000000000; // Common start of kernel space on x86_64 44 | printf("Attempting to access kernel space at: %p\n", kernel_addr); 45 | print_memory_info(kernel_addr); 46 | 47 | // This will cause a segmentation fault 48 | *(int *)kernel_addr = 42; 49 | 50 | // Clean up (this won't be reached due to the segfault) 51 | munmap(high_addr, PAGE_SIZE); 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /os/kernel/network_stack: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/os/kernel/network_stack -------------------------------------------------------------------------------- /os/process/change_euid.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | uid_t ruid, euid, suid; 9 | 10 | if (getresuid(&ruid, &euid, &suid) == -1) { 11 | fprintf(stderr, "Error getting user IDs: %s\n", strerror(errno)); 12 | return 1; 13 | } 14 | 15 | printf("Initial UIDs - Real: %d, Effective: %d, Saved: %d\n", ruid, euid, suid); 16 | 17 | // Attempt to change effective UID to 1000 18 | if (seteuid(1000) == -1) { 19 | fprintf(stderr, "Error changing effective UID: %s\n", strerror(errno)); 20 | return 1; 21 | } 22 | 23 | if (getresuid(&ruid, &euid, &suid) == -1) { 24 | fprintf(stderr, "Error getting updated user IDs: %s\n", strerror(errno)); 25 | return 1; 26 | } 27 | 28 | printf("Updated UIDs - Real: %d, Effective: %d, Saved: %d\n", ruid, euid, suid); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /os/process/chrootEx.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char *argv[]) { 7 | if (argc != 2) { 8 | fprintf(stderr, "Usage: %s \n", argv[0]); 9 | return 1; 10 | } 11 | 12 | const char *new_root = argv[1]; 13 | 14 | if (chroot(new_root) == -1) { 15 | fprintf(stderr, "Error changing root directory: %s\n", strerror(errno)); 16 | return 1; 17 | } 18 | 19 | if (chdir("/") == -1) { 20 | fprintf(stderr, "Error changing to new root directory: %s\n", strerror(errno)); 21 | return 1; 22 | } 23 | 24 | printf("Changed root to: %s\n", new_root); 25 | system("pwd"); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /os/process/cpu_affinity.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int main(int argc, char *argv[]) { 10 | if (argc != 2) { 11 | fprintf(stderr, "Usage: %s \n", argv[0]); 12 | return 1; 13 | } 14 | 15 | int cpu = atoi(argv[1]); 16 | cpu_set_t set; 17 | 18 | CPU_ZERO(&set); 19 | CPU_SET(cpu, &set); 20 | 21 | if (sched_setaffinity(0, sizeof(set), &set) == -1) { 22 | fprintf(stderr, "Error setting CPU affinity: %s\n", strerror(errno)); 23 | return 1; 24 | } 25 | 26 | printf("Set CPU affinity to CPU %d\n", cpu); 27 | 28 | for (long i = 0; i < 10000000000L; i++) { 29 | if (i % 1000000000 == 0) { 30 | printf("Still running on CPU %d\n", sched_getcpu()); 31 | } 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /os/process/scheduler/completely_fair_scheduler.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define MIN_NICE -20 8 | #define MAX_NICE 19 9 | 10 | typedef struct { 11 | int pid; 12 | int nice_value; 13 | unsigned long vruntime; // Virtual runtime 14 | unsigned long weight; // Process weight based on nice value 15 | } CFSProcess; 16 | 17 | // Calculate process weight based on nice value 18 | unsigned long calculate_weight(int nice) { 19 | // Simplified weight calculation 20 | return (MAX_NICE - nice + 1) * 100; 21 | } 22 | 23 | // Update virtual runtime based on actual runtime and weight 24 | void update_vruntime(CFSProcess* process, unsigned long runtime) { 25 | process->vruntime += (runtime * 1024) / process->weight; 26 | } 27 | 28 | // Find process with minimum vruntime 29 | int find_min_vruntime_process(CFSProcess* processes, int count) { 30 | int min_idx = 0; 31 | unsigned long min_vruntime = processes[0].vruntime; 32 | 33 | for (int i = 1; i < count; i++) { 34 | if (processes[i].vruntime < min_vruntime) { 35 | min_vruntime = processes[i].vruntime; 36 | min_idx = i; 37 | } 38 | } 39 | 40 | return min_idx; 41 | } 42 | 43 | void simulate_cfs(CFSProcess* processes, int count, int simulation_time) { 44 | printf("Starting CFS Simulation\n"); 45 | 46 | // Initialize process weights 47 | for (int i = 0; i < count; i++) { 48 | processes[i].weight = calculate_weight(processes[i].nice_value); 49 | processes[i].vruntime = 0; 50 | } 51 | 52 | // Simulation loop 53 | for (int time = 0; time < simulation_time; time++) { 54 | int next_process = find_min_vruntime_process(processes, count); 55 | 56 | printf("Time %d: Running PID %d (Nice: %d, VRuntime: %lu)\n", 57 | time, 58 | processes[next_process].pid, 59 | processes[next_process].nice_value, 60 | processes[next_process].vruntime); 61 | 62 | // Simulate execution and update vruntime 63 | update_vruntime(&processes[next_process], 1); 64 | } 65 | } 66 | 67 | int main() { 68 | CFSProcess processes[] = { 69 | {1, 0, 0, 0}, // Default nice value 70 | {2, -10, 0, 0}, // High priority 71 | {3, 10, 0, 0} // Low priority 72 | }; 73 | int process_count = sizeof(processes) / sizeof(processes[0]); 74 | 75 | simulate_cfs(processes, process_count, 15); 76 | 77 | return 0; 78 | } -------------------------------------------------------------------------------- /os/process/scheduler/firt_come_first_serve.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct { 5 | int pid; 6 | int arrival_time; 7 | int burst_time; 8 | int completion_time; 9 | int turnaround_time; 10 | int waiting_time; 11 | } Process; 12 | 13 | void fcfs_schedule(Process processes[], int n) { 14 | int current_time = 0; 15 | 16 | for (int i = 0; i < n; i++) { 17 | // If current time is less than arrival time, CPU will be idle 18 | if (current_time < processes[i].arrival_time) 19 | current_time = processes[i].arrival_time; 20 | 21 | processes[i].completion_time = current_time + processes[i].burst_time; 22 | processes[i].turnaround_time = processes[i].completion_time - processes[i].arrival_time; 23 | processes[i].waiting_time = processes[i].turnaround_time - processes[i].burst_time; 24 | 25 | current_time = processes[i].completion_time; 26 | } 27 | } 28 | 29 | void print_metrics(Process processes[], int n) { 30 | float avg_turnaround = 0, avg_waiting = 0; 31 | 32 | printf("\nProcess Metrics:\n"); 33 | printf("PID\tArrival\tBurst\tComplete\tTurnaround\tWaiting\n"); 34 | 35 | for (int i = 0; i < n; i++) { 36 | printf("%d\t%d\t%d\t%d\t\t%d\t\t%d\n", 37 | processes[i].pid, 38 | processes[i].arrival_time, 39 | processes[i].burst_time, 40 | processes[i].completion_time, 41 | processes[i].turnaround_time, 42 | processes[i].waiting_time); 43 | 44 | avg_turnaround += processes[i].turnaround_time; 45 | avg_waiting += processes[i].waiting_time; 46 | } 47 | 48 | printf("\nAverage Turnaround Time: %.2f\n", avg_turnaround/n); 49 | printf("Average Waiting Time: %.2f\n", avg_waiting/n); 50 | } 51 | 52 | int main() { 53 | Process processes[] = { 54 | {1, 0, 7, 0, 0, 0}, 55 | {2, 2, 4, 0, 0, 0}, 56 | {3, 4, 1, 0, 0, 0} 57 | }; 58 | int n = sizeof(processes)/sizeof(processes[0]); 59 | 60 | fcfs_schedule(processes, n); 61 | print_metrics(processes, n); 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /os/process/scheduler/preemptive_scheduler.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define QUANTUM_MS 100 9 | 10 | typedef struct { 11 | int pid; 12 | int remaining_time; 13 | } Task; 14 | 15 | Task* current_task = NULL; 16 | int is_running = 1; 17 | 18 | void timer_handler(int signum) { 19 | if (current_task != NULL) { 20 | printf("Preempting task %d (remaining time: %d ms)\n", 21 | current_task->pid, 22 | current_task->remaining_time); 23 | current_task->remaining_time -= QUANTUM_MS; 24 | 25 | if (current_task->remaining_time <= 0) { 26 | printf("Task %d completed\n", current_task->pid); 27 | free(current_task); 28 | current_task = NULL; 29 | } 30 | } 31 | } 32 | 33 | void setup_timer() { 34 | struct sigaction sa; 35 | struct itimerval timer; 36 | 37 | // Install timer_handler as the signal handler for SIGVTALRM 38 | memset(&sa, 0, sizeof(sa)); 39 | sa.sa_handler = &timer_handler; 40 | sigaction(SIGVTALRM, &sa, NULL); 41 | 42 | // Configure the timer to expire after QUANTUM_MS msec 43 | timer.it_value.tv_sec = 0; 44 | timer.it_value.tv_usec = QUANTUM_MS * 1000; 45 | timer.it_interval.tv_sec = 0; 46 | timer.it_interval.tv_usec = QUANTUM_MS * 1000; 47 | 48 | // Start the timer 49 | setitimer(SIGVTALRM, &timer, NULL); 50 | } 51 | 52 | Task* create_task(int pid, int execution_time) { 53 | Task* task = (Task*)malloc(sizeof(Task)); 54 | task->pid = pid; 55 | task->remaining_time = execution_time; 56 | return task; 57 | } 58 | 59 | int main() { 60 | setup_timer(); 61 | 62 | // Create and run a sample task 63 | current_task = create_task(1, 500); 64 | printf("Starting task %d (execution time: %d ms)\n", 65 | current_task->pid, 66 | current_task->remaining_time); 67 | 68 | // Simple execution loop 69 | while (is_running && current_task != NULL) { 70 | // Simulate CPU work 71 | usleep(10000); 72 | } 73 | 74 | printf("Scheduler terminated\n"); 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /os/process/scheduler/priority_scheduling.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct { 5 | int pid; 6 | int priority; 7 | int age; 8 | int burst_time; 9 | int remaining_time; 10 | } PriorityProcess; 11 | 12 | void age_processes(PriorityProcess processes[], int n) { 13 | for (int i = 0; i < n; i++) { 14 | if (processes[i].remaining_time > 0) { 15 | processes[i].age++; 16 | if (processes[i].age >= 5) { // Age threshold 17 | processes[i].priority++; 18 | processes[i].age = 0; 19 | printf("Process %d priority boosted to %d\n", 20 | processes[i].pid, 21 | processes[i].priority); 22 | } 23 | } 24 | } 25 | } 26 | 27 | int get_highest_priority_process(PriorityProcess processes[], int n) { 28 | int highest_priority = -1; 29 | int selected_process = -1; 30 | 31 | for (int i = 0; i < n; i++) { 32 | if (processes[i].remaining_time > 0) { 33 | if (selected_process == -1 || 34 | processes[i].priority > highest_priority) { 35 | highest_priority = processes[i].priority; 36 | selected_process = i; 37 | } 38 | } 39 | } 40 | 41 | return selected_process; 42 | } 43 | 44 | void priority_schedule_with_aging(PriorityProcess processes[], int n) { 45 | int current_time = 0; 46 | int completed = 0; 47 | 48 | while (completed < n) { 49 | age_processes(processes, n); 50 | int current_process = get_highest_priority_process(processes, n); 51 | 52 | if (current_process == -1) { 53 | current_time++; 54 | continue; 55 | } 56 | 57 | // Execute process for one time unit 58 | processes[current_process].remaining_time--; 59 | current_time++; 60 | 61 | if (processes[current_process].remaining_time == 0) { 62 | completed++; 63 | printf("Process %d completed at time %d\n", 64 | processes[current_process].pid, 65 | current_time); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /os/process/scheduler/process_state.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef enum { 6 | CREATED, 7 | RUNNING, 8 | WAITING, 9 | READY, 10 | TERMINATED 11 | } ProcessState; 12 | 13 | typedef struct { 14 | int pid; 15 | ProcessState state; 16 | int cpu_burst_time; 17 | int io_burst_time; 18 | } Process; 19 | 20 | // Function to create a new process 21 | Process* create_process(int pid, int cpu_time, int io_time) { 22 | Process* p = (Process*)malloc(sizeof(Process)); 23 | p->pid = pid; 24 | p->state = CREATED; 25 | p->cpu_burst_time = cpu_time; 26 | p->io_burst_time = io_time; 27 | return p; 28 | } 29 | 30 | // Function to transition process state 31 | void transition_state(Process* p, ProcessState new_state) { 32 | printf("Process %d: %d -> %d\n", p->pid, p->state, new_state); 33 | p->state = new_state; 34 | } 35 | 36 | // Function to simulate process execution 37 | void simulate_process(Process* p) { 38 | transition_state(p, READY); 39 | transition_state(p, RUNNING); 40 | 41 | if (p->io_burst_time > 0) { 42 | transition_state(p, WAITING); 43 | transition_state(p, READY); 44 | transition_state(p, RUNNING); 45 | } 46 | 47 | transition_state(p, TERMINATED); 48 | } 49 | 50 | int main() { 51 | Process* p1 = create_process(1, 100, 50); 52 | Process* p2 = create_process(2, 75, 0); 53 | 54 | printf("Simulating process 1 (CPU-I/O bound):\n"); 55 | simulate_process(p1); 56 | 57 | printf("\nSimulating process 2 (CPU bound):\n"); 58 | simulate_process(p2); 59 | 60 | free(p1); 61 | free(p2); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /performance/binary-search/binary_search: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/performance/binary-search/binary_search -------------------------------------------------------------------------------- /performance/binary-search/binary_search.asm: -------------------------------------------------------------------------------- 1 | section .text 2 | global binary_search_asm 3 | 4 | ; Function prototype: 5 | ; int binary_search_asm(int* arr, int size, int target) 6 | ; rdi = array pointer 7 | ; esi = size 8 | ; edx = target value 9 | binary_search_asm: 10 | xor eax, eax ; left = 0 11 | lea ecx, [esi-1] ; right = size - 1 12 | 13 | .loop: 14 | cmp eax, ecx ; if left > right, exit 15 | jg .not_found 16 | 17 | mov r8d, eax ; r8d = left 18 | add r8d, ecx ; r8d = left + right 19 | shr r8d, 1 ; r8d = (left + right) / 2 20 | 21 | ; Compare arr[mid] with target 22 | mov r9d, [rdi + r8*4] ; r9d = arr[mid] 23 | cmp r9d, edx 24 | je .found ; if equal, found the element 25 | 26 | ; Use conditional moves to avoid branches 27 | lea r10d, [r8 + 1] ; r10d = mid + 1 28 | lea r11d, [r8 - 1] ; r11d = mid - 1 29 | cmovl eax, r10d ; if arr[mid] < target, left = mid + 1 30 | cmovg ecx, r11d ; if arr[mid] > target, right = mid - 1 31 | jmp .loop 32 | 33 | .found: 34 | mov eax, r8d ; return mid index 35 | ret 36 | 37 | .not_found: 38 | mov eax, -1 ; return -1 39 | ret -------------------------------------------------------------------------------- /performance/binary-search/output_without_any_gcc_optimization.txt: -------------------------------------------------------------------------------- 1 | 2 | Array size: 100 3 | Iterations: 100000 4 | 5 | C Implementation: 6 | Time: 0.020974 seconds 7 | Cycles: 251 8 | Cycles per element: 2.52 9 | 10 | Assembly Implementation: 11 | Time: 0.007073 seconds 12 | Cycles: 84 13 | Cycles per element: 0.85 14 | 15 | 16 | Array size: 1000 17 | Iterations: 100000 18 | 19 | C Implementation: 20 | Time: 0.019905 seconds 21 | Cycles: 240 22 | Cycles per element: 0.24 23 | 24 | Assembly Implementation: 25 | Time: 0.007331 seconds 26 | Cycles: 87 27 | Cycles per element: 0.09 28 | 29 | 30 | Array size: 10000 31 | Iterations: 100000 32 | 33 | C Implementation: 34 | Time: 0.015891 seconds 35 | Cycles: 191 36 | Cycles per element: 0.02 37 | 38 | Assembly Implementation: 39 | Time: 0.006875 seconds 40 | Cycles: 82 41 | Cycles per element: 0.01 42 | 43 | 44 | Array size: 100000 45 | Iterations: 100000 46 | 47 | C Implementation: 48 | Time: 0.018071 seconds 49 | Cycles: 217 50 | Cycles per element: -0.03 51 | 52 | Assembly Implementation: 53 | Time: 0.007590 seconds 54 | Cycles: 92 55 | Cycles per element: -0.01 56 | 57 | -------------------------------------------------------------------------------- /playingAround/README.md: -------------------------------------------------------------------------------- 1 | # Building the Hello World Executable 2 | 3 | To understand how to convert `hello.c` into an executable `hello.out` using GCC, follow these steps: 4 | 5 | ## Step 1: Preprocessing 6 | 7 | ```bash 8 | gcc -E hello.c -o hello.i 9 | ``` 10 | 11 | This step preprocesses `hello.c` and outputs the expanded source code into `hello.i`. 12 | 13 | ## Step 2: Compilation 14 | 15 | ```bash 16 | gcc -S hello.i -o hello.s 17 | ``` 18 | 19 | Compile the preprocessed file to create an assembly code file `hello.s`. 20 | 21 | ## Step 3: Assembly 22 | 23 | ```bash 24 | gcc -c hello.s -o hello.o 25 | ``` 26 | 27 | Assemble the assembly code into machine code, producing an object file `hello.o`. 28 | 29 | 30 | ## Step 4: Linking 31 | 32 | 33 | ```bash 34 | gcc hello.o -o hello.out 35 | ``` 36 | 37 | Link the object file to create the final executable `hello.out`. 38 | -------------------------------------------------------------------------------- /playingAround/fixedTypes/alignment_benchmark: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/playingAround/fixedTypes/alignment_benchmark -------------------------------------------------------------------------------- /playingAround/fixedTypes/memAlignment.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Poorly aligned structure 5 | typedef struct { 6 | char a; // 1 byte 7 | int32_t b; // 4 bytes 8 | char c; // 1 byte 9 | } BadStruct; // Actual size: 12 bytes due to padding 10 | 11 | // Well aligned structure 12 | typedef struct { 13 | int32_t b; // 4 bytes 14 | char a; // 1 byte 15 | char c; // 1 byte 16 | // 2 bytes padding 17 | } GoodStruct; // Actual size: 8 bytes 18 | 19 | int main() { 20 | printf("Size of BadStruct: %zu\n", sizeof(BadStruct)); 21 | printf("Size of GoodStruct: %zu\n", sizeof(GoodStruct)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /playingAround/fixedTypes/type: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/playingAround/fixedTypes/type -------------------------------------------------------------------------------- /playingAround/fixedTypes/typeAware.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct { 7 | uint8_t age; 8 | uint32_t id; 9 | uint16_t year; 10 | } Person; 11 | 12 | void print_memory_layout(void* ptr, size_t size) { 13 | unsigned char* bytes = (unsigned char*)ptr; 14 | printf("Memory layout (hex): "); 15 | for (size_t i = 0; i < size; i++) { 16 | printf("%02x ", bytes[i]); 17 | } 18 | printf("\n"); 19 | } 20 | 21 | int main() { 22 | Person person = {25, 12345678, 2024}; 23 | 24 | printf("Size of Person struct: %zu bytes\n", sizeof(Person)); 25 | printf("Offset of age: %zu\n", offsetof(Person, age)); 26 | printf("Offset of id: %zu\n", offsetof(Person, id)); 27 | printf("Offset of year: %zu\n", offsetof(Person, year)); 28 | 29 | print_memory_layout(&person, sizeof(Person)); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /playingAround/inputBuffering/basicRing.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define BUFFER_SIZE 256 // Must be power of 2 for efficient wrapping 6 | 7 | typedef struct { 8 | uint8_t data[BUFFER_SIZE]; 9 | volatile uint8_t write_ptr; // Volatile for interrupt safety 10 | volatile uint8_t read_ptr; 11 | } RingBuffer; 12 | 13 | void ring_buffer_init(RingBuffer* buffer) { 14 | buffer->write_ptr = 0; 15 | buffer->read_ptr = 0; 16 | } 17 | 18 | bool ring_buffer_write(RingBuffer* buffer, uint8_t data) { 19 | uint8_t next_write = (buffer->write_ptr + 1) & (BUFFER_SIZE - 1); 20 | 21 | if (next_write == buffer->read_ptr) { 22 | return false; // Buffer full 23 | } 24 | 25 | buffer->data[buffer->write_ptr] = data; 26 | buffer->write_ptr = next_write; 27 | return true; 28 | } 29 | 30 | bool ring_buffer_read(RingBuffer* buffer, uint8_t* data) { 31 | if (buffer->read_ptr == buffer->write_ptr) { 32 | return false; // Buffer empty 33 | } 34 | 35 | *data = buffer->data[buffer->read_ptr]; 36 | buffer->read_ptr = (buffer->read_ptr + 1) & (BUFFER_SIZE - 1); 37 | return true; 38 | } 39 | 40 | uint8_t ring_buffer_size(RingBuffer* buffer) { 41 | return (buffer->write_ptr - buffer->read_ptr) & (BUFFER_SIZE - 1); 42 | } 43 | -------------------------------------------------------------------------------- /security/exploits/heap/heap_safe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/security/exploits/heap/heap_safe -------------------------------------------------------------------------------- /security/exploits/heap/heap_safe.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_NAME_LEN 128 6 | 7 | struct user_data_safe { 8 | int priority; 9 | char* name; 10 | size_t name_len; 11 | }; 12 | 13 | void process_user_safe(const char* user_input1, const char* user_input2) { 14 | struct user_data_safe* user1 = malloc(sizeof(struct user_data_safe)); 15 | struct user_data_safe* user2 = malloc(sizeof(struct user_data_safe)); 16 | 17 | if (!user1 || !user2) { 18 | printf("Memory allocation failed\n"); 19 | goto cleanup; 20 | } 21 | 22 | // Calculate required buffer sizes 23 | size_t len1 = strnlen(user_input1, MAX_NAME_LEN); 24 | size_t len2 = strnlen(user_input2, MAX_NAME_LEN); 25 | 26 | // Initialize user1 27 | user1->priority = 1; 28 | user1->name = malloc(len1 + 1); 29 | user1->name_len = len1; 30 | 31 | // Initialize user2 32 | user2->priority = 2; 33 | user2->name = malloc(len2 + 1); 34 | user2->name_len = len2; 35 | 36 | if (!user1->name || !user2->name) { 37 | printf("Memory allocation failed\n"); 38 | goto cleanup; 39 | } 40 | 41 | // Safe string operations 42 | strncpy(user1->name, user_input1, len1); 43 | user1->name[len1] = '\0'; 44 | 45 | strncpy(user2->name, user_input2, len2); 46 | user2->name[len2] = '\0'; 47 | 48 | printf("User1 priority: %d, name: %s\n", user1->priority, user1->name); 49 | printf("User2 priority: %d, name: %s\n", user2->priority, user2->name); 50 | 51 | cleanup: 52 | if (user1) { 53 | free(user1->name); 54 | free(user1); 55 | } 56 | if (user2) { 57 | free(user2->name); 58 | free(user2); 59 | } 60 | } 61 | 62 | int main(int argc, char** argv) { 63 | if (argc != 3) { 64 | printf("Usage: %s \n", argv[0]); 65 | return 1; 66 | } 67 | process_user_safe(argv[1], argv[2]); 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /security/exploits/heap/heap_vuln: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/security/exploits/heap/heap_vuln -------------------------------------------------------------------------------- /security/exploits/heap/heap_vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct user_data { 6 | int priority; 7 | char* name; 8 | }; 9 | 10 | void process_user(char* user_input1, char* user_input2) { 11 | struct user_data* user1 = malloc(sizeof(struct user_data)); 12 | struct user_data* user2 = malloc(sizeof(struct user_data)); 13 | 14 | if (!user1 || !user2) { 15 | printf("Memory allocation failed\n"); 16 | return; 17 | } 18 | 19 | // Initialize user1 20 | user1->priority = 1; 21 | user1->name = malloc(8); // Only allocate 8 bytes for name 22 | 23 | // Initialize user2 24 | user2->priority = 2; 25 | user2->name = malloc(8); 26 | 27 | // Vulnerable strcpy operations 28 | strcpy(user1->name, user_input1); // No bounds checking 29 | strcpy(user2->name, user_input2); // No bounds checking 30 | 31 | printf("User1 priority: %d, name: %s\n", user1->priority, user1->name); 32 | printf("User2 priority: %d, name: %s\n", user2->priority, user2->name); 33 | 34 | // Clean up 35 | free(user1->name); 36 | free(user2->name); 37 | free(user1); 38 | free(user2); 39 | } 40 | 41 | int main(int argc, char** argv) { 42 | if (argc != 3) { 43 | printf("Usage: %s \n", argv[0]); 44 | return 1; 45 | } 46 | process_user(argv[1], argv[2]); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /security/exploits/heap/input1.txt: -------------------------------------------------------------------------------- 1 | AAAAAAAABBBBCCCCDDDDEEEE 2 | -------------------------------------------------------------------------------- /security/exploits/heap/input2.txt: -------------------------------------------------------------------------------- 1 | AAAA 2 | -------------------------------------------------------------------------------- /security/exploits/memSeal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Conceptual implementation of memory sealing 6 | int mseal(void* addr, size_t length, unsigned long flags) { 7 | // This is a demonstration - actual implementation would be a syscall 8 | if (addr == NULL || length == 0) { 9 | errno = EINVAL; 10 | return -1; 11 | } 12 | 13 | // Mark page as sealed 14 | struct sealed_page { 15 | void* start; 16 | size_t len; 17 | int sealed; 18 | } page = { 19 | .start = addr, 20 | .len = length, 21 | .sealed = 1 22 | }; 23 | 24 | // In reality, this information would be stored in kernel structures 25 | printf("Page sealed: %p - %zu bytes\n", page.start, page.len); 26 | return 0; 27 | } 28 | 29 | int main() { 30 | // Allocate a page of memory 31 | void* page = mmap(NULL, 4096, 32 | PROT_READ | PROT_WRITE, 33 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 34 | 35 | if (page == MAP_FAILED) { 36 | perror("mmap failed"); 37 | return 1; 38 | } 39 | 40 | // Seal the page 41 | if (mseal(page, 4096, 0) == -1) { 42 | perror("mseal failed"); 43 | munmap(page, 4096); 44 | return 1; 45 | } 46 | 47 | // Attempting to modify permissions should now fail 48 | if (mprotect(page, 4096, PROT_EXEC) == -1) { 49 | printf("Expected failure: cannot modify sealed page\n"); 50 | } 51 | 52 | munmap(page, 4096); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /security/exploits/memory_analyzer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void analyze_memory(const char* input) { 5 | char buffer[20]; 6 | int control_value = 0xDEADBEEF; 7 | void* stack_ptr; 8 | 9 | // Get stack pointer - works on both 32 and 64 bit 10 | #ifdef __x86_64__ 11 | asm volatile("mov %%rsp, %0" : "=r"(stack_ptr)); 12 | #else 13 | asm volatile("mov %%esp, %0" : "=r"(stack_ptr)); 14 | #endif 15 | 16 | printf("Before overflow:\n"); 17 | printf("Buffer address: %p\n", (void*)buffer); 18 | printf("Control value address: %p\n", (void*)&control_value); 19 | printf("Stack pointer: %p\n", stack_ptr); 20 | 21 | // Print initial memory state 22 | printf("\nInitial buffer contents:"); 23 | for (int i = 0; i < 20; i++) { 24 | if (i % 8 == 0) printf("\n%p: ", (void*)((char*)buffer + i)); 25 | printf("%02x ", (unsigned char)buffer[i]); 26 | } 27 | 28 | printf("\n\nCopying input...\n"); 29 | strcpy(buffer, input); 30 | 31 | printf("\nAfter overflow:\n"); 32 | printf("Buffer contents:"); 33 | for (int i = 0; i < 20; i++) { 34 | if (i % 8 == 0) printf("\n%p: ", (void*)((char*)buffer + i)); 35 | printf("%02x ", (unsigned char)buffer[i]); 36 | } 37 | 38 | printf("\n\nControl value: 0x%08x\n", control_value); 39 | if (control_value != 0xDEADBEEF) { 40 | printf("WARNING: Control value has been modified!\n"); 41 | } 42 | } 43 | 44 | int main(int argc, char* argv[]) { 45 | if (argc != 2) { 46 | printf("Usage: %s \n", argv[0]); 47 | return 1; 48 | } 49 | analyze_memory(argv[1]); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /security/exploits/nonExec.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | // Allocate memory with read/write permissions 7 | void* buffer = mmap(NULL, 4096, 8 | PROT_READ | PROT_WRITE, 9 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 10 | 11 | if (buffer == MAP_FAILED) { 12 | perror("mmap failed"); 13 | return 1; 14 | } 15 | 16 | // Write some data 17 | strcpy(buffer, "Hello, World!"); 18 | 19 | // Try to make it executable 20 | if (mprotect(buffer, 4096, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) { 21 | perror("mprotect failed"); 22 | } 23 | 24 | // Clean up 25 | munmap(buffer, 4096); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /security/exploits/overflow_verifier.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | jmp_buf env; 7 | 8 | void handler(int sig) { 9 | printf("\n[!] Segmentation fault detected!\n"); 10 | longjmp(env, 1); 11 | } 12 | 13 | void verify_overflow(const char* input) { 14 | char buffer[20]; 15 | int canary = 0xDEADBEEF; 16 | void* return_addr; 17 | 18 | // Get return address - works on both 32 and 64 bit 19 | #ifdef __x86_64__ 20 | asm volatile( 21 | "mov 8(%%rbp), %0" 22 | : "=r"(return_addr) 23 | ); 24 | #else 25 | asm volatile( 26 | "mov 4(%%ebp), %0" 27 | : "=r"(return_addr) 28 | ); 29 | #endif 30 | 31 | printf("Initial state:\n"); 32 | printf("Buffer address: %p\n", (void*)buffer); 33 | printf("Canary address: %p\n", (void*)&canary); 34 | printf("Return address: %p\n", return_addr); 35 | printf("Canary value: 0x%08x\n", canary); 36 | 37 | if (!setjmp(env)) { 38 | printf("\nAttempting buffer operation...\n"); 39 | strcpy(buffer, input); 40 | 41 | printf("\nPost-operation state:\n"); 42 | printf("Canary value: 0x%08x\n", canary); 43 | printf("Buffer contents: "); 44 | for (int i = 0; i < 20; i++) { 45 | printf("%02x ", (unsigned char)buffer[i]); 46 | } 47 | printf("\n"); 48 | 49 | if (canary != 0xDEADBEEF) { 50 | printf("\n[!] Canary corrupted - Buffer overflow detected!\n"); 51 | } 52 | } 53 | } 54 | 55 | int main(int argc, char* argv[]) { 56 | signal(SIGSEGV, handler); 57 | if (argc != 2) { 58 | printf("Usage: %s \n", argv[0]); 59 | return 1; 60 | } 61 | verify_overflow(argv[1]); 62 | return 0; 63 | } -------------------------------------------------------------------------------- /security/exploits/register_tracker.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print_registers() { 5 | unsigned int eax, ebx, ecx, edx, esi, edi, ebp, esp; 6 | 7 | asm volatile( 8 | "movl %%eax, %0\n" 9 | "movl %%ebx, %1\n" 10 | "movl %%ecx, %2\n" 11 | "movl %%edx, %3\n" 12 | "movl %%esi, %4\n" 13 | "movl %%edi, %5\n" 14 | "movl %%ebp, %6\n" 15 | "movl %%esp, %7\n" 16 | : "=r"(eax), "=r"(ebx), "=r"(ecx), "=r"(edx), 17 | "=r"(esi), "=r"(edi), "=r"(ebp), "=r"(esp) 18 | ); 19 | 20 | printf("Register Values:\n"); 21 | printf("EAX: 0x%08x\n", eax); 22 | printf("EBX: 0x%08x\n", ebx); 23 | printf("ECX: 0x%08x\n", ecx); 24 | printf("EDX: 0x%08x\n", edx); 25 | printf("ESI: 0x%08x\n", esi); 26 | printf("EDI: 0x%08x\n", edi); 27 | printf("EBP: 0x%08x\n", ebp); 28 | printf("ESP: 0x%08x\n", esp); 29 | } 30 | 31 | void vulnerable_function(const char* input) { 32 | char buffer[20]; 33 | 34 | printf("\nBefore buffer operation:\n"); 35 | print_registers(); 36 | 37 | strcpy(buffer, input); 38 | 39 | printf("\nAfter buffer operation:\n"); 40 | print_registers(); 41 | } 42 | 43 | int main(int argc, char* argv[]) { 44 | if (argc != 2) { 45 | printf("Usage: %s \n", argv[0]); 46 | return 1; 47 | } 48 | 49 | vulnerable_function(argv[1]); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /security/exploits/stackCanaries.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Function to generate a random canary value 8 | static uint64_t generate_canary(void) { 9 | // Generate 64-bit random value 10 | uint64_t canary = 0; 11 | for (int i = 0; i < 8; i++) { 12 | canary = (canary << 8) | (rand() & 0xFF); 13 | } 14 | return canary; 15 | } 16 | 17 | // Initialize random seed at program start 18 | void __attribute__((constructor)) setup_canary() { 19 | srand((unsigned int)time(NULL)); 20 | } 21 | 22 | // Function to check if canary has been modified 23 | void check_canary(uint64_t canary, uint64_t original) { 24 | if (canary != original) { 25 | fprintf(stderr, "Stack smashing detected! Program terminated.\n"); 26 | fprintf(stderr, "Expected canary: 0x%lx\n", original); 27 | fprintf(stderr, "Found canary: 0x%lx\n", canary); 28 | exit(EXIT_FAILURE); 29 | } 30 | } 31 | 32 | void protected_function(const char* input) { 33 | if (input == NULL) { 34 | fprintf(stderr, "Invalid input provided\n"); 35 | return; 36 | } 37 | 38 | // Generate and store canary value 39 | uint64_t canary = generate_canary(); 40 | 41 | // Buffer for user input 42 | char buffer[32]; 43 | 44 | // Store canary after buffer 45 | uint64_t *canary_location = (uint64_t*)(buffer + sizeof(buffer)); 46 | *canary_location = canary; 47 | 48 | // Copy input - intentionally vulnerable for demonstration 49 | // Note: In real code, you should NEVER use strcpy without bounds checking 50 | printf("Copying input: %s\n", input); 51 | strcpy(buffer, input); 52 | 53 | // Verify canary hasn't been modified 54 | check_canary(*canary_location, canary); 55 | 56 | printf("Buffer contents: %s\n", buffer); 57 | } 58 | 59 | int main(int argc, char** argv) { 60 | if (argc != 2) { 61 | printf("Usage: %s \n", argv[0]); 62 | printf("Example:\n"); 63 | printf(" Safe: %s \"Hello World\"\n", argv[0]); 64 | printf(" Unsafe: %s \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n", argv[0]); 65 | return EXIT_FAILURE; 66 | } 67 | 68 | printf("Running with input of length: %zu\n", strlen(argv[1])); 69 | protected_function(argv[1]); 70 | printf("Function completed successfully!\n"); 71 | 72 | return EXIT_SUCCESS; 73 | } 74 | -------------------------------------------------------------------------------- /security/exploits/stack_monitor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print_stack_frame(void* stack_start, int frame_size) { 5 | unsigned char* ptr = (unsigned char*)stack_start; 6 | printf("\nStack Frame Contents:\n"); 7 | for (int i = 0; i < frame_size; i += 16) { 8 | printf("%p: ", (void*)(ptr + i)); 9 | // Print hex values 10 | for (int j = 0; j < 16 && (i + j) < frame_size; j++) { 11 | printf("%02x ", ptr[i + j]); 12 | } 13 | // Print ASCII representation 14 | printf(" |"); 15 | for (int j = 0; j < 16 && (i + j) < frame_size; j++) { 16 | char c = ptr[i + j]; 17 | printf("%c", (c >= 32 && c <= 126) ? c : '.'); 18 | } 19 | printf("|\n"); 20 | } 21 | } 22 | 23 | void monitor_stack(const char* input) { 24 | char buffer[20]; 25 | void* stack_ptr; 26 | void* base_ptr; 27 | 28 | // Get stack and base pointers - works on both 32 and 64 bit 29 | #ifdef __x86_64__ 30 | asm volatile( 31 | "mov %%rsp, %0\n" 32 | "mov %%rbp, %1\n" 33 | : "=r"(stack_ptr), "=r"(base_ptr) 34 | ); 35 | #else 36 | asm volatile( 37 | "mov %%esp, %0\n" 38 | "mov %%ebp, %1\n" 39 | : "=r"(stack_ptr), "=r"(base_ptr) 40 | ); 41 | #endif 42 | 43 | printf("Stack Pointer: %p\n", stack_ptr); 44 | printf("Base Pointer: %p\n", base_ptr); 45 | printf("Buffer Address: %p\n", (void*)buffer); 46 | 47 | // Print initial stack state 48 | printf("\nBefore strcpy:"); 49 | print_stack_frame(stack_ptr, (char*)base_ptr - (char*)stack_ptr + 16); 50 | 51 | strcpy(buffer, input); 52 | 53 | // Print stack after overflow 54 | printf("\nAfter strcpy:"); 55 | print_stack_frame(stack_ptr, (char*)base_ptr - (char*)stack_ptr + 16); 56 | } 57 | 58 | int main(int argc, char* argv[]) { 59 | if (argc != 2) { 60 | printf("Usage: %s \n", argv[0]); 61 | return 1; 62 | } 63 | monitor_stack(argv[1]); 64 | return 0; 65 | } -------------------------------------------------------------------------------- /security/exploits/vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void vulnerable_function(const char* input) { 6 | char buffer[20]; 7 | int important_value = 100; 8 | 9 | // Vulnerable copy operation 10 | strcpy(buffer, input); 11 | 12 | printf("Important value: %d\n", important_value); 13 | } 14 | 15 | int main(int argc, char* argv[]) { 16 | if (argc != 2) { 17 | printf("Usage: %s \n", argv[0]); 18 | return 1; 19 | } 20 | 21 | vulnerable_function(argv[1]); 22 | printf("Program completed normally\n"); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /security/exploits/vulnerable.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void vulnerable_function(char* input) { 5 | char buffer[32]; 6 | // Unsafe function that doesn't check buffer bounds 7 | strcpy(buffer, input); 8 | printf("Buffer contains: %s\n", buffer); 9 | } 10 | 11 | int main(int argc, char** argv) { 12 | if (argc != 2) { 13 | printf("Usage: %s \n", argv[0]); 14 | return 1; 15 | } 16 | 17 | vulnerable_function(argv[1]); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /security/protection/aslr_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void print_addresses() { 7 | void* stack_var; 8 | void* heap_var = malloc(1); 9 | extern void* __libc_start_main; 10 | 11 | printf("Stack variable: %p\n", (void*)&stack_var); 12 | printf("Heap variable: %p\n", heap_var); 13 | printf("Libc function: %p\n", &__libc_start_main); 14 | printf("Main function: %p\n", (void*)&print_addresses); 15 | 16 | free(heap_var); 17 | } 18 | 19 | int main() { 20 | printf("Process ID: %d\n\n", getpid()); 21 | 22 | for (int i = 0; i < 3; i++) { 23 | printf("Run %d:\n", i + 1); 24 | print_addresses(); 25 | printf("\n"); 26 | sleep(1); 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /security/protection/canary_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // Custom stack canary implementation 7 | typedef struct { 8 | char buffer[20]; 9 | unsigned int canary; 10 | void (*function_ptr)(void); 11 | } protected_buffer; 12 | 13 | // Generate random canary value 14 | unsigned int generate_canary() { 15 | static int initialized = 0; 16 | if (!initialized) { 17 | srand(time(NULL)); 18 | initialized = 1; 19 | } 20 | return rand() ^ 0xDEADBEEF; 21 | } 22 | 23 | // Verify canary value 24 | int verify_canary(unsigned int canary, unsigned int expected) { 25 | if (canary != expected) { 26 | printf("[!] Stack corruption detected! Expected: 0x%08x, Found: 0x%08x\n", 27 | expected, canary); 28 | exit(1); 29 | } 30 | return 1; 31 | } 32 | 33 | void safe_function() { 34 | protected_buffer buf; 35 | unsigned int canary_value = generate_canary(); 36 | 37 | // Initialize buffer and set canary 38 | memset(buf.buffer, 0, sizeof(buf.buffer)); 39 | buf.canary = canary_value; 40 | buf.function_ptr = safe_function; 41 | 42 | // Get user input 43 | printf("Enter string: "); 44 | fgets(buf.buffer, sizeof(buf.buffer), stdin); 45 | 46 | // Verify canary before using function pointer 47 | verify_canary(buf.canary, canary_value); 48 | 49 | printf("Buffer contents: %s\n", buf.buffer); 50 | } 51 | 52 | int main() { 53 | safe_function(); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /security/protection/heapASLR.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | void allocate_and_print(int count) { 5 | for (int i = 0; i < count; i++) { 6 | int *ptr = (int*)malloc(sizeof(int)); 7 | printf("Heap allocation %d: %p\n", i + 1, (void*)ptr); 8 | free(ptr); 9 | } 10 | } 11 | 12 | int main() { 13 | printf("Running with PID: %d\n", getpid()); 14 | allocate_and_print(5); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /security/protection/heapASLR.s: -------------------------------------------------------------------------------- 1 | .file "heapASLR.c" 2 | .text 3 | .section .rodata 4 | .LC0: 5 | .string "Heap allocation %d: %p\n" 6 | .text 7 | .globl allocate_and_print 8 | .type allocate_and_print, @function 9 | allocate_and_print: 10 | .LFB6: 11 | .cfi_startproc 12 | endbr64 13 | pushq %rbp 14 | .cfi_def_cfa_offset 16 15 | .cfi_offset 6, -16 16 | movq %rsp, %rbp 17 | .cfi_def_cfa_register 6 18 | subq $32, %rsp 19 | movl %edi, -20(%rbp) 20 | movl $0, -12(%rbp) 21 | jmp .L2 22 | .L3: 23 | movl $4, %edi 24 | call malloc@PLT 25 | movq %rax, -8(%rbp) 26 | movl -12(%rbp), %eax 27 | leal 1(%rax), %ecx 28 | movq -8(%rbp), %rax 29 | movq %rax, %rdx 30 | movl %ecx, %esi 31 | leaq .LC0(%rip), %rax 32 | movq %rax, %rdi 33 | movl $0, %eax 34 | call printf@PLT 35 | movq -8(%rbp), %rax 36 | movq %rax, %rdi 37 | call free@PLT 38 | addl $1, -12(%rbp) 39 | .L2: 40 | movl -12(%rbp), %eax 41 | cmpl -20(%rbp), %eax 42 | jl .L3 43 | nop 44 | nop 45 | leave 46 | .cfi_def_cfa 7, 8 47 | ret 48 | .cfi_endproc 49 | .LFE6: 50 | .size allocate_and_print, .-allocate_and_print 51 | .section .rodata 52 | .LC1: 53 | .string "Running with PID: %d\n" 54 | .text 55 | .globl main 56 | .type main, @function 57 | main: 58 | .LFB7: 59 | .cfi_startproc 60 | endbr64 61 | pushq %rbp 62 | .cfi_def_cfa_offset 16 63 | .cfi_offset 6, -16 64 | movq %rsp, %rbp 65 | .cfi_def_cfa_register 6 66 | call getpid@PLT 67 | movl %eax, %esi 68 | leaq .LC1(%rip), %rax 69 | movq %rax, %rdi 70 | movl $0, %eax 71 | call printf@PLT 72 | movl $5, %edi 73 | call allocate_and_print 74 | movl $0, %eax 75 | popq %rbp 76 | .cfi_def_cfa 7, 8 77 | ret 78 | .cfi_endproc 79 | .LFE7: 80 | .size main, .-main 81 | .ident "GCC: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0" 82 | .section .note.GNU-stack,"",@progbits 83 | .section .note.gnu.property,"a" 84 | .align 8 85 | .long 1f - 0f 86 | .long 4f - 1f 87 | .long 5 88 | 0: 89 | .string "GNU" 90 | 1: 91 | .align 8 92 | .long 0xc0000002 93 | .long 3f - 2f 94 | 2: 95 | .long 0x3 96 | 3: 97 | .align 8 98 | 4: 99 | -------------------------------------------------------------------------------- /security/protection/nx_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // Function to demonstrate stack execution attempt 7 | void test_stack_execution() { 8 | // Array to hold machine code (NOP sled followed by simple exit) 9 | unsigned char code[] = { 10 | 0x90, 0x90, 0x90, 0x90, // NOP sled 11 | 0xb8, 0x01, 0x00, 0x00, 0x00, // mov eax, 1 12 | 0xbb, 0x00, 0x00, 0x00, 0x00, // mov ebx, 0 13 | 0xcd, 0x80 // int 0x80 14 | }; 15 | 16 | void (*func)() = (void(*)())code; 17 | 18 | printf("Attempting to execute code on stack at address: %p\n", (void*)code); 19 | func(); // This should fail with NX enabled 20 | } 21 | 22 | // Function to test executable heap 23 | void test_executable_heap() { 24 | // Allocate executable memory 25 | void* executable_memory = mmap(NULL, 4096, 26 | PROT_READ | PROT_WRITE | PROT_EXEC, 27 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 28 | 29 | if (executable_memory == MAP_FAILED) { 30 | perror("mmap failed"); 31 | return; 32 | } 33 | 34 | // Copy shellcode to executable memory 35 | unsigned char code[] = { 36 | 0xb8, 0x01, 0x00, 0x00, 0x00, // mov eax, 1 37 | 0xbb, 0x00, 0x00, 0x00, 0x00, // mov ebx, 0 38 | 0xcd, 0x80 // int 0x80 39 | }; 40 | 41 | memcpy(executable_memory, code, sizeof(code)); 42 | 43 | void (*func)() = (void(*)())executable_memory; 44 | printf("Executing code in allocated memory at address: %p\n", executable_memory); 45 | func(); 46 | 47 | munmap(executable_memory, 4096); 48 | } 49 | 50 | int main() { 51 | printf("Testing stack execution protection:\n"); 52 | printf("==================================\n\n"); 53 | 54 | // Get page size 55 | long page_size = sysconf(_SC_PAGESIZE); 56 | printf("System page size: %ld bytes\n\n", page_size); 57 | 58 | // Print memory protection settings 59 | printf("Memory Protection Settings:\n"); 60 | FILE* maps = fopen("/proc/self/maps", "r"); 61 | if (maps) { 62 | char line[256]; 63 | while (fgets(line, sizeof(line), maps)) { 64 | printf("%s", line); 65 | } 66 | fclose(maps); 67 | } 68 | 69 | printf("\nAttempting stack execution...\n"); 70 | test_stack_execution(); 71 | 72 | printf("\nAttempting execution in allocated memory...\n"); 73 | test_executable_heap(); 74 | 75 | return 0; 76 | } -------------------------------------------------------------------------------- /security/protection/protection_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | jmp_buf env; 10 | 11 | void signal_handler(int sig) { 12 | printf("Caught signal %d\n", sig); 13 | longjmp(env, 1); 14 | } 15 | 16 | void test_protections() { 17 | // Test stack canary 18 | char buffer[16]; 19 | printf("Testing stack canary:\n"); 20 | printf("Buffer address: %p\n", (void*)buffer); 21 | 22 | // Test ASLR 23 | void* heap_ptr = malloc(16); 24 | printf("\nTesting ASLR:\n"); 25 | printf("Heap allocation: %p\n", heap_ptr); 26 | printf("Function address: %p\n", (void*)&test_protections); 27 | 28 | // Test NX 29 | printf("\nTesting NX protection:\n"); 30 | unsigned char shellcode[] = { 31 | 0x90, 0x90, 0x90, 0x90, // NOP sled 32 | 0xc3 // ret 33 | }; 34 | 35 | if (!setjmp(env)) { 36 | void (*func)() = (void(*)())shellcode; 37 | func(); 38 | printf("Stack execution succeeded (NX might be disabled)\n"); 39 | } else { 40 | printf("Stack execution failed (NX is working)\n"); 41 | } 42 | 43 | free(heap_ptr); 44 | } 45 | 46 | int main() { 47 | signal(SIGSEGV, signal_handler); 48 | 49 | printf("Protection Mechanism Test\n"); 50 | printf("========================\n\n"); 51 | 52 | // Print compilation flags 53 | printf("Compilation information:\n"); 54 | #ifdef __SSP__ 55 | printf("Stack protector: Enabled\n"); 56 | #else 57 | printf("Stack protector: Disabled\n"); 58 | #endif 59 | 60 | #ifdef __PIE__ 61 | printf("Position Independent Executable: Yes\n"); 62 | #else 63 | printf("Position Independent Executable: No\n"); 64 | #endif 65 | 66 | // Print ASLR status 67 | FILE* aslr_status = fopen("/proc/sys/kernel/randomize_va_space", "r"); 68 | if (aslr_status) { 69 | char status; 70 | fscanf(aslr_status, "%c", &status); 71 | printf("ASLR Status: %c (0=disabled, 1=partial, 2=full)\n", status); 72 | fclose(aslr_status); 73 | } 74 | 75 | printf("\nRunning protection tests:\n"); 76 | printf("=========================\n"); 77 | 78 | for (int i = 0; i < 3; i++) { 79 | printf("\nIteration %d:\n", i + 1); 80 | test_protections(); 81 | sleep(1); 82 | } 83 | 84 | return 0; 85 | } -------------------------------------------------------------------------------- /unix/decode.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct { 5 | uint8_t has_rex; 6 | uint8_t rex_w; 7 | uint8_t rex_r; 8 | uint8_t rex_x; 9 | uint8_t rex_b; 10 | uint8_t modrm; 11 | uint8_t sib; 12 | uint8_t opcode; 13 | } x86_instruction; 14 | 15 | void decode_instruction(uint8_t *bytes, size_t length, x86_instruction *inst) { 16 | size_t index = 0; 17 | 18 | // Check for REX prefix 19 | if ((bytes[index] & 0xF0) == 0x40) { 20 | inst->has_rex = 1; 21 | inst->rex_w = (bytes[index] & 0x08) >> 3; 22 | inst->rex_r = (bytes[index] & 0x04) >> 2; 23 | inst->rex_x = (bytes[index] & 0x02) >> 1; 24 | inst->rex_b = bytes[index] & 0x01; 25 | index++; 26 | } 27 | 28 | // Get opcode 29 | inst->opcode = bytes[index++]; 30 | 31 | // Check if instruction has ModRM byte 32 | if (index < length) { 33 | inst->modrm = bytes[index++]; 34 | 35 | // Check if SIB byte is present 36 | uint8_t mod = (inst->modrm >> 6) & 0x03; 37 | uint8_t rm = inst->modrm & 0x07; 38 | if (mod != 0x03 && rm == 0x04) { 39 | inst->sib = bytes[index++]; 40 | } 41 | } 42 | } 43 | 44 | int main() { 45 | // Example instruction bytes (MOV RAX, RCX with REX prefix) 46 | uint8_t instruction[] = { 0x48, 0x89, 0xC8 }; 47 | x86_instruction decoded_inst = {0}; 48 | 49 | decode_instruction(instruction, sizeof(instruction), &decoded_inst); 50 | 51 | printf("REX.W: %d\n", decoded_inst.rex_w); 52 | printf("REX.R: %d\n", decoded_inst.rex_r); 53 | printf("REX.X: %d\n", decoded_inst.rex_x); 54 | printf("REX.B: %d\n", decoded_inst.rex_b); 55 | printf("Opcode: 0x%02X\n", decoded_inst.opcode); 56 | printf("ModRM: 0x%02X\n", decoded_inst.modrm); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /unix/processor_sim: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/unix/processor_sim -------------------------------------------------------------------------------- /unix/zero_copy_server/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -Wall -O2 3 | LDFLAGS = -luring 4 | 5 | TARGET = zero_copy_server 6 | SRCS = main.c zero_copy_server.c 7 | OBJS = $(SRCS:.c=.o) 8 | 9 | $(TARGET): $(OBJS) 10 | $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS) 11 | 12 | %.o: %.c 13 | $(CC) $(CFLAGS) -c $< -o $@ 14 | 15 | clean: 16 | rm -f $(TARGET) $(OBJS) -------------------------------------------------------------------------------- /unix/zero_copy_server/main.c: -------------------------------------------------------------------------------- 1 | #include "zero_copy_server.h" 2 | 3 | int main() { 4 | struct io_uring ring; 5 | struct io_uring_cqe *cqe; 6 | struct conn_info *conn_table; 7 | int server_socket; 8 | 9 | conn_table = init_conn_table(); 10 | 11 | setup_io_uring(&ring); 12 | 13 | server_socket = setup_listening_socket(SERVER_PORT); 14 | printf("Server listening on port %d\n", SERVER_PORT); 15 | 16 | add_accept_request(&ring, server_socket, conn_table); 17 | 18 | while (1) { 19 | int ret = io_uring_submit_and_wait(&ring, 1); 20 | if (ret < 0) { 21 | fatal_error("io_uring_submit_and_wait"); 22 | } 23 | 24 | unsigned head; 25 | unsigned completed = 0; 26 | io_uring_for_each_cqe(&ring, head, cqe) { 27 | handle_completion(&ring, cqe, conn_table); 28 | completed++; 29 | } 30 | 31 | io_uring_cq_advance(&ring, completed); 32 | } 33 | 34 | // Cleanup 35 | for (int i = 0; i < MAX_CONNECTIONS; i++) { 36 | cleanup_conn(&conn_table[i]); 37 | } 38 | free(conn_table); 39 | io_uring_queue_exit(&ring); 40 | close(server_socket); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /unix/zero_copy_server/zero_copy_server: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/unix/zero_copy_server/zero_copy_server -------------------------------------------------------------------------------- /unix/zero_copy_server/zero_copy_server.h: -------------------------------------------------------------------------------- 1 | #ifndef ZERO_COPY_SERVER_H 2 | #define ZERO_COPY_SERVER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #define QUEUE_DEPTH 256 17 | #define BLOCK_SZ 4096 18 | #define READ_SZ 4096 // Reduced buffer size for better handling 19 | #define SERVER_PORT 8000 20 | #define MAX_CONNECTIONS 1024 21 | 22 | enum { 23 | EVENT_TYPE_ACCEPT = 0, 24 | EVENT_TYPE_READ, 25 | EVENT_TYPE_WRITE 26 | }; 27 | 28 | struct conn_info { 29 | int fd; 30 | bool in_use; 31 | void *buf; 32 | size_t buf_size; 33 | }; 34 | 35 | struct io_data { 36 | int event_type; 37 | int fd; 38 | struct iovec iov; 39 | struct conn_info *conn; 40 | }; 41 | 42 | void fatal_error(const char *syscall); 43 | void setup_io_uring(struct io_uring *ring); 44 | int setup_listening_socket(int port); 45 | void add_accept_request(struct io_uring *ring, int server_socket, struct conn_info *conn_table); 46 | void add_read_request(struct io_uring *ring, struct conn_info *conn); 47 | void handle_completion(struct io_uring *ring, struct io_uring_cqe *cqe, struct conn_info *conn_table); 48 | struct conn_info *init_conn_table(void); 49 | void cleanup_conn(struct conn_info *conn); 50 | 51 | #endif -------------------------------------------------------------------------------- /utils/matrixMul/matrixOpt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/utils/matrixMul/matrixOpt -------------------------------------------------------------------------------- /utils/matrixMul/matrix_baseline.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import time 3 | 4 | def matrix_multiply(A, B): 5 | n = len(A) 6 | C = [[0 for _ in range(n)] for _ in range(n)] 7 | 8 | start_time = time.time() 9 | 10 | # Basic triple loop multiplication 11 | for i in range(n): 12 | for j in range(n): 13 | for k in range(n): 14 | C[i][j] += A[i][k] * B[k][j] 15 | 16 | end_time = time.time() 17 | print(f"Time taken: {end_time - start_time:.4f} seconds") 18 | return C 19 | 20 | # Generate random matrices 21 | n = 1024 22 | A = [[np.random.random() for _ in range(n)] for _ in range(n)] 23 | B = [[np.random.random() for _ in range(n)] for _ in range(n)] 24 | 25 | # Run multiplication 26 | result = matrix_multiply(A, B) 27 | -------------------------------------------------------------------------------- /utils/matrixMul/matrix_basic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/utils/matrixMul/matrix_basic -------------------------------------------------------------------------------- /utils/matrixMul/matrix_basic.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define N 1024 6 | 7 | double** create_matrix() { 8 | double** matrix = (double**)malloc(N * sizeof(double*)); 9 | for (int i = 0; i < N; i++) { 10 | matrix[i] = (double*)malloc(N * sizeof(double)); 11 | for (int j = 0; j < N; j++) { 12 | matrix[i][j] = (double)rand() / RAND_MAX; 13 | } 14 | } 15 | return matrix; 16 | } 17 | 18 | void free_matrix(double** matrix) { 19 | for (int i = 0; i < N; i++) { 20 | free(matrix[i]); 21 | } 22 | free(matrix); 23 | } 24 | 25 | void matrix_multiply(double** A, double** B, double** C) { 26 | clock_t start = clock(); 27 | 28 | for (int i = 0; i < N; i++) { 29 | for (int j = 0; j < N; j++) { 30 | C[i][j] = 0; 31 | for (int k = 0; k < N; k++) { 32 | C[i][j] += A[i][k] * B[k][j]; 33 | } 34 | } 35 | } 36 | 37 | clock_t end = clock(); 38 | double time_spent = (double)(end - start) / CLOCKS_PER_SEC; 39 | printf("Time taken: %.4f seconds\n", time_spent); 40 | } 41 | 42 | int main() { 43 | srand(time(NULL)); 44 | 45 | double** A = create_matrix(); 46 | double** B = create_matrix(); 47 | double** C = create_matrix(); 48 | 49 | printf("Starting basic matrix multiplication...\n"); 50 | matrix_multiply(A, B, C); 51 | 52 | free_matrix(A); 53 | free_matrix(B); 54 | free_matrix(C); 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /utils/matrixMul/matrix_cache: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/utils/matrixMul/matrix_cache -------------------------------------------------------------------------------- /utils/matrixMul/matrix_cache.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define N 1024 6 | #define BLOCK_SIZE 32 // Adjust based on your L1 cache size 7 | 8 | // Function declarations 9 | static inline int min(int a, int b) { 10 | return (a < b) ? a : b; 11 | } 12 | 13 | double** create_matrix() { 14 | double** matrix = (double**)malloc(N * sizeof(double*)); 15 | if (matrix == NULL) { 16 | fprintf(stderr, "Memory allocation failed!\n"); 17 | exit(1); 18 | } 19 | 20 | for (int i = 0; i < N; i++) { 21 | matrix[i] = (double*)malloc(N * sizeof(double)); 22 | if (matrix[i] == NULL) { 23 | fprintf(stderr, "Memory allocation failed!\n"); 24 | exit(1); 25 | } 26 | for (int j = 0; j < N; j++) { 27 | matrix[i][j] = (double)rand() / RAND_MAX; 28 | } 29 | } 30 | return matrix; 31 | } 32 | 33 | void free_matrix(double** matrix) { 34 | for (int i = 0; i < N; i++) { 35 | free(matrix[i]); 36 | } 37 | free(matrix); 38 | } 39 | 40 | void matrix_multiply_blocked(double** A, double** B, double** C) { 41 | clock_t start = clock(); 42 | 43 | // Initialize C to zero 44 | for (int i = 0; i < N; i++) { 45 | for (int j = 0; j < N; j++) { 46 | C[i][j] = 0; 47 | } 48 | } 49 | 50 | // Blocked matrix multiplication 51 | for (int i = 0; i < N; i += BLOCK_SIZE) { 52 | for (int k = 0; k < N; k += BLOCK_SIZE) { 53 | for (int j = 0; j < N; j += BLOCK_SIZE) { 54 | // Multiply blocks 55 | for (int ii = i; ii < min(i + BLOCK_SIZE, N); ii++) { 56 | for (int kk = k; kk < min(k + BLOCK_SIZE, N); kk++) { 57 | for (int jj = j; jj < min(j + BLOCK_SIZE, N); jj++) { 58 | C[ii][jj] += A[ii][kk] * B[kk][jj]; 59 | } 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | clock_t end = clock(); 67 | double time_spent = (double)(end - start) / CLOCKS_PER_SEC; 68 | printf("Time taken: %.4f seconds\n", time_spent); 69 | } 70 | 71 | int main() { 72 | srand(time(NULL)); 73 | 74 | double** A = create_matrix(); 75 | double** B = create_matrix(); 76 | double** C = create_matrix(); 77 | 78 | printf("Starting blocked matrix multiplication...\n"); 79 | matrix_multiply_blocked(A, B, C); 80 | 81 | free_matrix(A); 82 | free_matrix(B); 83 | free_matrix(C); 84 | 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /utils/matrixMul/matrix_optimized: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/utils/matrixMul/matrix_optimized -------------------------------------------------------------------------------- /utils/myGirl.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohitmishra786/BitsAndBytes/83339052d198858c0b6c20bf248dae42119c6d61/utils/myGirl.gif --------------------------------------------------------------------------------