xref: /dragonfly/lib/libc/stdtime/strftime.c (revision 279dd846)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Copyright (c) 2011 The FreeBSD Foundation
6  * All rights reserved.
7  * Portions of this software were developed by David Chisnall
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms are permitted
11  * provided that the above copyright notice and this paragraph are
12  * duplicated in all such forms and that any documentation,
13  * advertising materials, and other materials related to such
14  * distribution and use acknowledge that the software was developed
15  * by the University of California, Berkeley. The name of the
16  * University may not be used to endorse or promote products derived
17  * from this software without specific prior written permission.
18  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21  *
22  * @(#)strftime.c	5.4 (Berkeley) 3/14/89
23  * $FreeBSD: head/lib/libc/stdtime/strftime.c 237211 2012-06-17 21:40:13Z jilles $
24  */
25 
26 
27 #include "namespace.h"
28 #include "private.h"
29 
30 #include "tzfile.h"
31 #include <fcntl.h>
32 #include <sys/stat.h>
33 #include "un-namespace.h"
34 #include "timelocal.h"
35 
36 static char *	_add(const char *, char *, const char *);
37 static char *	_conv(int, const char *, char *, const char *);
38 static char *	_fmt(const char *, const struct tm *, char *, const char *,
39 			int *, locale_t);
40 static char *	_yconv(int, int, int, int, char *, const char *);
41 
42 extern char *	tzname[];
43 
44 #ifndef YEAR_2000_NAME
45 #define YEAR_2000_NAME	"CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
46 #endif /* !defined YEAR_2000_NAME */
47 
48 #define IN_NONE	0
49 #define IN_SOME	1
50 #define IN_THIS	2
51 #define IN_ALL	3
52 
53 #define PAD_DEFAULT	0
54 #define PAD_LESS	1
55 #define PAD_SPACE	2
56 #define PAD_ZERO	3
57 
58 static const char fmt_padding[][4][5] = {
59 	/* DEFAULT,	LESS,	SPACE,	ZERO */
60 #define PAD_FMT_MONTHDAY	0
61 #define PAD_FMT_HMS		0
62 #define PAD_FMT_CENTURY		0
63 #define PAD_FMT_SHORTYEAR	0
64 #define PAD_FMT_MONTH		0
65 #define PAD_FMT_WEEKOFYEAR	0
66 #define PAD_FMT_DAYOFMONTH	0
67 	{ "%02d",	"%d",	"%2d",	"%02d" },
68 #define PAD_FMT_SDAYOFMONTH	1
69 #define PAD_FMT_SHMS		1
70 	{ "%2d",	"%d",	"%2d",	"%02d" },
71 #define	PAD_FMT_DAYOFYEAR	2
72 	{ "%03d",	"%d",	"%3d",	"%03d" },
73 #define PAD_FMT_YEAR		3
74 	{ "%04d",	"%d",	"%4d",	"%04d" }
75 };
76 
77 size_t
78 strftime_l(char * __restrict s, size_t maxsize, const char * __restrict format,
79     const struct tm * __restrict t, locale_t loc)
80 {
81 	char *	p;
82 	int	warn;
83 	FIX_LOCALE(loc);
84 
85 	tzset();
86 	warn = IN_NONE;
87 	p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn, loc);
88 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
89 	if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
90 		fprintf_l(stderr, loc, "\n");
91 		if (format == NULL)
92 			fprintf_l(stderr, loc, "NULL strftime format ");
93 		else	fprintf_l(stderr, loc, "strftime format \"%s\" ",
94 				format);
95 		fprintf_l(stderr, loc, "yields only two digits of years in ");
96 		if (warn == IN_SOME)
97 			fprintf_l(stderr, loc, "some locales");
98 		else if (warn == IN_THIS)
99 			fprintf_l(stderr, loc, "the current locale");
100 		else	fprintf_l(stderr, loc, "all locales");
101 		fprintf_l(stderr, loc, "\n");
102 	}
103 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
104 	if (p == s + maxsize)
105 		return 0;
106 	*p = '\0';
107 	return p - s;
108 }
109 
110 size_t
111 strftime(char * __restrict s, size_t maxsize, const char * __restrict format,
112     const struct tm * __restrict t)
113 {
114 	return strftime_l(s, maxsize, format, t, __get_locale());
115 }
116 
117 static char *
118 _fmt(const char *format, const struct tm * const t, char *pt,
119     const char * const ptlim, int *warnp, locale_t loc)
120 {
121 	int Ealternative, Oalternative, PadIndex;
122 	struct lc_time_T *tptr = __get_current_time_locale(loc);
123 
124 	for ( ; *format; ++format) {
125 		if (*format == '%') {
126 			Ealternative = 0;
127 			Oalternative = 0;
128 			PadIndex	 = PAD_DEFAULT;
129 label:
130 			switch (*++format) {
131 			case '\0':
132 				--format;
133 				break;
134 			case 'A':
135 				pt = _add((t->tm_wday < 0 ||
136 					t->tm_wday >= DAYSPERWEEK) ?
137 					"?" : tptr->weekday[t->tm_wday],
138 					pt, ptlim);
139 				continue;
140 			case 'a':
141 				pt = _add((t->tm_wday < 0 ||
142 					t->tm_wday >= DAYSPERWEEK) ?
143 					"?" : tptr->wday[t->tm_wday],
144 					pt, ptlim);
145 				continue;
146 			case 'B':
147 				pt = _add((t->tm_mon < 0 ||
148 					t->tm_mon >= MONSPERYEAR) ?
149 					"?" : (Oalternative ? tptr->alt_month :
150 					tptr->month)[t->tm_mon],
151 					pt, ptlim);
152 				continue;
153 			case 'b':
154 			case 'h':
155 				pt = _add((t->tm_mon < 0 ||
156 					t->tm_mon >= MONSPERYEAR) ?
157 					"?" : tptr->mon[t->tm_mon],
158 					pt, ptlim);
159 				continue;
160 			case 'C':
161 				/*
162 				** %C used to do a...
163 				**	_fmt("%a %b %e %X %Y", t);
164 				** ...whereas now POSIX 1003.2 calls for
165 				** something completely different.
166 				** (ado, 1993-05-24)
167 				*/
168 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
169 					pt, ptlim);
170 				continue;
171 			case 'c':
172 				{
173 				int warn2 = IN_SOME;
174 
175 				pt = _fmt(tptr->c_fmt, t, pt, ptlim, &warn2, loc);
176 				if (warn2 == IN_ALL)
177 					warn2 = IN_THIS;
178 				if (warn2 > *warnp)
179 					*warnp = warn2;
180 				}
181 				continue;
182 			case 'D':
183 				pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp, loc);
184 				continue;
185 			case 'd':
186 				pt = _conv(t->tm_mday, fmt_padding[PAD_FMT_DAYOFMONTH][PadIndex],
187 					pt, ptlim);
188 				continue;
189 			case 'E':
190 				if (Ealternative || Oalternative)
191 					break;
192 				Ealternative++;
193 				goto label;
194 			case 'O':
195 				/*
196 				** C99 locale modifiers.
197 				** The sequences
198 				**	%Ec %EC %Ex %EX %Ey %EY
199 				**	%Od %oe %OH %OI %Om %OM
200 				**	%OS %Ou %OU %OV %Ow %OW %Oy
201 				** are supposed to provide alternate
202 				** representations.
203 				**
204 				** FreeBSD extension
205 				**      %OB
206 				*/
207 				if (Ealternative || Oalternative)
208 					break;
209 				Oalternative++;
210 				goto label;
211 			case 'e':
212 				pt = _conv(t->tm_mday,
213 					fmt_padding[PAD_FMT_SDAYOFMONTH][PadIndex], pt, ptlim);
214 				continue;
215 			case 'F':
216 				pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp, loc);
217 				continue;
218 			case 'H':
219 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_HMS][PadIndex],
220 					pt, ptlim);
221 				continue;
222 			case 'I':
223 				pt = _conv((t->tm_hour % 12) ?
224 					(t->tm_hour % 12) : 12,
225 					fmt_padding[PAD_FMT_HMS][PadIndex], pt, ptlim);
226 				continue;
227 			case 'j':
228 				pt = _conv(t->tm_yday + 1,
229 					fmt_padding[PAD_FMT_DAYOFYEAR][PadIndex], pt, ptlim);
230 				continue;
231 			case 'k':
232 				/*
233 				** This used to be...
234 				**	_conv(t->tm_hour % 12 ?
235 				**		t->tm_hour % 12 : 12, 2, ' ');
236 				** ...and has been changed to the below to
237 				** match SunOS 4.1.1 and Arnold Robbins'
238 				** strftime version 3.0. That is, "%k" and
239 				** "%l" have been swapped.
240 				** (ado, 1993-05-24)
241 				*/
242 				pt = _conv(t->tm_hour, fmt_padding[PAD_FMT_SHMS][PadIndex],
243 					pt, ptlim);
244 				continue;
245 #ifdef KITCHEN_SINK
246 			case 'K':
247 				/*
248 				** After all this time, still unclaimed!
249 				*/
250 				pt = _add("kitchen sink", pt, ptlim);
251 				continue;
252 #endif /* defined KITCHEN_SINK */
253 			case 'l':
254 				/*
255 				** This used to be...
256 				**	_conv(t->tm_hour, 2, ' ');
257 				** ...and has been changed to the below to
258 				** match SunOS 4.1.1 and Arnold Robbin's
259 				** strftime version 3.0. That is, "%k" and
260 				** "%l" have been swapped.
261 				** (ado, 1993-05-24)
262 				*/
263 				pt = _conv((t->tm_hour % 12) ?
264 					(t->tm_hour % 12) : 12,
265 					fmt_padding[PAD_FMT_SHMS][PadIndex], pt, ptlim);
266 				continue;
267 			case 'M':
268 				pt = _conv(t->tm_min, fmt_padding[PAD_FMT_HMS][PadIndex],
269 					pt, ptlim);
270 				continue;
271 			case 'm':
272 				pt = _conv(t->tm_mon + 1,
273 					fmt_padding[PAD_FMT_MONTH][PadIndex], pt, ptlim);
274 				continue;
275 			case 'n':
276 				pt = _add("\n", pt, ptlim);
277 				continue;
278 			case 'p':
279 				pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
280 					tptr->pm :
281 					tptr->am,
282 					pt, ptlim);
283 				continue;
284 			case 'R':
285 				pt = _fmt("%H:%M", t, pt, ptlim, warnp, loc);
286 				continue;
287 			case 'r':
288 				pt = _fmt(tptr->ampm_fmt, t, pt, ptlim,
289 					warnp, loc);
290 				continue;
291 			case 'S':
292 				pt = _conv(t->tm_sec, fmt_padding[PAD_FMT_HMS][PadIndex],
293 					pt, ptlim);
294 				continue;
295 			case 's':
296 				{
297 					struct tm	tm;
298 					char		buf[INT_STRLEN_MAXIMUM(
299 								time_t) + 1];
300 					time_t		mkt;
301 
302 					tm = *t;
303 					mkt = mktime(&tm);
304 					if (TYPE_SIGNED(time_t))
305 						snprintf(buf, sizeof(buf),
306 						    "%"PRIdMAX,
307 						    (intmax_t) mkt);
308 					else	snprintf(buf, sizeof(buf),
309 						    "%"PRIuMAX,
310 						    (uintmax_t) mkt);
311 					pt = _add(buf, pt, ptlim);
312 				}
313 				continue;
314 			case 'T':
315 				pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp, loc);
316 				continue;
317 			case 't':
318 				pt = _add("\t", pt, ptlim);
319 				continue;
320 			case 'U':
321 				pt = _conv((t->tm_yday + DAYSPERWEEK -
322 					t->tm_wday) / DAYSPERWEEK,
323 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
324 				continue;
325 			case 'u':
326 				/*
327 				** From Arnold Robbins' strftime version 3.0:
328 				** "ISO 8601: Weekday as a decimal number
329 				** [1 (Monday) - 7]"
330 				** (ado, 1993-05-24)
331 				*/
332 				pt = _conv((t->tm_wday == 0) ?
333 					DAYSPERWEEK : t->tm_wday,
334 					"%d", pt, ptlim);
335 				continue;
336 			case 'V':	/* ISO 8601 week number */
337 			case 'G':	/* ISO 8601 year (four digits) */
338 			case 'g':	/* ISO 8601 year (two digits) */
339 /*
340 ** From Arnold Robbins' strftime version 3.0: "the week number of the
341 ** year (the first Monday as the first day of week 1) as a decimal number
342 ** (01-53)."
343 ** (ado, 1993-05-24)
344 **
345 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
346 ** "Week 01 of a year is per definition the first week which has the
347 ** Thursday in this year, which is equivalent to the week which contains
348 ** the fourth day of January. In other words, the first week of a new year
349 ** is the week which has the majority of its days in the new year. Week 01
350 ** might also contain days from the previous year and the week before week
351 ** 01 of a year is the last week (52 or 53) of the previous year even if
352 ** it contains days from the new year. A week starts with Monday (day 1)
353 ** and ends with Sunday (day 7). For example, the first week of the year
354 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
355 ** (ado, 1996-01-02)
356 */
357 				{
358 					int	year;
359 					int	base;
360 					int	yday;
361 					int	wday;
362 					int	w;
363 
364 					year = t->tm_year;
365 					base = TM_YEAR_BASE;
366 					yday = t->tm_yday;
367 					wday = t->tm_wday;
368 					for ( ; ; ) {
369 						int	len;
370 						int	bot;
371 						int	top;
372 
373 						len = isleap_sum(year, base) ?
374 							DAYSPERLYEAR :
375 							DAYSPERNYEAR;
376 						/*
377 						** What yday (-3 ... 3) does
378 						** the ISO year begin on?
379 						*/
380 						bot = ((yday + 11 - wday) %
381 							DAYSPERWEEK) - 3;
382 						/*
383 						** What yday does the NEXT
384 						** ISO year begin on?
385 						*/
386 						top = bot -
387 							(len % DAYSPERWEEK);
388 						if (top < -3)
389 							top += DAYSPERWEEK;
390 						top += len;
391 						if (yday >= top) {
392 							++base;
393 							w = 1;
394 							break;
395 						}
396 						if (yday >= bot) {
397 							w = 1 + ((yday - bot) /
398 								DAYSPERWEEK);
399 							break;
400 						}
401 						--base;
402 						yday += isleap_sum(year, base) ?
403 							DAYSPERLYEAR :
404 							DAYSPERNYEAR;
405 					}
406 #ifdef XPG4_1994_04_09
407 					if ((w == 52 &&
408 						t->tm_mon == TM_JANUARY) ||
409 						(w == 1 &&
410 						t->tm_mon == TM_DECEMBER))
411 							w = 53;
412 #endif /* defined XPG4_1994_04_09 */
413 					if (*format == 'V')
414 						pt = _conv(w, fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
415 							pt, ptlim);
416 					else if (*format == 'g') {
417 						*warnp = IN_ALL;
418 						pt = _yconv(year, base, 0, 1,
419 							pt, ptlim);
420 					} else	pt = _yconv(year, base, 1, 1,
421 							pt, ptlim);
422 				}
423 				continue;
424 			case 'v':
425 				/*
426 				** From Arnold Robbins' strftime version 3.0:
427 				** "date as dd-bbb-YYYY"
428 				** (ado, 1993-05-24)
429 				*/
430 				pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp, loc);
431 				continue;
432 			case 'W':
433 				pt = _conv((t->tm_yday + DAYSPERWEEK -
434 					(t->tm_wday ?
435 					(t->tm_wday - 1) :
436 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
437 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
438 				continue;
439 			case 'w':
440 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
441 				continue;
442 			case 'X':
443 				pt = _fmt(tptr->X_fmt, t, pt, ptlim, warnp, loc);
444 				continue;
445 			case 'x':
446 				{
447 				int	warn2 = IN_SOME;
448 
449 				pt = _fmt(tptr->x_fmt, t, pt, ptlim, &warn2, loc);
450 				if (warn2 == IN_ALL)
451 					warn2 = IN_THIS;
452 				if (warn2 > *warnp)
453 					*warnp = warn2;
454 				}
455 				continue;
456 			case 'y':
457 				*warnp = IN_ALL;
458 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
459 					pt, ptlim);
460 				continue;
461 			case 'Y':
462 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
463 					pt, ptlim);
464 				continue;
465 			case 'Z':
466 #ifdef TM_ZONE
467 				if (t->TM_ZONE != NULL)
468 					pt = _add(t->TM_ZONE, pt, ptlim);
469 				else
470 #endif /* defined TM_ZONE */
471 				if (t->tm_isdst >= 0)
472 					pt = _add(tzname[t->tm_isdst != 0],
473 						pt, ptlim);
474 				/*
475 				** C99 says that %Z must be replaced by the
476 				** empty string if the time zone is not
477 				** determinable.
478 				*/
479 				continue;
480 			case 'z':
481 				{
482 				long		diff;
483 				char const *	sign;
484 
485 				if (t->tm_isdst < 0)
486 					continue;
487 #ifdef TM_GMTOFF
488 				diff = t->TM_GMTOFF;
489 #else /* !defined TM_GMTOFF */
490 				/*
491 				** C99 says that the UT offset must
492 				** be computed by looking only at
493 				** tm_isdst. This requirement is
494 				** incorrect, since it means the code
495 				** must rely on magic (in this case
496 				** altzone and timezone), and the
497 				** magic might not have the correct
498 				** offset. Doing things correctly is
499 				** tricky and requires disobeying C99;
500 				** see GNU C strftime for details.
501 				** For now, punt and conform to the
502 				** standard, even though it's incorrect.
503 				**
504 				** C99 says that %z must be replaced by the
505 				** empty string if the time zone is not
506 				** determinable, so output nothing if the
507 				** appropriate variables are not available.
508 				*/
509 				if (t->tm_isdst == 0)
510 					diff = -timezone;
511 				else
512 					continue;
513 #endif /* !defined TM_GMTOFF */
514 				if (diff < 0) {
515 					sign = "-";
516 					diff = -diff;
517 				} else	sign = "+";
518 				pt = _add(sign, pt, ptlim);
519 				diff /= SECSPERMIN;
520 				diff = (diff / MINSPERHOUR) * 100 +
521 					(diff % MINSPERHOUR);
522 				pt = _conv(diff,
523 					fmt_padding[PAD_FMT_YEAR][PadIndex], pt, ptlim);
524 				}
525 				continue;
526 			case '+':
527 				pt = _fmt(tptr->date_fmt, t, pt, ptlim,
528 					warnp, loc);
529 				continue;
530 			case '-':
531 				if (PadIndex != PAD_DEFAULT)
532 					break;
533 				PadIndex = PAD_LESS;
534 				goto label;
535 			case '_':
536 				if (PadIndex != PAD_DEFAULT)
537 					break;
538 				PadIndex = PAD_SPACE;
539 				goto label;
540 			case '0':
541 				if (PadIndex != PAD_DEFAULT)
542 					break;
543 				PadIndex = PAD_ZERO;
544 				goto label;
545 			case '%':
546 			/*
547 			** X311J/88-090 (4.12.3.5): if conversion char is
548 			** undefined, behavior is undefined. Print out the
549 			** character itself as printf(3) also does.
550 			*/
551 			default:
552 				break;
553 			}
554 		}
555 		if (pt == ptlim)
556 			break;
557 		*pt++ = *format;
558 	}
559 	return pt;
560 }
561 
562 static char *
563 _conv(const int n, const char * const format, char * const pt,
564     const char * const ptlim)
565 {
566 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
567 
568 	snprintf(buf, sizeof(buf), format, n);
569 	return _add(buf, pt, ptlim);
570 }
571 
572 static char *
573 _add(const char *str, char *pt, const char * const ptlim)
574 {
575 	while (pt < ptlim && (*pt = *str++) != '\0')
576 		++pt;
577 	return pt;
578 }
579 
580 /*
581 ** POSIX and the C Standard are unclear or inconsistent about
582 ** what %C and %y do if the year is negative or exceeds 9999.
583 ** Use the convention that %C concatenated with %y yields the
584 ** same output as %Y, and that %Y contains at least 4 bytes,
585 ** with more only if necessary.
586 */
587 
588 static char *
589 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
590     char *pt, const char * const ptlim)
591 {
592 	int	lead;
593 	int	trail;
594 
595 #define DIVISOR	100
596 	trail = a % DIVISOR + b % DIVISOR;
597 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
598 	trail %= DIVISOR;
599 	if (trail < 0 && lead > 0) {
600 		trail += DIVISOR;
601 		--lead;
602 	} else if (lead < 0 && trail > 0) {
603 		trail -= DIVISOR;
604 		++lead;
605 	}
606 	if (convert_top) {
607 		if (lead == 0 && trail < 0)
608 			pt = _add("-0", pt, ptlim);
609 		else	pt = _conv(lead, "%02d", pt, ptlim);
610 	}
611 	if (convert_yy)
612 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
613 	return pt;
614 }
615