Porting #SF patch #565 Real Time Clock /CMOS fix (#4)

by Michele Giacomone

Detailed description:

  -Observed issues

   Due to some limitations only dates between 1980 and 2038 can be
   used in a reliable way.
   Also, bochs incorrectly assumes a linear correspondence between
   the data returned by the <time.h> functions localtime() and
   mktime(), and isn't setting the latter properly.
   Bochs keeps its internal time value dependent to these functions
   after setup, assuming that their internal settings won't change
   on the go - which is not the case.
   In my OS, and in my timezone, this leads to incorrect startup values
   for 5 months each year and unreliable values if the simulation is
   kept going for a long time. (a feedback between localtime() and
   mktime() is created which keeps shifting back the time)
   Also, the RTC simulation is not realistic since the clock fixes
   itself across DST changes, without updating any DST related flag,
   a behavior that no guest OS expects.

  -Proposed fix

   This is implemented in such way that no bochs' previous behavior
   is changed, a part from the broken ones, with legacy in mind
   == the user can keep using bochs exactly as before knowing nothing
      of this patch

   +Make the internal s.timeval variable a Bit64s, so it can fit all
    values that the cmos can correctly represent, reported below:
    MIN     setting  -62167219200 =>  0000/01/01 SAT  0:00:00
    MAX BCD setting  253402300799 =>  9999/12/31 FRI 23:59:59
    MAX BIN setting  745690751999 => 25599/12/31 FRI 23:59:59
    And then fix each reference to these so it can handle such values
    And make bochs correctly wrap around for under/overflows, so that
    only the most significant bits of the century are lost.

   +Do the same thing to the bochs time0 parameter, so all the above
    values can be chosen at startup (despite being now legal values,
    1 and 2 will still be treated as "local" and "utc"). Note that
    normally only BCD settings are valid since bochs' CMOS defaults
    to such operating mode - the only way to use the binary range
    is by loading a cmos memory map.

   +Make the internal s.timeval variable independent from external
    factors. This means providing a small set of time handling
    functions, contained in "iodev/utctime.h", which must work in
    any environment in which bochs compiles, accessing no external
    resource. This also means that after startup, s.timeval will only
    be changed internally, and no call to the OS time functions will
    be made.

   +Make the internal s.timeval variable timezone independent, to
    have a linear correlation between its values and valid CMOS
    settings. To make it easier, s.timeval is gonna be treated as
    if the current timezone was UTC: so,
     - if the user selects UTC as time0, s.timeval will become current
       time(NULL)
     - if the user selects localtime, s.timeval will be computed as
       the value which will display the same broken down time as
       localtime(&now)
     - if the user inputs a time formatted string the proper s.timeval
       to displayed will be easily calculated,
     - if the user inputs a starting time value, s.timeval will be
       computed as the value which will display the same broken down
       time as localtime(&user_input) to ensure the same operation as
       before.
    A "tz=utc" is displayed when bochs prints out the current time
    value, to warn users about the difference in meaning between the
    internally kept time value and the value they can set through
    the "time0=" parameter. This might be changed to communicate
    instead the time value they can input to get the same setting,
    but performing such calculation (except for the startup time)
    suffers from all the mktime()/localtime() problems listed above
    so I did not do it.
    The range of "time0" is automatically adjusted so all users in
    all time zones can set any legal value despite "time0=" having a
    local meaning.

  A thorough explanation of what I did and why can be found in the
  "iodev/utctime.h" library header.

---------

Co-authored-by: Stanislav Shwartsman <sshwarts@users.sourceforge.net>
Co-authored-by: Volker Ruppert <Volker.Ruppert@t-online.de>
This commit is contained in:
Stanislav Shwartsman 2023-12-01 23:55:35 +02:00 committed by GitHub
parent 4de6c097a4
commit ffc722f4e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 505 additions and 143 deletions

7
.gitignore vendored
View File

@ -37,6 +37,13 @@ bochs-msvc-src.zip
# /bochs/bios/
/bochs/bios/Makefile
/bochs/bios/_rombios*_.c
/bochs/bios/biossums
/bochs/bios/rombios*.s
/bochs/bios/rombios*.sym
/bochs/bios/rombios*.txt
/bochs/bios/rombios*.bin
/bochs/bios/rombios32.out
# /bochs/build/linux/
/bochs/build/linux/DOC-linux.html

Binary file not shown.

Binary file not shown.

View File

@ -1,4 +1,4 @@
# Copyright (C) 2001-2020 The Bochs Project
# Copyright (C) 2001-2023 The Bochs Project
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
@ -45,8 +45,9 @@ IASL = @IASL@
BX_INCDIRS = -I.. -I$(srcdir)/.. -I../iodev -I$(srcdir)/../iodev
LOCAL_CXXFLAGS =
UPSTREAM_RELEASE_DATE = $(shell grep "Updated:" ../README | sed 's/Updated://')
BUILDDATE = `date -u -d '$(UPSTREAM_RELEASE_DATE)' '+%m/%d/%y'`
# UPSTREAM_RELEASE_DATE = $(shell grep "Updated:" ../README | sed 's/Updated://')
# BUILDDATE = `date -u -d '$(UPSTREAM_RELEASE_DATE)' '+%m/%d/%y'`
BUILDDATE = `date -u '+%m/%d/%y'`
BIOS_BUILD_DATE = "-DBIOS_BUILD_DATE=\"$(BUILDDATE)\""
#
# -------- end configurable options --------------------------

View File

