Application developer reference / API 14
DOS64 SDK documentation
Build native x86-64 applications using the DOS64 API table and small C helper libraries. This reference describes the public headers, runtime, module contracts, and application lifecycle.
PE means Portable Executable, the file format used for these executables. It does not imply compatibility with arbitrary Windows applications or refer to Windows Preinstallation Environment.
Headers, code, and libraries
The published disk image contains these SDK files on C:. The API header in this image declares DOS64_API_VERSION 14. No kernel implementation sources are published by this site.
C:\SDK\ INCLUDE\dos64_*.h BIN\bmetal.dll LIB\libbmetal.dll.a
| Component | Role and dependency |
|---|---|
dos64_api.h | ABI types, service tables, constants, and the versioned DOS64_API structure. All modules depend on it. |
dos64_runtime.h | Runtime requirements descriptor and the imported Dos64Run entry. Used by PE startup. |
dos64_stdio.h | Header-only text output and integer formatting over Api->Write. |
dos64_gfx.h, dos64_font8x16.h | Header-only drawing helpers, layer operations, and the built-in bitmap font. |
dos64_input.h | Header-only keyboard and mouse queries, plus HID key constants. |
dos64_fs.h | Header-only file, directory, FAT timestamp, and raw disk helpers. |
dos64_time.h | Header-only monotonic and wall-clock helpers. |
dos64_audio.h | PCM output and WAV decoding/writing; includes the filesystem module. |
dos64_thread.h | Cooperative threads, mutexes, and condition variables. |
dos64_queue.h | Bounded message queues over threads and synchronization. |
dos64_audio_stream.h | Background WAV playback over audio, queues, and threads. |
libbmetal.dll.a | MinGW import library. Resolves the Dos64Run import at link time; not a static implementation of all services. |
bmetal.dll | Windows host implementation of the DOS64 interface. Place beside the executable for Windows testing. GUI-subsystem apps show a three-second bMETAL logo and host/runtime information splash before starting. DOS64 resolves supported runtime imports through its kernel instead and does not show this Windows splash. |
The helper modules are C headers, not dynamically loaded plugins. Include only what you use. Each header keeps its own API pointer in each translation unit: initialize its wrappers in every C file that uses them. Do not mix the stdio/filesystem headers with another libc's conflicting types and functions.
lib/dos64_startup.o, the import library, Windows runtime, startup source, and a compiled example with source. The disk image was built on and published here on ; it lacks the startup object. The self-contained example below supplies its own entry adapter and does not require the object.First application and build
Extract the standalone SDK ZIP, or copy C:\SDK\INCLUDE and C:\SDK\LIB from the image into local include/ and lib/ directories. Install an x86-64 MinGW-w64 GCC toolchain. Save this complete example as hello.c (replacing the ZIP's example if using this self-contained entry adapter):
#include <dos64_stdio.h>
#include <dos64_runtime.h>
int __attribute__((ms_abi)) start(const DOS64_API *Api)
{
stdio_init(Api);
puts("Hello from DOS64");
printf("Arguments: %s\n", Api->Arguments);
return 0;
}
int __attribute__((ms_abi)) dos64_entry(void)
{
static const DOS64_REQUIREMENTS Required = {
sizeof(DOS64_REQUIREMENTS),
DOS64_RUNTIME_MAJOR, DOS64_RUNTIME_MINOR,
sizeof(DOS64_API), DOS64_API_VERSION,
DOS64_REQUIRED_SERVICES
};
return Dos64Run(start, &Required);
}
x86_64-w64-mingw32-gcc -m64 -O2 -Wall -Wextra -Werror \ -ffreestanding -nostdlib -nostartfiles -fno-stack-protector -mno-red-zone \ -Iinclude -Wl,-e,dos64_entry -Wl,--subsystem,console -Wl,--dynamicbase \ hello.c -Llib -lbmetal -o hello.exe
Copy hello.exe onto a DOS64 data volume while the VM is stopped, then run it from the shell, for example C:\HELLO.EXE sdk-test. Expect a greeting followed by Arguments: sdk-test. On Windows, put bmetal.dll beside it. Native Linux does not execute this PE file directly.
With the full kit, you may instead omit the dos64_entry function and link lib/dos64_startup.o before -Llib -lbmetal. Never supply both entry adapters. Do not use a normal CRT main entry or link ordinary Windows/Linux library calls into a DOS64 application.
Implementation map for maintainers: canonical public interfaces live in src/libapi/; sdk/include/ forwards to them in the source tree. sdk/startup.c implements the PE adapter; sdk/windows/dos64.c implements the Windows backend; sdk/windows/dos64.def exports Dos64Run. sdk/build.sh builds headers, DLL, import library, and startup object; sdk/package.sh assembles the full kit. These are repository build components, not tools included in the public image.
Core API and runtime negotiation
dos64_api.h defines the contract. The application callback is int __attribute__((ms_abi)) start(const DOS64_API *Api). Both PE and freestanding ELF use the Microsoft x64 callback ABI. ELF applications still require a DOS64-specific loader/build contract; they are not Linux executables.
| Field / function | Contract |
|---|---|
Api->Size, Api->Version | Available table bytes and API revision. New members are appended; never assume a newer field exists just because your header declares it. |
Api->Arguments | Non-null text following the program name, not an argv array. |
Api->Write(const char *Text) | Writes a null-terminated string to DOS64 console, serial output, and log. |
Api->Sleep(unsigned int Milliseconds) | Polls input while sleeping; API 12+ blocks only the calling cooperative thread. |
Dos64Run(Application, Required) | Runtime entry declared by dos64_runtime.h. Negotiates the descriptor and invokes the application. Do not call it recursively from start. |
DOS64_REQUIREMENTS | Size, runtime Major/Minor, ApiSize, ApiVersion, and RequiredServices. The runtime must support the requested table size/version and every required service bit. |
dos64_runtime_compatible(Required, Major, Minor, Services) | Returns nonzero if descriptor size matches, major matches, requested minor is no newer, API fits, and all required services exist. |
Service bits: TEXT=1, GFX=2, INPUT=4, TIME=8, AUDIO=16, FS=32, SYSTEM=64 (use the DOS64_SERVICE_* constants). Default DOS64_REQUIRED_SERVICES requires all except audio. Audio remains optional and must be checked separately. Do not lower requirements unless your code actually supports the older/smaller interface.
Before optional direct calls, check Version, the end offset of the member against Size, and the function pointer. API 9 adds system status; 10 text styles; 11 threads; 12 synchronization; 13 batched rectangles; 14 opaque image drawing.
if (Api->Version >= 10 &&
Api->Size >= __builtin_offsetof(DOS64_API, SetTextStyle)
+ sizeof(Api->SetTextStyle) &&
Api->SetTextStyle != 0) {
if (Api->SetTextStyle(DOS64_TEXT_CYAN) != 0) {
Api->Write("Text style is unavailable\n");
}
}
Return an integer exit status from start. Close files, stop playback, join workers, and destroy owned resources before returning. DOS64 closes leftover file handles and stops audio at program exit, but explicit cleanup is the correct normal path.
Text output
dos64_stdio.h is a minimal, header-only console formatter, not a complete C standard library. Call stdio_init(Api) before output.
| Interface | Behavior |
|---|---|
putchar(int Character) | Writes a character through the string output path; returns its unsigned-byte value. Not a binary output API. |
puts(const char *Text) | Writes text and a newline; returns 0. |
printf(Format, ...), vprintf(Format, Arguments) | Return emitted character count. Support %% %c %s %d %i %u %x %X %p, l/ll/z lengths, 0/- flags, and field width. No floating point or precision formatting. |
Api->SetTextStyle(Style) | API 10+. Returns 0 or -1 for unsupported style. DOS64_TEXT_*: DEFAULT, CYAN, LAVENDER, CORAL, MUTED, SUCCESS. Changes framebuffer text style, not plain-text logs. |
Graphics and layers
dos64_gfx.h wraps Api->Gfx. Call gfx_init(Api). Coordinates are signed pixels clipped to the selected surface; draw into a back buffer, then call gfx_present(). Colors are straight-alpha 0xAARRGGBB, not RGBA byte order.
| Functions / types | Usage |
|---|---|
gfx_width(), gfx_height() | Screen dimensions in pixels. |
gfx_set_color(Color), gfx_clear(Color) | Select drawing color; clear replaces selected surface contents. GFX_COLOR_ARGB(A,R,G,B) constructs a color; named opaque colors and GFX_TRANSPARENT are provided. |
gfx_putpixel(X,Y), gfx_getpixel(X,Y), gfx_line(X0,Y0,X1,Y1) | Pixel and line operations. Pixel reads outside the surface return 0. |
gfx_rect(X,Y,W,H), gfx_fill_rect(X,Y,W,H), gfx_circle(Cx,Cy,R), gfx_fill_circle(Cx,Cy,R) | Outline and filled primitives using current color. |
gfx_fill_rects(const DOS64_RECT *Rectangles, unsigned int Count) | Each rectangle contains X, Y, Width, Height, Color. Uses API 13 batching when available, otherwise individual fills. |
gfx_draw_image(Pixels,SourceWidth,SourceHeight,Stride,X,Y,Width,Height) | Nearest-neighbor scaling of opaque ARGB pixels; source alpha is ignored. Stride is pixels per source row, not bytes. API 14 fast path, otherwise per-pixel fallback. Fast-path destination dimensions are limited to 65535. |
gfx_layer_create(W,H), gfx_layer_destroy(Layer), gfx_layer_select(Layer) | Create a transparent surface, destroy it, or select a drawing target. Layer 0 (GFX_LAYER_BASE) is the screen-sized opaque base. Create returns a handle; errors are -1. |
gfx_layer_set_position(Layer,X,Y), gfx_layer_set_opacity(Layer,Opacity), gfx_layer_set_visible(Layer,Visible), gfx_layer_set_z_order(Layer,Z) | Return 0 on success, -1 on failure. Opacity 0..255; compositing is source-over in ascending Z order. Drawing coordinates remain local to the selected layer. |
gfx_draw_text(X,Y,Text,Foreground,Background) | 8x16 ASCII text; newline advances a line, carriage return resets X, unsupported bytes become '?'. Transparent background skips background fills. Leaves foreground selected. |
gfx_present(), sleep_ms(Ms) | Present the composed frame; sleep through the API. Console text shares the graphics screen. |
dos64_font8x16.h provides Font8x16[128][16]: one byte per glyph row, most-significant bit at the left. It needs no initialization and is used by gfx_draw_text; it is not a Unicode/font-loading service.
#include <dos64_gfx.h>
#include <dos64_input.h>
int __attribute__((ms_abi)) start(const DOS64_API *Api)
{
gfx_init(Api);
input_init(Api);
for (;;) {
input_poll();
if (key_pressed(KEY_ESC)) { break; }
gfx_clear(GFX_BLACK);
gfx_draw_text(24, 24, "Escape to exit", GFX_CYAN, GFX_TRANSPARENT);
gfx_present();
Api->Sleep(16);
}
return 0;
}
This and the following module examples implement only start. Link each separately with the full-kit startup object, or append the entry adapter from the first example. Do not combine several start functions in one executable.
Keyboard and mouse
dos64_input.h wraps Api->Input. Initialize with input_init(Api), then call input_poll() once per loop before querying state. Calls never wait for a key.
| Interface | Meaning |
|---|---|
input_getchar() | Next queued typed ASCII character, or -1 when none is waiting. Drain in a loop for text input. |
key_down(Key) | Held state. KEY_* values are USB HID usages, not ASCII or platform virtual-key codes. |
key_pressed(Key), key_released(Key) | Transitions accumulated since the previous poll, including a quick tap between polls. |
mouse_x/y(), mouse_dx/dy(), mouse_wheel() | Screen position and movement/wheel accumulated since the previous poll. |
mouse_down(Button), mouse_pressed(Button), mouse_released(Button) | Button state/edges. Pass MOUSE_LEFT=0, MOUSE_RIGHT=1, MOUSE_MIDDLE=2 (indices, not masks). |
Key constants include letters, digits, F1..F12, arrows, navigation keys, Escape, Enter, and left/right Ctrl/Shift/Alt. The underlying Input.Modifiers is the HID modifier bitmap. One loop should own polling; additional polls reset transition/delta snapshots.
Files, directories, and disks
dos64_fs.h wraps Api->Fs and Api->Disk. Call fs_init(Api). FILE is an opaque handle, not a host libc file. DOS64 permits at most eight open files. Paths accept slash or backslash; relative paths use the shell/process working directory.
| Functions | Results and limitations |
|---|---|
fopen(Path,Mode), fclose(File) | Open returns a handle or null. Modes: r, w, a, r+, w+, a+; b is ignored. Close returns 0/-1. |
fread(Buffer,Size,Count,File), fwrite(Buffer,Size,Count,File) | Return completed item counts, not necessarily bytes. Compare with Count; use Size=1 for byte counts. |
fseek(File,Offset,Whence), ftell(File) | Signed 64-bit offset; SEEK_SET=0, SEEK_CUR=1, SEEK_END=2. Seek returns 0/-1; tell returns position or failure. |
feof(File), ferror(File), fflush(File) | Inspect EOF/error state; flush returns 0/-1. fflush(0) flushes every open file. Detailed filesystem status is Api->Fs.LastError() (EFI status). |
fgetc(File), fputc(Character,File), fgets(Buffer,Size,File), fputs(Text,File) | Character I/O uses EOF=-1. fgets needs a valid buffer and positive Size, retains newline, and returns null if no character was read. fputs returns 0 or EOF. |
remove(Path), rename(Old,New), mkdir(Path), rmdir(Path), chdir(Path) | File/directory operations, 0 on success and -1 on failure. |
readdir(Index,&Entry) | Lists the current directory by index. Returns 1 for an entry, 0 past end; treat negative results as failure. DOS64_DIRENT contains Name[256], Size, IsDirectory, and FAT Date/Time. |
fat_year/month/day(Date), fat_hour/minute/second(Time) | Decode packed FAT timestamps. Seconds have two-second granularity. |
disk_present(), disk_sector_size(), disk_sector_count() | Raw whole-disk availability and geometry, not the current partition. |
disk_read(Lba,Count,Buffer), disk_write(Lba,Count,Buffer), disk_flush() | Return 0 or an EFI error status. Buffer must cover Count × sector size; validate disk bounds and buffer arithmetic yourself. |
#include <dos64_stdio.h>
#include <dos64_fs.h>
int __attribute__((ms_abi)) start(const DOS64_API *Api)
{
stdio_init(Api);
fs_init(Api);
FILE *File = fopen("README.TXT", "rb");
if (!File) {
printf("Open failed: %llx\n", Api->Fs.LastError());
return 1;
}
char Buffer[128];
unsigned long long Count = fread(Buffer, 1, sizeof(Buffer) - 1, File);
Buffer[Count] = '\0';
int Failed = ferror(File) != 0;
if (fclose(File) != 0) { Failed = 1; }
if (Failed) { puts("Read or close failed"); return 1; }
puts(Buffer);
return 0;
}
Time and pacing
dos64_time.h wraps Api->Time; call time_init(Api). Use monotonic time for durations and wall time only for dates.
| Interface | Contract |
|---|---|
time_ticks(), time_ticks_per_second() | Raw timing counter and its frequency; DOS64 uses calibrated TSC. |
time_ns(), time_us(), time_ms() | Unsigned 64-bit monotonic readings in the named units. |
time_delay_ns(Ns), time_delay_us(Us) | Busy-wait: no input polling or cooperative yield. Keep delays short; use Api->Sleep(Ms) for normal pacing. |
time_now(DOS64_DATETIME *Time) | 0 on success. Year, Month, Day, Hour, Minute, Second, Weekday (Sunday=0), Nanosecond. Firmware clock is interpreted as UTC; RTC resolution is one second. |
time_unix_ns(), time_unix() | Unix epoch nanoseconds or seconds; 0 if no clock. Nanosecond resolution is not nanosecond wall-clock accuracy: the RTC anchor can be about a second off. |
PCM audio and WAV files
dos64_audio.h supplies device output and a WAV helper. audio_init(Api) also initializes the filesystem wrapper. Check audio_present() before opening; audio is not a required default service.
| Interface | Contract |
|---|---|
audio_open(Rate), audio_stop(), audio_volume(Percent) | Open/restart at 44100 or 48000 Hz, returning 0 on success. Volume range is 0..100. Stop releases playback. |
audio_write(const short *Frames, Count) | Nonblocking signed 16-bit interleaved stereo. Count is stereo frames (two shorts each), not bytes. Returns accepted frames; retain and retry unwritten frames. |
audio_free_frames(), audio_queued_frames() | Ring-buffer space and pending playback. Unfilled space plays silence; wait cooperatively instead of spinning. |
wav_open(WAV *Wav,Path), wav_open_pcm(Wav,Samples,Frames,Rate) | 0 on success, -1 on invalid/unsupported source. Files support PCM 8/16/24-bit, mono/stereo, including PCM extensible format. PCM memory input borrows signed 16-bit stereo storage, which must outlive playback. |
wav_start(Wav), wav_pump(Wav) | Start returns 0/-1; output is 44100 for 44100 Hz sources, otherwise 48000, with linear resampling. Pump feeds nonblocking output: 0 still active, 1 fully played. It is not a complete error-status interface; inspect Wav->ReadFailed and file error state. |
wav_close(Wav), wav_save(Path,Frames,FrameCount,Rate) | Close the source file after stopping playback. Save writes a canonical PCM16 stereo WAV and returns 0/-1. |
WAV holds decode buffers, source metadata, and playback position. Keep it alive for the entire playback. Internal conversion helpers (wav_u16/u32, wav_next_frame, wav_generate) support the public lifecycle; applications normally do not call them directly.
Threads and synchronization
dos64_thread.h exposes cooperative, single-CPU scheduling, not preemptive parallel workers. Check thread_init(Api) == 0 for API 11 thread services or thread_sync_init(Api) == 0 for API 12 synchronization. Both validate table size and required pointers.
| Interface | Contract |
|---|---|
thread_start(Entry,Argument,StackBytes) | Returns DOS64_THREAD handle or 0 on failure; StackBytes=0 requests the default. Entry must be void *__attribute__((ms_abi)) worker(void *Argument). |
thread_pause(), thread_sleep_ms(Ms) | Yield or sleep so other workers can run. A loop that never yields/sleeps/waits can stall peers. |
thread_wait(Thread,void **Result), thread_current() | Join and collect the worker's returned pointer, or obtain current handle. Pass null Result to discard it. Join returns 0 on success. |
mutex_create(), mutex_destroy(Mutex), mutex_lock(Mutex), mutex_unlock(Mutex) | Creation returns handle or 0; operations return 0/-1. Use a mutex for shared state rather than relying on cooperative scheduling alone. |
condition_create/destroy, condition_wait(Condition,Mutex), condition_signal/broadcast | Creation returns handle or 0; other calls return 0/-1. Wait with the mutex held, and recheck the protected predicate in a loop after waking. |
Keep worker arguments and return storage alive until join completes. Do not destroy locks or conditions with active users. Finish and join workers before destroying their resources or returning from the application.
Bounded message queues
dos64_queue.h builds a fixed-size FIFO over API 12 mutexes and conditions. It copies items by value into caller-owned storage; pointers inside those items remain the application's responsibility.
| Interface | Contract |
|---|---|
queue_init(Queue,Api,Storage,Capacity,ItemBytes) | Zero-initialize DOS64_QUEUE; allocate at least Capacity × ItemBytes valid bytes. Initializes synchronization and returns a queue status. |
queue_send(Queue,Item), queue_receive(Queue,Item) | Block cooperatively while full/empty. Item points to one complete item; not a pointer-to-pointer unless the item itself is a pointer. |
queue_try_send, queue_try_receive | Do not wait for capacity/data; return WOULD_BLOCK when full/empty. They still use the internal mutex. |
queue_close(Queue) | Rejects new sends, wakes waiting peers, and allows receivers to drain buffered items before CLOSED. |
queue_destroy(Queue) | Close and join all users first. No new operation may race destruction. Keep storage alive until all operations and cleanup finish. |
Status constants: QUEUE_OK=0, QUEUE_CLOSED=1, QUEUE_WOULD_BLOCK=2, QUEUE_ERROR=-1. Do not interpret every nonzero result as the same error. queue_transfer and queue_error are implementation helpers, not separate services.
#include <dos64_queue.h>
int __attribute__((ms_abi)) start(const DOS64_API *Api)
{
DOS64_QUEUE Queue = {0};
unsigned int Storage[4], Sent = 42, Received = 0;
if (queue_init(&Queue, Api, Storage, 4, sizeof(Storage[0])) != QUEUE_OK) {
Api->Write("Queue initialization failed\n");
return 1;
}
int Failed = queue_try_send(&Queue, &Sent) != QUEUE_OK;
if (!Failed) {
Failed = queue_try_receive(&Queue, &Received) != QUEUE_OK;
if (!Failed && Received != Sent) { Failed = 1; }
}
if (queue_close(&Queue) != QUEUE_OK) { Failed = 1; }
if (queue_destroy(&Queue) != QUEUE_OK) { Failed = 1; }
if (Failed) { Api->Write("Queue operation failed\n"); }
return Failed;
}
Background audio stream
dos64_audio_stream.h combines the WAV decoder with a cooperative worker and command queue. It lets the application poll input and draw while playback is fed in bounded batches. It needs audio and API 12 thread/synchronization services.
| Interface | Contract |
|---|---|
wav_stream_start(WAV_STREAM *Stream,Api,WAV *Wav) | Zero-initialize Stream. Wav must have an opened file or PCM source. Returns 0/-1, initializes queue and worker, and opens audio. Only one audio owner is supported. |
wav_stream_status(Stream) | 0 running, 1 finished, -1 failed. Snapshot only: it does not yield. Sleep/yield in a status loop. |
wav_stream_stop(Stream) | Cancels if needed, joins the worker, stops audio, and destroys its queue. Returns 0/-1. Call even after normal completion; then close the WAV. |
Initialize audio, open the WAV, then start the stream. While status is 0, service input and sleep. After completion or user cancellation, stop/join the stream before wav_close. Retain the WAV, stream, and borrowed PCM storage throughout. If initialization fails, inspect the logged failure and do not query or stop an inactive stream. Internal wav_stream_worker is owned by the helper.
System status and compatibility
There is no separate system header: use dos64_api.h and the API 9+ Api->System table, checking table bounds first.
| Interface | Description |
|---|---|
System.Keyboard, System.Mouse | Device kinds: DOS64_DEVICE_NONE=0, USB=1, PS2=2, HOST=3, I2C=4. HOST indicates Windows-managed input. |
System.StorageDevices | Storage-device count on DOS64; accessible volume count on Windows. Do not assume identical host and bare-metal hardware semantics. |
System.DriveInfo(Index,&Info) | Returns 1 for an available entry and 0 if no entry is returned. DOS64_DRIVE_INFO contains Letter, Device[8], Partition, Writable, Current, SizeBytes. Windows reports Partition=0 when unknown. |
Troubleshooting: an unresolved Dos64Run usually means the import library is missing or ordered incorrectly; a missing dos64_entry means neither entry adapter was linked. A Windows DLL-load error needs the matching bmetal.dll. Negotiation failure means the requested runtime/API/services are unavailable: rebuild against compatible headers rather than bypassing checks. Missing audio is a supported capability outcome, not proof the whole runtime failed.
The Windows backend is a test host, not proof of device compatibility on DOS64. It uses host files and volumes, and does not expose a raw disk (Disk.Present is 0; sector operations return unsupported status). Keep application calls within the documented API, check every fallible operation, and verify on the actual DOS64 image before distributing a program.