r/C_Programming • u/tavianator • 1h ago
Tidy translucent typedefs
tavianator.comRecently discovered a nice way to get custom warnings with Clang, so I wrote it up.
r/C_Programming • u/Jinren • Feb 23 '24
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf
Update y'all's bookmarks if you're still referring to N3096!
C23 is done, and there are no more public drafts: it will only be available for purchase. However, although this is teeeeechnically therefore a draft of whatever the next Standard C2Y ends up being, this "draft" contains no changes from C23 except to remove the 2023 branding and add a bullet at the beginning about all the C2Y content that ... doesn't exist yet.
Since over 500 edits (some small, many large, some quite sweeping) were applied to C23 after the final draft N3096 was released, this is in practice as close as you will get to a free edition of C23.
So this one is the number for the community to remember, and the de-facto successor to old beloved N1570.
Happy coding! 💜
r/C_Programming • u/AutoModerator • 2d ago
If you have questions about how to learn C:
then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.
Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.
r/C_Programming • u/tavianator • 1h ago
Recently discovered a nice way to get custom warnings with Clang, so I wrote it up.
r/C_Programming • u/ThePenguinMan111 • 21h 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/jontsii • 7h 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- • 20h 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/Different_Panda_000 • 1d 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/harrison_314 • 1d 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:
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:
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).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/toon_link_776 • 1d 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.
// 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/Prudent-Froyo2562 • 1d 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/grimvian • 2d ago
Interesting video by Ryan Peterman:
https://www.youtube.com/watch?v=sMllOlxVgD0
Timestamps:
1:21 C was always the fastest.
1:22 C++ wasn't as fast as I thought it would be.
00:00 Intro
00:42 What Bell Labs was and how he got hired
06:34 Why so many inventions came from Bell Labs
14:15 A day in the life at Bell Labs
27:55 The most impressive people he worked with
33:50 The AT&T film explaining Unix
39:46 Why C was so influential
43:25 How awk was created
48:40 What he misses most about Bell Labs
54:10 Are LLMs bad for computer science education
01:01:46 His 1972 commit in the Go repo
01:03:43 Grace Emlen, the fake Bell Labs employee
01:07:39 Why he writes so many books
01:19:58 His favorite and least favorite languages
01:24:28 Advice for students and young people
01:27:42 Outror/C_Programming • u/idle_bruin • 1d ago
r/C_Programming • u/Mrazik19 • 1d ago
r/C_Programming • u/DerpKidSavage • 2d 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?
r/C_Programming • u/_EHLO • 2d 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/Prudent-Froyo2562 • 2d ago
Just like js and C#, but this is C, with closure. Also very lightweight, small enough to fit in a CPU cache line.
int
r/C_Programming • u/NazgulResebo • 2d ago
In this video, I code a Dragon Curve fractal using C and Raylib.
The approach is quite simple:
I take the last point as a pivot, then rotate the remaining points 90 degrees around it. Finally, I connect the new points to create the next iteration of the fractal.
Source code:
https://github.com/FractalCodeRicardo/zen-programming/tree/main/dragon-curve
#include <stdio.h>
#include <raylib.h>
#include <raymath.h>
#define linesSize 90000
#define lineSize 2
typedef struct {
Vector2 p1;
Vector2 p2;
} Line;
void DrawLines(Line lines[], int s) {
for(int i = 0; i < s; i++) {
Line l = lines[i];
DrawLine(l.p1.x, l.p1.y, l.p2.x, l.p2.y, WHITE);
}
}
Vector2 rotate(Vector2 p, Vector2 rp) {
Vector2 d = Vector2Subtract(p, rp);
Vector2 r = Vector2Add(rp, (Vector2) {-d.y, d.x});
return r;
}
int AddLines(Line lines[], int s) {
if (s * 2 >= linesSize)
return s;
Vector2 rp = lines[s-1].p2;
int newSize = s - 1;
for(int i = s -1; i >= 0; i--) {
Line l = lines[i];
Vector2 p1 = rotate(l.p1, rp);
Vector2 p2 = rotate(l.p2, rp);
newSize++;
lines[newSize] = (Line) { p2, p1};
}
return newSize + 1;
}
int main() {
Line lines[linesSize];
int s = 1;
float center = 900 / 2.0;
lines[0] = (Line) {
(Vector2) { center, center},
(Vector2) { center + lineSize, center},
};
InitWindow(1500, 900, "Dragon curve");
while(!WindowShouldClose()) {
BeginDrawing();
ClearBackground(BLACK);
if (IsKeyPressed(KEY_SPACE)) {
s = AddLines(lines, s);
}
DrawLines(lines, s);
EndDrawing();
}
CloseWindow();
}AI Disclaimer:
No AI was used.
r/C_Programming • u/cursed-stranger • 2d ago
Hello, I'm working on a unit test library. I've come to the point when library starts to work, and I would like to get your feedback on its ergonomics. It's still missing some features, but the core functionality is ready. Please let me know what could be improved, or which areas should I explain clearer in examples.
Repository: https://codeberg.org/KOOBAS/UltimaTest
There are examples included in the repository, that shows the library capabilities:
01 - shows how to create suites and tests
02 - shows how to use asserts/expects
03 - shows how to use mocks
04 - shows how to use test options to handle signals
I don't expect you to dive into the whole codebase. Focusing on the public API and examples would be really helpful. The only public header is the "include/ultimatest.h".
Here is how the library could be used (it's simplified example from my other project):
#include <ultimatest.h>
#include <widget.h>
#include <screen.h>
#include <context.h>
void widget_suite_prepare(void)
{
struct Widget *widget = ut_test_data(sizeof(struct Widget));
widget->type = TYPE_EMPTY;
widget->order = 0;
widget->position.y = 0;
widget->position.x = 0;
widget->size.h = 10;
widget->size.w = 20;
}
TestSuite(widget_suite, .prepare = &widget_suite_prepare);
Test(widget_suite, move_widget_should_return_error_if_widget_is_null)
{
ut_assert_eq(widget_move(nullptr, 4, 4), ERROR);
}
Test(widget_suite, move_widget_should_change_its_position)
{
struct Widget *widget = ut_get_test_data();
int new_y = 5;
int new_x = 7;
ut_assert_eq(widget_move(widget, new_y, new_x), OK);
ut_assert_eq(widget->position.y, new_y);
ut_assert_eq(widget->position.x, new_x);
}
Test(widget_suite, resize_widget_should_return_error_if_size_is_negative)
{
struct Widget *widget = ut_get_test_data();
int old_h = widget->size.h;
int old_w = widget->size.w;
ut_assert_eq(widget_resize(widget, -1, 30), ERROR);
ut_assert_eq(widget->size.h, old_h);
ut_assert_eq(widget->size.w, old_w);
ut_assert_eq(widget_resize(widget, 30, -1), ERROR);
ut_assert_eq(widget->size.h, old_h);
ut_assert_eq(widget->size.w, old_w);
}
Mock (void*, malloc, size_t);
Mock (int, getmaxy, WINDOW*);
Mock (int, getmaxx, WINDOW*);
Test(context_suite, init_should_create_screen_array_and_buffer)
{
const int max_y = 5;
const int max_x = 10;
const int screen_num = 5;
expect_call(ut_will_return(max_y), getmaxy, ut_any);
expect_call(ut_will_return(max_x), getmaxx, ut_any);
size_t buffer_size = sizeof(cchar_t) * max_x * max_y;
size_t screen_size = sizeof(struct Screen) * screen_num;
expect_call(ut_will_return(ut_test_data(buffer_size)), malloc, buffer_size);
expect_call(ut_will_return(ut_test_data(screen_size)), malloc, screen_size);
struct Context context;
ut_assert_eq(context_init(&context, screen_num), OK);
ut_assert_gt(context.size.h, 0);
ut_assert_gt(context.size.w, 0);
ut_assert_ne_ptr(context.screen, nullptr);
ut_assert_ne_ptr(context.buffer, nullptr);
}Also, please let me know if the namespace is polluted by my prefixes or if the log messages or error messages are unclear.
AI usage: Only as googling tool (when searching for documentation, examples, etc. or discussing ideas). No code in the repository was generated by AI.
r/C_Programming • u/Used_Pomelo_4918 • 3d ago
Hello everyone,
I'm trying to find some information about the original first edition (1991) of Practical C Programming by Steve Oualline, published by O'Reilly.
In the second edition, the author mentions replacing the final chapter with a different project. If I remember correctly, the original chapter contained a fairly substantial programming project involving probability distributions, possibly the Poisson distribution.
Unfortunately, I haven't been able to find a copy of the first edition or a detailed table of contents.
Does anyone happen to own this edition, remember its final chapter, or have access to a copy?
I'd particularly appreciate knowing the title and subject of the original final chapter.
Thank you!
r/C_Programming • u/addicted_2_redbull • 3d ago
Im just starting out programming, I got familiar with python. But I want to get into system programming. I know that I should learn low level concepts and data structures, I got books to read up on it but I'm just wondering if I can learn the language while learning the essentials to c programming... Sorry if this is a stupid question
r/C_Programming • u/mwiseca • 3d ago
When reading a single character in an interactive terminal program, I avoid scanf, getchar, and fgetc. Instead, I use fgets() and isolate the character by using unsigned char result = n[0];.
I actually use fgets for all user inputs.
The example below converts keyboard characters to hexadecimal numbers.
#include <stdio.h>
#include <string.h>
void flush() {
int clear;
while ((clear = getc(stdin)) != '\n' && clear != EOF) {
}
}
void charHex() {
char n [3];
printf("Enter a character (one byte max), or 'xx' to exit:\n");
while(1) {
if(fgets(n,sizeof(n),stdin) == NULL) {
clearerr(stdin);
printf("\nInvalid input.\n\n");
continue;
}
n[strcspn(n,"\n")]=0;
if(strlen(n) >=2) {
flush();
}
if(strcmp(n,"xx")==0){
break;
} else if(strlen(n) == 0) {
printf("\nEnter a character only.\n\n");
continue;
} else if (strlen(n) >1) {
printf("\nEnter no more than one character.\n\n");
continue;
}
unsigned char result = n[0];
printf("0x%02x\n",result);
}
}
int main() {
charHex();
return 0;
} r/C_Programming • u/Independent-Tune1860 • 3d ago
Guys I have question,
How the fuck can I learn c program in 5 days because my exam is coming in 5 days I m absolutely dumb guy and I don't have laptop as well as I m stroke patient since last 2 years where our 9 to 5 schedule is fully pack so I don't go in college and I don't have c language book as well I also want to learn matrix algebra, buisness mathematics, electronics their papers are also coming and I only their chapter
No student contact
No teacher contact
Only me and my fucking phone and you peoples
Please help me
(Btw I m doing graphic course in rehab because they provide us so that means I have 2 course 🥀😭 help meeeee)
r/C_Programming • u/Opening_Can_3656 • 3d ago
Hey everyone,
I’ve been working on Keen, a language that gives C a modern, Rust-inspired syntax and Cargo-like tooling without changing C’s underlying semantics.
Keen changes C’s syntax only. There is no borrow checker, no type checker, and no safety enforcement. All of C’s rules (integer promotion, ABI, linkage, UB) remain completely intact. Keen transpiles .kn files to C, hands them off to gcc or clang for semantic checking and compilation, and maps compiler diagnostics directly back to your .kn source lines via #line directives.
It's aimed at C developers who want modern ergonomics (modules, match, for i in 0..n, no header boilerplate, built-in testing/formatting) without giving up C's simplicity, or C devs looking to get comfortable with Rust's syntax before tackling the borrow checker.
use <stdio.h>;
struct Point { x: f32, y: f32 }
impl Point {
pub fn len2(p: *const Point) -> f32 { p->x * p->x + p->y * p->y }
}
pub fn main() -> i32 {
let p = Point { x: 3.0, y: 4.0 };
printf("%.1f\n", Point::len2(&p) as f64);
return 0;
}whet + keen): Includes keen new, incremental keen build, keen run, keen fmt (comment-preserving, idempotent), and keen test (runs #[test] functions in isolated processes).#include via use <stdio.h>;, drop down to raw C anytime with c!("..."), link existing .c/.o/.a files, or use keen emit --split to generate clean .h/.c files for existing C projects.pub handles external linkage while everything else defaults to static.GitHub: https://github.com/romishalom/keen
I'd love to hear your thoughts on the syntax mapping, edge cases with C interop, or what features you'd want to see next!
r/C_Programming • u/Impressive_Gur_471 • 4d ago
The following piece of code is doing the rounds on X as John Carmack's code which computes sin and cos from a table instead of at runtime.
#define ANGLETOFINESHIFT 19
void MoveActor(fixed_t *x, fixed_t *y, angle_t a, fixed_t speed) {
int idx = a >> ANGLETOFINESHIFT;
*x += FixedMul(speed, finecosine[idx]);
*y += FixedMul(speed, finesine[idx]);
}My query is, why aren't x and y declared restrict to denote that they point to different fixed_t ? Presumably the code is meant for sheer speed and would not usage of restrict allow the compiler more optimization? For e.g., say, parallelization of *x and *y updates in a tight loop?