@ -2,7 +2,7 @@
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001-2021 The Bochs Project
// Copyright (C) 2001-2023 The Bochs Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
@ -573,6 +573,12 @@ typedef unsigned long Bit32u;
shr ebx, #16
ret
imodu:
div bl
mov al, ah
xor ah, ah
ret
ASM_END
// for access to RAM area which is used by interrupt vectors
@ -841,6 +847,8 @@ static Bit16u inw();
static void outw();
static void init_rtc();
static bx_bool rtc_updating();
static Bit8u bin2bcd();
static Bit8u bcd2bin();
static Bit8u _read_byte();
static Bit16u _read_word();
@ -928,7 +936,7 @@ Bit16u cdrom_boot();
#endif // BX_ELTORITO_BOOT
static char bios_svn_version_string[] = "$Revision$ $Date$";
// static char bios_svn_version_string[] = "$Revision$ $Date$";
#define BIOS_COPYRIGHT_STRING "(c) 2001-2021 The Bochs Project"
@ -1255,6 +1263,51 @@ rtc_updating()
return(1); // update-in-progress never transitioned to 0
}
Bit8u
bin2bcd(value)
Bit8u value;
{
ASM_START
push bp
mov bp, sp
push dx
mov dh, ah
xor ah, ah
mov al, 4[bp]
mov dl, #10
div dl
shl al, #4
add al, ah
mov ah, dh
pop dx
pop bp
ASM_END
}
Bit8u
bcd2bin(value)
Bit8u value;
{
ASM_START
push bp
mov bp, sp
push dx
mov al, 4[bp]
mov dh, al
and dh, #0x0f
shr al, #4
mov dl, #10
mul dl
add al, dh
pop dx
pop bp
ASM_END
}
#define read_byte(seg, offset) _read_byte(offset, seg)
Bit8u
@ -2011,8 +2064,7 @@ void s3_resume_panic()
void
print_bios_banner()
{
printf(BX_APPNAME" BIOS - build: %s\n%s\nOptions: ",
BIOS_BUILD_DATE, bios_svn_version_string);
printf(BX_APPNAME" BIOS - build: %s\nOptions: ", BIOS_BUILD_DATE);
printf(
#if BX_APM
"apmbios "
@ -2264,7 +2316,7 @@ log_bios_start()
#if BX_DEBUG_SERIAL
outb(BX_DEBUG_PORT+UART_LCR, 0x03); /* setup for serial logging: 8N1 */
#endif
BX_INFO("%s\n", bios_svn_version_string);
BX_INFO("BIOS BUILD DATE: %s\n", BIOS_BUILD_DATE);
}
bx_bool
@ -8461,7 +8513,7 @@ int1a_function(regs, ds, iret_addr)
Bit16u ds; // previous DS:, DS set to 0x0000 by asm wrapper
iret_addr_t iret_addr; // CS,IP,Flags pushed from original INT call
{
Bit8u val8;
Bit8u val8,hr;
BX_DEBUG_INT1A("int1a: AX=%04x BX=%04x CX=%04x DX=%04x DS=%04x\n", regs.u.r16.ax, regs.u.r16.bx, regs.u.r16.cx, regs.u.r16.dx, ds);
@ -8506,10 +8558,24 @@ int1a_function(regs, ds, iret_addr)
break;
}
regs.u.r8.dh = inb_cmos(0x00); // Seconds
regs.u.r8.cl = inb_cmos(0x02); // Minutes
regs.u.r8.ch = inb_cmos(0x04); // Hours
regs.u.r8.dl = inb_cmos(0x0b) & 0x01; // Stat Reg B
val8 = inb_cmos(0x0b);
if(val8&0x04){
regs.u.r8.dh = bin2bcd(inb_cmos(0x00)); // Seconds
regs.u.r8.cl = bin2bcd(inb_cmos(0x02)); // Minutes
hr = inb_cmos(0x04);
if(!(val8&0x02)&&(hr&0x80)) hr = (hr & 0x7f) + 12;
if(!(val8&0x02)&&(!(hr%12))) hr -= 12;
regs.u.r8.ch = bin2bcd(hr); // Hours
}else{
regs.u.r8.dh = inb_cmos(0x00); // Seconds
regs.u.r8.cl = inb_cmos(0x02); // Minutes
hr = inb_cmos(0x04);
if(!(val8&0x02)&&(hr&0x80)) hr = (hr & 0x7f) + 0x12;
if(!(val8&0x02)&&(!(hr%0x12))) hr -= 0x12;
regs.u.r8.ch = hr; // Hours
}
regs.u.r8.dl = val8 & 0x01; // Stat Reg B
regs.u.r8.ah = 0;
regs.u.r8.al = regs.u.r8.ch;
ClearCF(iret_addr.flags); // OK
@ -8530,11 +8596,29 @@ int1a_function(regs, ds, iret_addr)
init_rtc();
// fall through as if an update were not in progress
}
outb_cmos(0x00, regs.u.r8.dh); // Seconds
outb_cmos(0x02, regs.u.r8.cl); // Minutes
outb_cmos(0x04, regs.u.r8.ch); // Hours
val8 = inb_cmos(0x0b);
if(val8 & 0x04){
hr = bcd2bin(regs.u.r8.ch);
if(!(val8&0x02)&&(hr>=12)) hr |= 0x80;
if(!(val8&0x02)&&(hr>12)) hr -= 12;
if(!(val8&0x02)&&(hr==00)) hr = 12;
outb_cmos(0x00, bcd2bin(regs.u.r8.dh)); // Seconds
outb_cmos(0x02, bcd2bin(regs.u.r8.cl)); // Minutes
outb_cmos(0x04, hr); // Hours
}else{
hr = regs.u.r8.ch;
if(!(val8&0x02)&&(hr>=0x12)) hr |= 0x80;
if(!(val8&0x02)&&(hr>0x12)) hr -= 0x12;
if(!(val8&0x02)&&(hr==0x00)) hr = 0x12;
outb_cmos(0x00, regs.u.r8.dh); // Seconds
outb_cmos(0x02, regs.u.r8.cl); // Minutes
outb_cmos(0x04, hr); // Hours
}
// Set Daylight Savings time enabled bit to requested value
val8 = (inb_cmos(0x0b) & 0x60) | 0x02 | (regs.u.r8.dl & 0x01);
val8 = (val8 & 0x66) | (regs.u.r8.dl & 0x01);
// (reg B already selected)
outb_cmos(0x0b, val8);
regs.u.r8.ah = 0;
@ -8548,10 +8632,21 @@ int1a_function(regs, ds, iret_addr)
SetCF(iret_addr.flags);
break;
}
regs.u.r8.cl = inb_cmos(0x09); // Year
regs.u.r8.dh = inb_cmos(0x08); // Month
regs.u.r8.dl = inb_cmos(0x07); // Day of Month
regs.u.r8.ch = inb_cmos(0x32); // Century
val8 = inb_cmos(0x0b);
if(val8 & 0x04){
regs.u.r8.cl = bin2bcd(inb_cmos(0x09)); // Year
regs.u.r8.dh = bin2bcd(inb_cmos(0x08)); // Month
regs.u.r8.dl = bin2bcd(inb_cmos(0x07)); // Day of Month
regs.u.r8.ch = bin2bcd(inb_cmos(0x32)); // Century
}else{
regs.u.r8.cl = inb_cmos(0x09); // Year
regs.u.r8.dh = inb_cmos(0x08); // Month
regs.u.r8.dl = inb_cmos(0x07); // Day of Month
regs.u.r8.ch = inb_cmos(0x32); // Century
}
regs.u.r8.al = regs.u.r8.ch;
ClearCF(iret_addr.flags); // OK
break;
@ -8572,11 +8667,21 @@ int1a_function(regs, ds, iret_addr)
SetCF(iret_addr.flags);
break;
}
outb_cmos(0x09, regs.u.r8.cl); // Year
outb_cmos(0x08, regs.u.r8.dh); // Month
outb_cmos(0x07, regs.u.r8.dl); // Day of Month
outb_cmos(0x32, regs.u.r8.ch); // Century
val8 = inb_cmos(0x0b) & 0x7f; // clear halt-clock bit
val8=inb_cmos(0x0b);
if(val8&0x04){
outb_cmos(0x09, bcd2bin(regs.u.r8.cl)); // Year
outb_cmos(0x08, bcd2bin(regs.u.r8.dh)); // Month
outb_cmos(0x07, bcd2bin(regs.u.r8.dl)); // Day of Month
outb_cmos(0x32, bcd2bin(regs.u.r8.ch)); // Century
}else{
outb_cmos(0x09, regs.u.r8.cl); // Year
outb_cmos(0x08, regs.u.r8.dh); // Month
outb_cmos(0x07, regs.u.r8.dl); // Day of Month
outb_cmos(0x32, regs.u.r8.ch); // Century
}
val8 = val8 & 0x7f; // clear halt-clock bit
outb_cmos(0x0b, val8);
regs.u.r8.ah = 0;
regs.u.r8.al = val8; // AL = val last written to Reg B
@ -8605,9 +8710,23 @@ int1a_function(regs, ds, iret_addr)
init_rtc();
// fall through as if an update were not in progress
}
outb_cmos(0x01, regs.u.r8.dh); // Seconds alarm
outb_cmos(0x03, regs.u.r8.cl); // Minutes alarm
outb_cmos(0x05, regs.u.r8.ch); // Hours alarm
if(val8&0x04){
hr = bcd2bin(regs.u.r8.ch);
outb_cmos(0x01, bcd2bin(regs.u.r8.dh)); // Seconds alarm
outb_cmos(0x03, bcd2bin(regs.u.r8.cl)); // Minutes alarm
if((val8&0x02)&&(hr>=12)) hr |= 0x80;
if((val8&0x02)&&(hr==00)) hr = 12;
outb_cmos(0x05, hr); // Hours alarm
}else{
hr = regs.u.r8.ch;
outb_cmos(0x01, regs.u.r8.dh); // Seconds alarm
outb_cmos(0x03, regs.u.r8.cl); // Minutes alarm
if((val8&0x02)&&(hr>=0x12)) hr |= 0x80;
if((val8&0x02)&&(hr==0x00)) hr = 0x12;
outb_cmos(0x05, hr); // Hours alarm
}
outb(PORT_PIC2_DATA, inb(PORT_PIC2_DATA) & 0xfe); // enable IRQ 8
// enable Status Reg B alarm bit, clear halt clock bit
outb_cmos(0x0b, (val8 & 0x7f) | 0x20);

