xref: /dflybsd-src/lib/libc/stdtime/strftime.c (revision 4badba3841ae9f4d60211d1c5ed006e17b38c299)
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 		(void) fprintf_l(stderr, loc, "\n");
91 		if (format == NULL)
92 			(void) fprintf_l(stderr, loc, "NULL strftime format ");
93 		else	(void) fprintf_l(stderr, loc, "strftime format \"%s\" ",
94 				format);
95 		(void) fprintf_l(stderr, loc, "yields only two digits of years in ");
96 		if (warn == IN_SOME)
97 			(void) fprintf_l(stderr, loc, "some locales");
98 		else if (warn == IN_THIS)
99 			(void) fprintf_l(stderr, loc, "the current locale");
100 		else	(void) fprintf_l(stderr, loc, "all locales");
101 		(void) 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 						(void) sprintf(buf, "%ld",
306 							(long) mkt);
307 					else	(void) sprintf(buf, "%lu",
308 							(unsigned long) mkt);
309 					pt = _add(buf, pt, ptlim);
310 				}
311 				continue;
312 			case 'T':
313 				pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp, loc);
314 				continue;
315 			case 't':
316 				pt = _add("\t", pt, ptlim);
317 				continue;
318 			case 'U':
319 				pt = _conv((t->tm_yday + DAYSPERWEEK -
320 					t->tm_wday) / DAYSPERWEEK,
321 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
322 				continue;
323 			case 'u':
324 				/*
325 				** From Arnold Robbins' strftime version 3.0:
326 				** "ISO 8601: Weekday as a decimal number
327 				** [1 (Monday) - 7]"
328 				** (ado, 1993-05-24)
329 				*/
330 				pt = _conv((t->tm_wday == 0) ?
331 					DAYSPERWEEK : t->tm_wday,
332 					"%d", pt, ptlim);
333 				continue;
334 			case 'V':	/* ISO 8601 week number */
335 			case 'G':	/* ISO 8601 year (four digits) */
336 			case 'g':	/* ISO 8601 year (two digits) */
337 /*
338 ** From Arnold Robbins' strftime version 3.0: "the week number of the
339 ** year (the first Monday as the first day of week 1) as a decimal number
340 ** (01-53)."
341 ** (ado, 1993-05-24)
342 **
343 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
344 ** "Week 01 of a year is per definition the first week which has the
345 ** Thursday in this year, which is equivalent to the week which contains
346 ** the fourth day of January. In other words, the first week of a new year
347 ** is the week which has the majority of its days in the new year. Week 01
348 ** might also contain days from the previous year and the week before week
349 ** 01 of a year is the last week (52 or 53) of the previous year even if
350 ** it contains days from the new year. A week starts with Monday (day 1)
351 ** and ends with Sunday (day 7). For example, the first week of the year
352 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
353 ** (ado, 1996-01-02)
354 */
355 				{
356 					int	year;
357 					int	base;
358 					int	yday;
359 					int	wday;
360 					int	w;
361 
362 					year = t->tm_year;
363 					base = TM_YEAR_BASE;
364 					yday = t->tm_yday;
365 					wday = t->tm_wday;
366 					for ( ; ; ) {
367 						int	len;
368 						int	bot;
369 						int	top;
370 
371 						len = isleap_sum(year, base) ?
372 							DAYSPERLYEAR :
373 							DAYSPERNYEAR;
374 						/*
375 						** What yday (-3 ... 3) does
376 						** the ISO year begin on?
377 						*/
378 						bot = ((yday + 11 - wday) %
379 							DAYSPERWEEK) - 3;
380 						/*
381 						** What yday does the NEXT
382 						** ISO year begin on?
383 						*/
384 						top = bot -
385 							(len % DAYSPERWEEK);
386 						if (top < -3)
387 							top += DAYSPERWEEK;
388 						top += len;
389 						if (yday >= top) {
390 							++base;
391 							w = 1;
392 							break;
393 						}
394 						if (yday >= bot) {
395 							w = 1 + ((yday - bot) /
396 								DAYSPERWEEK);
397 							break;
398 						}
399 						--base;
400 						yday += isleap_sum(year, base) ?
401 							DAYSPERLYEAR :
402 							DAYSPERNYEAR;
403 					}
404 #ifdef XPG4_1994_04_09
405 					if ((w == 52 &&
406 						t->tm_mon == TM_JANUARY) ||
407 						(w == 1 &&
408 						t->tm_mon == TM_DECEMBER))
409 							w = 53;
410 #endif /* defined XPG4_1994_04_09 */
411 					if (*format == 'V')
412 						pt = _conv(w, fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex],
413 							pt, ptlim);
414 					else if (*format == 'g') {
415 						*warnp = IN_ALL;
416 						pt = _yconv(year, base, 0, 1,
417 							pt, ptlim);
418 					} else	pt = _yconv(year, base, 1, 1,
419 							pt, ptlim);
420 				}
421 				continue;
422 			case 'v':
423 				/*
424 				** From Arnold Robbins' strftime version 3.0:
425 				** "date as dd-bbb-YYYY"
426 				** (ado, 1993-05-24)
427 				*/
428 				pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp, loc);
429 				continue;
430 			case 'W':
431 				pt = _conv((t->tm_yday + DAYSPERWEEK -
432 					(t->tm_wday ?
433 					(t->tm_wday - 1) :
434 					(DAYSPERWEEK - 1))) / DAYSPERWEEK,
435 					fmt_padding[PAD_FMT_WEEKOFYEAR][PadIndex], pt, ptlim);
436 				continue;
437 			case 'w':
438 				pt = _conv(t->tm_wday, "%d", pt, ptlim);
439 				continue;
440 			case 'X':
441 				pt = _fmt(tptr->X_fmt, t, pt, ptlim, warnp, loc);
442 				continue;
443 			case 'x':
444 				{
445 				int	warn2 = IN_SOME;
446 
447 				pt = _fmt(tptr->x_fmt, t, pt, ptlim, &warn2, loc);
448 				if (warn2 == IN_ALL)
449 					warn2 = IN_THIS;
450 				if (warn2 > *warnp)
451 					*warnp = warn2;
452 				}
453 				continue;
454 			case 'y':
455 				*warnp = IN_ALL;
456 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
457 					pt, ptlim);
458 				continue;
459 			case 'Y':
460 				pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
461 					pt, ptlim);
462 				continue;
463 			case 'Z':
464 #ifdef TM_ZONE
465 				if (t->TM_ZONE != NULL)
466 					pt = _add(t->TM_ZONE, pt, ptlim);
467 				else
468 #endif /* defined TM_ZONE */
469 				if (t->tm_isdst >= 0)
470 					pt = _add(tzname[t->tm_isdst != 0],
471 						pt, ptlim);
472 				/*
473 				** C99 says that %Z must be replaced by the
474 				** empty string if the time zone is not
475 				** determinable.
476 				*/
477 				continue;
478 			case 'z':
479 				{
480 				int		diff;
481 				char const *	sign;
482 
483 				if (t->tm_isdst < 0)
484 					continue;
485 #ifdef TM_GMTOFF
486 				diff = t->TM_GMTOFF;
487 #else /* !defined TM_GMTOFF */
488 				/*
489 				** C99 says that the UTC offset must
490 				** be computed by looking only at
491 				** tm_isdst. This requirement is
492 				** incorrect, since it means the code
493 				** must rely on magic (in this case
494 				** altzone and timezone), and the
495 				** magic might not have the correct
496 				** offset. Doing things correctly is
497 				** tricky and requires disobeying C99;
498 				** see GNU C strftime for details.
499 				** For now, punt and conform to the
500 				** standard, even though it's incorrect.
501 				**
502 				** C99 says that %z must be replaced by the
503 				** empty string if the time zone is not
504 				** determinable, so output nothing if the
505 				** appropriate variables are not available.
506 				*/
507 				if (t->tm_isdst == 0)
508 					diff = -timezone;
509 				else
510 					continue;
511 #endif /* !defined TM_GMTOFF */
512 				if (diff < 0) {
513 					sign = "-";
514 					diff = -diff;
515 				} else	sign = "+";
516 				pt = _add(sign, pt, ptlim);
517 				diff /= SECSPERMIN;
518 				diff = (diff / MINSPERHOUR) * 100 +
519 					(diff % MINSPERHOUR);
520 				pt = _conv(diff,
521 					fmt_padding[PAD_FMT_YEAR][PadIndex], pt, ptlim);
522 				}
523 				continue;
524 			case '+':
525 				pt = _fmt(tptr->date_fmt, t, pt, ptlim,
526 					warnp, loc);
527 				continue;
528 			case '-':
529 				if (PadIndex != PAD_DEFAULT)
530 					break;
531 				PadIndex = PAD_LESS;
532 				goto label;
533 			case '_':
534 				if (PadIndex != PAD_DEFAULT)
535 					break;
536 				PadIndex = PAD_SPACE;
537 				goto label;
538 			case '0':
539 				if (PadIndex != PAD_DEFAULT)
540 					break;
541 				PadIndex = PAD_ZERO;
542 				goto label;
543 			case '%':
544 			/*
545 			** X311J/88-090 (4.12.3.5): if conversion char is
546 			** undefined, behavior is undefined. Print out the
547 			** character itself as printf(3) also does.
548 			*/
549 			default:
550 				break;
551 			}
552 		}
553 		if (pt == ptlim)
554 			break;
555 		*pt++ = *format;
556 	}
557 	return pt;
558 }
559 
560 static char *
561 _conv(const int n, const char * const format, char * const pt,
562     const char * const ptlim)
563 {
564 	char	buf[INT_STRLEN_MAXIMUM(int) + 1];
565 
566 	(void) sprintf(buf, format, n);
567 	return _add(buf, pt, ptlim);
568 }
569 
570 static char *
571 _add(const char *str, char *pt, const char * const ptlim)
572 {
573 	while (pt < ptlim && (*pt = *str++) != '\0')
574 		++pt;
575 	return pt;
576 }
577 
578 /*
579 ** POSIX and the C Standard are unclear or inconsistent about
580 ** what %C and %y do if the year is negative or exceeds 9999.
581 ** Use the convention that %C concatenated with %y yields the
582 ** same output as %Y, and that %Y contains at least 4 bytes,
583 ** with more only if necessary.
584 */
585 
586 static char *
587 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
588     char *pt, const char * const ptlim)
589 {
590 	int	lead;
591 	int	trail;
592 
593 #define DIVISOR	100
594 	trail = a % DIVISOR + b % DIVISOR;
595 	lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
596 	trail %= DIVISOR;
597 	if (trail < 0 && lead > 0) {
598 		trail += DIVISOR;
599 		--lead;
600 	} else if (lead < 0 && trail > 0) {
601 		trail -= DIVISOR;
602 		++lead;
603 	}
604 	if (convert_top) {
605 		if (lead == 0 && trail < 0)
606 			pt = _add("-0", pt, ptlim);
607 		else	pt = _conv(lead, "%02d", pt, ptlim);
608 	}
609 	if (convert_yy)
610 		pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
611 	return pt;
612 }
613