xref: /netbsd-src/lib/libc/time/strftime.c (revision af56d1fe9956bd7c616e18c1b7f025f464618471)
1 /*	$NetBSD: strftime.c,v 1.25 2013/04/21 17:45:46 joerg 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.25 2013/04/21 17:45:46 joerg 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 	if (loc == NULL)
125 		loc = _C_locale;
126 
127 	warn = IN_NONE;
128 	p = _fmt(sp, ((format == NULL) ? "%c" : format), t, s, s + maxsize,
129 	    &warn, loc);
130 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
131 	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
132 		(void) fprintf(stderr, "\n");
133 		if (format == NULL)
134 			(void) fprintf(stderr, "NULL strftime format ");
135 		else	(void) fprintf(stderr, "strftime format \"%s\" ",
136 				format);
137 		(void) fprintf(stderr, "yields only two digits of years in ");
138 		if (warn == IN_SOME)
139 			(void) fprintf(stderr, "some locales");
140 		else if (warn == IN_THIS)
141 			(void) fprintf(stderr, "the current locale");
142 		else	(void) fprintf(stderr, "all locales");
143 		(void) fprintf(stderr, "\n");
144 	}
145 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
146 	if (p == s + maxsize)
147 		return 0;
148 	*p = '\0';
149 	return p - s;
150 }
151 
152 static char *
153 _fmt(const timezone_t sp, const char *format, const struct tm *const t,
154 	char *pt, const char *const ptlim, int *warnp, locale_t loc)
155 {
156 	for ( ; *format; ++format) {
157 		if (*format == '%') {
158 label:
159 			switch (*++format) {
160 			case '\0':
161 				--format;
162 				break;
163 			case 'A':
164 				pt = _add((t->tm_wday < 0 ||
165 					t->tm_wday >= DAYSPERWEEK) ?
166 					"?" : _TIME_LOCALE(loc)->day[t->tm_wday],
167 					pt, ptlim);
168 				continue;
169 			case 'a':
170 				pt = _add((t->tm_wday < 0 ||
171 					t->tm_wday >= DAYSPERWEEK) ?
172 					"?" : _TIME_LOCALE(loc)->abday[t->tm_wday],
173 					pt, ptlim);
174 				continue;
175 			case 'B':
176 				pt = _add((t->tm_mon < 0 ||
177 					t->tm_mon >= MONSPERYEAR) ?
178 					"?" : _TIME_LOCALE(loc)->mon[t->tm_mon],
179 					pt, ptlim);
180 				continue;
181 			case 'b':
182 			case 'h':
183 				pt = _add((t->tm_mon < 0 ||
184 					t->tm_mon >= MONSPERYEAR) ?
185 					"?" : _TIME_LOCALE(loc)->abmon[t->tm_mon],
186 					pt, ptlim);
187 				continue;
188 			case 'C':
189 				/*
190 				** %C used to do a...
191 				**	_fmt("%a %b %e %X %Y", t);
192 				** ...whereas now POSIX 1003.2 calls for
193 				** something completely different.
194 				** (ado, 1993-05-24)
195 				*/
196 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
197 					pt, ptlim);
198 				continue;
199 			case 'c':
200 				{
201 				int warn2 = IN_SOME;
202 
203 				pt = _fmt(sp, _TIME_LOCALE(loc)->c_fmt, t, pt,
204 				    ptlim, &warn2, loc);
205 				if (warn2 == IN_ALL)
206 					warn2 = IN_THIS;
207 				if (warn2 > *warnp)
208 					*warnp = warn2;
209 				}
210 				continue;
211 			case 'D':
212 				pt = _fmt(sp, "%m/%d/%y", t, pt, ptlim, warnp,
213 				    loc);
214 				continue;
215 			case 'd':
216 				pt = _conv(t->tm_mday, "%02d", pt, ptlim);
217 				continue;
218 			case 'E':
219 			case 'O':
220 				/*
221 				** C99 locale modifiers.
222 				** The sequences
223 				**	%Ec %EC %Ex %EX %Ey %EY
224 				**	%Od %oe %OH %OI %Om %OM
225 				**	%OS %Ou %OU %OV %Ow %OW %Oy
226 				** are supposed to provide alternate
227 				** representations.
228 				*/
229 				goto label;
230 			case 'e':
231 				pt = _conv(t->tm_mday, "%2d", pt, ptlim);
232 				continue;
233 			case 'F':
234 				pt = _fmt(sp, "%Y-%m-%d", t, pt, ptlim, warnp,
235 				    loc);
236 				continue;
237 			case 'H':
238 				pt = _conv(t->tm_hour, "%02d", pt, ptlim);
239 				continue;
240 			case 'I':
241 				pt = _conv((t->tm_hour % 12) ?
242 					(t->tm_hour % 12) : 12,
243 					"%02d", pt, ptlim);
244 				continue;
245 			case 'j':
246 				pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
247 				continue;
248 			case 'k':
249 				/*
250 				** This used to be...
251 				**	_conv(t->tm_hour % 12 ?
252 				**		t->tm_hour % 12 : 12, 2, ' ');
253 				** ...and has been changed to the below to
254 				** match SunOS 4.1.1 and Arnold Robbins'
255 				** strftime version 3.0. That is, "%k" and
256 				** "%l" have been swapped.
257 				** (ado, 1993-05-24)
258 				*/
259 				pt = _conv(t->tm_hour, "%2d", pt, ptlim);
260 				continue;
261 #ifdef KITCHEN_SINK
262 			case 'K':
263 				/*
264 				** After all this time, still unclaimed!
265 				*/
266 				pt = _add("kitchen sink", pt, ptlim);
267 				continue;
268 #endif /* defined KITCHEN_SINK */
269 			case 'l':
270 				/*
271 				** This used to be...
272 				**	_conv(t->tm_hour, 2, ' ');
273 				** ...and has been changed to the below to
274 				** match SunOS 4.1.1 and Arnold Robbin's
275 				** strftime version 3.0. That is, "%k" and
276 				** "%l" have been swapped.
277 				** (ado, 1993-05-24)
278 				*/
279 				pt = _conv((t->tm_hour % 12) ?
280 					(t->tm_hour % 12) : 12,
281 					"%2d", pt, ptlim);
282 				continue;
283 			case 'M':
284 				pt = _conv(t->tm_min, "%02d", pt, ptlim);
285 				continue;
286 			case 'm':
287 				pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
288 				continue;
289 			case 'n':
290 				pt = _add("\n", pt, ptlim);
291 				continue;
292 			case 'p':
293 				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
294 					_TIME_LOCALE(loc)->am_pm[1] :
295 					_TIME_LOCALE(loc)->am_pm[0],
296 					pt, ptlim);
297 				continue;
298 			case 'R':
299 				pt = _fmt(sp, "%H:%M", t, pt, ptlim, warnp,
300 				    loc);
301 				continue;
302 			case 'r':
303 				pt = _fmt(sp, _TIME_LOCALE(loc)->t_fmt_ampm, t,
304 				    pt, ptlim, warnp, loc);
305 				continue;
306 			case 'S':
307 				pt = _conv(t->tm_sec, "%02d", pt, ptlim);
308 				continue;
309 			case 's':
310 				{
311 					struct tm	tm;
312 					char		buf[INT_STRLEN_MAXIMUM(
313 								time_t) + 1];
314 					time_t		mkt;
315 
316 					tm = *t;
317 					mkt = mktime(&tm);
318 					/* CONSTCOND */
319 					if (TYPE_SIGNED(time_t))
320 						(void) snprintf(buf, sizeof(buf),
321 						    "%lld", (long long) mkt);
322 					else	(void) snprintf(buf, sizeof(buf),
323 						    "%llu", (unsigned long long)
324 						    mkt);
325 					pt = _add(buf, pt, ptlim);
326 				}
327 				continue;
328 			case 'T':
329 				pt = _fmt(sp, "%H:%M:%S", t, pt, ptlim, warnp,
330 				    loc);
331 				continue;
332 			case 't':
333 				pt = _add("\t", pt, ptlim);
334 				continue;
335 			case 'U':
336 				pt = _conv((t->tm_yday + DAYSPERWEEK -
337 					t->tm_wday) / DAYSPERWEEK,
338 					"%02d", pt, ptlim);
339 				continue;
340 			case 'u':
341 				/*
342 				** From Arnold Robbins' strftime version 3.0:
343 				** "ISO 8601: Weekday as a decimal number
344 				** [1 (Monday) - 7]"
345 				** (ado, 1993-05-24)
346 				*/
347 				pt = _conv((t->tm_wday == 0) ?
348 					DAYSPERWEEK : t->tm_wday,
349 					"%d", pt, ptlim);
350 				continue;
351 			case 'V':	/* ISO 8601 week number */
352 			case 'G':	/* ISO 8601 year (four digits) */
353 			case 'g':	/* ISO 8601 year (two digits) */
354 /*
355 ** From Arnold Robbins' strftime version 3.0: "the week number of the
356 ** year (the first Monday as the first day of week 1) as a decimal number
357 ** (01-53)."
358 ** (ado, 1993-05-24)
359 **
360 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
361 ** "Week 01 of a year is per definition the first week which has the
362 ** Thursday in this year, which is equivalent to the week which contains
363 ** the fourth day of January. In other words, the first week of a new year
364 ** is the week which has the majority of its days in the new year. Week 01
365 ** might also contain days from the previous year and the week before week
366 ** 01 of a year is the last week (52 or 53) of the previous year even if
367 ** it contains days from the new year. A week starts with Monday (day 1)
368 ** and ends with Sunday (day 7). For example, the first week of the year
369 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
370 ** (ado, 1996-01-02)
371 */
372 				{
373 					int	year;
374 					int	base;
375 					int	yday;
376 					int	wday;
377 					int	w;
378 
379 					year = t->tm_year;
380 					base = TM_YEAR_BASE;
381 					yday = t->tm_yday;
382 					wday = t->tm_wday;
383 					for ( ; ; ) {
384 						int	len;
385 						int	bot;
386 						int	top;
387 
388 						len = isleap_sum(year, base) ?
389 							DAYSPERLYEAR :
390 							DAYSPERNYEAR;
391 						/*
392 						** What yday (-3 ... 3) does
393 						** the ISO year begin on?
394 						*/
395 						bot = ((yday + 11 - wday) %
396 							DAYSPERWEEK) - 3;
397 						/*
398 						** What yday does the NEXT
399 						** ISO year begin on?
400 						*/
401 						top = bot -
402 							(len % DAYSPERWEEK);
403 						if (top < -3)
404 							top += DAYSPERWEEK;
405 						top += len;
406 						if (yday >= top) {
407 							++base;
408 							w = 1;
409 							break;
410 						}
411 						if (yday >= bot) {
412 							w = 1 + ((yday - bot) /
413 								DAYSPERWEEK);
414 							break;
415 						}
416 						--base;
417 						yday += isleap_sum(year, base) ?
418 							DAYSPERLYEAR :
419 							DAYSPERNYEAR;
420 					}
421 #ifdef XPG4_1994_04_09
422 					if ((w == 52 &&
423 						t->tm_mon == TM_JANUARY) ||
424 						(w == 1 &&
425 						t->tm_mon == TM_DECEMBER))
426 							w = 53;
427 #endif /* defined XPG4_1994_04_09 */
428 					if (*format == 'V')
429 						pt = _conv(w, "%02d",
430 							pt, ptlim);
431 					else if (*format == 'g') {
432 						*warnp = IN_ALL;
433 						pt = _yconv(year, base, 0, 1,
434 							pt, ptlim);
435 					} else	pt = _yconv(year, base, 1, 1,
436 							pt, ptlim);
437 				}
438 				continue;
439 			case 'v':
440 				/*
441 				** From Arnold Robbins' strftime version 3.0:
442 				** "date as dd-bbb-YYYY"
443 				** (ado, 1993-05-24)
444 				*/
445 				pt = _fmt(sp, "%e-%b-%Y", t, pt, ptlim, warnp,
446 				    loc);
447 				continue;
448 			case 'W':
449 				pt = _conv((t->tm_yday + DAYSPERWEEK -
450 					(t->tm_wday ?
451 					(t->tm_wday - 1) :
452 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
453 					"%02d", pt, ptlim);
454 				continue;
455 			case 'w':
456 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
457 				continue;
458 			case 'X':
459 				pt = _fmt(sp, _TIME_LOCALE(loc)->t_fmt, t, pt,
460 				    ptlim, warnp, loc);
461 				continue;
462 			case 'x':
463 				{
464 				int	warn2 = IN_SOME;
465 
466 				pt = _fmt(sp, _TIME_LOCALE(loc)->d_fmt, t, pt,
467 				    ptlim, &warn2, loc);
468 				if (warn2 == IN_ALL)
469 					warn2 = IN_THIS;
470 				if (warn2 > *warnp)
471 					*warnp = warn2;
472 				}
473 				continue;
474 			case 'y':
475 				*warnp = IN_ALL;
476 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
477 					pt, ptlim);
478 				continue;
479 			case 'Y':
480 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
481 					pt, ptlim);
482 				continue;
483 			case 'Z':
484 #ifdef TM_ZONE
485 				if (t->TM_ZONE != NULL)
486 					pt = _add(t->TM_ZONE, pt, ptlim);
487 				else
488 #endif /* defined TM_ZONE */
489 				if (t->tm_isdst >= 0)
490 					pt = _add((sp ?
491 					    tzgetname(sp, t->tm_isdst) :
492 					    tzname[t->tm_isdst != 0]),
493 					    pt, ptlim);
494 				/*
495 				** C99 says that %Z must be replaced by the
496 				** empty string if the time zone is not
497 				** determinable.
498 				*/
499 				continue;
500 			case 'z':
501 				{
502 				int		diff;
503 				char const *	sign;
504 
505 				if (t->tm_isdst < 0)
506 					continue;
507 #ifdef TM_GMTOFF
508 				diff = (int)t->TM_GMTOFF;
509 #else /* !defined TM_GMTOFF */
510 				/*
511 				** C99 says that the UTC offset must
512 				** be computed by looking only at
513 				** tm_isdst. This requirement is
514 				** incorrect, since it means the code
515 				** must rely on magic (in this case
516 				** altzone and timezone), and the
517 				** magic might not have the correct
518 				** offset. Doing things correctly is
519 				** tricky and requires disobeying C99;
520 				** see GNU C strftime for details.
521 				** For now, punt and conform to the
522 				** standard, even though it's incorrect.
523 				**
524 				** C99 says that %z must be replaced by the
525 				** empty string if the time zone is not
526 				** determinable, so output nothing if the
527 				** appropriate variables are not available.
528 				*/
529 #ifndef STD_INSPIRED
530 				if (t->tm_isdst == 0)
531 #ifdef USG_COMPAT
532 					diff = -timezone;
533 #else /* !defined USG_COMPAT */
534 					continue;
535 #endif /* !defined USG_COMPAT */
536 				else
537 #ifdef ALTZONE
538 					diff = -altzone;
539 #else /* !defined ALTZONE */
540 					continue;
541 #endif /* !defined ALTZONE */
542 #else /* defined STD_INSPIRED */
543 				{
544 					struct tm tmp;
545 					time_t lct, gct;
546 
547 					/*
548 					** Get calendar time from t
549 					** being treated as local.
550 					*/
551 					tmp = *t; /* mktime discards const */
552 					lct = mktime(&tmp);
553 
554 					if (lct == (time_t)-1)
555 						continue;
556 
557 					/*
558 					** Get calendar time from t
559 					** being treated as GMT.
560 					**/
561 					tmp = *t; /* mktime discards const */
562 					gct = timegm(&tmp);
563 
564 					if (gct == (time_t)-1)
565 						continue;
566 
567 					/* LINTED difference will fit int */
568 					diff = (intmax_t)gct - (intmax_t)lct;
569 				}
570 #endif /* defined STD_INSPIRED */
571 #endif /* !defined TM_GMTOFF */
572 				if (diff < 0) {
573 					sign = "-";
574 					diff = -diff;
575 				} else	sign = "+";
576 				pt = _add(sign, pt, ptlim);
577 				diff /= SECSPERMIN;
578 				diff = (diff / MINSPERHOUR) * 100 +
579 					(diff % MINSPERHOUR);
580 				pt = _conv(diff, "%04d", pt, ptlim);
581 				}
582 				continue;
583 #if 0
584 			case '+':
585 				pt = _fmt(sp, _TIME_LOCALE(loc)->date_fmt, t,
586 				    pt, ptlim, warnp, loc);
587 				continue;
588 #endif
589 			case '%':
590 			/*
591 			** X311J/88-090 (4.12.3.5): if conversion char is
592 			** undefined, behavior is undefined. Print out the
593 			** character itself as printf(3) also does.
594 			*/
595 			default:
596 				break;
597 			}
598 		}
599 		if (pt == ptlim)
600 			break;
601 		*pt++ = *format;
602 	}
603 	return pt;
604 }
605 
606 size_t
607 strftime(char * const s, const size_t maxsize,
608     const char * const format, const struct tm * const	t)
609 {
610 	tzset();
611 	return strftime_z(NULL, s, maxsize, format, t);
612 }
613 
614 size_t
615 strftime_l(char * __restrict s, size_t maxsize, const char * __restrict format,
616     const struct tm * __restrict t, locale_t loc)
617 {
618 	tzset();
619 	return strftime_lz(NULL, s, maxsize, format, t, loc);
620 }
621 
622 static char *
623 _conv(const int	n, const char *const format, char *const pt,
624     const char *const ptlim)
625 {
626 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
627 
628 	(void) snprintf(buf, sizeof(buf), format, n);
629 	return _add(buf, pt, ptlim);
630 }
631 
632 static char *
633 _add(const char *str, char *pt, const char *const ptlim)
634 {
635 	while (pt < ptlim && (*pt = *str++) != '\0')
636 		++pt;
637 	return pt;
638 }
639 
640 /*
641 ** POSIX and the C Standard are unclear or inconsistent about
642 ** what %C and %y do if the year is negative or exceeds 9999.
643 ** Use the convention that %C concatenated with %y yields the
644 ** same output as %Y, and that %Y contains at least 4 bytes,
645 ** with more only if necessary.
646 */
647 
648 static char *
649 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
650     char *pt, const char *const ptlim)
651 {
652 	register int	lead;
653 	register int	trail;
654 
655 #define DIVISOR	100
656 	trail = a % DIVISOR + b % DIVISOR;
657 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
658 	trail %= DIVISOR;
659 	if (trail < 0 && lead > 0) {
660 		trail += DIVISOR;
661 		--lead;
662 	} else if (lead < 0 && trail > 0) {
663 		trail -= DIVISOR;
664 		++lead;
665 	}
666 	if (convert_top) {
667 		if (lead == 0 && trail < 0)
668 			pt = _add("-0", pt, ptlim);
669 		else	pt = _conv(lead, "%02d", pt, ptlim);
670 	}
671 	if (convert_yy)
672 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
673 	return pt;
674 }
675 
676 #ifdef LOCALE_HOME
677 static struct lc_time_T *
678 _loc(void)
679 {
680 	static const char	locale_home[] = LOCALE_HOME;
681 	static const char	lc_time[] = "LC_TIME";
682 	static char *		locale_buf;
683 
684 	int			fd;
685 	int			oldsun;	/* "...ain't got nothin' to do..." */
686 	char *			lbuf;
687 	char *			name;
688 	char *			p;
689 	const char **		ap;
690 	const char *		plim;
691 	char			filename[FILENAME_MAX];
692 	struct stat		st;
693 	size_t			namesize;
694 	size_t			bufsize;
695 
696 	/*
697 	** Use localebuf.mon[0] to signal whether locale is already set up.
698 	*/
699 	if (localebuf.mon[0])
700 		return &localebuf;
701 	name = setlocale(LC_TIME, NULL);
702 	if (name == NULL || *name == '\0')
703 		goto no_locale;
704 	/*
705 	** If the locale name is the same as our cache, use the cache.
706 	*/
707 	lbuf = locale_buf;
708 	if (lbuf != NULL && strcmp(name, lbuf) == 0) {
709 		p = lbuf;
710 		for (ap = (const char **) &localebuf;
711 			ap < (const char **) (&localebuf + 1);
712 				++ap)
713 					*ap = p += strlen(p) + 1;
714 		return &localebuf;
715 	}
716 	/*
717 	** Slurp the locale file into the cache.
718 	*/
719 	namesize = strlen(name) + 1;
720 	if (sizeof filename <
721 		((sizeof locale_home) + namesize + (sizeof lc_time)))
722 			goto no_locale;
723 	oldsun = 0;
724 	(void) sprintf(filename, "%s/%s/%s", locale_home, name, lc_time);
725 	fd = open(filename, O_RDONLY);
726 	if (fd < 0) {
727 		/*
728 		** Old Sun systems have a different naming and data convention.
729 		*/
730 		oldsun = 1;
731 		(void) sprintf(filename, "%s/%s/%s", locale_home,
732 			lc_time, name);
733 		fd = open(filename, O_RDONLY);
734 		if (fd < 0)
735 			goto no_locale;
736 	}
737 	if (fstat(fd, &st) != 0)
738 		goto bad_locale;
739 	if (st.st_size <= 0)
740 		goto bad_locale;
741 	bufsize = namesize + st.st_size;
742 	locale_buf = NULL;
743 	lbuf = (lbuf == NULL) ? malloc(bufsize) : realloc(lbuf, bufsize);
744 	if (lbuf == NULL)
745 		goto bad_locale;
746 	(void) strcpy(lbuf, name);
747 	p = lbuf + namesize;
748 	plim = p + st.st_size;
749 	if (read(fd, p, (size_t) st.st_size) != st.st_size)
750 		goto bad_lbuf;
751 	if (close(fd) != 0)
752 		goto bad_lbuf;
753 	/*
754 	** Parse the locale file into localebuf.
755 	*/
756 	if (plim[-1] != '\n')
757 		goto bad_lbuf;
758 	for (ap = (const char **) &localebuf;
759 		ap < (const char **) (&localebuf + 1);
760 			++ap) {
761 				if (p == plim)
762 					goto bad_lbuf;
763 				*ap = p;
764 				while (*p != '\n')
765 					++p;
766 				*p++ = '\0';
767 	}
768 	if (oldsun) {
769 		/*
770 		** SunOS 4 used an obsolescent format; see localdtconv(3).
771 		** c_fmt had the ``short format for dates and times together''
772 		** (SunOS 4 date, "%a %b %e %T %Z %Y" in the C locale);
773 		** date_fmt had the ``long format for dates''
774 		** (SunOS 4 strftime %C, "%A, %B %e, %Y" in the C locale).
775 		** Discard the latter in favor of the former.
776 		*/
777 		localebuf.date_fmt = localebuf.c_fmt;
778 	}
779 	/*
780 	** Record the successful parse in the cache.
781 	*/
782 	locale_buf = lbuf;
783 
784 	return &localebuf;
785 
786 bad_lbuf:
787 	free(lbuf);
788 bad_locale:
789 	(void) close(fd);
790 no_locale:
791 	localebuf = C_time_locale;
792 	locale_buf = NULL;
793 	return &localebuf;
794 }
795 #endif /* defined LOCALE_HOME */
796