xref: /netbsd-src/lib/libc/time/strftime.c (revision 7d3af8c6a2070d16ec6d1aef203d052d6683100d)
1 /*	$NetBSD: strftime.c,v 1.26 2013/05/17 12:55:57 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.26 2013/05/17 12:55:57 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 	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 						    "%lld", (long long) mkt);
319 					else	(void) snprintf(buf, sizeof(buf),
320 						    "%llu", (unsigned long long)
321 						    mkt);
322 					pt = _add(buf, pt, ptlim);
323 				}
324 				continue;
325 			case 'T':
326 				pt = _fmt(sp, "%H:%M:%S", t, pt, ptlim, warnp,
327 				    loc);
328 				continue;
329 			case 't':
330 				pt = _add("\t", pt, ptlim);
331 				continue;
332 			case 'U':
333 				pt = _conv((t->tm_yday + DAYSPERWEEK -
334 					t->tm_wday) / DAYSPERWEEK,
335 					"%02d", pt, ptlim);
336 				continue;
337 			case 'u':
338 				/*
339 				** From Arnold Robbins' strftime version 3.0:
340 				** "ISO 8601: Weekday as a decimal number
341 				** [1 (Monday) - 7]"
342 				** (ado, 1993-05-24)
343 				*/
344 				pt = _conv((t->tm_wday == 0) ?
345 					DAYSPERWEEK : t->tm_wday,
346 					"%d", pt, ptlim);
347 				continue;
348 			case 'V':	/* ISO 8601 week number */
349 			case 'G':	/* ISO 8601 year (four digits) */
350 			case 'g':	/* ISO 8601 year (two digits) */
351 /*
352 ** From Arnold Robbins' strftime version 3.0: "the week number of the
353 ** year (the first Monday as the first day of week 1) as a decimal number
354 ** (01-53)."
355 ** (ado, 1993-05-24)
356 **
357 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
358 ** "Week 01 of a year is per definition the first week which has the
359 ** Thursday in this year, which is equivalent to the week which contains
360 ** the fourth day of January. In other words, the first week of a new year
361 ** is the week which has the majority of its days in the new year. Week 01
362 ** might also contain days from the previous year and the week before week
363 ** 01 of a year is the last week (52 or 53) of the previous year even if
364 ** it contains days from the new year. A week starts with Monday (day 1)
365 ** and ends with Sunday (day 7). For example, the first week of the year
366 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
367 ** (ado, 1996-01-02)
368 */
369 				{
370 					int	year;
371 					int	base;
372 					int	yday;
373 					int	wday;
374 					int	w;
375 
376 					year = t->tm_year;
377 					base = TM_YEAR_BASE;
378 					yday = t->tm_yday;
379 					wday = t->tm_wday;
380 					for ( ; ; ) {
381 						int	len;
382 						int	bot;
383 						int	top;
384 
385 						len = isleap_sum(year, base) ?
386 							DAYSPERLYEAR :
387 							DAYSPERNYEAR;
388 						/*
389 						** What yday (-3 ... 3) does
390 						** the ISO year begin on?
391 						*/
392 						bot = ((yday + 11 - wday) %
393 							DAYSPERWEEK) - 3;
394 						/*
395 						** What yday does the NEXT
396 						** ISO year begin on?
397 						*/
398 						top = bot -
399 							(len % DAYSPERWEEK);
400 						if (top < -3)
401 							top += DAYSPERWEEK;
402 						top += len;
403 						if (yday >= top) {
404 							++base;
405 							w = 1;
406 							break;
407 						}
408 						if (yday >= bot) {
409 							w = 1 + ((yday - bot) /
410 								DAYSPERWEEK);
411 							break;
412 						}
413 						--base;
414 						yday += isleap_sum(year, base) ?
415 							DAYSPERLYEAR :
416 							DAYSPERNYEAR;
417 					}
418 #ifdef XPG4_1994_04_09
419 					if ((w == 52 &&
420 						t->tm_mon == TM_JANUARY) ||
421 						(w == 1 &&
422 						t->tm_mon == TM_DECEMBER))
423 							w = 53;
424 #endif /* defined XPG4_1994_04_09 */
425 					if (*format == 'V')
426 						pt = _conv(w, "%02d",
427 							pt, ptlim);
428 					else if (*format == 'g') {
429 						*warnp = IN_ALL;
430 						pt = _yconv(year, base, 0, 1,
431 							pt, ptlim);
432 					} else	pt = _yconv(year, base, 1, 1,
433 							pt, ptlim);
434 				}
435 				continue;
436 			case 'v':
437 				/*
438 				** From Arnold Robbins' strftime version 3.0:
439 				** "date as dd-bbb-YYYY"
440 				** (ado, 1993-05-24)
441 				*/
442 				pt = _fmt(sp, "%e-%b-%Y", t, pt, ptlim, warnp,
443 				    loc);
444 				continue;
445 			case 'W':
446 				pt = _conv((t->tm_yday + DAYSPERWEEK -
447 					(t->tm_wday ?
448 					(t->tm_wday - 1) :
449 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
450 					"%02d", pt, ptlim);
451 				continue;
452 			case 'w':
453 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
454 				continue;
455 			case 'X':
456 				pt = _fmt(sp, _TIME_LOCALE(loc)->t_fmt, t, pt,
457 				    ptlim, warnp, loc);
458 				continue;
459 			case 'x':
460 				{
461 				int	warn2 = IN_SOME;
462 
463 				pt = _fmt(sp, _TIME_LOCALE(loc)->d_fmt, t, pt,
464 				    ptlim, &warn2, loc);
465 				if (warn2 == IN_ALL)
466 					warn2 = IN_THIS;
467 				if (warn2 > *warnp)
468 					*warnp = warn2;
469 				}
470 				continue;
471 			case 'y':
472 				*warnp = IN_ALL;
473 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
474 					pt, ptlim);
475 				continue;
476 			case 'Y':
477 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
478 					pt, ptlim);
479 				continue;
480 			case 'Z':
481 #ifdef TM_ZONE
482 				if (t->TM_ZONE != NULL)
483 					pt = _add(t->TM_ZONE, pt, ptlim);
484 				else
485 #endif /* defined TM_ZONE */
486 				if (t->tm_isdst >= 0)
487 					pt = _add((sp ?
488 					    tzgetname(sp, t->tm_isdst) :
489 					    tzname[t->tm_isdst != 0]),
490 					    pt, ptlim);
491 				/*
492 				** C99 says that %Z must be replaced by the
493 				** empty string if the time zone is not
494 				** determinable.
495 				*/
496 				continue;
497 			case 'z':
498 				{
499 				int		diff;
500 				char const *	sign;
501 
502 				if (t->tm_isdst < 0)
503 					continue;
504 #ifdef TM_GMTOFF
505 				diff = (int)t->TM_GMTOFF;
506 #else /* !defined TM_GMTOFF */
507 				/*
508 				** C99 says that the UTC offset must
509 				** be computed by looking only at
510 				** tm_isdst. This requirement is
511 				** incorrect, since it means the code
512 				** must rely on magic (in this case
513 				** altzone and timezone), and the
514 				** magic might not have the correct
515 				** offset. Doing things correctly is
516 				** tricky and requires disobeying C99;
517 				** see GNU C strftime for details.
518 				** For now, punt and conform to the
519 				** standard, even though it's incorrect.
520 				**
521 				** C99 says that %z must be replaced by the
522 				** empty string if the time zone is not
523 				** determinable, so output nothing if the
524 				** appropriate variables are not available.
525 				*/
526 #ifndef STD_INSPIRED
527 				if (t->tm_isdst == 0)
528 #ifdef USG_COMPAT
529 					diff = -timezone;
530 #else /* !defined USG_COMPAT */
531 					continue;
532 #endif /* !defined USG_COMPAT */
533 				else
534 #ifdef ALTZONE
535 					diff = -altzone;
536 #else /* !defined ALTZONE */
537 					continue;
538 #endif /* !defined ALTZONE */
539 #else /* defined STD_INSPIRED */
540 				{
541 					struct tm tmp;
542 					time_t lct, gct;
543 
544 					/*
545 					** Get calendar time from t
546 					** being treated as local.
547 					*/
548 					tmp = *t; /* mktime discards const */
549 					lct = mktime(&tmp);
550 
551 					if (lct == (time_t)-1)
552 						continue;
553 
554 					/*
555 					** Get calendar time from t
556 					** being treated as GMT.
557 					**/
558 					tmp = *t; /* mktime discards const */
559 					gct = timegm(&tmp);
560 
561 					if (gct == (time_t)-1)
562 						continue;
563 
564 					/* LINTED difference will fit int */
565 					diff = (intmax_t)gct - (intmax_t)lct;
566 				}
567 #endif /* defined STD_INSPIRED */
568 #endif /* !defined TM_GMTOFF */
569 				if (diff < 0) {
570 					sign = "-";
571 					diff = -diff;
572 				} else	sign = "+";
573 				pt = _add(sign, pt, ptlim);
574 				diff /= SECSPERMIN;
575 				diff = (diff / MINSPERHOUR) * 100 +
576 					(diff % MINSPERHOUR);
577 				pt = _conv(diff, "%04d", pt, ptlim);
578 				}
579 				continue;
580 #if 0
581 			case '+':
582 				pt = _fmt(sp, _TIME_LOCALE(loc)->date_fmt, t,
583 				    pt, ptlim, warnp, loc);
584 				continue;
585 #endif
586 			case '%':
587 			/*
588 			** X311J/88-090 (4.12.3.5): if conversion char is
589 			** undefined, behavior is undefined. Print out the
590 			** character itself as printf(3) also does.
591 			*/
592 			default:
593 				break;
594 			}
595 		}
596 		if (pt == ptlim)
597 			break;
598 		*pt++ = *format;
599 	}
600 	return pt;
601 }
602 
603 size_t
604 strftime(char * const s, const size_t maxsize,
605     const char * const format, const struct tm * const	t)
606 {
607 	tzset();
608 	return strftime_z(NULL, s, maxsize, format, t);
609 }
610 
611 size_t
612 strftime_l(char * __restrict s, size_t maxsize, const char * __restrict format,
613     const struct tm * __restrict t, locale_t loc)
614 {
615 	tzset();
616 	return strftime_lz(NULL, s, maxsize, format, t, loc);
617 }
618 
619 static char *
620 _conv(const int	n, const char *const format, char *const pt,
621     const char *const ptlim)
622 {
623 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
624 
625 	(void) snprintf(buf, sizeof(buf), format, n);
626 	return _add(buf, pt, ptlim);
627 }
628 
629 static char *
630 _add(const char *str, char *pt, const char *const ptlim)
631 {
632 	while (pt < ptlim && (*pt = *str++) != '\0')
633 		++pt;
634 	return pt;
635 }
636 
637 /*
638 ** POSIX and the C Standard are unclear or inconsistent about
639 ** what %C and %y do if the year is negative or exceeds 9999.
640 ** Use the convention that %C concatenated with %y yields the
641 ** same output as %Y, and that %Y contains at least 4 bytes,
642 ** with more only if necessary.
643 */
644 
645 static char *
646 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
647     char *pt, const char *const ptlim)
648 {
649 	register int	lead;
650 	register int	trail;
651 
652 #define DIVISOR	100
653 	trail = a % DIVISOR + b % DIVISOR;
654 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
655 	trail %= DIVISOR;
656 	if (trail < 0 && lead > 0) {
657 		trail += DIVISOR;
658 		--lead;
659 	} else if (lead < 0 && trail > 0) {
660 		trail -= DIVISOR;
661 		++lead;
662 	}
663 	if (convert_top) {
664 		if (lead == 0 && trail < 0)
665 			pt = _add("-0", pt, ptlim);
666 		else	pt = _conv(lead, "%02d", pt, ptlim);
667 	}
668 	if (convert_yy)
669 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
670 	return pt;
671 }
672 
673 #ifdef LOCALE_HOME
674 static struct lc_time_T *
675 _loc(void)
676 {
677 	static const char	locale_home[] = LOCALE_HOME;
678 	static const char	lc_time[] = "LC_TIME";
679 	static char *		locale_buf;
680 
681 	int			fd;
682 	int			oldsun;	/* "...ain't got nothin' to do..." */
683 	char *			lbuf;
684 	char *			name;
685 	char *			p;
686 	const char **		ap;
687 	const char *		plim;
688 	char			filename[FILENAME_MAX];
689 	struct stat		st;
690 	size_t			namesize;
691 	size_t			bufsize;
692 
693 	/*
694 	** Use localebuf.mon[0] to signal whether locale is already set up.
695 	*/
696 	if (localebuf.mon[0])
697 		return &localebuf;
698 	name = setlocale(LC_TIME, NULL);
699 	if (name == NULL || *name == '\0')
700 		goto no_locale;
701 	/*
702 	** If the locale name is the same as our cache, use the cache.
703 	*/
704 	lbuf = locale_buf;
705 	if (lbuf != NULL && strcmp(name, lbuf) == 0) {
706 		p = lbuf;
707 		for (ap = (const char **) &localebuf;
708 			ap < (const char **) (&localebuf + 1);
709 				++ap)
710 					*ap = p += strlen(p) + 1;
711 		return &localebuf;
712 	}
713 	/*
714 	** Slurp the locale file into the cache.
715 	*/
716 	namesize = strlen(name) + 1;
717 	if (sizeof filename <
718 		((sizeof locale_home) + namesize + (sizeof lc_time)))
719 			goto no_locale;
720 	oldsun = 0;
721 	(void) sprintf(filename, "%s/%s/%s", locale_home, name, lc_time);
722 	fd = open(filename, O_RDONLY);
723 	if (fd < 0) {
724 		/*
725 		** Old Sun systems have a different naming and data convention.
726 		*/
727 		oldsun = 1;
728 		(void) sprintf(filename, "%s/%s/%s", locale_home,
729 			lc_time, name);
730 		fd = open(filename, O_RDONLY);
731 		if (fd < 0)
732 			goto no_locale;
733 	}
734 	if (fstat(fd, &st) != 0)
735 		goto bad_locale;
736 	if (st.st_size <= 0)
737 		goto bad_locale;
738 	bufsize = namesize + st.st_size;
739 	locale_buf = NULL;
740 	lbuf = (lbuf == NULL) ? malloc(bufsize) : realloc(lbuf, bufsize);
741 	if (lbuf == NULL)
742 		goto bad_locale;
743 	(void) strcpy(lbuf, name);
744 	p = lbuf + namesize;
745 	plim = p + st.st_size;
746 	if (read(fd, p, (size_t) st.st_size) != st.st_size)
747 		goto bad_lbuf;
748 	if (close(fd) != 0)
749 		goto bad_lbuf;
750 	/*
751 	** Parse the locale file into localebuf.
752 	*/
753 	if (plim[-1] != '\n')
754 		goto bad_lbuf;
755 	for (ap = (const char **) &localebuf;
756 		ap < (const char **) (&localebuf + 1);
757 			++ap) {
758 				if (p == plim)
759 					goto bad_lbuf;
760 				*ap = p;
761 				while (*p != '\n')
762 					++p;
763 				*p++ = '\0';
764 	}
765 	if (oldsun) {
766 		/*
767 		** SunOS 4 used an obsolescent format; see localdtconv(3).
768 		** c_fmt had the ``short format for dates and times together''
769 		** (SunOS 4 date, "%a %b %e %T %Z %Y" in the C locale);
770 		** date_fmt had the ``long format for dates''
771 		** (SunOS 4 strftime %C, "%A, %B %e, %Y" in the C locale).
772 		** Discard the latter in favor of the former.
773 		*/
774 		localebuf.date_fmt = localebuf.c_fmt;
775 	}
776 	/*
777 	** Record the successful parse in the cache.
778 	*/
779 	locale_buf = lbuf;
780 
781 	return &localebuf;
782 
783 bad_lbuf:
784 	free(lbuf);
785 bad_locale:
786 	(void) close(fd);
787 no_locale:
788 	localebuf = C_time_locale;
789 	locale_buf = NULL;
790 	return &localebuf;
791 }
792 #endif /* defined LOCALE_HOME */
793