Add Chapter 4 source code examples and exercises

Introduce the first batch of practical code examples for Chapter 4,
covering fundamental C programming.
This commit is contained in:
Edson Brandi 2025-11-07 23:34:26 +00:00
parent be78fa799d
commit 763601b5bc
No known key found for this signature in database
GPG key ID: 604D961A8EC70166
19 changed files with 337 additions and 0 deletions

Binary file not shown.

View file

@ -0,0 +1,21 @@
#include <stdio.h>
// Function definition
unsigned int read_register(unsigned int address)
{
// Simulated register value based on address
unsigned int value = address * 2;
printf("[driver] Reading register at address 0x%X...\n", address);
return value;
}
int main(void)
{
unsigned int reg_addr = 0x10; // pretend this is a hardware register address
unsigned int data;
data = read_register(reg_addr); // Call the function
printf("[driver] Value read: 0x%X\n", data);
return 0;
}

View file

@ -0,0 +1,4 @@
# Makefile for hello.c
hello: hello.c
cc -o hello hello.c

View file

@ -0,0 +1,6 @@
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}

View file

@ -0,0 +1,14 @@
CC = cc
CFLAGS = -Wall -Wextra -std=c99
linkage_demo: main.o foo.o
$(CC) $(CFLAGS) -o linkage_demo main.o foo.o
main.o: main.c
$(CC) $(CFLAGS) -c main.c
foo.o: foo.c
$(CC) $(CFLAGS) -c foo.c
clean:
rm -f *.o linkage_demo

View file

@ -0,0 +1,33 @@
#include <stdio.h>
/*
* Global variable with external linkage:
* - Visible to other files (translation units) in the program.
* - No 'static' keyword means it has external linkage by default.
*/
int shared_counter = 0;
/*
* File-private variable with internal linkage:
* - The 'static' keyword at file scope means this name
* is only visible inside foo.c.
*/
static int internal_flag = 1;
/*
* Function with external linkage by default:
* - Can be called from other files if they declare its prototype.
*/
void increment(void) {
/*
* Local variable with no linkage:
* - Exists only during this function call.
* - Cannot be accessed from anywhere else.
*/
int step = 1;
if (internal_flag) // Only code in foo.c can see internal_flag
shared_counter += step; // Modifies the global shared_counter
printf("Counter: %d\n", shared_counter);
}

View file

@ -0,0 +1,23 @@
#include <stdio.h>
/*
* 'extern' tells the compiler:
* - This variable exists in another file (foo.c).
* - Do not allocate storage for it here.
*/
extern int shared_counter;
/*
* Forward declaration for the function defined in foo.c:
* - Lets us call increment() from this file.
*/
void increment(void);
int main(void) {
increment(); // Calls increment() from foo.c
shared_counter += 10; // Legal: shared_counter has external linkage
increment();
// internal_flag = 0; // ERROR: not visible here (internal linkage in foo.c)
return 0;
}

View file

@ -0,0 +1,14 @@
CC = cc
CFLAGS = -Wall -Wextra -std=c99
mathprog: main.o mathutils.o
$(CC) $(CFLAGS) -o mathprog main.o mathutils.o
main.o: main.c mathutils.h
$(CC) $(CFLAGS) -c main.c
mathutils.o: mathutils.c mathutils.h
$(CC) $(CFLAGS) -c mathutils.c
clean:
rm -f *.o mathprog

View file

@ -0,0 +1,9 @@
#include <stdio.h>
#include "mathutils.h"
int main(void)
{
printf("Sum: %d\n", add(3, 4));
printf("Difference: %d\n", subtract(10, 4));
return 0;
}

View file

@ -0,0 +1,11 @@
#include "mathutils.h"
int add(int a, int b)
{
return a + b;
}
int subtract(int a, int b)
{
return a - b;
}

View file

@ -0,0 +1,7 @@
#ifndef MATHUTILS_H
#define MATHUTILS_H
int add(int a, int b);
int subtract(int a, int b);
#endif // MATHUTILS_H

View file

@ -0,0 +1,9 @@
#include "mydevice.h"
int main(void)
{
mydevice_probe();
mydevice_attach();
mydevice_detach();
return 0;
}

View file

@ -0,0 +1,18 @@
#include <stdio.h>
#include "mydevice.h"
// Function definitions
void mydevice_probe(void)
{
printf("[mydevice] Probing hardware... done.\n");
}
void mydevice_attach(void)
{
printf("[mydevice] Attaching device and initializing resources...\n");
}
void mydevice_detach(void)
{
printf("[mydevice] Detaching device and cleaning up.\n");
}

View file

@ -0,0 +1,9 @@
#ifndef MYDEVICE_H
#define MYDEVICE_H
// Function declarations (prototypes)
void mydevice_probe(void);
void mydevice_attach(void);
void mydevice_detach(void);
#endif // MYDEVICE_H

View file

