libc: сплит «1 функция = 1 модуль» — вся библиотека, wildcard-сборка

- bios/conio/env/errno/gfx/io/mem/mouse/stdio/stdlib/string/sys/time/
  video разложены по модулям: общие статики и helpers — в internal
  _-модулях (_conio.h/_mouse.h/_gfx.h/_palette.h/_atexit.h/_time.h)
- lib/Makefile: LIBC_C = wildcard libc/*/*.c — гранулярность файлов
  = гранулярность DCE линкера
- эффект _CODE: gfx_text 6986→2568 Б, gfx_mous −1745, gfx_demo/d16
  −542; ранее timedir −3270, ls −3098, stattest −2995
- комментарии оставшихся модулей переведены на русский; puts: убран
  мёртвый pchars; videomode_raw разложен на get/set
- docs/libc-split-asm-cases.md — правила asm-связок между модулями;
  docs/libc-roadmap.md — план этапа
- восстановлен examples/mdview/SAMPLE.MD (нужен make floppy)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-06 16:08:58 +03:00
parent 46553f4e07
commit 4a081501d8
237 changed files with 4830 additions and 3933 deletions
+23
View File
@@ -0,0 +1,23 @@
/*
* _time.h — внутренние календарные хелперы для time()/gmtime()/mktime().
*
* НЕ публичный заголовок: живёт рядом с исходниками. Каждый хелпер —
* свой модуль (_tm_mdays.c/_tm_is_leap.c/_tm_year_days.c/_tm_month_days.c),
* чтобы приложение тянуло только те, которые реально вызывает.
*/
#ifndef _TIME_INTERNAL_H
#define _TIME_INTERNAL_H
/* Дней в месяце невисокосного года (Jan..Dec). */
extern const unsigned char _tm_mdays[12];
/* 1, если год високосный (по григорианскому календарю). */
int _tm_is_leap(unsigned int y);
/* Дней от 1970-01-01 до (y, 1, 1). */
unsigned long _tm_year_days(unsigned int y);
/* Дней от 1 января до начала месяца (месяц 1-based). */
unsigned int _tm_month_days(unsigned int y, unsigned int m);
#endif
+8
View File
@@ -0,0 +1,8 @@
/* _tm_is_leap — проверка високосности года (григорианский календарь). */
#include "_time.h"
int _tm_is_leap(unsigned int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
+8
View File
@@ -0,0 +1,8 @@
/* _tm_mdays — дней в месяце невисокосного года (Jan..Dec). Общая
* таблица для gmtime и _tm_month_days; модуль только с данными. */
#include "_time.h"
const unsigned char _tm_mdays[12] = {
31,28,31,30,31,30,31,31,30,31,30,31
};
+12
View File
@@ -0,0 +1,12 @@
/* _tm_month_days — дней от 1 января до начала месяца (месяц 1-based),
* с учётом високосности. */
#include "_time.h"
unsigned int _tm_month_days(unsigned int y, unsigned int m)
{
unsigned int d = 0;
for (unsigned int i = 0; i < m - 1; i++) d += _tm_mdays[i];
if (m > 2 && _tm_is_leap(y)) d++;
return d;
}
+11
View File
@@ -0,0 +1,11 @@
/* _tm_year_days — дней от 1970-01-01 до 1 января года y. */
#include "_time.h"
unsigned long _tm_year_days(unsigned int y)
{
unsigned long d = 0;
for (unsigned int i = 1970; i < y; i++)
d += _tm_is_leap(i) ? 366 : 365;
return d;
}
+27
View File
@@ -0,0 +1,27 @@
/* asctime — форматирует struct tm как "Day Mon DD HH:MM:SS YYYY\n"
* в статический буфер (перезаписывается следующим вызовом). */
#include <stdio.h>
#include <time.h>
static const char *const dnames[7] = {
"Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};
static const char *const mnames[12] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
/* "Day Mon DD HH:MM:SS YYYY\n" — 25 символов + NUL. */
static char asctime_buf[26];
char *asctime(struct tm *tm)
{
sprintf(asctime_buf, "%s %s %2d %02d:%02d:%02d %d\n",
dnames[tm->tm_wday % 7],
mnames[tm->tm_mon % 12],
tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec,
tm->tm_year + 1900);
return asctime_buf;
}
+8
View File
@@ -0,0 +1,8 @@
/* ctime — время эпохи одной строкой: asctime(localtime(timep)). */
#include <time.h>
char *ctime(time_t *timep)
{
return asctime(localtime(timep));
}
+49
View File
@@ -0,0 +1,49 @@
/*
* getdatetime — чтение RTC через ESTEX SYSTIME ($21).
*
* $21 SYSTIME → D=day E=month IX=year H=hour L=min B=sec C=dow
*
* Раскладка структуры (datetime_t, 8 байт):
* +0 day, +1 month, +2..3 year, +4 hour, +5 min, +6 sec, +7 dow
*
* Пишет прямо в *dt — без статического скретча. Ключевой трюк —
* `ex (sp), hl` после RST: в HL час:мин, на вершине стека dt —
* один байт меняет их местами, дальше идём по структуре через HL.
*/
#include <time.h>
void getdatetime(datetime_t *dt) __naked
{
(void)dt;
__asm
push ix ; save caller IX (BIOS clobbers it)
push hl ; stash dt across RST (clobbers HL)
ld c, #0x21 ; ESTEX SYSTIME
rst #0x10
;; Returns: D=day E=month IX=year H=hour L=min B=sec C=dow
;; ex (sp), hl: TOS<->HL. Now HL = dt, TOS = hour:min stash.
ex (sp), hl
ld (hl), d ; +0 day
inc hl
ld (hl), e ; +1 month
inc hl
push ix ; year stack
pop de ; DE = year
ld (hl), e ; +2 year low
inc hl
ld (hl), d ; +3 year high
inc hl
pop de ; D = hour, E = min (from earlier ex(sp))
ld (hl), d ; +4 hour
inc hl
ld (hl), e ; +5 min
inc hl
ld (hl), b ; +6 sec
inc hl
ld (hl), c ; +7 dow
pop ix ; restore caller IX
ret
__endasm;
}
+44
View File
@@ -0,0 +1,44 @@
/*
* gmtime — разложить секунды эпохи в struct tm.
*
* localtime и gmtime делят один статический буфер — при необходимости
* пережить следующий вызов клиент копирует результат (поведение POSIX).
* Таймзон нет: localtime() просто вызывает gmtime().
*/
#include <time.h>
#include "_time.h"
static struct tm tm_buf;
struct tm *gmtime(time_t *timep)
{
unsigned long sec = *timep;
tm_buf.tm_sec = (unsigned char)(sec % 60); sec /= 60;
tm_buf.tm_min = (unsigned char)(sec % 60); sec /= 60;
tm_buf.tm_hour = (unsigned char)(sec % 24); sec /= 24;
/* sec теперь — дни с 1970-01-01 (четверг). */
tm_buf.tm_wday = (unsigned char)((4 + sec) % 7);
/* подобрать год */
unsigned int y = 1970;
unsigned long days = sec;
while (days >= (unsigned long)(_tm_is_leap(y) ? 366 : 365)) {
days -= _tm_is_leap(y) ? 366 : 365;
y++;
}
tm_buf.tm_year = (int)y - 1900;
tm_buf.tm_yday = (int)days;
/* подобрать месяц/день */
unsigned int m = 0;
while (m < 12) {
unsigned int dim = _tm_mdays[m] + ((m == 1) && _tm_is_leap(y) ? 1u : 0u);
if (days < dim) break;
days -= dim;
m++;
}
tm_buf.tm_mon = (unsigned char)m;
tm_buf.tm_mday = (unsigned char)(days + 1);
tm_buf.tm_isdst = 0;
tm_buf.tm_hundredth = 0;
return &tm_buf;
}
+8
View File
@@ -0,0 +1,8 @@
/* localtime — идентичен gmtime: таймзоны на Sprinter не поддержаны. */
#include <time.h>
struct tm *localtime(time_t *timep)
{
return gmtime(timep);
}
+22
View File
@@ -0,0 +1,22 @@
/* mktime — struct tm → секунды Unix-эпохи (без таймзон/DST).
* Попутно заполняет tm_wday/tm_yday, чтобы клиент мог их читать. */
#include <time.h>
#include "_time.h"
time_t mktime(struct tm *tm)
{
unsigned int y = (unsigned int)(tm->tm_year + 1900);
unsigned long days = _tm_year_days(y)
+ _tm_month_days(y, (unsigned int)tm->tm_mon + 1)
+ (unsigned int)(tm->tm_mday - 1);
time_t epoch = days * 86400UL
+ (unsigned long)tm->tm_hour * 3600UL
+ (unsigned long)tm->tm_min * 60UL
+ tm->tm_sec;
/* Дозаполнить wday/yday для клиента. */
tm->tm_wday = (unsigned char)((4 + days) % 7);
tm->tm_yday = (int)_tm_month_days(y, (unsigned int)tm->tm_mon + 1)
+ (tm->tm_mday - 1);
return epoch;
}
-143
View File
@@ -1,143 +0,0 @@
/*
* posix_time.c — minimal POSIX <time.h> implementation on top of
* getdatetime() (ESTEX SYSTIME $21).
*
* SDCC's z80.lib bundles time/localtime/mktime AND _RtcRead in a
* single time.rel module, so the user can't override _RtcRead from a
* separate object — overriding triggers a "multiple definition"
* linker error. We sidestep that by implementing the whole POSIX time
* API ourselves; the linker then never pulls SDCC's time.rel.
*
* The epoch is Unix (1970-01-01 00:00:00). No timezone support —
* gmtime and localtime are identical. No DST.
*/
#include <stdio.h>
#include <time.h>
static const unsigned char mdays[12] = {
31,28,31,30,31,30,31,31,30,31,30,31
};
static const char *const dnames[7] = {
"Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};
static const char *const mnames[12] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
static int is_leap(unsigned int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
/* Days elapsed from 1970-01-01 to (y, 1, 1). */
static unsigned long year_days(unsigned int y)
{
unsigned long d = 0;
for (unsigned int i = 1970; i < y; i++)
d += is_leap(i) ? 366 : 365;
return d;
}
/* Days from Jan 1 to month start (1-based month input). */
static unsigned int month_days(unsigned int y, unsigned int m)
{
unsigned int d = 0;
for (unsigned int i = 0; i < m - 1; i++) d += mdays[i];
if (m > 2 && is_leap(y)) d++;
return d;
}
time_t time(time_t *t)
{
datetime_t dt;
getdatetime(&dt);
unsigned long days = year_days(dt.year)
+ month_days(dt.year, dt.month)
+ (dt.day - 1);
time_t epoch = days * 86400UL
+ (unsigned long)dt.hour * 3600UL
+ (unsigned long)dt.minute * 60UL
+ dt.second;
if (t) *t = epoch;
return epoch;
}
/* localtime and gmtime share one static buffer — caller copies if
* needed across further calls (matches POSIX behaviour). */
static struct tm tm_buf;
struct tm *gmtime(time_t *timep)
{
unsigned long sec = *timep;
tm_buf.tm_sec = (unsigned char)(sec % 60); sec /= 60;
tm_buf.tm_min = (unsigned char)(sec % 60); sec /= 60;
tm_buf.tm_hour = (unsigned char)(sec % 24); sec /= 24;
/* sec is now days since 1970-01-01 (Thursday). */
tm_buf.tm_wday = (unsigned char)((4 + sec) % 7);
/* find year */
unsigned int y = 1970;
unsigned long days = sec;
while (days >= (unsigned long)(is_leap(y) ? 366 : 365)) {
days -= is_leap(y) ? 366 : 365;
y++;
}
tm_buf.tm_year = (int)y - 1900;
tm_buf.tm_yday = (int)days;
/* find month/day */
unsigned int m = 0;
while (m < 12) {
unsigned int dim = mdays[m] + ((m == 1) && is_leap(y) ? 1u : 0u);
if (days < dim) break;
days -= dim;
m++;
}
tm_buf.tm_mon = (unsigned char)m;
tm_buf.tm_mday = (unsigned char)(days + 1);
tm_buf.tm_isdst = 0;
tm_buf.tm_hundredth = 0;
return &tm_buf;
}
struct tm *localtime(time_t *timep)
{
return gmtime(timep); /* no timezone */
}
time_t mktime(struct tm *tm)
{
unsigned int y = (unsigned int)(tm->tm_year + 1900);
unsigned long days = year_days(y)
+ month_days(y, (unsigned int)tm->tm_mon + 1)
+ (unsigned int)(tm->tm_mday - 1);
time_t epoch = days * 86400UL
+ (unsigned long)tm->tm_hour * 3600UL
+ (unsigned long)tm->tm_min * 60UL
+ tm->tm_sec;
/* Backfill wday/yday so callers can inspect them. */
tm->tm_wday = (unsigned char)((4 + days) % 7);
tm->tm_yday = (int)month_days(y, (unsigned int)tm->tm_mon + 1)
+ (tm->tm_mday - 1);
return epoch;
}
/* "Day Mon DD HH:MM:SS YYYY\n" — 25 chars + NUL. */
static char asctime_buf[26];
char *asctime(struct tm *tm)
{
sprintf(asctime_buf, "%s %s %2d %02d:%02d:%02d %d\n",
dnames[tm->tm_wday % 7],
mnames[tm->tm_mon % 12],
tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec,
tm->tm_year + 1900);
return asctime_buf;
}
char *ctime(time_t *timep)
{
return asctime(localtime(timep));
}
+50
View File
@@ -0,0 +1,50 @@
/*
* setdatetime — запись RTC через ESTEX SETTIME ($22).
*
* $22 SETTIME D=day E=month IX=year H=hour L=min B=sec → CF=err / A=errcode
*
* Читает прямо из *dt — без статического скретча. IX используется как
* указатель на структуру (перед RST перезагружается годом — так ждёт
* SETTIME). Возврат: 0 или -1 + errno.
*/
#include <time.h>
#include <errno.h>
int setdatetime(const datetime_t *dt) __naked
{
(void)dt;
__asm
push ix ; save caller IX
push hl
pop ix ; IX = dt
ld d, (hl) ; +0 D = day
inc hl
ld e, (hl) ; +1 E = month
inc hl
ld c, (hl) ; +2 year low
inc hl
ld b, (hl) ; +3 year high (BC->IX)
inc hl
push bc
ld b, (hl) ; +4 H = hour
inc hl
ld c, (hl) ; +5 L = min (BC->HL)
inc hl
push bc
ld b, (hl) ; +6 B = sec
pop hl
pop ix
ld c, #0x22 ; ESTEX SETTIME
rst #0x10
pop ix ; restore caller IX
jr c, _st_err2
ld de, #0
ret
_st_err2:
call __errno_set
ld de, #-1
ret
__endasm;
}
+9 -9
View File
@@ -1,12 +1,12 @@
/*
* sleep — block for N seconds using the 50 Hz frame interrupt.
* sleep — заблокироваться на N секунд по кадровому прерыванию 50 Гц.
*
* Sprinter ISR fires 50 times per second. `halt` parks the CPU until
* the next IRQ, so 50 halts = ~1 second of wall clock. This is the
* same trick solid-c uses in IO.ASM:285.
* ISR Sprinter срабатывает 50 раз в секунду. `halt` паркует CPU до
* следующего IRQ, так что 50 halt'ов = ~1 секунда стенного времени.
* Тот же трюк, что у solid-c в IO.ASM:285.
*
* Note: requires interrupts to be enabled (they are by default — ESTEX
* sets up IM 1 with the frame ISR before our program runs).
* Замечание: требует включённых прерываний (по умолчанию включены —
* ESTEX настраивает IM 1 с кадровым ISR до запуска нашей программы).
*/
#include <unistd.h>
@@ -16,11 +16,11 @@ void sleep(unsigned int seconds) __naked
(void)seconds;
__asm
inter:
;; HL = seconds on entry (SDCC single int arg).
;; HL = seconds на входе (единственный int-аргумент SDCC).
ld a, h
or a, l
ret Z ; sleep(0) return immediately
ld b, #50 ; 50 halts per second (50 Hz interrupt)
ret Z ; sleep(0) вернуться сразу
ld b, #50 ; 50 halt-ов на секунду (50 Гц)
inner:
halt
djnz inner
+21 -84
View File
@@ -1,93 +1,30 @@
/*
* time.cgetdatetime / setdatetime via ESTEX SYSTIME ($21) / SETTIME ($22).
* time — текущие секунды Unix-эпохи из RTC (getdatetime / ESTEX
* SYSTIME $21).
*
* $21 SYSTIME → D=day E=month IX=year H=hour L=min B=sec C=dow
* $22 SETTIME D=day E=month IX=year H=hour L=min B=sec → CF=err / A=errcode
* SDCC-шная z80.lib кладёт time/localtime/mktime И _RtcRead в один
* модуль time.rel, так что _RtcRead нельзя переопределить из
* отдельного объектника — будет "multiple definition". Обходим это,
* реализуя весь POSIX time API сами; тогда линкер никогда не тянет
* SDCC-шный time.rel.
*
* Struct layout (datetime_t, 8 bytes):
* +0 day, +1 month, +2..3 year, +4 hour, +5 min, +6 sec, +7 dow
*
* Both routines write/read *dt directly — no static scratch. The key
* trick in getdatetime is `ex (sp), hl` after RST: HL holds hour:min,
* stack TOS holds dt — one byte swaps them, then we walk the struct
* via HL. setdatetime uses IX as the struct pointer (re-loaded with
* year just before RST since that's what SETTIME expects).
* Эпоха — Unix (1970-01-01 00:00:00). Без таймзон и DST.
*/
#include <time.h>
#include <errno.h>
#include "_time.h"
void getdatetime(datetime_t *dt) __naked
time_t time(time_t *t)
{
(void)dt;
__asm
push ix ; save caller IX (BIOS clobbers it)
push hl ; stash dt across RST (clobbers HL)
ld c, #0x21 ; ESTEX SYSTIME
rst #0x10
;; Returns: D=day E=month IX=year H=hour L=min B=sec C=dow
;; ex (sp), hl: TOS<->HL. Now HL = dt, TOS = hour:min stash.
ex (sp), hl
ld (hl), d ; +0 day
inc hl
ld (hl), e ; +1 month
inc hl
push ix ; year stack
pop de ; DE = year
ld (hl), e ; +2 year low
inc hl
ld (hl), d ; +3 year high
inc hl
pop de ; D = hour, E = min (from earlier ex(sp))
ld (hl), d ; +4 hour
inc hl
ld (hl), e ; +5 min
inc hl
ld (hl), b ; +6 sec
inc hl
ld (hl), c ; +7 dow
pop ix ; restore caller IX
ret
__endasm;
}
int setdatetime(const datetime_t *dt) __naked
{
(void)dt;
__asm
push ix ; save caller IX
push hl
pop ix ; IX = dt
ld d, (hl) ; +0 D = day
inc hl
ld e, (hl) ; +1 E = month
inc hl
ld c, (hl) ; +2 year low
inc hl
ld b, (hl) ; +3 year high (BC->IX)
inc hl
push bc
ld b, (hl) ; +4 H = hour
inc hl
ld c, (hl) ; +5 L = min (BC->HL)
inc hl
push bc
ld b, (hl) ; +6 B = sec
pop hl
pop ix
ld c, #0x22 ; ESTEX SETTIME
rst #0x10
pop ix ; restore caller IX
jr c, _st_err2
ld de, #0
ret
_st_err2:
call __errno_set
ld de, #-1
ret
__endasm;
datetime_t dt;
getdatetime(&dt);
unsigned long days = _tm_year_days(dt.year)
+ _tm_month_days(dt.year, dt.month)
+ (dt.day - 1);
time_t epoch = days * 86400UL
+ (unsigned long)dt.hour * 3600UL
+ (unsigned long)dt.minute * 60UL
+ dt.second;
if (t) *t = epoch;
return epoch;
}