Home | History | Annotate | Line # | Download | only in time
strftime.c revision 1.29
      1 /*	$NetBSD: strftime.c,v 1.29 2013/09/20 19:06:54 christos Exp $	*/
      2 
      3 #include <sys/cdefs.h>
      4 #if defined(LIBC_SCCS) && !defined(lint)
      5 #if 0
      6 static char	elsieid[] = "@(#)strftime.c	7.64";
      7 static char	elsieid[] = "@(#)strftime.c	8.3";
      8 #else
      9 __RCSID("$NetBSD: strftime.c,v 1.29 2013/09/20 19:06:54 christos Exp $");
     10 #endif
     11 #endif /* LIBC_SCCS and not lint */
     12 
     13 #include "namespace.h"
     14 
     15 #include <stddef.h>
     16 #include <locale.h>
     17 #include "setlocale_local.h"
     18 
     19 /*
     20 ** Based on the UCB version with the copyright notice and sccsid
     21 ** appearing below.
     22 **
     23 ** This is ANSIish only when "multibyte character == plain character".
     24 */
     25 
     26 #include "private.h"
     27 
     28 /*
     29 ** We don't use these extensions in strftime operation even when
     30 ** supported by the local tzcode configuration.  A strictly
     31 ** conforming C application may leave them in undefined state.
     32 */
     33 
     34 #ifdef _LIBC
     35 #undef TM_ZONE
     36 #undef TM_GMTOFF
     37 #endif
     38 
     39 /*
     40 ** Copyright (c) 1989, 1993
     41 **	The Regents of the University of California.  All rights reserved.
     42 **
     43 ** Redistribution and use in source and binary forms, with or without
     44 ** modification, are permitted provided that the following conditions
     45 ** are met:
     46 ** 1. Redistributions of source code must retain the above copyright
     47 **    notice, this list of conditions and the following disclaimer.
     48 ** 2. Redistributions in binary form must reproduce the above copyright
     49 **    notice, this list of conditions and the following disclaimer in the
     50 **    documentation and/or other materials provided with the distribution.
     51 ** 3. All advertising materials mentioning features or use of this software
     52 **    must display the following acknowledgement:
     53 **	This product includes software developed by the University of
     54 **	California, Berkeley and its contributors.
     55 ** 4. Neither the name of the University nor the names of its contributors
     56 **    may be used to endorse or promote products derived from this software
     57 **    without specific prior written permission.
     58 **
     59 ** THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62 ** ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65 ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66 ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69 ** SUCH DAMAGE.
     70 */
     71 
     72 #ifndef LIBC_SCCS
     73 #ifndef lint
     74 static const char	sccsid[] = "@(#)strftime.c	5.4 (Berkeley) 3/14/89";
     75 #endif /* !defined lint */
     76 #endif /* !defined LIBC_SCCS */
     77 
     78 #include "tzfile.h"
     79 #include "fcntl.h"
     80 #include "locale.h"
     81 
     82 #ifdef __weak_alias
     83 __weak_alias(strftime_l, _strftime_l)
     84 __weak_alias(strftime_lz, _strftime_lz)
     85 __weak_alias(strftime_z, _strftime_z)
     86 #endif
     87 
     88 #include "sys/localedef.h"
     89 #define _TIME_LOCALE(loc) \
     90     ((_TimeLocale *)((loc)->part_impl[(size_t)LC_TIME]))
     91 #define c_fmt   d_t_fmt
     92 
     93 static char *	_add(const char *, char *, const char *);
     94 static char *	_conv(int, const char *, char *, const char *);
     95 static char *	_fmt(const timezone_t, const char *, const struct tm *, char *,
     96 			const char *, int *, locale_t);
     97 static char *	_yconv(int, int, int, int, char *, const char *);
     98 
     99 extern char *	tzname[];
    100 
    101 #ifndef YEAR_2000_NAME
    102 #define YEAR_2000_NAME	"CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
    103 #endif /* !defined YEAR_2000_NAME */
    104 
    105 #define IN_NONE	0
    106 #define IN_SOME	1
    107 #define IN_THIS	2
    108 #define IN_ALL	3
    109 
    110 size_t
    111 strftime_z(const timezone_t sp, char * __restrict s, size_t maxsize,
    112     const char * __restrict format, const struct tm * __restrict t)
    113 {
    114 	return strftime_lz(sp, s, maxsize, format, t, _current_locale());
    115 }
    116 
    117 size_t
    118 strftime_lz(const timezone_t sp, char *const s, const size_t maxsize,
    119     const char *const format, const struct tm *const t, locale_t loc)
    120 {
    121 	char *	p;
    122 	int	warn;
    123 
    124 	warn = IN_NONE;
    125 	p = _fmt(sp, ((format == NULL) ? "%c" : format), t, s, s + maxsize,
    126 	    &warn, loc);
    127 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
    128 	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
    129 		(void) fprintf(stderr, "\n");
    130 		if (format == NULL)
    131 			(void) fprintf(stderr, "NULL strftime format ");
    132 		else	(void) fprintf(stderr, "strftime format \"%s\" ",
    133 				format);
    134 		(void) fprintf(stderr, "yields only two digits of years in ");
    135 		if (warn == IN_SOME)
    136 			(void) fprintf(stderr, "some locales");
    137 		else if (warn == IN_THIS)
    138 			(void) fprintf(stderr, "the current locale");
    139 		else	(void) fprintf(stderr, "all locales");
    140 		(void) fprintf(stderr, "\n");
    141 	}
    142 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
    143 	if (p == s + maxsize)
    144 		return 0;
    145 	*p = '\0';
    146 	return p - s;
    147 }
    148 
    149 static char *
    150 _fmt(const timezone_t sp, const char *format, const struct tm *const t,
    151 	char *pt, const char *const ptlim, int *warnp, locale_t loc)
    152 {
    153 	for ( ; *format; ++format) {
    154 		if (*format == '%') {
    155 label:
    156 			switch (*++format) {
    157 			case '\0':
    158 				--format;
    159 				break;
    160 			case 'A':
    161 				pt = _add((t->tm_wday < 0 ||
    162 					t->tm_wday >= DAYSPERWEEK) ?
    163 					"?" : _TIME_LOCALE(loc)->day[t->tm_wday],
    164 					pt, ptlim);
    165 				continue;
    166 			case 'a':
    167 				pt = _add((t->tm_wday < 0 ||
    168 					t->tm_wday >= DAYSPERWEEK) ?
    169 					"?" : _TIME_LOCALE(loc)->abday[t->tm_wday],
    170 					pt, ptlim);
    171 				continue;
    172 			case 'B':
    173 				pt = _add((t->tm_mon < 0 ||
    174 					t->tm_mon >= MONSPERYEAR) ?
    175 					"?" : _TIME_LOCALE(loc)->mon[t->tm_mon],
    176 					pt, ptlim);
    177 				continue;
    178 			case 'b':
    179 			case 'h':
    180 				pt = _add((t->tm_mon < 0 ||
    181 					t->tm_mon >= MONSPERYEAR) ?
    182 					"?" : _TIME_LOCALE(loc)->abmon[t->tm_mon],
    183 					pt, ptlim);
    184 				continue;
    185 			case 'C':
    186 				/*
    187 				** %C used to do a...
    188 				**	_fmt("%a %b %e %X %Y", t);
    189 				** ...whereas now POSIX 1003.2 calls for
    190 				** something completely different.
    191 				** (ado, 1993-05-24)
    192 				*/
    193 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
    194 					pt, ptlim);
    195 				continue;
    196 			case 'c':
    197 				{
    198 				int warn2 = IN_SOME;
    199 
    200 				pt = _fmt(sp, _TIME_LOCALE(loc)->c_fmt, t, pt,
    201 				    ptlim, &warn2, loc);
    202 				if (warn2 == IN_ALL)
    203 					warn2 = IN_THIS;
    204 				if (warn2 > *warnp)
    205 					*warnp = warn2;
    206 				}
    207 				continue;
    208 			case 'D':
    209 				pt = _fmt(sp, "%m/%d/%y", t, pt, ptlim, warnp,
    210 				    loc);
    211 				continue;
    212 			case 'd':
    213 				pt = _conv(t->tm_mday, "%02d", pt, ptlim);
    214 				continue;
    215 			case 'E':
    216 			case 'O':
    217 				/*
    218 				** C99 locale modifiers.
    219 				** The sequences
    220 				**	%Ec %EC %Ex %EX %Ey %EY
    221 				**	%Od %oe %OH %OI %Om %OM
    222 				**	%OS %Ou %OU %OV %Ow %OW %Oy
    223 				** are supposed to provide alternate
    224 				** representations.
    225 				*/
    226 				goto label;
    227 			case 'e':
    228 				pt = _conv(t->tm_mday, "%2d", pt, ptlim);
    229 				continue;
    230 			case 'F':
    231 				pt = _fmt(sp, "%Y-%m-%d", t, pt, ptlim, warnp,
    232 				    loc);
    233 				continue;
    234 			case 'H':
    235 				pt = _conv(t->tm_hour, "%02d", pt, ptlim);
    236 				continue;
    237 			case 'I':
    238 				pt = _conv((t->tm_hour % 12) ?
    239 					(t->tm_hour % 12) : 12,
    240 					"%02d", pt, ptlim);
    241 				continue;
    242 			case 'j':
    243 				pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
    244 				continue;
    245 			case 'k':
    246 				/*
    247 				** This used to be...
    248 				**	_conv(t->tm_hour % 12 ?
    249 				**		t->tm_hour % 12 : 12, 2, ' ');
    250 				** ...and has been changed to the below to
    251 				** match SunOS 4.1.1 and Arnold Robbins'
    252 				** strftime version 3.0. That is, "%k" and
    253 				** "%l" have been swapped.
    254 				** (ado, 1993-05-24)
    255 				*/
    256 				pt = _conv(t->tm_hour, "%2d", pt, ptlim);
    257 				continue;
    258 #ifdef KITCHEN_SINK
    259 			case 'K':
    260 				/*
    261 				** After all this time, still unclaimed!
    262 				*/
    263 				pt = _add("kitchen sink", pt, ptlim);
    264 				continue;
    265 #endif /* defined KITCHEN_SINK */
    266 			case 'l':
    267 				/*
    268 				** This used to be...
    269 				**	_conv(t->tm_hour, 2, ' ');
    270 				** ...and has been changed to the below to
    271 				** match SunOS 4.1.1 and Arnold Robbin's
    272 				** strftime version 3.0. That is, "%k" and
    273 				** "%l" have been swapped.
    274 				** (ado, 1993-05-24)
    275 				*/
    276 				pt = _conv((t->tm_hour % 12) ?
    277 					(t->tm_hour % 12) : 12,
    278 					"%2d", pt, ptlim);
    279 				continue;
    280 			case 'M':
    281 				pt = _conv(t->tm_min, "%02d", pt, ptlim);
    282 				continue;
    283 			case 'm':
    284 				pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
    285 				continue;
    286 			case 'n':
    287 				pt = _add("\n", pt, ptlim);
    288 				continue;
    289 			case 'p':
    290 				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
    291 					_TIME_LOCALE(loc)->am_pm[1] :
    292 					_TIME_LOCALE(loc)->am_pm[0],
    293 					pt, ptlim);
    294 				continue;
    295 			case 'R':
    296 				pt = _fmt(sp, "%H:%M", t, pt, ptlim, warnp,
    297 				    loc);
    298 				continue;
    299 			case 'r':
    300 				pt = _fmt(sp, _TIME_LOCALE(loc)->t_fmt_ampm, t,
    301 				    pt, ptlim, warnp, loc);
    302 				continue;
    303 			case 'S':
    304 				pt = _conv(t->tm_sec, "%02d", pt, ptlim);
    305 				continue;
    306 			case 's':
    307 				{
    308 					struct tm	tm;
    309 					char		buf[INT_STRLEN_MAXIMUM(
    310 								time_t) + 1];
    311 					time_t		mkt;
    312 
    313 					tm = *t;
    314 					mkt = mktime(&tm);
    315 					/* CONSTCOND */
    316 					if (TYPE_SIGNED(time_t))
    317 						(void)snprintf(buf, sizeof(buf),
    318 						    "%jd", (intmax_t) mkt);
    319 					else	(void)snprintf(buf, sizeof(buf),
    320 						    "%ju", (uintmax_t) mkt);
    321 					pt = _add(buf, pt, ptlim);
    322 				}
    323 				continue;
    324 			case 'T':
    325 				pt = _fmt(sp, "%H:%M:%S", t, pt, ptlim, warnp,
    326 				    loc);
    327 				continue;
    328 			case 't':
    329 				pt = _add("\t", pt, ptlim);
    330 				continue;
    331 			case 'U':
    332 				pt = _conv((t->tm_yday + DAYSPERWEEK -
    333 					t->tm_wday) / DAYSPERWEEK,
    334 					"%02d", pt, ptlim);
    335 				continue;
    336 			case 'u':
    337 				/*
    338 				** From Arnold Robbins' strftime version 3.0:
    339 				** "ISO 8601: Weekday as a decimal number
    340 				** [1 (Monday) - 7]"
    341 				** (ado, 1993-05-24)
    342 				*/
    343 				pt = _conv((t->tm_wday == 0) ?
    344 					DAYSPERWEEK : t->tm_wday,
    345 					"%d", pt, ptlim);
    346 				continue;
    347 			case 'V':	/* ISO 8601 week number */
    348 			case 'G':	/* ISO 8601 year (four digits) */
    349 			case 'g':	/* ISO 8601 year (two digits) */
    350 /*
    351 ** From Arnold Robbins' strftime version 3.0: "the week number of the
    352 ** year (the first Monday as the first day of week 1) as a decimal number
    353 ** (01-53)."
    354 ** (ado, 1993-05-24)
    355 **
    356 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
    357 ** "Week 01 of a year is per definition the first week which has the
    358 ** Thursday in this year, which is equivalent to the week which contains
    359 ** the fourth day of January. In other words, the first week of a new year
    360 ** is the week which has the majority of its days in the new year. Week 01
    361 ** might also contain days from the previous year and the week before week
    362 ** 01 of a year is the last week (52 or 53) of the previous year even if
    363 ** it contains days from the new year. A week starts with Monday (day 1)
    364 ** and ends with Sunday (day 7). For example, the first week of the year
    365 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
    366 ** (ado, 1996-01-02)
    367 */
    368 				{
    369 					int	year;
    370 					int	base;
    371 					int	yday;
    372 					int	wday;
    373 					int	w;
    374 
    375 					year = t->tm_year;
    376 					base = TM_YEAR_BASE;
    377 					yday = t->tm_yday;
    378 					wday = t->tm_wday;
    379 					for ( ; ; ) {
    380 						int	len;
    381 						int	bot;
    382 						int	top;
    383 
    384 						len = isleap_sum(year, base) ?
    385 							DAYSPERLYEAR :
    386 							DAYSPERNYEAR;
    387 						/*
    388 						** What yday (-3 ... 3) does
    389 						** the ISO year begin on?
    390 						*/
    391 						bot = ((yday + 11 - wday) %
    392 							DAYSPERWEEK) - 3;
    393 						/*
    394 						** What yday does the NEXT
    395 						** ISO year begin on?
    396 						*/
    397 						top = bot -
    398 							(len % DAYSPERWEEK);
    399 						if (top < -3)
    400 							top += DAYSPERWEEK;
    401 						top += len;
    402 						if (yday >= top) {
    403 							++base;
    404 							w = 1;
    405 							break;
    406 						}
    407 						if (yday >= bot) {
    408 							w = 1 + ((yday - bot) /
    409 								DAYSPERWEEK);
    410 							break;
    411 						}
    412 						--base;
    413 						yday += isleap_sum(year, base) ?
    414 							DAYSPERLYEAR :
    415 							DAYSPERNYEAR;
    416 					}
    417 #ifdef XPG4_1994_04_09
    418 					if ((w == 52 &&
    419 						t->tm_mon == TM_JANUARY) ||
    420 						(w == 1 &&
    421 						t->tm_mon == TM_DECEMBER))
    422 							w = 53;
    423 #endif /* defined XPG4_1994_04_09 */
    424 					if (*format == 'V')
    425 						pt = _conv(w, "%02d",
    426 							pt, ptlim);
    427 					else if (*format == 'g') {
    428 						*warnp = IN_ALL;
    429 						pt = _yconv(year, base, 0, 1,
    430 							pt, ptlim);
    431 					} else	pt = _yconv(year, base, 1, 1,
    432 							pt, ptlim);
    433 				}
    434 				continue;
    435 			case 'v':
    436 				/*
    437 				** From Arnold Robbins' strftime version 3.0:
    438 				** "date as dd-bbb-YYYY"
    439 				** (ado, 1993-05-24)
    440 				*/
    441 				pt = _fmt(sp, "%e-%b-%Y", t, pt, ptlim, warnp,
    442 				    loc);
    443 				continue;
    444 			case 'W':
    445 				pt = _conv((t->tm_yday + DAYSPERWEEK -
    446 					(t->tm_wday ?
    447 					(t->tm_wday - 1) :
    448 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
    449 					"%02d", pt, ptlim);
    450 				continue;
    451 			case 'w':
    452 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
    453 				continue;
    454 			case 'X':
    455 				pt = _fmt(sp, _TIME_LOCALE(loc)->t_fmt, t, pt,
    456 				    ptlim, warnp, loc);
    457 				continue;
    458 			case 'x':
    459 				{
    460 				int	warn2 = IN_SOME;
    461 
    462 				pt = _fmt(sp, _TIME_LOCALE(loc)->d_fmt, t, pt,
    463 				    ptlim, &warn2, loc);
    464 				if (warn2 == IN_ALL)
    465 					warn2 = IN_THIS;
    466 				if (warn2 > *warnp)
    467 					*warnp = warn2;
    468 				}
    469 				continue;
    470 			case 'y':
    471 				*warnp = IN_ALL;
    472 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
    473 					pt, ptlim);
    474 				continue;
    475 			case 'Y':
    476 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
    477 					pt, ptlim);
    478 				continue;
    479 			case 'Z':
    480 #ifdef TM_ZONE
    481 				if (t->TM_ZONE != NULL)
    482 					pt = _add(t->TM_ZONE, pt, ptlim);
    483 				else
    484 #endif /* defined TM_ZONE */
    485 				if (t->tm_isdst >= 0)
    486 					pt = _add((sp ?
    487 					    tzgetname(sp, t->tm_isdst) :
    488 					    tzname[t->tm_isdst != 0]),
    489 					    pt, ptlim);
    490 				/*
    491 				** C99 says that %Z must be replaced by the
    492 				** empty string if the time zone is not
    493 				** determinable.
    494 				*/
    495 				continue;
    496 			case 'z':
    497 				{
    498 				int		diff;
    499 				char const *	sign;
    500 
    501 				if (t->tm_isdst < 0)
    502 					continue;
    503 #ifdef TM_GMTOFF
    504 				diff = (int)t->TM_GMTOFF;
    505 #else /* !defined TM_GMTOFF */
    506 				/*
    507 				** C99 says that the UT offset must
    508 				** be computed by looking only at
    509 				** tm_isdst. This requirement is
    510 				** incorrect, since it means the code
    511 				** must rely on magic (in this case
    512 				** altzone and timezone), and the
    513 				** magic might not have the correct
    514 				** offset. Doing things correctly is
    515 				** tricky and requires disobeying C99;
    516 				** see GNU C strftime for details.
    517 				** For now, punt and conform to the
    518 				** standard, even though it's incorrect.
    519 				**
    520 				** C99 says that %z must be replaced by the
    521 				** empty string if the time zone is not
    522 				** determinable, so output nothing if the
    523 				** appropriate variables are not available.
    524 				*/
    525 #ifndef STD_INSPIRED
    526 				if (t->tm_isdst == 0)
    527 #ifdef USG_COMPAT
    528 					diff = -timezone;
    529 #else /* !defined USG_COMPAT */
    530 					continue;
    531 #endif /* !defined USG_COMPAT */
    532 				else
    533 #ifdef ALTZONE
    534 					diff = -altzone;
    535 #else /* !defined ALTZONE */
    536 					continue;
    537 #endif /* !defined ALTZONE */
    538 #else /* defined STD_INSPIRED */
    539 				{
    540 					struct tm tmp;
    541 					time_t lct, gct;
    542 
    543 					/*
    544 					** Get calendar time from t
    545 					** being treated as local.
    546 					*/
    547 					tmp = *t; /* mktime discards const */
    548 					lct = mktime(&tmp);
    549 
    550 					if (lct == (time_t)-1)
    551 						continue;
    552 
    553 					/*
    554 					** Get calendar time from t
    555 					** being treated as GMT.
    556 					**/
    557 					tmp = *t; /* mktime discards const */
    558 					gct = timegm(&tmp);
    559 
    560 					if (gct == (time_t)-1)
    561 						continue;
    562 
    563 					/* LINTED difference will fit int */
    564 					diff = (intmax_t)gct - (intmax_t)lct;
    565 				}
    566 #endif /* defined STD_INSPIRED */
    567 #endif /* !defined TM_GMTOFF */
    568 				if (diff < 0) {
    569 					sign = "-";
    570 					diff = -diff;
    571 				} else	sign = "+";
    572 				pt = _add(sign, pt, ptlim);
    573 				diff /= SECSPERMIN;
    574 				diff = (diff / MINSPERHOUR) * 100 +
    575 					(diff % MINSPERHOUR);
    576 				pt = _conv(diff, "%04d", pt, ptlim);
    577 				}
    578 				continue;
    579 #if 0
    580 			case '+':
    581 				pt = _fmt(sp, _TIME_LOCALE(loc)->date_fmt, t,
    582 				    pt, ptlim, warnp, loc);
    583 				continue;
    584 #endif
    585 			case '%':
    586 			/*
    587 			** X311J/88-090 (4.12.3.5): if conversion char is
    588 			** undefined, behavior is undefined. Print out the
    589 			** character itself as printf(3) also does.
    590 			*/
    591 			default:
    592 				break;
    593 			}
    594 		}
    595 		if (pt == ptlim)
    596 			break;
    597 		*pt++ = *format;
    598 	}
    599 	return pt;
    600 }
    601 
    602 size_t
    603 strftime(char * const s, const size_t maxsize,
    604     const char * const format, const struct tm * const	t)
    605 {
    606 	tzset();
    607 	return strftime_z(NULL, s, maxsize, format, t);
    608 }
    609 
    610 size_t
    611 strftime_l(char * __restrict s, size_t maxsize, const char * __restrict format,
    612     const struct tm * __restrict t, locale_t loc)
    613 {
    614 	tzset();
    615 	return strftime_lz(NULL, s, maxsize, format, t, loc);
    616 }
    617 
    618 static char *
    619 _conv(const int	n, const char *const format, char *const pt,
    620     const char *const ptlim)
    621 {
    622 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
    623 
    624 	(void) snprintf(buf, sizeof(buf), format, n);
    625 	return _add(buf, pt, ptlim);
    626 }
    627 
    628 static char *
    629 _add(const char *str, char *pt, const char *const ptlim)
    630 {
    631 	while (pt < ptlim && (*pt = *str++) != '\0')
    632 		++pt;
    633 	return pt;
    634 }
    635 
    636 /*
    637 ** POSIX and the C Standard are unclear or inconsistent about
    638 ** what %C and %y do if the year is negative or exceeds 9999.
    639 ** Use the convention that %C concatenated with %y yields the
    640 ** same output as %Y, and that %Y contains at least 4 bytes,
    641 ** with more only if necessary.
    642 */
    643 
    644 static char *
    645 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
    646     char *pt, const char *const ptlim)
    647 {
    648 	int	lead;
    649 	int	trail;
    650 
    651 #define DIVISOR	100
    652 	trail = a % DIVISOR + b % DIVISOR;
    653 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
    654 	trail %= DIVISOR;
    655 	if (trail < 0 && lead > 0) {
    656 		trail += DIVISOR;
    657 		--lead;
    658 	} else if (lead < 0 && trail > 0) {
    659 		trail -= DIVISOR;
    660 		++lead;
    661 	}
    662 	if (convert_top) {
    663 		if (lead == 0 && trail < 0)
    664 			pt = _add("-0", pt, ptlim);
    665 		else	pt = _conv(lead, "%02d", pt, ptlim);
    666 	}
    667 	if (convert_yy)
    668 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
    669 	return pt;
    670 }
    671 
    672 #ifdef LOCALE_HOME
    673 static struct lc_time_T *
    674 _loc(void)
    675 {
    676 	static const char	locale_home[] = LOCALE_HOME;
    677 	static const char	lc_time[] = "LC_TIME";
    678 	static char *		locale_buf;
    679 
    680 	int			fd;
    681 	int			oldsun;	/* "...ain't got nothin' to do..." */
    682 	char *			lbuf;
    683 	char *			name;
    684 	char *			p;
    685 	const char **		ap;
    686 	const char *		plim;
    687 	char			filename[FILENAME_MAX];
    688 	struct stat		st;
    689 	size_t			namesize;
    690 	size_t			bufsize;
    691 
    692 	/*
    693 	** Use localebuf.mon[0] to signal whether locale is already set up.
    694 	*/
    695 	if (localebuf.mon[0])
    696 		return &localebuf;
    697 	name = setlocale(LC_TIME, NULL);
    698 	if (name == NULL || *name == '\0')
    699 		goto no_locale;
    700 	/*
    701 	** If the locale name is the same as our cache, use the cache.
    702 	*/
    703 	lbuf = locale_buf;
    704 	if (lbuf != NULL && strcmp(name, lbuf) == 0) {
    705 		p = lbuf;
    706 		for (ap = (const char **) &localebuf;
    707 			ap < (const char **) (&localebuf + 1);
    708 				++ap)
    709 					*ap = p += strlen(p) + 1;
    710 		return &localebuf;
    711 	}
    712 	/*
    713 	** Slurp the locale file into the cache.
    714 	*/
    715 	namesize = strlen(name) + 1;
    716 	if (sizeof filename <
    717 		((sizeof locale_home) + namesize + (sizeof lc_time)))
    718 			goto no_locale;
    719 	oldsun = 0;
    720 	(void) sprintf(filename, "%s/%s/%s", locale_home, name, lc_time);
    721 	fd = open(filename, O_RDONLY);
    722 	if (fd < 0) {
    723 		/*
    724 		** Old Sun systems have a different naming and data convention.
    725 		*/
    726 		oldsun = 1;
    727 		(void) sprintf(filename, "%s/%s/%s", locale_home,
    728 			lc_time, name);
    729 		fd = open(filename, O_RDONLY);
    730 		if (fd < 0)
    731 			goto no_locale;
    732 	}
    733 	if (fstat(fd, &st) != 0)
    734 		goto bad_locale;
    735 	if (st.st_size <= 0)
    736 		goto bad_locale;
    737 	bufsize = namesize + st.st_size;
    738 	locale_buf = NULL;
    739 	lbuf = (lbuf == NULL) ? malloc(bufsize) : realloc(lbuf, bufsize);
    740 	if (lbuf == NULL)
    741 		goto bad_locale;
    742 	(void) strcpy(lbuf, name);
    743 	p = lbuf + namesize;
    744 	plim = p + st.st_size;
    745 	if (read(fd, p, (size_t) st.st_size) != st.st_size)
    746 		goto bad_lbuf;
    747 	if (close(fd) != 0)
    748 		goto bad_lbuf;
    749 	/*
    750 	** Parse the locale file into localebuf.
    751 	*/
    752 	if (plim[-1] != '\n')
    753 		goto bad_lbuf;
    754 	for (ap = (const char **) &localebuf;
    755 		ap < (const char **) (&localebuf + 1);
    756 			++ap) {
    757 				if (p == plim)
    758 					goto bad_lbuf;
    759 				*ap = p;
    760 				while (*p != '\n')
    761 					++p;
    762 				*p++ = '\0';
    763 	}
    764 	if (oldsun) {
    765 		/*
    766 		** SunOS 4 used an obsolescent format; see localdtconv(3).
    767 		** c_fmt had the ``short format for dates and times together''
    768 		** (SunOS 4 date, "%a %b %e %T %Z %Y" in the C locale);
    769 		** date_fmt had the ``long format for dates''
    770 		** (SunOS 4 strftime %C, "%A, %B %e, %Y" in the C locale).
    771 		** Discard the latter in favor of the former.
    772 		*/
    773 		localebuf.date_fmt = localebuf.c_fmt;
    774 	}
    775 	/*
    776 	** Record the successful parse in the cache.
    777 	*/
    778 	locale_buf = lbuf;
    779 
    780 	return &localebuf;
    781 
    782 bad_lbuf:
    783 	free(lbuf);
    784 bad_locale:
    785 	(void) close(fd);
    786 no_locale:
    787 	localebuf = C_time_locale;
    788 	locale_buf = NULL;
    789 	return &localebuf;
    790 }
    791 #endif /* defined LOCALE_HOME */
    792