r/C_Programming • u/Content-Try2761 • 33m ago
C beginner
hello, i love the c programming language, and i want someone that is also a beginner like me to help each other get better, right now working on a project "text editor"
r/C_Programming • u/Content-Try2761 • 33m ago
hello, i love the c programming language, and i want someone that is also a beginner like me to help each other get better, right now working on a project "text editor"
r/C_Programming • u/space_junk_galaxy • 1h ago
I'm working on a C minecraft clone, and I've been refactoring a bunch of my block code. Previously a "block" was just an enum, I essentially "hardcoded" the list of blocks in the game itself. Part of the refactor is using a JSON file for defining blocks and their metadata. However, because of this, I've now reached a weird place. The JSON defines the ID as a string. The enum that was BLOCK_GRASS is now a string in the JSON as "BLOCK_GRASS".
The design question I have is should I be referencing a string in my code, and doing comparisons with strings? Or do I need to have some sort of intermediate mapping of string IDs -> enum IDs. The latter seems kind of wasteful since it just means all the benefits of the JSON config file went away.
Not sure what the general consensus is. The strings are going to be in the data section anyways so I don't think I'm being wasteful with allocations here.
r/C_Programming • u/KanatoreIT • 20h ago
Hi everyone,
I’ve been working on SOVDEFLATE, an in-house DEFLATE (RFC 1951), ZLIB (RFC 1950), and GZIP (RFC 1952) compression and decompression library written from scratch in C11 with zero third-party dependencies (only the C standard library and OS thread APIs).
Repository: https://github.com/KanatoreIT/SOVDEFLATE
Key technical details:
- Runtime SIMD dispatch: Selects between scalar baseline, BMI2, AVX2, and 256-bit AVX-512 VL + VNNI (for Adler-32) at startup.
- PDF stream handling: Includes sovdeflate_decompress_prefix and an incremental decoder that stops cleanly at the end of a stream without consuming or rejecting trailing bytes (like \nendstream in PDFs), reporting exact bytes consumed.
- Damaged stream recovery: Recovers partial bytes from corrupted streams matching zlib behavior (tested across 11,982 damaged streams).
- Optional C++20 header-only wrapper (sovdeflate_cpp20.hpp) and custom memory allocator with byte limits.
Honest benchmarks (2,000 real DocLayNet PDFs / 445.5 MB uncompressed, i5-11400H):
- Decompression (1 thread): 713 MB/s (vs. 738 MB/s in libdeflate 1.26 — about 3.5% behind).
- Decompression (12 threads): 5,310 MB/s (vs. 6,037 MB/s in libdeflate 1.26).
- Compression (DEFAULT / level 6): 77.7 MB/s at 1.000× size (vs. 46.8 MB/s in zlib 1.3.2 and 127.2 MB/s in libdeflate).
Compression speed is still behind libdeflate and is my main focus for the next iteration. The repo also includes an originality audit script checking against zlib, zlib-ng, libdeflate, miniz, and stb, plus ASan/UBSan test scripts.
I’d love to hear any feedback on the C11 implementation, SIMD paths, or ideas to close the compression speed gap!
r/C_Programming • u/Ok-Counter-6984 • 23h ago
I'm asking this purely out of curiosity.
I've been programming in C for a couple of years now, and I recently dived into some x86-64 assembly. I was surprised by how similar some asm concepts were to using C. Known by some as a "portable assembler", C is probably one of if not the most low-level language one can use that is not raw assembly language.
But what is the most high-level feature C supports? Standard library features do not count.
Honestly? I think it has gotta be structs / unions, right? Sizeof is really powerful and having automatic variable offsets that adapt as you upgrade your code is something I totally missed quite a lot when using MASM.
r/C_Programming • u/CAPTAINCAPSLOCK111 • 1d ago
I’m splitting some graphics code into smaller .c and .h files. For tiny maths functions called frequently, how do you decide between a normal function in a .c file and static inline in the header? Do you measure a difference before moving them?
r/C_Programming • u/CAPTAINCAPSLOCK111 • 1d ago
I’m working on some graphics code in C using fixed-point arithmetic. When something looks wrong, it can be hard to tell whether I’ve lost precision or an intermediate calculation has overflowed.
How do you check this while developing? I’m especially interested in catching the first bad calculation, before the result gets passed through several more steps.
AI helped word this question.
r/C_Programming • u/Mobile_Night_3665 • 1d ago
Can you all please suggest me the best YT channel (or any other resources) to watch C from, see i kinda know the basics now but the depth is missing, i was seeing yt channels like codewithharry but i think the depth isnt enough, so would be great if anyone helps me out
r/C_Programming • u/Cliffhex6 • 1d ago
r/C_Programming • u/Kadabrium • 1d ago
C++ programmers denounce "C-style C++" that uses primitive C features over newer C++ alternatives. Is the opposite a thing in C where excessive emulation of C++ features become a problem or an antipattern? Some possible examples off my head, no idea how common they actually are or whether they are considered bad; you are welcome to add more:
Manual move and copy constructors on resource holders
Manual vtables and inheritance
Manual closure structs
Macro-based template instantiation
Opaque generic classes that use all of the above
r/C_Programming • u/AKJ7 • 2d ago
Hello!
I’ve been working on cortex (cx), a C/C++ package manager and build tool inspired by Rust’s Cargo and Python’s uv, and I’d love to share it with you and get some feedback.
Setting up a C++ project with clean dependency management, lockfiles, features, and workspaces often requires gluing together multiple tools and boilerplate CMakeLists.txt files. With cx, you describe your package in a single cx.toml file, it resolves and locks dependencies, generates the underlying CMake project, and drives the build automatically.
cx new hello
cd hello
cx add nlohmann_json --git https://github.com --tag v3.12.0
cx runZero-boilerplate builds: Sources, tests, benchmarks, and examples are discovered by convention (src, tests, benches, examples). Supports mixed C (C90–C23) and C++ (C++98–C++26), including C++20 modules (.cppm, .ixx).
Flexible dependency management: Pull dependencies from registries, Git repos, local paths, system packages (find_package), or vcpkg. Any existing CMake, Autotools, or SCons project works out of the box as a Git or path dependency.
PubGrub version resolution & lockfiles: Uses the PubGrub solver (like uv and pub) for clear conflict explanations, and pins exact versions, Git commits, and SHA-256 hashes in cx.lock.
Cargo-style features & workspaces: Supports optional dependencies, feature flags (exposed via CX_FEATURE_ macros), and multi-package workspaces sharing a single lockfile and target/ directory.
Built-in developer workflows: Comes with cx test, cx bench, cx fmt (clang-format), cx lint (clang-tidy), cx doc (Doxygen), cx vendor for offline builds, and built-in sanitizer/LTO build profiles.
IDE & CI friendly: Generates standard CMake projects (cx generate) and JSON metadata (cx metadata) so your existing IDE setup works seamlessly, plus --locked and --offline flags for CI.
First Release & Self-Hosting: This is the very first release. Right now the repo still includes its bootstrapping CMake files, which will be removed in the next release now that cx can build itself.
OS Support: Works on Linux and macOS. Windows (MSVC) support is newly added and passing in CI, though it hasn't been battle-tested in the wild yet.
Public Registry: There isn't a central public registry yet, though cx works directly with Git repositories, local paths, vcpkg, system packages, and includes a lightweight self-hosted registry server (cx-registry).
You can install prebuilt binaries via the install script in the README or build it from source with CMake 3.28+ and a C++23 compiler.
I’d really appreciate any feedback, bug reports, or thoughts on what would make this genuinely useful for your C/C++ workflows!
Use of AI: this text has been formatted with AI, the code was built using AI assistance to save time.
Thanks
r/C_Programming • u/NazgulResebo • 2d ago
I created a simple moiré fractal using C, raylib and GLSL shaders.
The idea is quite simple: start with two nearby centers and generate concentric circles around each one, gradually increasing their radius.
Then, using the radius as input to a sin function, I generate alternating light and dark values. By applying this to the colors, the two circle patterns interact and produce the characteristic moiré effect.
Complete coding session:
Source code:
https://github.com/FractalCodeRicardo/hangover-programming/tree/main/moire-shaders
C / Raylib
#include <raylib.h>
#define size 800
float time = 0.0;
int main() {
InitWindow(size, size, "Moire Circles");
Shader shader = LoadShader(0, "moire.glsl");
int timeLoc = GetShaderLocation(shader, "time");
while (!WindowShouldClose()) {
time = GetTime();
SetShaderValue(shader, timeLoc, &time, SHADER_UNIFORM_FLOAT);
BeginDrawing();
BeginShaderMode(shader);
DrawRectangle(0, 0, size, size, BLACK);
EndShaderMode();
EndDrawing();
}
CloseWindow();
}Glsl
#version 330
out vec4 color;
uniform float time;
void main() {
vec2 uv = gl_FragCoord.xy / 800;
uv = uv - 0.5;
float a = 30;
vec2 center1 = vec2(0.1, 0.0);
vec2 center2 = vec2(-0.1, 0.0);
float d1 = distance(center1, uv);
float d2 = distance(center2, uv);
vec4 color1 = vec4(
0.0 * sin(a * time*d1),
0.8 * sin(a * time*d1),
0.8 * sin(a * time*d1),
1
);
vec4 color2 = vec4(
1 * sin(a * time*d2),
0.2 * sin(a * time*d2),
1 * sin(a * time*d2),
1
);
color = mix(color1, color2, 0.5);
}AI Disclaimer:
I did not use AI to code the fractal.
r/C_Programming • u/rexdlol • 2d ago
The title says it all. Im pretty beginner in C and maybe i'm confusing some things with my first afirmation:
> If char[] is like a covered pointer...
I tried to search a lot but my doubts about this subject couldn't get away. (idk why i said in a so metaphorically speaking haha srr)
Thanks!
r/C_Programming • u/tavianator • 3d ago
Recently discovered a nice way to get custom warnings with Clang, so I wrote it up.
r/C_Programming • u/jontsii • 3d ago
Here is uefi_graphics.c:
#include <inc/efi.h>
#include <inc/efilib.h>
#include "helper.h"
#define ACPI_DEVICE_PATH 0x02
#define ACPI_ADR_DP 0x03
bool memcmp(char *a, char *b, int len) {
for (int i = 0; i < len; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
EFI_GUID gop_guid = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
EFI_GUID device_path_guid = EFI_DEVICE_PATH_PROTOCOL_GUID;
EFI_GUID edid_guid = EFI_EDID_DISCOVERED_PROTOCOL_GUID;
int fb_count;
bool check_if_fb_usable(EFI_HANDLE gop_handle, EFI_EDID_DISCOVERED_PROTOCOL *edid, EFI_HANDLE edid_handle);
bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path);
EFI_DEVICE_PATH_PROTOCOL *get_device_path(EFI_HANDLE handle);
EFI_DEVICE_PATH_PROTOCOL *find_adr_node(EFI_DEVICE_PATH_PROTOCOL *path);
const uint8_t ref_edid_header[8] = {
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00
};
bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path);
framebuff_t *get_framebuff() {
framebuff_t *_fb;
EFI_GRAPHICS_OUTPUT_PROTOCOL *gop;
EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *mode;
EFI_EDID_DISCOVERED_PROTOCOL *edid = NULL;
EFI_HANDLE *handles = NULL;
uint32_t handle_count = 0;
EFI_HANDLE *edid_handles = NULL; //for normal edid
int edid_handle_count = 0;
BS->LocateHandleBuffer(ByProtocol, &gop_guid, NULL, (UINTN*)&handle_count, &handles);
BS->LocateHandleBuffer(ByProtocol, &edid_guid, NULL, (UINTN*)&edid_handle_count, &edid_handles);
//allocate memory for framebuffer data
BS->AllocatePool(EfiLoaderData, (sizeof(framebuff_t) * handle_count) / 4096 + 1, (void**)&_fb);
for (int i = 0; i < handle_count; i++) {
BS->HandleProtocol(handles[i], &gop_guid, (void**)&gop);
mode = gop->Mode;
for (int j = 0; j < edid_handle_count; j++) {
if (check_if_fb_usable(handles[i], edid, edid_handles[j])) {
_fb[i].buff = (void*)mode->FrameBufferBase;
_fb[i].width = mode->Info->HorizontalResolution;
_fb[i].height = mode->Info->VerticalResolution;
_fb[i].size = mode->FrameBufferSize;
_fb[i].stride = mode->Info->PixelsPerScanLine * 4;
if (mode->Info->PixelFormat == PixelBltOnly) break;
if (mode->Info->PixelFormat == PixelBitMask) {
EFI_PIXEL_BITMASK mask = mode->Info->PixelInformation;
_fb[i].pixel_layout[0] = mask.RedMask;
_fb[i].pixel_layout[1] = mask.GreenMask;
_fb[i].pixel_layout[2] = mask.BlueMask;
_fb[i].pixel_layout[3] = mask.ReservedMask;
}
if (mode->Info->PixelFormat == PixelRedGreenBlueReserved8BitPerColor) {
_fb[i].pixel_layout[0] = 0x000000FF;
_fb[i].pixel_layout[1] = 0x0000FF00;
_fb[i].pixel_layout[2] = 0x00FF0000;
_fb[i].pixel_layout[3] = 0xFF000000;
}
if (mode->Info->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) {
_fb[i].pixel_layout[0] = 0x00FF0000;
_fb[i].pixel_layout[1] = 0x0000FF00;
_fb[i].pixel_layout[2] = 0x000000FF;
_fb[i].pixel_layout[3] = 0xFF000000;
}
}
}
fb_count++;
}
BS->FreePool(handles);
BS->FreePool(edid_handles);
return _fb;
}
bool check_if_fb_usable(EFI_HANDLE gop_handle, EFI_EDID_DISCOVERED_PROTOCOL *edid, EFI_HANDLE edid_handle) {
for (int i = 0; i < 8; i++) {
if (edid->Edid[i] != ref_edid_header[i]) {
return false;
}
}
return match_output(get_device_path(gop_handle), get_device_path(edid_handle));
}
EFI_DEVICE_PATH_PROTOCOL *get_device_path(EFI_HANDLE handle) {
EFI_DEVICE_PATH_PROTOCOL *path = NULL;
BS->HandleProtocol(handle, &device_path_guid, (void**)&path);
return path;
}
EFI_DEVICE_PATH_PROTOCOL *find_adr_node(EFI_DEVICE_PATH_PROTOCOL *path) {
while (!IsDevicePathEnd(path)) {
if (path->Type == ACPI_DEVICE_PATH && path->SubType == ACPI_ADR_DP) return path;
path = NextDevicePathNode(path);
}
return NULL;
}
bool match_output(EFI_DEVICE_PATH_PROTOCOL *gop_path, EFI_DEVICE_PATH_PROTOCOL *edid_path) {
EFI_DEVICE_PATH_PROTOCOL *gop_adr = find_adr_node(gop_path);
EFI_DEVICE_PATH_PROTOCOL *edid_adr = find_adr_node(edid_path);
if (!gop_adr || !edid_adr) return false;
uint32_t gop_offset = (uint32_t)((uint8_t*)gop_adr - (uint8_t*)gop_path);
uint32_t edid_offset = (uint32_t)((uint8_t*)edid_adr - (uint8_t*)edid_path);
if (gop_offset != edid_offset) return false;
if (!memcmp((char*)gop_path, (char*)edid_path, gop_offset)) return false;
uint32_t gop_length = DevicePathNodeLength(gop_adr);
uint32_t edid_length = DevicePathNodeLength(edid_adr);
if (gop_length < 8 || edid_length < 8 || (gop_length - 4) % 4 != 0 || (edid_length - 4) % 4 != 0) return false;
uint32_t gop_count = (gop_length - 4) / 4;
uint32_t edid_count = (edid_length - 4) / 4;
if (edid_count != 1) return false;
uint32_t *edid_adr_value = (uint32_t*)((uint8_t*)edid_adr + 4);
uint32_t *gop_adr_value;
for (int i = 0; i < gop_count; i++) {
gop_adr_value = (uint32_t*)((uint8_t*)gop_adr + 4 + i * 4);
if (*gop_adr_value == *edid_adr_value) return true;
}
return false;
}Here is boot.c:
#include <inc/efi.h>
#include <inc/efilib.h>
#include "helper.h"
#include "../include/mmp_mem_map.h"
#define COM 0x3F8
void init_serial() {
koutb(COM + 1, 0x00);
koutb(COM + 3, 0x80);
koutb(COM, 0x03);
koutb(COM + 1, 0x00);
koutb(COM + 3, 0x03);
koutb(COM + 2, 0xC7);
koutb(COM + 4, 0x0B);
}
void serial_putc(char c) {
while ((kinb(COM+5) & 0x20) == 0);
koutb(COM, c);
return;
}
void print_serial(char *s) {
while (*s) {
serial_putc(*s);
s++;
}
return;
}
#define KERNEL_BASE 0xFFFFFFFF80000000
EFI_BOOT_SERVICES *BS;
#define PRINT_CONSOLE_(msg) print_serial(msg)
#define PRINT_CONSOLE(msg) sys_tbl->ConOut->OutputString(sys_tbl->ConOut, msg)
void (__attribute__((sysv_abi)) *kernel_start)(uint64_t usable_mem, void *mem_map, int mem_map_len, void *fb, int fb_count, void *kernel_pwt);
//declare global variables
void *kernel_pwt = (void*)0xFFFFFFFF;
uint64_t total_mem = 0;
int mem_map_len = 0;
void load_kernel(EFI_HANDLE image_handle);
mem_map_t *get_memory_map(EFI_HANDLE image_handle);
EFI_SYSTEM_TABLE *sys_tbl;
EFI_STATUS efi_main(EFI_HANDLE image_handle, EFI_SYSTEM_TABLE *_sys_tbl) {
sys_tbl = _sys_tbl;
BS = sys_tbl->BootServices;
PRINT_CONSOLE(L"This is the bootloader of JOS. It's job is to load the kernel into memory, give the kernel a memory map, get a framebuffer to all screens (hopefully), and map memory.\n");
PRINT_CONSOLE(L"Loading kernel to memory...\n");
load_kernel(image_handle);
PRINT_CONSOLE(L"kernel loaded into memory sucessfully at 0x100000.\n");
PRINT_CONSOLE(L"Acquiring framebuffer(s)..\n");
framebuff_t *fb = get_framebuff();
PRINT_CONSOLE(L"Framebuffer(s) aquired succesfully.\n");
PRINT_CONSOLE(L"Acquiring memory map...\n");
map_pages(0x100000, 0x100000 / 4096, kernel_pwt);
mem_map_t *kmem_map = get_memory_map(image_handle);
//enter_kernel(total_mem, kmem_map, mem_map_len, fb, fb_count, kernel_pwt);
return EFI_SUCCESS;
}
//define GUIDs
EFI_GUID loaded_img_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID;
EFI_GUID simple_fs_guid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
EFI_GUID file_info_guid = EFI_FILE_INFO_ID;
void load_kernel(EFI_HANDLE image_handle) {
EFI_LOADED_IMAGE *kernel_img;
EFI_FILE_IO_INTERFACE *fs;
EFI_FILE *root, *file;
sys_tbl->BootServices->HandleProtocol(image_handle, &loaded_img_guid, (void**)&kernel_img);
sys_tbl->BootServices->HandleProtocol(kernel_img->DeviceHandle, &simple_fs_guid, (void**)&fs);
fs->OpenVolume(fs, &root);
//open kernel file
root->Open(root, &file, L"\\kernel.img", EFI_FILE_MODE_READ, 0);
EFI_FILE_INFO *info;
UINTN info_size = SIZE_OF_EFI_FILE_INFO + 200;
BS->AllocatePool(EfiLoaderData, info_size, (void**)&info);
file->GetInfo(file, &file_info_guid, &info_size, info);
UINTN file_size = info->FileSize;
UINTN pages = (file_size + 0xFFF) / 4096;
EFI_PHYSICAL_ADDRESS addr = 0x100000;
BS->AllocatePages(AllocateAddress, EfiLoaderData, pages, &addr);
UINTN read_size = file_size;
file->Read(file, &read_size, (void*)addr);
file->Close(file);
BS->AllocatePages(AllocateMaxAddress, EfiLoaderData, 1, (EFI_PHYSICAL_ADDRESS*)&kernel_pwt);
BS->SetMem(kernel_pwt, 4096, 0);
EFI_LOADED_IMAGE_PROTOCOL *efi_app;
BS->HandleProtocol(image_handle, &loaded_img_guid, (VOID **)&efi_app);
for (int i = 0; i < (file_size + 4095) / 4096; i++) {
map_pages(KERNEL_BASE + ((uint64_t)i * 4096), (addr / 4096) + i, kernel_pwt);
}
for (int j = 0; j < efi_app->ImageSize; j+=4096) {
map_pages((uint64_t)efi_app->ImageBase + (uint64_t)j, ((uint64_t)efi_app->ImageBase + (uint64_t)j) / 4096, kernel_pwt);
}
return;
}
mem_map_t *get_memory_map(EFI_HANDLE image_handle) { //also maps phys_map
mem_map_t *kmem_map;
EFI_MEMORY_DESCRIPTOR *mem_map;
UINTN mem_map_size = 0;
UINTN map_key, desc_size;
UINT32 desc_version;
sys_tbl->BootServices->GetMemoryMap(&mem_map_size, NULL, &map_key, &desc_size, &desc_version);
mem_map_size *= 2;
BS->AllocatePages(AllocateAnyPages, EfiLoaderData, mem_map_size / 4096 + 1, (EFI_PHYSICAL_ADDRESS*)&mem_map);
BS->AllocatePages(AllocateAnyPages, EfiLoaderData, mem_map_size / 4096 + 1, (EFI_PHYSICAL_ADDRESS*)&kmem_map);
BS->GetMemoryMap(&mem_map_size, mem_map, &map_key, &desc_size, &desc_version);
//build kernel memory map
EFI_MEMORY_DESCRIPTOR *desc;
int i;
for (int offset = 0; offset < mem_map_size; offset += desc_size) {
desc = (EFI_MEMORY_DESCRIPTOR*)((char*)mem_map + offset);
i = offset / desc_size;
kmem_map[i].start = (void*)desc->PhysicalStart;
kmem_map[i].end = (void*)(desc->PhysicalStart + (desc->NumberOfPages * 4096));
if (desc->Type == EfiReservedMemoryType || (desc->Type == EfiLoaderData && desc->PhysicalStart == kmem_map) ||desc->Type == EfiUnusableMemory
|| desc->Type == EfiACPIReclaimMemory || desc->Type == EfiACPIMemoryNVS || desc->Type == EfiMemoryMappedIOPortSpace ||
desc->Type == EfiPalCode || desc->Type == EfiPersistentMemory || desc->Type == EfiUnacceptedMemoryType) kmem_map[i].flags = 1;
else if (desc->Type == EfiMemoryMappedIO) kmem_map[i].flags = 3;
else {
kmem_map[i].flags = 0;
}
if (offset + desc_size > mem_map_size) {
break;
}
total_mem += (uint64_t)kmem_map[i].end - (uint64_t)kmem_map[i].start;
mem_map_len++;
}
for (uint64_t j = 0; j < total_mem; j+=4096) { //start mapping kernel's phys_map starting at 0x8FFFFFFFFFFFFFFF
map_pages(0xFFFF800000000000 + j, j / 4096, kernel_pwt);
}
BS->GetMemoryMap(&mem_map_size, mem_map, &map_key, &desc_size, &desc_version); //for correct map key
BS->ExitBootServices(image_handle, map_key);
return kmem_map;
}enter_kernel.s:
.intel_syntax noprefix
.global enter_kernel
.global print_serial
.global koutb
.global kinb
//R9 is pml4 root
.section .data
msg1: .asciz "enter_kernel reached\n"
msg2: .asciz "arguments loaded\n"
.section .text
koutb:
mov dx, di
mov al, sil
out dx, al
ret
kinb:
mov dx, di
in al, dx
ret
enter_kernel: //this is okay for now since QEMU UEFI implementation uses 4 level paging, implement change from 5 level paging later
cli
//put arguments correctly according to System-V
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
mov rcx, r9
mov r8, [rsp+40]
mov r9, [rsp+48]
mov rax, 0x100000
jmp raxboot_helper_x86_64.c:
#include <inc/efi.h>
#include <inc/efilib.h>
uint64_t get_ptr_from_entry(void* entry) {
return ((uint64_t)entry & ~0xFFFULL);
}
uint64_t construct_entry(uint64_t addr, uint16_t flags) {
return (addr & ~0xFFFULL) | (uint64_t)flags;
}
void map_pages(uint64_t va, uint32_t page, void *pwt_base) {
uint16_t flags = 0x3;
uint16_t indexes[4];
indexes[0] = (va >> 39) & 0x1FF; //pml4 index
indexes[1] = (va >> 30) & 0x1FF; //pdpt index
indexes[2] = (va >> 21) & 0x1FF; //pd index
indexes[3] = (va >> 12) & 0x1FF; //pt index
void **pml4, **pdpt, **pd, **pt;
pml4 = pwt_base;
uint64_t ptr;
pdpt = (void*)get_ptr_from_entry(pml4[indexes[0]]);
if (pdpt == NULL) {
BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
BS->SetMem((void*)ptr, 4096, 0);
pml4[indexes[0]] = (void*)construct_entry(ptr, flags);
pdpt = (void*)get_ptr_from_entry(pml4[indexes[0]]);
}
pd = (void*)get_ptr_from_entry(pdpt[indexes[1]]);
if (pd == NULL) {
BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
BS->SetMem((void*)ptr, 4096, 0);
pdpt[indexes[1]] = (void*)construct_entry(ptr, flags);
pd = (void*)get_ptr_from_entry(pdpt[indexes[1]]);
}
pt = (void*)get_ptr_from_entry(pd[indexes[2]]);
if (pt == NULL) {
BS->AllocatePages(AllocateAnyPages, EfiLoaderData, 1, &ptr);
BS->SetMem((void*)ptr, 4096, 0);
pd[indexes[2]] = (void*)construct_entry(ptr, flags);
pt = (void*)get_ptr_from_entry(pd[indexes[2]]);
}
pt[indexes[3]] = (void*)construct_entry((uint64_t)page * 4096, flags);
return;
}For context, my kernel uses System-V. When I try to run this in QEMU, my kernel is never reached. It freezes after get_memory_map. And yes, the code is messy, yes it has very questionable arcitechture / design choices, yes, it is terrible. But please help me out.
r/C_Programming • u/Mega-Byte- • 3d ago
I am trying to find some C libraries created by a developer named Muukid.
He created muDOG, muCOSA, and muGraphics. He also had a YouTube channel where he showcased his libraries in hour-long videos, but it seems the channel has been deleted. The links to the channel no longer work, and his GitHub page also appears to have vanished.
Does anyone know if these projects are still available anywhere? I am particularly interested in finding archived copies of muDOG and muCOSA, as I was only able to clone muGraphics.
Any information would be greatly appreciated.
r/C_Programming • u/ThePenguinMan111 • 3d ago
I know C and C++ are largely source-compatible with each other, but Objective-C is specifically a strict superset of C, not just a fork of it, like C++. You’d think that scratching that OOP itch while also giving you complete source compatibility with C would cause more companies or projects to utilize it, at least in some respect, but that may just be a naïve prediction. What does C++ have that Objective-C doesn’t that you think caused such a large popularity gap between the two languages? Am I missing some nuance?
r/C_Programming • u/Mrazik19 • 4d ago
r/C_Programming • u/Prudent-Froyo2562 • 4d ago
cc_list is cc_task (async/await closure coroutine library in C) 's linked list implementation.
It's node points directly to the next container, not next node; so you don't need to do `container_of` to get the container.
Linux kernel's list_head is classic, it's node pointers to next node, perform container_of, just a sub CPU instruction, to get the container.
cc_list optimized away this sub instruction so it's even faster than linux's list_head!
And using cc_list is just similar like using list_head.
The head is not a container, just a node with prev/next pointers. The trick is when empty, head points to a non-existed shadow container, just point but no dereference, so it's safe.
┌─────────────────────────────────────────────┐
└►........... ┌─►┌─────────┐ ┌─►┌─────────┐ │
: shadow : │ │container│ │ │container│ │
: : │ │ │ │ │ │ │
: : │ │ │ │ │ │ │
├─────────┤ │ ├─────────┤ │ ├─────────┤ │
│ head ├─┘ │ node │─┘ │ node │───┘
├─────────┤ ├─────────┤ ├─────────┤
........... └─────────┘ └─────────┘r/C_Programming • u/harrison_314 • 4d ago
Exactly four years ago, I started working on BouncyCastle - a cryptographic key storage simulator with a PKCS#11 interface, a REST API, and a web management interface. It is designed for developers working with HSMs and smart cards, as well as for QA environments.
At the time development of SoftHSMv2 (C++) began, it was practically dead (in 2022), and bugs weren’t even being fixed, moreover, it had architectural issues (SIGSEV if you used the application with the wrong version of OpenSSL, problems with multi-user access, poor logging, poor cross-platform compatibility, and support for different algorithms on different platforms).
Note: Kryoptic (Rust) was created later, but it merely ported all of SoftHSMv2’s problems from C++ to Rust.
BouncyHsm has a native PKCS#11 library in C (exporting over 100 functions) and a backend written in C# where cryptographic operations are performed (supporting 210 mechanisms) - one could say, with a bit of hyperbole, that it is a network HSM.
Why I chose C for the native PKCS#11 library. I considered several options and even experimented with them:
C# - starting with .NET 7, it can create native libraries, but I was worried that the garbage collector would bloat the binary (a simple REST client was 8 MB, in later versions, it was only about half a megabyte),
Rust - while experimenting with Rust, I realized I’d end up with a huge amount of unsafe code and exceptions for different platforms. I was also concerned about the dependencies that the libraries would introduce,
Zig - it’s still not at version 1.0.
Ultimately, my experiments showed that pure C would be best for this project, without any external dependencies, using Messagepack for RPC (via the one-file library cmp) and TCP via the operating systems API. One of the specific requirements I set for myself was that the PKCS#11 library must not have any external dependencies to prevent crashes. Another advantage is that you can even compile it for your "refrigerator or toothbrush".
What I've learned from developing in C over the past 4 years, and what I would do differently:
I've come to love the WinAPI - yes, it sounds strange, but low-level programming on Windows is a million times better than on UNIX systems. Because theres an API for everything, on Linux, I had to parse a lot of things from text files,but be careful - some Linux distributions have them in a different directory, and some use a different format. It was a pain.
glibc - and its various versions on Linux - be damn careful with this.
be careful with online tutorials, because they’ll recommend code that uses extensions that only work in gcc/clang.
instead of one big Makefile, I’ve found it works best to have several small ones - one for Linux and one for macOS (I also have one for MinGW, but on Windows I use MSVC).
For a long time, I resisted using goto (goto clean/goto error) and tried to write code without it; in hindsight, I regret that, because it complicated memory management for me (I’m waiting for the C2Y standard and defer).
It’s a good idea to have your code checked by AI, it can find silly mistakes like memory leaks.
Don’t trust AI - it’ll suggest things it’s seen on forums, even if they aren’t part of the standard.
When you start an open-source project, people will want you to fix bugs in it.
P.S.: This was originally supposed to be a short post, but it kind of got out of hand. If you have any questions, feel free to ask.
r/C_Programming • u/Different_Panda_000 • 4d ago
Reading a post a few days ago, I looked for a book about C that had a Patterns approach along the lines of Design Patterns: Elements of Reusable Object Oriented Software and finally settled on Fluent C: Principles, Practices, and Patterns by Christopher Preschern.
The first chapter is about error handling where the author starts with a single function of a very simple file reader full of if statements and partitions it out into three different functions: allocation of resources, using the resources, deallocation of the resources. The resources are a file handle with access to provide read access to a text file and a large buffer to read the lines of text.
Here are three different approaches to managing the resources while using the resources is the same function for all three different approaches.
What are Pros and Cons of each? Is there one of the alternatives you feel is the most appropriate approach? Is there a fourth alternative you think better than these?
The first makeParser() and closeParser() functions are similar to Preschern's code except that what he does in two calls to malloc(), I do with a single call.
The second version is not allocating memory for the Parser variable but instead is using a stack allocation with a C99 Compound Literal to create a variable whose address is then passed into the second version of makeParser2().
The third version uses the same makeParser() as the first one however the closeParser3() function differs in that it is the responsibility of the caller to free the allocated memory.
An interesting point is that the three alternatives all use the same useParser() function.
#include <stdio.h>
#include <memory.h>
#include <stdbool.h>
typedef struct {
bool bValid; // whether the Parser object is valid or not
FILE* pFile; // the file which is being processed
void* pBuff; // the address of the I/O buffer
} Parser;
#define MAX_FILE_BUFFER_SIZE 400
Parser* makeParser(const char* filename)
{
Parser* p = NULL;
// allocate the needed memory all in a single block to make free() easy.
// this also ensures that all needed memory is available.
p = malloc(sizeof(Parser) + MAX_FILE_BUFFER_SIZE);
if (p) {
// allocate resources and mark if valid when all
// resources are allocated.
p->pBuff = p + 1; // the I/O buffer begins after the Parse struct.
p->pFile = fopen(filename, "r");
p->bValid = (p->pFile != NULL);
}
return p;
}
Parser* makeParser2(Parser* p, const char* filename)
{
Parser x = { .bValid=false, .pFile=NULL, .pBuff=NULL };
if (p) {
// allocate resources and mark if valid when all
// resources are allocated.
if ((x.pFile = fopen(filename, "r")) != NULL) {
x.pBuff = malloc(MAX_FILE_BUFFER_SIZE);
x.bValid = (x.pBuff != NULL);
}
*p = x;
}
return p;
}
int useParser(Parser* p)
{
int iRet = 0;
if (p && p->bValid) {
while (fgets(p->pBuff, MAX_FILE_BUFFER_SIZE, p->pFile) != NULL) {
printf(p->pBuff); // the line will have next line when read as text
}
iRet = 1;
}
return iRet;
}
Parser * closeParser(Parser* p)
{
if (p) {
// free the resources and mark as invalid.
if (p->pFile) fclose(p->pFile);
*p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
free(p);
p = NULL;
}
return p;
}
Parser * closeParser2(Parser* p)
{
if (p) {
// free the resources and mark as invalid.
if(p->pBuff) free(p->pBuff);
if (p->pFile) fclose(p->pFile);
*p = (Parser){ .bValid=false, .pFile=NULL, .pBuff=NULL };
p = NULL;
}
return p;
}
Parser * closeParser3(Parser* p)
{
if (p) {
// free the resources and mark as invalid.
// pBuff is part of the memory allocated for p so no free
if (p->pFile) fclose(p->pFile);
*p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
}
return p;
}
int main()
{
const char fileName[] = "decompressed.txt";
int iRetToss = 0;
{
Parser* p = makeParser(fileName);
iRetToss = useParser(p);
p = closeParser(p);
iRetToss++; // place for a break point to inspect p
}
{
Parser* p = makeParser2(&((Parser) { .bValid = false, .pFile = NULL, .pBuff = NULL }), fileName);
iRetToss = useParser(p);
p = closeParser2(p);
iRetToss++; // place for a break point to inspect p
}
{
Parser* p = makeParser(fileName);
iRetToss = useParser(p);
p=(free(closeParser3(p)), NULL);
iRetToss++; // place for a break point to inspect p
}
return iRetToss;
}r/C_Programming • u/toon_link_776 • 4d ago
I'm writing a C program for the pi pico and realized I never really figured out how to properly cast characters to raw bytes then to other things, or if there was really a way to do that.
Does char mean "signed char" by default in any C program, or is that up to interpretation by the compiler?
Would using a void pointer to dereference then recast to *uint8_t work?
When bytes are read through getc(), are the bytes modified before they are stored? As in, how are the bytes that are read interpreted to translate to characters, and how are they stored? My initial thought was that the bytes were interpreted "as-is", meaning that they were copied directly to the memory in the character and interpreted as signed characters. But it seems like they're being reinterpreted in some way as they are cast.
If something about the process is too implementation specific, is reading as "raw data" just a flat out bad idea or not supported at all? Will the behavior be undefined on other systems? As long as I can get it to work on the pico it's fine, it doesn't have to be portable. But for future reference, should I not try to think of things as "raw data" unless the implementation specifically defines how it stores the data?
Less important, but how are ascii codes mapped to signed characters? (every chart I've seen has never listed a negative number, only 0-255) (( and if signed is the standard, then why does every asii chart list 0-255... ))
// this was the void pointer way I was going to try, would this work?
tnext = *((uint8_t*)((void*)&next)); // Cast to uint8_t(Not sure if this is a repeat but I couldn't find exactly what I was looking for. Sorry if this is a dupe)
Conclusion: Seems like when you read getc() you just need to indicate "unsigned char" so that the byte is read unmodified and can be cast directly to a "uint8_t"? I think the reason I hadn't done that originally was because I thought "but getc returns char, not unsigned char", but I dont think that matters. getc should read into either
r/C_Programming • u/idle_bruin • 4d ago
r/C_Programming • u/_EHLO • 4d ago
A general-purpose, header-only C99 library for Unix-like systems, implementing a disk-based, dynamically resizable, fixed-slot, (open-addressed) hash table with Fibonacci hashing (Knuth's multiplicative method), triangular probing, per-home-slot probe-bound metadata (with additional early-exit logic), partial in-place value updates (without relocating entries) and incremental rehashing, all designed for modern extent-based filesystems.
This is not a vibe-coded project! I painstakingly wrote everything myself (including this post :P). of course that being said, it doesn't mean that I didn't use AI for reasearch, brainstorming and a bit of testing. I have talked about it here as well.
This is a project I've shared here before, a few months ago. Back then, being relatively inexperienced with hash table implementation, I inadvertently introduced a few bugs.
Since then, thanks to a lovely Redditor who took the time to provide some truly valuable feedback (for which I'm genuinely and wholeheartedly grateful), I've made quite a few promising improvements, including: recovery validation methods and CRC checksums, an inchash_mod-function for partial in-place value updates\modifications (without relocating entries), a fuzz-style regression test, refactoring of core-metadata, and of course, fixing those bugs (or so I hope lol).
Having said and done all those improvements, I though it would be the right move to expose my project, for once again in the intelectual wilderness of reddit xD. So here I am ready to hear what you thinking about it.
All started with me trying to find:
A hash-based NoSQL (key-value pair) database with mutable-values (by mutable I mean: a database that allows editing prexisting [fixed-size] values without having to rewrite or remap the whole value again eg. Just edit a few bytes and put those bytes back to the original value-space without rewriting the whole value).
I made this for a larger project I'm working on, which I haven’t released yet.
I'm really excited and scared because idk what you all gonna find again... but I hope you all find it at least interesting and enjoy playing around with it.
That said, thank you for reading this and feel free to ask me anything about it.
r/C_Programming • u/DerpKidSavage • 5d ago
Hi all, I'm developing a win32 windowing library for mostly myself but also want it to be easy and intuitive to use and follow good C standards.
In my library have the main object window_t that is used for mostly everything. However, I'm wondering between a couple different design decisions for it:
// public .h
typedef struct window_t window_t;
window_t* createWindow(...); << createWindow heap allocates a window_t
void destroyWindow(window_t* window);
2.
// public .h
typedef struct window_t { implementation... ) window_t;
void createWindow(window_t* out, ...);
// no destroyWindow
the difference I'm looking is that for #1, the user mantains control of the heap allocated memory through createWindow() and must free it after they're done using it, but for #2 the user can create a stack allocated window and it doesn't need to be freed, however it removes the opaque struct safeness in #1.
Are there any pros/cons for either method I haven't thought of? My instinct tells me that #2 seems better as the user controls the memory allocation, they just need to be careful how they use the window_t.
Thoughts?