@ -0,0 +1,9 @@
# Makefile for hello_world kernel module
KMOD= mydriver
SRCS= mydriver.c
# Required for Newbus drivers - generates device_if.h and bus_if.h
SRCS+= device_if.h bus_if.h
.include <bsd.kmod.mk>

View file

@ -0,0 +1,116 @@
/*
* FreeBSD device driver lifecycle (quick map)
*
* 1) Kernel enumerates devices on a bus
* The bus framework walks hardware and creates device_t objects.
*
* 2) probe()
* The kernel asks your driver if it supports a given device.
* You inspect IDs or capabilities and return a score.
* - Return ENXIO if this driver does not match.
* - Return BUS_PROBE_DEFAULT or a better score if it matches.
*
* 3) attach()
* Called after a successful probe to bring the device online.
* Typical work:
* - Allocate resources (memory, IRQ) with bus_alloc_resource_any()
* - Map registers and set up bus_space
* - Initialize hardware to a known state
* - Set up interrupts and handlers
* Return 0 on success, or an errno if something fails.
*
* 4) Runtime
* Your driver services requests. This may include:
* - Interrupt handlers
* - I/O paths invoked by upper layers or devfs interfaces
* - Periodic tasks, callouts, or taskqueues
*
* 5) detach()
* Called when the device is being removed or the module unloads.
* Cleanup tasks:
* - Quiesce hardware, stop DMA, disable interrupts
* - Tear down handlers and timers
* - Unmap registers and release resources with bus_release_resource()
* Return 0 on success, or an errno if detach must be denied.
*
* 6) Optional lifecycle events
* - suspend() and resume() during power management
* - shutdown() during system shutdown
*
* Files to remember
* - mydriver.h declares the entry points that the kernel and bus code will call
* - mydriver.c defines those functions and contains the implementation details
*/
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <sys/systm.h> // device_printf
#include "mydriver.h"
/*
* mydriver_probe()
* Called early during device enumeration.
* Purpose: decide if this driver matches the hardware represented by dev.
* Return: BUS_PROBE_DEFAULT for a normal match, a better score for a strong match,
* or ENXIO if the device is not supported.
*/
int
mydriver_probe(device_t dev)
{
device_printf(dev, "Probing device...\n");
/*
* Here you would usually check vendor and device IDs or use bus-specific
* helper routines. If the device is not supported, return (ENXIO).
*/
return (BUS_PROBE_DEFAULT);
}
/*
* mydriver_attach()
* Called after a successful probe when the kernel is ready to attach the device.
* Purpose: allocate resources, map registers, initialise hardware, register interrupts,
* and make the device ready for use.
* Return: 0 on success, or an errno value (like ENOMEM or EIO) on failure.
*/
int
mydriver_attach(device_t dev)
{
device_printf(dev, "Attaching device and initializing resources...\n");
/*
* Typical steps you will add here:
* 1) Allocate device resources (I/O memory, IRQs) with bus_alloc_resource_any().
* 2) Map register space and set up bus_space tags and handles.
* 3) Initialise hardware registers to a known state.
* 4) Set up interrupt handlers if needed.
* 5) Create device nodes or child devices if this driver exposes them.
* On any failure, release what you allocated and return an errno.
*/
return (0);
}
/*
* mydriver_detach()
* Called when the device is being detached or the module is unloading.
* Purpose: stop the hardware, free resources, and leave the system clean.
* Return: 0 on success, or an errno value if detach must be refused.
*/
int
mydriver_detach(device_t dev)
{
device_printf(dev, "Detaching device and cleaning up...\n");
/*
* Typical steps you will add here:
* 1) Disable interrupts and stop DMA or timers.
* 2) Tear down interrupt handlers.
* 3) Unmap register space and free bus resources with bus_release_resource().
* 4) Destroy any device nodes or sysctl entries created at attach time.
*/
return (0);
}

View file

@ -0,0 +1,14 @@
#ifndef _MYDRIVER_H_
#define _MYDRIVER_H_
#include <sys/types.h>
#include <sys/bus.h>
// Public entry points: declared here so bus/framework code can call them
// These are the entry points the kernel will call during the device's lifecycle
// Function prototypes (declarations)
int mydriver_probe(device_t dev);
int mydriver_attach(device_t dev);
int mydriver_detach(device_t dev);
#endif /* _MYDRIVER_H_ */

Binary file not shown.

View file

@ -0,0 +1,20 @@
#include <stdio.h>
#include <string.h>
int main() {
// Fill stack with non-zero garbage
char garbage[100];
memset(garbage, 'Z', sizeof(garbage));
// Deliberately forget the null terminator
char broken[5] = {'B', 'S', 'D', '!', 'X'};
// Print as if it were a string - will likely show garbage now
printf("Broken string: %s\n", broken);
// Now with proper termination
char fixed[6] = {'B', 'S', 'D', '!', 'X', '\0'};
printf("Fixed string: %s\n", fixed);
return 0;
}