View File

@ -984,6 +984,27 @@ void bx_init_options()
// clock & cmos options
static const char *clock_sync_names[] = { "none", "realtime", "slowdown", "both", NULL };
Bit64s mintime,maxtime;
struct tm mtim,xtim;
mtim.tm_year =0000 -1900;
mtim.tm_mon = 1 - 1;
mtim.tm_mday = 1 ;
mtim.tm_hour = 00 ;
mtim.tm_min = 00 ;
mtim.tm_sec = 00 ;
mtim.tm_isdst = -1 ;
xtim.tm_year =9999 -1900;
xtim.tm_mon = 12 - 1;
xtim.tm_mday = 31 ;
xtim.tm_hour = 23 ;
xtim.tm_min = 59 ;
xtim.tm_sec = 59 ;
xtim.tm_isdst = -1 ;
mintime=mktime(&mtim); //Find which epoch corresponds to the upper limit expressed in local time
maxtime=mktime(&xtim); //Find which epoch corresponds to the lower limit expressed in local time
bx_param_enum_c *clock_sync = new bx_param_enum_c(clock_cmos,
"clock_sync", "Synchronisation method",
@ -995,7 +1016,7 @@ void bx_init_options()
"time0",
"Initial CMOS time for Bochs\n(1:localtime, 2:utc, other:time in seconds)",
"Initial time for Bochs CMOS clock, used if you really want two runs to be identical",
0, BX_MAX_BIT32U,
mintime, maxtime,
BX_CLOCK_TIME0_LOCAL);
bx_param_bool_c *rtc_sync = new bx_param_bool_c(clock_cmos,
"rtc_sync", "Sync RTC speed with realtime",
@ -1025,7 +1046,7 @@ void bx_init_options()
deplist->add(rtc_init);
use_cmosimage->set_dependent_list(deplist);
time0->set_ask_format("Enter Initial CMOS time (1:localtime, 2:utc, other:time in seconds): [%d] ");
time0->set_ask_format("Enter Initial CMOS time (1:localtime, 2:utc, other:time in seconds): [" FMT_LL "d] ");
clock_sync->set_ask_format("Enter Synchronisation method: [%s] ");
clock_cmos->set_options(clock_cmos->SHOW_PARENT);
cmosimage->set_options(cmosimage->SHOW_PARENT);
@ -3107,9 +3128,9 @@ static int parse_line_formatted(const char *context, int num_params, char *param
for (i=1; i<num_params; i++) {
if (!strncmp(params[i], "file=", 5)) {
SIM->get_param_string(BXPN_CMOSIMAGE_PATH)->set(&params[i][5]);
} else if (!strcmp(params[i], "rtc_init=time0")) {
} else if (!strncmp(params[i], "rtc_init=time0",14)) {
SIM->get_param_bool(BXPN_CMOSIMAGE_RTC_INIT)->set(0);
} else if (!strcmp(params[i], "rtc_init=image")) {
} else if (!strncmp(params[i], "rtc_init=image",14)) {
SIM->get_param_bool(BXPN_CMOSIMAGE_RTC_INIT)->set(1);
} else {
BX_ERROR(("%s: unknown parameter for cmosimage ignored.", context));
@ -3139,17 +3160,19 @@ static int parse_line_formatted(const char *context, int num_params, char *param
else if (!strncmp(params[i], "time0=", 6)) {
if (isalpha(params[i][6])) {
memset(&tm_time, 0, sizeof(tm_time));
n = sscanf(&params[i][6], "%3s %3s%3d %2d:%2d:%2d %d", wday, mon, &tm_time.tm_mday,
n = sscanf(&params[i][6], "%3s %3s %2d %2d:%2d:%2d %d", wday, mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min, &tm_time.tm_sec, &year);
if ((n == 7) && (year >= 1980) && (strstr(months, mon) != NULL)) {
if ((n == 7) && (strstr(months, mon) != NULL)) {
tm_time.tm_year = year - 1900;
tm_time.tm_mon = 12 - ((int)strlen(strstr(months, mon)) / 4);
tm_time.tm_isdst = -1;
SIM->get_param_num(BXPN_CLOCK_TIME0)->set(mktime(&tm_time));
} else {
PARSE_ERR(("%s: time0 string format malformed.", context));
}
} else {
SIM->get_param_num(BXPN_CLOCK_TIME0)->set(atoi(&params[i][6]));
Bit64s tmptm=atol(&params[i][6]);
SIM->get_param_num(BXPN_CLOCK_TIME0)->set(tmptm);
}
}
else {
@ -3438,8 +3461,7 @@ int bx_write_clock_cmos_options(FILE *fp)
{
fprintf(fp, "clock: sync=%s", SIM->get_param_enum(BXPN_CLOCK_SYNC)->get_selected());
switch (SIM->get_param_num(BXPN_CLOCK_TIME0)->get()) {
case 0: break;
switch (SIM->get_param_num(BXPN_CLOCK_TIME0)->get64()) {
case BX_CLOCK_TIME0_LOCAL:
fprintf(fp, ", time0=local");
break;
@ -3447,7 +3469,7 @@ int bx_write_clock_cmos_options(FILE *fp)
fprintf(fp, ", time0=utc");
break;
default:
fprintf(fp, ", time0=%u", SIM->get_param_num(BXPN_CLOCK_TIME0)->get());
fprintf(fp, ", time0=" FMT_LL "d", SIM->get_param_num(BXPN_CLOCK_TIME0)->get64());
}
fprintf(fp, ", rtc_sync=%d\n", SIM->get_param_bool(BXPN_CLOCK_RTC_SYNC)->get());

View File

@ -138,8 +138,6 @@
#define BX_HAVE_SYS_MMAN_H 0
#define BX_HAVE_XPM_H 0
#define BX_HAVE_XRANDR_H 0
#define BX_HAVE_TIMELOCAL 0
#define BX_HAVE_GMTIME 0
#define BX_HAVE_MKTIME 0
#define BX_HAVE_TMPFILE64 0
#define BX_HAVE_FSEEK64 0

36
bochs/configure vendored
View File

@ -22106,42 +22106,6 @@ then :
fi
for ac_func in timelocal
do :
ac_fn_c_check_func "$LINENO" "timelocal" "ac_cv_func_timelocal"
if test "x$ac_cv_func_timelocal" = xyes
then :
printf "%s\n" "#define HAVE_TIMELOCAL 1" >>confdefs.h
printf "%s\n" "#define BX_HAVE_TIMELOCAL 1" >>confdefs.h
fi
done
for ac_func in gmtime
do :
ac_fn_c_check_func "$LINENO" "gmtime" "ac_cv_func_gmtime"
if test "x$ac_cv_func_gmtime" = xyes
then :
printf "%s\n" "#define HAVE_GMTIME 1" >>confdefs.h
printf "%s\n" "#define BX_HAVE_GMTIME 1" >>confdefs.h
fi
done
for ac_func in mktime
do :
ac_fn_c_check_func "$LINENO" "mktime" "ac_cv_func_mktime"
if test "x$ac_cv_func_mktime" = xyes
then :
printf "%s\n" "#define HAVE_MKTIME 1" >>confdefs.h
printf "%s\n" "#define BX_HAVE_MKTIME 1" >>confdefs.h
fi
done
# Check whether --enable-largefile was given.
if test ${enable_largefile+y}
then :

View File

@ -234,8 +234,6 @@ AC_CHECK_FUNCS(nanosleep, AC_DEFINE(BX_HAVE_NANOSLEEP))
AC_CHECK_FUNCS(abort, AC_DEFINE(BX_HAVE_ABORT))
AC_CHECK_MEMBER(struct sockaddr_in.sin_len, AC_DEFINE(BX_HAVE_SOCKADDR_IN_SIN_LEN), , [#include <sys/socket.h>
#include <netinet/in.h> ])
AC_CHECK_FUNCS(timelocal, AC_DEFINE(BX_HAVE_TIMELOCAL))
AC_CHECK_FUNCS(gmtime, AC_DEFINE(BX_HAVE_GMTIME))
AC_CHECK_FUNCS(mktime, AC_DEFINE(BX_HAVE_MKTIME))
dnl As of autoconf 2.53, the standard largefile test fails for Linux/gcc.

View File

@ -182,10 +182,10 @@ int ask_uint(const char *prompt, const char *help, Bit32u min, Bit32u max, Bit32
}
}
// identical to ask_uint, but uses signed comparisons
int ask_int(const char *prompt, const char *help, Bit32s min, Bit32s max, Bit32s the_default, Bit32s *out)
// Identical to ask_uint but uses 64 bits signed integers
int ask_int(const char *prompt, const char *help, Bit64s min, Bit64s max, Bit64s the_default, Bit64s *out)
{
int n = max + 1;
Bit64s n = max + 1;
char buffer[1024];
char *clean;
int illegal;
@ -202,12 +202,12 @@ int ask_int(const char *prompt, const char *help, Bit32s min, Bit32s max, Bit32s
}
if ((clean[0] == '?') && (strlen(help) > 0)) {
bx_printf("\n%s\n", help);
bx_printf("Your choice must be an integer between %u and %u.\n\n", min, max);
bx_printf("Your choice must be an integer between " FMT_LL "d and " FMT_LL "d.\n\n", min, max);
continue;
}
illegal = (1 != sscanf(buffer, "%d", &n));
illegal = (1 != sscanf(buffer, "%ld", &n));
if (illegal || n<min || n>max) {
bx_printf("Your choice (%s) was not an integer between %d and %d.\n\n",
bx_printf("Your choice (%s) was not an integer between " FMT_LL "d and " FMT_LL "d.\n\n",
clean, min, max);
} else {
// choice is okay
@ -616,7 +616,8 @@ void bx_log_options(int individual)
int done = 0;
while (!done) {
bx_print_log_action_table();
Bit32s id, level, action;
Bit64s id;
Bit32s level, action;
Bit32s maxid = SIM->get_n_log_modules();
if (ask_int(log_options_prompt1, "", -1, maxid-1, -1, &id) < 0)
return;
@ -864,11 +865,11 @@ void text_print(bx_param_c *param)
if (base == 16)
format = "%s: 0x%x";
else
format = "%s: %d";
format = "%s: %ld";
if (nparam->get_label()) {
bx_printf(format, nparam->get_label(), (Bit32s)nval);
bx_printf(format, nparam->get_label(), (Bit64s)nval);
} else {
bx_printf(format, nparam->get_name(), (Bit32s)nval);
bx_printf(format, nparam->get_name(), (Bit64s)nval);
}
}
}
@ -950,10 +951,18 @@ int text_ask(bx_param_c *param)
prompt = "Enter new value or '?' for help: [%d] ";
}
Bit32u n = nparam->get();
status = ask_uint(prompt, help, (Bit32u)nparam->get_min(),
Bit64s m = nparam->get64();
if(nparam->get_base() != 10){
status = ask_uint(prompt, help, (Bit32u)nparam->get_min(),
(Bit32u)nparam->get_max(), n, &n, nparam->get_base());
}else{
status = ask_int(prompt, help, (Bit64s)nparam->get_min(),
(Bit64s)nparam->get_max(), m, &m);
}
if (status < 0) return status;
nparam->set(n);
if(nparam->get_base() != 10) nparam->set(n);
else nparam->set(m);
}
break;
case BXT_PARAM_BOOL:

View File

@ -1,4 +1,4 @@
# Copyright (C) 2001-2021 The Bochs Project
# Copyright (C) 2001-2023 The Bochs Project
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
@ -200,7 +200,7 @@ cmos.o: cmos.@CPP_SUFFIX@ iodev.h ../bochs.h ../config.h ../osdep.h \
../misc/bswap.h ../plugin.h \
../extplugin.h ../param_names.h ../pc_system.h ../bx_debug/debug.h \
../config.h ../osdep.h ../memory/memory-bochs.h ../gui/siminterface.h \
../gui/gui.h cmos.h virt_timer.h
../gui/gui.h cmos.h virt_timer.h utctime.h
devices.o: devices.@CPP_SUFFIX@ iodev.h ../bochs.h ../config.h ../osdep.h \
../gui/paramtree.h ../logio.h \
../instrument/stubs/instrument.h ../misc/bswap.h ../plugin.h \
@ -371,7 +371,7 @@ cmos.lo: cmos.@CPP_SUFFIX@ iodev.h ../bochs.h ../config.h ../osdep.h \
../misc/bswap.h ../plugin.h \
../extplugin.h ../param_names.h ../pc_system.h ../bx_debug/debug.h \
../config.h ../osdep.h ../memory/memory-bochs.h ../gui/siminterface.h \
../gui/gui.h cmos.h virt_timer.h
../gui/gui.h cmos.h virt_timer.h utctime.h
devices.lo: devices.@CPP_SUFFIX@ iodev.h ../bochs.h ../config.h ../osdep.h \
../gui/paramtree.h ../logio.h \
../misc/bswap.h ../plugin.h \

View File

@ -2,7 +2,7 @@
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002-2021 The Bochs Project
// Copyright (C) 2002-2023 The Bochs Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
@ -27,6 +27,7 @@
#include "iodev.h"
#include "cmos.h"
#include "virt_timer.h"
#include "utctime.h"
#define LOG_THIS theCmosDevice->
@ -127,9 +128,9 @@ bx_cmos_c::~bx_cmos_c(void)
{
save_image();
char *tmptime;
if ((tmptime = strdup(ctime(&(BX_CMOS_THIS s.timeval)))) != NULL) {
if ((tmptime = strdup(ascutc(utctime(&(BX_CMOS_THIS s.timeval))))) != NULL) {
tmptime[strlen(tmptime)-1]='\0';
BX_INFO(("Last time is %u (%s)", (unsigned) get_timeval(), tmptime));
BX_INFO(("Last time: " FMT_LL "d tz=utc (%s)", get_timeval(), tmptime));
free(tmptime);
}
SIM->get_bochs_root()->remove("cmos");
@ -170,36 +171,26 @@ void bx_cmos_c::init(void)
244, 0, 0, "cmos"); // one-shot, not-active
}
if (SIM->get_param_num(BXPN_CLOCK_TIME0)->get() == BX_CLOCK_TIME0_LOCAL) {
if (SIM->get_param_num(BXPN_CLOCK_TIME0)->get64() == BX_CLOCK_TIME0_LOCAL) {
time_t tmptime;
struct tm *tmptm;;
BX_INFO(("Using local time for initial clock"));
BX_CMOS_THIS s.timeval = time(NULL);
} else if (SIM->get_param_num(BXPN_CLOCK_TIME0)->get() == BX_CLOCK_TIME0_UTC) {
bool utc_ok = 0;
tmptime = time(NULL); //Calculate which timeval will display the local time
tmptm = localtime(&tmptime);
BX_CMOS_THIS s.timeval = timeutc(pushtm(tmptm));
} else if (SIM->get_param_num(BXPN_CLOCK_TIME0)->get64() == BX_CLOCK_TIME0_UTC) {
BX_INFO(("Using utc time for initial clock"));
BX_CMOS_THIS s.timeval = time(NULL);
#if BX_HAVE_GMTIME
#if BX_HAVE_MKTIME
struct tm *utc_holder = gmtime(&BX_CMOS_THIS s.timeval);
utc_holder->tm_isdst = -1;
utc_ok = 1;
BX_CMOS_THIS s.timeval = mktime(utc_holder);
#elif BX_HAVE_TIMELOCAL
struct tm *utc_holder = gmtime(&BX_CMOS_THIS s.timeval);
utc_holder->tm_isdst = 0; // XXX Is this correct???
utc_ok = 1;
BX_CMOS_THIS s.timeval = timelocal(utc_holder);
#endif //BX_HAVE_MKTIME
#endif //BX_HAVE_GMTIME
if (!utc_ok) {
BX_ERROR(("UTC time is not supported on your platform. Using current time(NULL)"));
}
BX_CMOS_THIS s.timeval = (Bit64s)time(NULL);
} else {
Bit64s tmpintime;
struct tm *tmptmtime;
BX_INFO(("Using specified time for initial clock"));
BX_CMOS_THIS s.timeval = SIM->get_param_num(BXPN_CLOCK_TIME0)->get();
tmpintime = SIM->get_param_num(BXPN_CLOCK_TIME0)->get64();
tmptmtime = localtime(&tmpintime);
BX_CMOS_THIS s.timeval = timeutc(pushtm(tmptmtime));
}
// load CMOS from image file if requested.
@ -264,11 +255,11 @@ void bx_cmos_c::init(void)
}
char *tmptime;
while((tmptime = strdup(ctime(&(BX_CMOS_THIS s.timeval)))) == NULL) {
while((tmptime = strdup(ascutc(utctime(&(BX_CMOS_THIS s.timeval))))) == NULL) {
BX_PANIC(("Out of memory."));
}
tmptime[strlen(tmptime)-1]='\0';
BX_INFO(("Setting initial clock to: %s (time0=%u)", tmptime, (Bit32u)BX_CMOS_THIS s.timeval));
BX_INFO(("Setting initial clock to: %s tz=utc (time0=" FMT_LL "d)", tmptime, (Bit64s)BX_CMOS_THIS s.timeval));
free(tmptime);
BX_CMOS_THIS s.timeval_change = 0;
@ -442,8 +433,25 @@ void bx_cmos_c::write(Bit32u address, Bit32u value, unsigned io_len)
case REG_MIN_ALARM: // minutes alarm
case REG_HOUR_ALARM: // hours alarm
BX_CMOS_THIS s.reg[BX_CMOS_THIS s.cmos_mem_address] = value;
BX_DEBUG(("alarm time changed to %02x:%02x:%02x", BX_CMOS_THIS s.reg[REG_HOUR_ALARM],
BX_CMOS_THIS s.reg[REG_MIN_ALARM], BX_CMOS_THIS s.reg[REG_SEC_ALARM]));
if(BX_CMOS_THIS s.rtc_mode_12hour) {
if(BX_CMOS_THIS s.rtc_mode_binary) {
BX_DEBUG(("alarm time changed to %02u:%02u:%02u %s", BX_CMOS_THIS s.reg[REG_HOUR_ALARM] & 0x7F,
BX_CMOS_THIS s.reg[REG_MIN_ALARM], BX_CMOS_THIS s.reg[REG_SEC_ALARM],
(BX_CMOS_THIS s.reg[REG_HOUR_ALARM] & 0x80)?"pm":"am"));
} else {
BX_DEBUG(("alarm time changed to %02x:%02x:%02x %s", BX_CMOS_THIS s.reg[REG_HOUR_ALARM] & 0x7F,
BX_CMOS_THIS s.reg[REG_MIN_ALARM], BX_CMOS_THIS s.reg[REG_SEC_ALARM],
(BX_CMOS_THIS s.reg[REG_HOUR_ALARM] & 0x80)?"pm":"am"));
}
} else {
if(BX_CMOS_THIS s.rtc_mode_binary) {
BX_DEBUG(("alarm time changed to %02u:%02u:%02u", BX_CMOS_THIS s.reg[REG_HOUR_ALARM],
BX_CMOS_THIS s.reg[REG_MIN_ALARM], BX_CMOS_THIS s.reg[REG_SEC_ALARM]));
} else {
BX_DEBUG(("alarm time changed to %02x:%02x:%02x", BX_CMOS_THIS s.reg[REG_HOUR_ALARM],
BX_CMOS_THIS s.reg[REG_MIN_ALARM], BX_CMOS_THIS s.reg[REG_SEC_ALARM]));
}
}
break;
case REG_SEC: // seconds
@ -766,19 +774,20 @@ void bx_cmos_c::uip_timer()
void bx_cmos_c::update_clock()
{
struct tm *time_calendar;
struct utctm *time_calendar;
unsigned year, month, day, century;
Bit8u val_bcd, hour;
Bit64s mintvalset=-62167219200,maxtvalset[2]={253402300799, 745690751999};
time_calendar = localtime(& BX_CMOS_THIS s.timeval);
while(BX_CMOS_THIS s.timeval>maxtvalset[BX_CMOS_THIS s.rtc_mode_binary?1:0]) {BX_CMOS_THIS s.timeval-=(maxtvalset[BX_CMOS_THIS s.rtc_mode_binary?1:0]-mintvalset+1);}
while(BX_CMOS_THIS s.timeval<mintvalset) {BX_CMOS_THIS s.timeval+=(maxtvalset[BX_CMOS_THIS s.rtc_mode_binary?1:0]-mintvalset+1);}
time_calendar = utctime(& BX_CMOS_THIS s.timeval);
// update seconds
BX_CMOS_THIS s.reg[REG_SEC] = bin_to_bcd(time_calendar->tm_sec,
BX_CMOS_THIS s.rtc_mode_binary);
BX_CMOS_THIS s.reg[REG_SEC] = bin_to_bcd(time_calendar->tm_sec, BX_CMOS_THIS s.rtc_mode_binary);
// update minutes
BX_CMOS_THIS s.reg[REG_MIN] = bin_to_bcd(time_calendar->tm_min,
BX_CMOS_THIS s.rtc_mode_binary);
BX_CMOS_THIS s.reg[REG_MIN] = bin_to_bcd(time_calendar->tm_min, BX_CMOS_THIS s.rtc_mode_binary);
// update hours
if (BX_CMOS_THIS s.rtc_mode_12hour) {
@ -789,8 +798,7 @@ void bx_cmos_c::update_clock()
val_bcd |= bin_to_bcd(hour, BX_CMOS_THIS s.rtc_mode_binary);
BX_CMOS_THIS s.reg[REG_HOUR] = val_bcd;
} else {
BX_CMOS_THIS s.reg[REG_HOUR] = bin_to_bcd(time_calendar->tm_hour,
BX_CMOS_THIS s.rtc_mode_binary);
BX_CMOS_THIS s.reg[REG_HOUR] = bin_to_bcd(time_calendar->tm_hour, BX_CMOS_THIS s.rtc_mode_binary);
}
// update day of the week
@ -826,7 +834,8 @@ void bx_cmos_c::update_clock()
void bx_cmos_c::update_timeval()
{
struct tm time_calendar;
struct utctm time_calendar;
Bit16s val_yr;
Bit8u val_bin, pm_flag;
// update seconds
@ -862,14 +871,14 @@ void bx_cmos_c::update_timeval()
BX_CMOS_THIS s.rtc_mode_binary) - 1;
// update year
val_bin = bcd_to_bin(BX_CMOS_THIS s.reg[REG_IBM_CENTURY_BYTE],
val_yr = bcd_to_bin(BX_CMOS_THIS s.reg[REG_IBM_CENTURY_BYTE],
BX_CMOS_THIS s.rtc_mode_binary);
val_bin = (val_bin - 19) * 100;
val_bin += bcd_to_bin(BX_CMOS_THIS s.reg[REG_YEAR],
val_yr = (val_yr - 19) * 100;
val_yr += bcd_to_bin(BX_CMOS_THIS s.reg[REG_YEAR],
BX_CMOS_THIS s.rtc_mode_binary);
time_calendar.tm_year = val_bin;
time_calendar.tm_year = val_yr;
BX_CMOS_THIS s.timeval = mktime(& time_calendar);
BX_CMOS_THIS s.timeval = timeutc(& time_calendar);
}
#if BX_DEBUGGER

View File

@ -2,7 +2,7 @@
// $Id$
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002-2021 The Bochs Project
// Copyright (C) 2002-2023 The Bochs Project
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
@ -52,7 +52,7 @@ public:
virtual void set_reg(Bit8u reg, Bit32u val) {
s.reg[reg] = val;
}
virtual time_t get_timeval() {
virtual Bit64s get_timeval() {
return s.timeval;
}
virtual void enable_irq(bool enabled) {
@ -64,7 +64,7 @@ public:
Bit32u periodic_interval_usec;
int one_second_timer_index;
int uip_timer_index;
time_t timeval;
Bit64s timeval; //Changed this from time_t to Bit64s - this struct seems to not be referenced ouside of this class despite being public
Bit8u cmos_mem_address;
Bit8u cmos_ext_mem_addr;
bool timeval_change;
@ -80,6 +80,7 @@ public:
} s; // state information
private:
static Bit32u read_handler(void *this_ptr, Bit32u address, unsigned io_len);
static void write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len);
#if !BX_USE_CMOS_SMF

234
bochs/iodev/utctime.h Normal file
View File

@ -0,0 +1,234 @@
/////////////////////////////////////////////////////////////////////////
// $Id: utctime.h
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001-2023 The Bochs Project
//
// Portable gmtime()/timegm() clones by Michele Giacomone
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
/////////////////////////////////////////////////////////////////////////
#ifndef UTCTIME_H
#define UTCTIME_H
/*
I wanted a couple of functions that could mimic the behavior of localtime()/mktime() but being linear (no timezone or DST issues) and portable.
For convenience I wrote them so that they behave as if the local timezone was UTC, which means that my "localtime" function - which will be utctime() - must provide identical results as gmtime(), and my "mktime" function - which will be timeutc() - must act exactly as the non-standard function timegm() or mktime() called with TZ set to UTC.
This allows a more realistic rtc/cmos simulation since the internally kept time value can no longer bounce around due to external factors.
Also, by doing this, across every system, a given internal value will always mean the same time and date setting.
If the user selects the cmos to be set up with their local time, the calculated difference between the current epoch value and bochs internal value could be communicated to them in the "startup time" debug message. The same goes if they choose to specify an epoch value, since that has to be interpreted as the epoch value which would set their corresponding local time, to ensure compatibility with previous bochs' behavior. If the user selects to set the current UTC time value instead, the value returned by time(NULL) is already what needed.
A few considerations on operand sizes:
These are the contents of "struct tm":
tm_sec int seconds after the minute 0-61*
tm_min int minutes after the hour 0-59
tm_hour int hours since midnight 0-23
tm_mday int day of the month 1-31
tm_mon int months since January 0-11
tm_year int years since 1900
tm_wday int days since Sunday 0-6
tm_yday int days since January 1 0-365
tm_isdst int Daylight Saving Time flag
*60 in C11. Technically to account for leap seconds. Since they have the same epoch value as the (normal) following second, and my functions can treat out of range values correctly, I can safely assume 0-59.
I use Bit64s instead of time_t to represent the number of seconds since 1970-1-1 00:00:00 (which I just call "epoch") since the latter is not well defined, and 32bits won't fully cover dates that a human might want to input (==at least a few hundred years both ways).
I also need to redefine "struct tm" to protect against different "int" sizes. As said below, to get everything to work properly the size of its elements has to be less than the size of the epoch, but must allow all in-range values, so Bit32s and Bit16s are the options. I choose Bit16s since bochs can't handle years less than 0 or more than 25599 (valid values: -1900 to 23699, included).
The following will work if division does round towards zero.
Everything will operate correctly for all the valid (values in range, or convertible to in range values) struct tm settings.
Despite the fact that "invalid" (values out of range and not convertible to in range values) struct tm settings could be used to get otherwise unreachable epoch values through timeutc() (but the reverse operation through utctime() would not be allowed since it can only return in-range values), timeutc() has to return -1 to properly mimic timegm()/mktime(). I'm not too happy with this since -1 means a possibly useful date (last second of 1969), and a better value would have been (1<<63), so that can be changed in the future if this -1 behavior is not used by bochs.
With the above considerations I tested that:
utctime() supports all values that can be converted to a VALID struct configuration (as gmtime() does):
MIN utctime() value: -1036267257600 => -30868/01/01 FRI 0:00:00
MAX utctime() value: 1031849193599 => 34667/12/31 TUE 23:59:59
Values out of this range will not set anything and a NULL pointer will be returned.
timeutc() supports all the same values, making it the exact inverse of utctime():
MIN utctime() value: -1036267257600 => -30868/01/01 FRI 0:00:00
MAX utctime() value: 1031849193599 => 34667/12/31 TUE 23:59:59
Out of range or not set values will be fixed through a call to utcime() before returning.
Invalid struct settings will cause timeutc() to return -1 and the struct not to be set.
A utctime_ext() function is provided. It is identical to utctime() but allows to use an external structure (in fact, it is called by utctime() to set the globally available struct utctm).
An ascutc() function is provided. It serves as an ascitime() clone. It makes up a string with no additional checks.
A pushtm() function is provided. It's used to copy a struct tm into the struct uctm globally available.
Bochs current CMOS code can only handle properly the following range (Gregorian calendar):
MIN setting -62167219200 => 0/01/01 SAT 0:00:00
MAX BCD setting 253402300799 => 9999/12/31 FRI 23:59:59
MAX BIN setting 745690751999 => 25599/12/31 FRI 23:59:59
With binary mode only accessible by loading a cmos memory map file
Either way, settings out of the currently valid range must wrap around correctly, giving the impression of a simple overflow. Luckily the valid range starts on a Saturday and ends on a Friday.
The allowed epoch values could all fit in 40bits
*/
struct utctm {
Bit16s tm_sec; // seconds after the minute 0-59
Bit16s tm_min; // minutes after the hour 0-59
Bit16s tm_hour; // hours since midnight 0-23
Bit16s tm_mday; // day of the month 1-31
Bit16s tm_mon; // months since January 0-11
Bit16s tm_year; // years since 1900
Bit16s tm_wday; // days since Sunday 0-6
Bit16s tm_yday; // days since January 1 0-365
};
char *ascutc(struct utctm *src)
{
static const char wdaystr[8][4] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "N/D"};
static const char monstr[13][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "N/D"};
static char timestr[28];
sprintf(timestr,"%.3s %.3s %2d %2d:%02d:%02d %6d\n", wdaystr[((src->tm_wday>=0)&&(src->tm_wday<7))?src->tm_wday:7], monstr[((src->tm_mon>=0)&&(src->tm_mon<12))?src->tm_mon:12], ((Bit16u)src->tm_mday)%100, ((Bit16u)src->tm_hour)%100, ((Bit16u)src->tm_min)%100, ((Bit16u)src->tm_sec)%100, (Bit32s)src->tm_year+1900); //Set the string up using extra caution to protect against bogus values, since snprintf() might not be available
return (char*) &timestr;
}
struct utctm *utctime_ext(const Bit64s *a,struct utctm *trgt)
{
static const Bit32s monthlydays[2][13]={{0,31,59,90,120,151,181,212,243,273,304,334,365},{0,31,60,91,121,152,182,213,244,274,305,335,366}}; //Days elapsed between the start of the selected month and the start of the year
Bit8u isleap=0; //Leap year flag
struct utctm bdt; //Structure to temporary store the output
Bit64s etmp=*a; //Temporary variable, epoch since 1970
Bit64s tsec; //Temporary variable, seconds
Bit64s eyear=2001; //Temporary variable, year
tsec=etmp%(24*60*60); //Get time of day
etmp/=(24*60*60); //Get days number
etmp-=11323; //Use 2001-01-01 as the base of the days number, it being the nearest first non-leap year of a 400yrs cycle
if(tsec<0){etmp--;tsec+=(24*60*60);}; //Get a positive time_of_day number and a properly rounded days number
bdt.tm_sec=tsec%60; //Set the seconds value
tsec/=60;
bdt.tm_min=tsec%60; //Set the minutes value
tsec/=60;
bdt.tm_hour=tsec; //Set the hour value
bdt.tm_wday=(etmp-6)%7;
if(bdt.tm_wday<0) bdt.tm_wday+=7; //Set the day of the week value
if(etmp<0){eyear+=400*(etmp/146097-1);etmp%=146097;etmp+=146097;}; //Years before 2001 accounted for
eyear+=400*(etmp/146097); //Add the number of 400yr cycles
etmp%=146097;
eyear+=100*(etmp/36524); //Add the number of 100yr cycles
etmp%=36524;
eyear+=4*(etmp/1461); //Add the number of 4yr cycles
etmp%=1461;
while((eyear%4)&&(etmp>=365)){eyear++;etmp-=365;} //Add the number of remaining years;
isleap|=((eyear%400)? 0: 2);
isleap|=((eyear% 4)? 0: 1);
isleap&=((eyear%100)?~0:~1);
isleap=(isleap?1:0); //Find out if the year is leap
eyear-=1900;
bdt.tm_year=eyear; //Set the year value
bdt.tm_yday=etmp; //Set the day of the year value
bdt.tm_mon=0;
while(etmp>=monthlydays[isleap][bdt.tm_mon+1]) bdt.tm_mon++; //Set the month value
etmp-=monthlydays[isleap][bdt.tm_mon];
bdt.tm_mday=etmp+1; //Set the day of the month value
if(eyear != bdt.tm_year) return NULL; //If the calculated year is too high fail
trgt->tm_sec=bdt.tm_sec; //Else write back in the structure proper values
trgt->tm_min=bdt.tm_min; //And return its address
trgt->tm_hour=bdt.tm_hour;
trgt->tm_wday=bdt.tm_wday;
trgt->tm_yday=bdt.tm_yday;
trgt->tm_mday=bdt.tm_mday;
trgt->tm_mon=bdt.tm_mon;
trgt->tm_year=bdt.tm_year;
return trgt;
}
Bit64s timeutc(struct utctm *bdt)
{
static const Bit32s monthlydays[2][13]={{0,31,59,90,120,151,181,212,243,273,304,334,365},{0,31,60,91,121,152,182,213,244,274,305,335,366}}; //Days elapsed between the start of the selected month and the start of the year
Bit8u isleap=3; //Leap year flag
Bit32s tmon; //Temporary month value
Bit64s epoch=0; //Value to return
Bit64s etmp; //Temporary variable
etmp=bdt->tm_year;
tmon=bdt->tm_mon;
etmp+=tmon/12;
tmon%=12;
if(tmon<0){etmp--;tmon+=12;}; //Broken month value accounted for
etmp-=101; //Years passed since 2001
if(etmp<0){epoch+=(146097*(etmp/400 - 1)); etmp%=400; etmp+=400;}; //Years before 2001 accounted for
epoch+=(etmp/400)*146097; //Add in epoch the number of days corresponding to completed 400yr cycles
etmp%=400;
isleap&=((etmp==399)?~0:~2); //Clear bit1 if the year can not be divided by 400
epoch+=(etmp/100)*36524; //Add in epoch the number of days corresponding to completed 100yr cycles
etmp%=100;
isleap&=((etmp==99)?~1:~0); //Clear bit0 if the year can be divided by 100
epoch+=(etmp/4)*1461; //Add in epoch the number of days corresponding to completed 4yr cycles
etmp%=4;
isleap&=((etmp==3)?~0:~1); //Clear bit0 if the year can not divided by 4
isleap=(isleap?1:0); //Shrink the flag to a single bit
epoch+=etmp*365; //Add in epoch the number of days corresponding to completed years
//Now we have in epoch the number (positive or negative) of days between the start of the current year and the start of 2001 and isleap set if the year is leap
epoch+=monthlydays[isleap][tmon];
epoch+=bdt->tm_mday-1; //Now we have in epoch the number of entire days between the current date and 2001-01-01 00:00
epoch*=24;
epoch+=bdt->tm_hour; //Now we have in epoch the number of hours
epoch*=60;
epoch+=bdt->tm_min; //Now we have in epoch the number of minutes
epoch*=60;
epoch+=bdt->tm_sec; //Now we have a positive or negative number of seconds between the input time and 2001-01-01 00:00:00
epoch+=978307200; //Now we have a positive or negative number of seconds between the input time and 1970-01-01 00:00:00
if(utctime_ext(&epoch,bdt)) return epoch; //Set if possible all fields so they are in their proper ranges
else return -1;
}
static struct utctm timedata;
struct utctm *utctime(const Bit64s *a)
{
return utctime_ext(a,&timedata);
}
struct utctm *pushtm(struct tm *src)
{
timedata.tm_sec=src->tm_sec;
timedata.tm_min=src->tm_min;
timedata.tm_hour=src->tm_hour;
timedata.tm_wday=src->tm_wday;
timedata.tm_yday=src->tm_yday;
timedata.tm_mday=src->tm_mday;
timedata.tm_mon=src->tm_mon;
timedata.tm_year=src->tm_year;
return &timedata;
}
#endif // UTCTIME_H