xref: /PHP-8.0/sapi/phpdbg/phpdbg_out.c (revision 5d6e923d)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Felipe Pena <felipe@php.net>                                |
14    | Authors: Joe Watkins <joe.watkins@live.co.uk>                        |
15    | Authors: Bob Weinand <bwoebi@php.net>                                |
16    +----------------------------------------------------------------------+
17 */
18 
19 #include "zend.h"
20 #include "php.h"
21 #include "spprintf.h"
22 #include "phpdbg.h"
23 #include "phpdbg_io.h"
24 #include "phpdbg_eol.h"
25 #include "ext/standard/html.h"
26 
27 #ifdef _WIN32
28 #	include "win32/time.h"
29 #endif
30 
31 ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
32 
33 /* copied from php-src/main/snprintf.c and slightly modified */
34 /*
35  * NUM_BUF_SIZE is the size of the buffer used for arithmetic conversions
36  *
37  * XXX: this is a magic number; do not decrease it
38  * Emax = 1023
39  * NDIG = 320
40  * NUM_BUF_SIZE >= strlen("-") + Emax + strlrn(".") + NDIG + strlen("E+1023") + 1;
41  */
42 #define NUM_BUF_SIZE        2048
43 
44 /*
45  * Descriptor for buffer area
46  */
47 struct buf_area {
48 	char *buf_end;
49 	char *nextb; /* pointer to next byte to read/write   */
50 };
51 
52 typedef struct buf_area buffy;
53 
54 /*
55  * The INS_CHAR macro inserts a character in the buffer and writes
56  * the buffer back to disk if necessary
57  * It uses the char pointers sp and bep:
58  *      sp points to the next available character in the buffer
59  *      bep points to the end-of-buffer+1
60  * While using this macro, note that the nextb pointer is NOT updated.
61  *
62  * NOTE: Evaluation of the c argument should not have any side-effects
63  */
64 #define INS_CHAR(c, sp, bep, cc) \
65 	{                            \
66 		if (sp < bep)            \
67 		{                        \
68 			*sp++ = c;           \
69 		}                        \
70 		cc++;                    \
71 	}
72 
73 #define NUM( c )			( c - '0' )
74 
75 #define STR_TO_DEC( str, num )		\
76     num = NUM( *str++ ) ;		\
77     while ( isdigit((int)*str ) )		\
78     {					\
79 	num *= 10 ;			\
80 	num += NUM( *str++ ) ;		\
81     }
82 
83 /*
84  * This macro does zero padding so that the precision
85  * requirement is satisfied. The padding is done by
86  * adding '0's to the left of the string that is going
87  * to be printed.
88  */
89 #define FIX_PRECISION( adjust, precision, s, s_len )	\
90     if ( adjust )					\
91 	while ( s_len < precision )			\
92 	{						\
93 	    *--s = '0' ;				\
94 	    s_len++ ;					\
95 	}
96 
97 /*
98  * Macro that does padding. The padding is done by printing
99  * the character ch.
100  */
101 #define PAD( width, len, ch )	do		\
102 	{					\
103 	    INS_CHAR( ch, sp, bep, cc ) ;	\
104 	    width-- ;				\
105 	}					\
106 	while ( width > len )
107 
108 /*
109  * Prefix the character ch to the string str
110  * Increase length
111  * Set the has_prefix flag
112  */
113 #define PREFIX( str, length, ch )	 *--str = ch ; length++ ; has_prefix = YES
114 
115 #include <locale.h>
116 #define LCONV_DECIMAL_POINT (*lconv->decimal_point)
117 #define NUL '\0'
118 #define S_NULL "(null)"
119 #define S_NULL_LEN 6
120 #define FLOAT_DIGITS 6
121 
122 /*
123  * Do format conversion placing the output in buffer
124  */
format_converter(register buffy * odp,const char * fmt,zend_bool escape_xml,va_list ap)125 static int format_converter(register buffy *odp, const char *fmt, zend_bool escape_xml, va_list ap) {
126 	char *sp;
127 	char *bep;
128 	int cc = 0;
129 	int i;
130 
131 	char *s = NULL, *free_s = NULL;
132 	size_t s_len;
133 	zend_bool free_zcopy;
134 	zval *zvp, zcopy;
135 
136 	int min_width = 0;
137 	int precision = 0;
138 	enum {
139 		LEFT, RIGHT
140 	} adjust;
141 	char pad_char;
142 	char prefix_char;
143 
144 	double fp_num;
145 	wide_int i_num = (wide_int) 0;
146 	u_wide_int ui_num;
147 
148 	char num_buf[NUM_BUF_SIZE];
149 	char char_buf[2];			/* for printing %% and %<unknown> */
150 
151 	struct lconv *lconv = NULL;
152 
153 	/*
154 	 * Flag variables
155 	 */
156 	length_modifier_e modifier;
157 	boolean_e alternate_form;
158 	boolean_e print_sign;
159 	boolean_e print_blank;
160 	boolean_e adjust_precision;
161 	boolean_e adjust_width;
162 	bool_int is_negative;
163 
164 	sp = odp->nextb;
165 	bep = odp->buf_end;
166 
167 	while (*fmt) {
168 		if (*fmt != '%') {
169 			INS_CHAR(*fmt, sp, bep, cc);
170 		} else {
171 			/*
172 			 * Default variable settings
173 			 */
174 			adjust = RIGHT;
175 			alternate_form = print_sign = print_blank = NO;
176 			pad_char = ' ';
177 			prefix_char = NUL;
178 			free_zcopy = 0;
179 
180 			fmt++;
181 
182 			/*
183 			 * Try to avoid checking for flags, width or precision
184 			 */
185 			if (isascii((int)*fmt) && !islower((int)*fmt)) {
186 				/*
187 				 * Recognize flags: -, #, BLANK, +
188 				 */
189 				for (;; fmt++) {
190 					if (*fmt == '-')
191 						adjust = LEFT;
192 					else if (*fmt == '+')
193 						print_sign = YES;
194 					else if (*fmt == '#')
195 						alternate_form = YES;
196 					else if (*fmt == ' ')
197 						print_blank = YES;
198 					else if (*fmt == '0')
199 						pad_char = '0';
200 					else
201 						break;
202 				}
203 
204 				/*
205 				 * Check if a width was specified
206 				 */
207 				if (isdigit((int)*fmt)) {
208 					STR_TO_DEC(fmt, min_width);
209 					adjust_width = YES;
210 				} else if (*fmt == '*') {
211 					min_width = va_arg(ap, int);
212 					fmt++;
213 					adjust_width = YES;
214 					if (min_width < 0) {
215 						adjust = LEFT;
216 						min_width = -min_width;
217 					}
218 				} else
219 					adjust_width = NO;
220 
221 				/*
222 				 * Check if a precision was specified
223 				 */
224 				if (*fmt == '.') {
225 					adjust_precision = YES;
226 					fmt++;
227 					if (isdigit((int)*fmt)) {
228 						STR_TO_DEC(fmt, precision);
229 					} else if (*fmt == '*') {
230 						precision = va_arg(ap, int);
231 						fmt++;
232 						if (precision < 0)
233 							precision = 0;
234 					} else
235 						precision = 0;
236 
237 					if (precision > FORMAT_CONV_MAX_PRECISION && *fmt != 's' && *fmt != 'v' && *fmt != 'b') {
238 						precision = FORMAT_CONV_MAX_PRECISION;
239 					}
240 				} else
241 					adjust_precision = NO;
242 			} else
243 				adjust_precision = adjust_width = NO;
244 
245 			/*
246 			 * Modifier check
247 			 */
248 			switch (*fmt) {
249 				case 'L':
250 					fmt++;
251 					modifier = LM_LONG_DOUBLE;
252 					break;
253 				case 'I':
254 					fmt++;
255 #if SIZEOF_LONG_LONG
256 					if (*fmt == '6' && *(fmt+1) == '4') {
257 						fmt += 2;
258 						modifier = LM_LONG_LONG;
259 					} else
260 #endif
261 						if (*fmt == '3' && *(fmt+1) == '2') {
262 							fmt += 2;
263 							modifier = LM_LONG;
264 						} else {
265 #ifdef _WIN64
266 							modifier = LM_LONG_LONG;
267 #else
268 							modifier = LM_LONG;
269 #endif
270 						}
271 					break;
272 				case 'l':
273 					fmt++;
274 #if SIZEOF_LONG_LONG
275 					if (*fmt == 'l') {
276 						fmt++;
277 						modifier = LM_LONG_LONG;
278 					} else
279 #endif
280 						modifier = LM_LONG;
281 					break;
282 					case 'z':
283 					fmt++;
284 					modifier = LM_SIZE_T;
285 					break;
286 				case 'j':
287 					fmt++;
288 #if SIZEOF_INTMAX_T
289 					modifier = LM_INTMAX_T;
290 #else
291 					modifier = LM_SIZE_T;
292 #endif
293 					break;
294 				case 't':
295 					fmt++;
296 #if SIZEOF_PTRDIFF_T
297 					modifier = LM_PTRDIFF_T;
298 #else
299 					modifier = LM_SIZE_T;
300 #endif
301 					break;
302 				case 'h':
303 					fmt++;
304 					if (*fmt == 'h') {
305 						fmt++;
306 					}
307 					/* these are promoted to int, so no break */
308 				default:
309 					modifier = LM_STD;
310 					break;
311 			}
312 
313 			/*
314 			 * Argument extraction and printing.
315 			 * First we determine the argument type.
316 			 * Then, we convert the argument to a string.
317 			 * On exit from the switch, s points to the string that
318 			 * must be printed, s_len has the length of the string
319 			 * The precision requirements, if any, are reflected in s_len.
320 			 *
321 			 * NOTE: pad_char may be set to '0' because of the 0 flag.
322 			 *   It is reset to ' ' by non-numeric formats
323 			 */
324 			switch (*fmt) {
325 				case 'Z':
326 					zvp = (zval *) va_arg(ap, zval *);
327 					free_zcopy = zend_make_printable_zval(zvp, &zcopy);
328 					if (free_zcopy) {
329 						zvp = &zcopy;
330 					}
331 					s_len = Z_STRLEN_P(zvp);
332 					s = Z_STRVAL_P(zvp);
333 					if (adjust_precision && precision < s_len) {
334 						s_len = precision;
335 					}
336 					break;
337 				case 'u':
338 					switch(modifier) {
339 						default:
340 							i_num = (wide_int) va_arg(ap, unsigned int);
341 							break;
342 						case LM_LONG_DOUBLE:
343 							goto fmt_error;
344 						case LM_LONG:
345 							i_num = (wide_int) va_arg(ap, unsigned long int);
346 							break;
347 						case LM_SIZE_T:
348 							i_num = (wide_int) va_arg(ap, size_t);
349 							break;
350 #if SIZEOF_LONG_LONG
351 						case LM_LONG_LONG:
352 							i_num = (wide_int) va_arg(ap, u_wide_int);
353 							break;
354 #endif
355 #if SIZEOF_INTMAX_T
356 						case LM_INTMAX_T:
357 							i_num = (wide_int) va_arg(ap, uintmax_t);
358 							break;
359 #endif
360 #if SIZEOF_PTRDIFF_T
361 						case LM_PTRDIFF_T:
362 							i_num = (wide_int) va_arg(ap, ptrdiff_t);
363 							break;
364 #endif
365 					}
366 					/*
367 					 * The rest also applies to other integer formats, so fall
368 					 * into that case.
369 					 */
370 				case 'd':
371 				case 'i':
372 					/*
373 					 * Get the arg if we haven't already.
374 					 */
375 					if ((*fmt) != 'u') {
376 						switch(modifier) {
377 							default:
378 								i_num = (wide_int) va_arg(ap, int);
379 								break;
380 							case LM_LONG_DOUBLE:
381 								goto fmt_error;
382 							case LM_LONG:
383 								i_num = (wide_int) va_arg(ap, long int);
384 								break;
385 							case LM_SIZE_T:
386 #if SIZEOF_SSIZE_T
387 								i_num = (wide_int) va_arg(ap, ssize_t);
388 #else
389 								i_num = (wide_int) va_arg(ap, size_t);
390 #endif
391 								break;
392 #if SIZEOF_LONG_LONG
393 							case LM_LONG_LONG:
394 								i_num = (wide_int) va_arg(ap, wide_int);
395 								break;
396 #endif
397 #if SIZEOF_INTMAX_T
398 							case LM_INTMAX_T:
399 								i_num = (wide_int) va_arg(ap, intmax_t);
400 								break;
401 #endif
402 #if SIZEOF_PTRDIFF_T
403 							case LM_PTRDIFF_T:
404 								i_num = (wide_int) va_arg(ap, ptrdiff_t);
405 								break;
406 #endif
407 						}
408 					}
409 					s = ap_php_conv_10(i_num, (*fmt) == 'u', &is_negative,
410 								&num_buf[NUM_BUF_SIZE], &s_len);
411 					FIX_PRECISION(adjust_precision, precision, s, s_len);
412 
413 					if (*fmt != 'u') {
414 						if (is_negative) {
415 							prefix_char = '-';
416 						} else if (print_sign) {
417 							prefix_char = '+';
418 						} else if (print_blank) {
419 							prefix_char = ' ';
420 						}
421 					}
422 					break;
423 
424 
425 				case 'o':
426 					switch(modifier) {
427 						default:
428 							ui_num = (u_wide_int) va_arg(ap, unsigned int);
429 							break;
430 						case LM_LONG_DOUBLE:
431 							goto fmt_error;
432 						case LM_LONG:
433 							ui_num = (u_wide_int) va_arg(ap, unsigned long int);
434 							break;
435 						case LM_SIZE_T:
436 							ui_num = (u_wide_int) va_arg(ap, size_t);
437 							break;
438 #if SIZEOF_LONG_LONG
439 						case LM_LONG_LONG:
440 							ui_num = (u_wide_int) va_arg(ap, u_wide_int);
441 							break;
442 #endif
443 #if SIZEOF_INTMAX_T
444 						case LM_INTMAX_T:
445 							ui_num = (u_wide_int) va_arg(ap, uintmax_t);
446 							break;
447 #endif
448 #if SIZEOF_PTRDIFF_T
449 						case LM_PTRDIFF_T:
450 							ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
451 							break;
452 #endif
453 					}
454 					s = ap_php_conv_p2(ui_num, 3, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
455 					FIX_PRECISION(adjust_precision, precision, s, s_len);
456 					if (alternate_form && *s != '0') {
457 						*--s = '0';
458 						s_len++;
459 					}
460 					break;
461 
462 
463 				case 'x':
464 				case 'X':
465 					switch(modifier) {
466 						default:
467 							ui_num = (u_wide_int) va_arg(ap, unsigned int);
468 							break;
469 						case LM_LONG_DOUBLE:
470 							goto fmt_error;
471 						case LM_LONG:
472 							ui_num = (u_wide_int) va_arg(ap, unsigned long int);
473 							break;
474 						case LM_SIZE_T:
475 							ui_num = (u_wide_int) va_arg(ap, size_t);
476 							break;
477 #if SIZEOF_LONG_LONG
478 						case LM_LONG_LONG:
479 							ui_num = (u_wide_int) va_arg(ap, u_wide_int);
480 							break;
481 #endif
482 #if SIZEOF_INTMAX_T
483 						case LM_INTMAX_T:
484 							ui_num = (u_wide_int) va_arg(ap, uintmax_t);
485 							break;
486 #endif
487 #if SIZEOF_PTRDIFF_T
488 						case LM_PTRDIFF_T:
489 							ui_num = (u_wide_int) va_arg(ap, ptrdiff_t);
490 							break;
491 #endif
492 					}
493 					s = ap_php_conv_p2(ui_num, 4, *fmt, &num_buf[NUM_BUF_SIZE], &s_len);
494 					FIX_PRECISION(adjust_precision, precision, s, s_len);
495 					if (alternate_form && i_num != 0) {
496 						*--s = *fmt;	/* 'x' or 'X' */
497 						*--s = '0';
498 						s_len += 2;
499 					}
500 					break;
501 
502 
503 				case 's':
504 				case 'v':
505 					s = va_arg(ap, char *);
506 					if (s != NULL) {
507 						if (adjust_precision) {
508 							s_len = precision;
509 						} else {
510 							s_len = strlen(s);
511 						}
512 
513 						if (escape_xml) {
514 							/* added: support for xml escaping */
515 
516 							int old_slen = s_len, i = 0;
517 							char *old_s = s, *s_ptr;
518 							free_s = s_ptr = s = emalloc(old_slen * 6 + 1);
519 							do {
520 								if (old_s[i] == '&' || old_s[i] == '"' || old_s[i] == '<') {
521 									*s_ptr++ = '&';
522 									switch (old_s[i]) {
523 										case '"':
524 											s_len += 5;
525 											*s_ptr++ = 'q';
526 											*s_ptr++ = 'u';
527 											*s_ptr++ = 'o';
528 											*s_ptr++ = 't';
529 											break;
530 										case '<':
531 											s_len += 3;
532 											*s_ptr++ = 'l';
533 											*s_ptr++ = 't';
534 											break;
535 										case '&':
536 											s_len += 4;
537 											*s_ptr++ = 'a';
538 											*s_ptr++ = 'm';
539 											*s_ptr++ = 'p';
540 											break;
541 									}
542 									*s_ptr++ = ';';
543 								} else {
544 									*s_ptr++ = old_s[i];
545 								}
546 							} while (i++ < old_slen);
547 						}
548 					} else {
549 						s = S_NULL;
550 						s_len = S_NULL_LEN;
551 					}
552 					pad_char = ' ';
553 					break;
554 
555 
556 				case 'b':
557 					if (escape_xml) {
558 						s = PHPDBG_G(err_buf).xml;
559 					} else {
560 						s = PHPDBG_G(err_buf).msg;
561 					}
562 
563 					if (s != NULL) {
564 						if (escape_xml) {
565 							s_len = PHPDBG_G(err_buf).xmllen;
566 						} else {
567 							s_len = PHPDBG_G(err_buf).msglen;
568 						}
569 
570 						if (adjust_precision && precision != s_len) {
571 							s_len = precision;
572 						}
573 					} else {
574 						s = "";
575 						s_len = 0;
576 					}
577 					pad_char = ' ';
578 					break;
579 
580 
581 				case 'r':
582 					if (PHPDBG_G(req_id)) {
583 						s_len = spprintf(&s, 0, "req=\"" ZEND_ULONG_FMT "\"", PHPDBG_G(req_id));
584 						free_s = s;
585 					} else {
586 						s = "";
587 						s_len = 0;
588 					}
589 					break;
590 
591 
592 				case 'f':
593 				case 'F':
594 				case 'e':
595 				case 'E':
596 
597 					switch(modifier) {
598 						case LM_LONG_DOUBLE:
599 							fp_num = (double) va_arg(ap, long double);
600 							break;
601 						case LM_STD:
602 							fp_num = va_arg(ap, double);
603 							break;
604 						default:
605 							goto fmt_error;
606 					}
607 
608 					if (zend_isnan(fp_num)) {
609 						s = "NAN";
610 						s_len = 3;
611 					} else if (zend_isinf(fp_num)) {
612 						s = "INF";
613 						s_len = 3;
614 					} else {
615 						if (!lconv) {
616 							lconv = localeconv();
617 						}
618 
619 						s = php_conv_fp((*fmt == 'f')?'F':*fmt, fp_num, alternate_form,
620 						 (adjust_precision == NO) ? FLOAT_DIGITS : precision,
621 						 (*fmt == 'f')?LCONV_DECIMAL_POINT:'.',
622 									&is_negative, &num_buf[1], &s_len);
623 						if (is_negative)
624 							prefix_char = '-';
625 						else if (print_sign)
626 							prefix_char = '+';
627 						else if (print_blank)
628 							prefix_char = ' ';
629 					}
630 					break;
631 
632 
633 				case 'g':
634 				case 'k':
635 				case 'G':
636 				case 'H':
637 					switch(modifier) {
638 						case LM_LONG_DOUBLE:
639 							fp_num = (double) va_arg(ap, long double);
640 							break;
641 						case LM_STD:
642 							fp_num = va_arg(ap, double);
643 							break;
644 						default:
645 							goto fmt_error;
646 					}
647 
648 					if (zend_isnan(fp_num)) {
649 						s = "NAN";
650 						s_len = 3;
651 						break;
652 					} else if (zend_isinf(fp_num)) {
653 						if (fp_num > 0) {
654 							s = "INF";
655 							s_len = 3;
656 						} else {
657 							s = "-INF";
658 							s_len = 4;
659 						}
660 						break;
661 					}
662 
663 					if (adjust_precision == NO) {
664 						precision = FLOAT_DIGITS;
665 					} else if (precision == 0) {
666 						precision = 1;
667 					}
668 					/*
669 					 * * We use &num_buf[ 1 ], so that we have room for the sign
670 					 */
671 					if (!lconv) {
672 						lconv = localeconv();
673 					}
674 
675 					s = php_gcvt(fp_num, precision, (*fmt=='H' || *fmt == 'k') ? '.' : LCONV_DECIMAL_POINT, (*fmt == 'G' || *fmt == 'H')?'E':'e', &num_buf[1]);
676 					if (*s == '-') {
677 						prefix_char = *s++;
678 					} else if (print_sign) {
679 						prefix_char = '+';
680 					} else if (print_blank) {
681 						prefix_char = ' ';
682 					}
683 
684 					s_len = strlen(s);
685 
686 					if (alternate_form && (strchr(s, '.')) == NULL) {
687 						s[s_len++] = '.';
688 					}
689 					break;
690 
691 
692 				case 'c':
693 					char_buf[0] = (char) (va_arg(ap, int));
694 					s = &char_buf[0];
695 					s_len = 1;
696 					pad_char = ' ';
697 					break;
698 
699 
700 				case '%':
701 					char_buf[0] = '%';
702 					s = &char_buf[0];
703 					s_len = 1;
704 					pad_char = ' ';
705 					break;
706 
707 
708 				case 'n':
709 					*(va_arg(ap, int *)) = cc;
710 					goto skip_output;
711 
712 					/*
713 					 * Always extract the argument as a "char *" pointer. We
714 					 * should be using "void *" but there are still machines
715 					 * that don't understand it.
716 					 * If the pointer size is equal to the size of an unsigned
717 					 * integer we convert the pointer to a hex number, otherwise
718 					 * we print "%p" to indicate that we don't handle "%p".
719 					 */
720 				case 'p':
721 					if (sizeof(char *) <= sizeof(u_wide_int)) {
722 						ui_num = (u_wide_int)((size_t) va_arg(ap, char *));
723 						s = ap_php_conv_p2(ui_num, 4, 'x',
724 								&num_buf[NUM_BUF_SIZE], &s_len);
725 						if (ui_num != 0) {
726 							*--s = 'x';
727 							*--s = '0';
728 							s_len += 2;
729 						}
730 					} else {
731 						s = "%p";
732 						s_len = 2;
733 					}
734 					pad_char = ' ';
735 					break;
736 
737 
738 				case NUL:
739 					/*
740 					 * The last character of the format string was %.
741 					 * We ignore it.
742 					 */
743 					continue;
744 
745 
746 fmt_error:
747 				php_error(E_ERROR, "Illegal length modifier specified '%c' in s[np]printf call", *fmt);
748 					/*
749 					 * The default case is for unrecognized %'s.
750 					 * We print %<char> to help the user identify what
751 					 * option is not understood.
752 					 * This is also useful in case the user wants to pass
753 					 * the output of format_converter to another function
754 					 * that understands some other %<char> (like syslog).
755 					 * Note that we can't point s inside fmt because the
756 					 * unknown <char> could be preceded by width etc.
757 					 */
758 				default:
759 					char_buf[0] = '%';
760 					char_buf[1] = *fmt;
761 					s = char_buf;
762 					s_len = 2;
763 					pad_char = ' ';
764 					break;
765 			}
766 
767 			if (prefix_char != NUL) {
768 				*--s = prefix_char;
769 				s_len++;
770 			}
771 			if (adjust_width && adjust == RIGHT && min_width > s_len) {
772 				if (pad_char == '0' && prefix_char != NUL) {
773 					INS_CHAR(*s, sp, bep, cc)
774 						s++;
775 					s_len--;
776 					min_width--;
777 				}
778 				PAD(min_width, s_len, pad_char);
779 			}
780 			/*
781 			 * Print the string s.
782 			 */
783 			for (i = s_len; i != 0; i--) {
784 				INS_CHAR(*s, sp, bep, cc);
785 				s++;
786 			}
787 
788 			if (adjust_width && adjust == LEFT && min_width > s_len)
789 				PAD(min_width, s_len, pad_char);
790 			if (free_zcopy) {
791 				zval_ptr_dtor_str(&zcopy);
792 			}
793 		}
794 skip_output:
795 		if (free_s) {
796 			efree(free_s);
797 			free_s = NULL;
798 		}
799 
800 		fmt++;
801 	}
802 	odp->nextb = sp;
803 	return (cc);
804 }
805 
strx_printv(int * ccp,char * buf,size_t len,const char * format,zend_bool escape_xml,va_list ap)806 static void strx_printv(int *ccp, char *buf, size_t len, const char *format, zend_bool escape_xml, va_list ap) {
807 	buffy od;
808 	int cc;
809 
810 	/*
811 	 * First initialize the descriptor
812 	 * Notice that if no length is given, we initialize buf_end to the
813 	 * highest possible address.
814 	 */
815 	if (len == 0) {
816 		od.buf_end = (char *) ~0;
817 		od.nextb   = (char *) ~0;
818 	} else {
819 		od.buf_end = &buf[len-1];
820 		od.nextb   = buf;
821 	}
822 
823 	/*
824 	 * Do the conversion
825 	 */
826 	cc = format_converter(&od, format, escape_xml, ap);
827 	if (len != 0 && od.nextb <= od.buf_end) {
828 		*(od.nextb) = '\0';
829 	}
830 	if (ccp) {
831 		*ccp = cc;
832 	}
833 }
834 
phpdbg_xml_vsnprintf(char * buf,size_t len,const char * format,zend_bool escape_xml,va_list ap)835 static int phpdbg_xml_vsnprintf(char *buf, size_t len, const char *format, zend_bool escape_xml, va_list ap) {
836 	int cc;
837 
838 	strx_printv(&cc, buf, len, format, escape_xml, ap);
839 	return (cc);
840 }
841 
phpdbg_xml_vasprintf(char ** buf,const char * format,zend_bool escape_xml,va_list ap)842 PHPDBG_API int phpdbg_xml_vasprintf(char **buf, const char *format, zend_bool escape_xml, va_list ap) {
843 	va_list ap2;
844 	int cc;
845 
846 	va_copy(ap2, ap);
847 	cc = phpdbg_xml_vsnprintf(NULL, 0, format, escape_xml, ap2);
848 	va_end(ap2);
849 
850 	*buf = NULL;
851 
852 	if (cc >= 0) {
853 		*buf = emalloc(++cc);
854 		if ((cc = phpdbg_xml_vsnprintf(*buf, cc, format, escape_xml, ap)) < 0) {
855 			efree(*buf);
856 			*buf = NULL;
857 		}
858 	}
859 
860 	return cc;
861 }
862 /* copy end */
863 
_phpdbg_asprintf(char ** buf,const char * format,...)864 PHPDBG_API int _phpdbg_asprintf(char **buf, const char *format, ...) {
865 	int ret;
866 	va_list va;
867 
868 	va_start(va, format);
869 	ret = phpdbg_xml_vasprintf(buf, format, 0, va);
870 	va_end(va);
871 
872 	return ret;
873 }
874 
phpdbg_encode_xml(char ** buf,char * msg,int msglen,int from,char * to)875 static int phpdbg_encode_xml(char **buf, char *msg, int msglen, int from, char *to) {
876 	int i;
877 	int tolen = to ? strlen(to) : 5;
878 	char *tmp = *buf = emalloc(msglen * tolen);
879 	for (i = 0; i++ < msglen; msg++) {
880 		if (*msg == '&') {
881 			memcpy(tmp, ZEND_STRL("&amp;"));
882 			tmp += sizeof("&amp;") - 1;
883 		} else if (*msg == '<') {
884 			memcpy(tmp, ZEND_STRL("&lt;"));
885 			tmp += sizeof("&lt;") - 1;
886 		} else if (((int) *msg) == from) {
887 			memcpy(tmp, to, tolen);
888 			tmp += tolen;
889 		} else {
890 			*tmp++ = *msg;
891 		}
892 	}
893 
894 	{
895 		int len = tmp - *buf;
896 		*buf = erealloc(*buf, len + 1);
897 		return len;
898 	}
899 }
900 
phpdbg_encode_ctrl_chars(char ** buf,int * buflen)901 static void phpdbg_encode_ctrl_chars(char **buf, int *buflen) {
902 	char *tmp, *tmpptr;
903 	int len;
904 	int i;
905 
906 	tmp = tmpptr = emalloc(*buflen * 5);
907 
908 	for (i = 0; i < *buflen; i++) {
909 		if ((*buf)[i] < 0x20) {
910 			*tmpptr++ = '&';
911 			*tmpptr++ = '#';
912 			if ((unsigned int) ((*buf)[i]) > 9) {
913 				*tmpptr++ = ((*buf)[i] / 10) + '0';
914 			}
915 			*tmpptr++ = ((*buf)[i] % 10) + '0';
916 			*tmpptr++ = ';';
917 		} else {
918 			*tmpptr++ = (*buf)[i];
919 		}
920 	}
921 
922 	len = tmpptr - tmp;
923 
924 	efree(*buf);
925 	*buf = erealloc(tmp, len + 1);
926 	*buflen = len;
927 }
928 
phpdbg_process_print(int fd,int type,const char * tag,const char * msg,int msglen,const char * xml,int xmllen)929 static int phpdbg_process_print(int fd, int type, const char *tag, const char *msg, int msglen, const char *xml, int xmllen) {
930 	char *msgout = NULL, *buf;
931 	int msgoutlen, xmloutlen, buflen;
932 	const char *severity;
933 
934 	if ((PHPDBG_G(flags) & PHPDBG_WRITE_XML) && PHPDBG_G(in_script_xml) && PHPDBG_G(in_script_xml) != type) {
935 		phpdbg_mixed_write(fd, ZEND_STRL("</stream>"));
936 		PHPDBG_G(in_script_xml) = 0;
937 	}
938 
939 	switch (type) {
940 		case P_ERROR:
941 			severity = "error";
942 			if (!PHPDBG_G(last_was_newline)) {
943 				if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
944 					phpdbg_mixed_write(fd, ZEND_STRL("<phpdbg>\n" "</phpdbg>"));
945 				} else {
946 					phpdbg_mixed_write(fd, ZEND_STRL("\n"));
947 				}
948 				PHPDBG_G(last_was_newline) = 1;
949 			}
950 			if (PHPDBG_G(flags) & PHPDBG_IS_COLOURED) {
951 				msgoutlen = phpdbg_asprintf(&msgout, "\033[%sm[%.*s]\033[0m\n", PHPDBG_G(colors)[PHPDBG_COLOR_ERROR]->code, msglen, msg);
952 			} else {
953 				msgoutlen = phpdbg_asprintf(&msgout, "[%.*s]\n", msglen, msg);
954 			}
955 			break;
956 
957 		case P_NOTICE:
958 			severity = "notice";
959 			if (!PHPDBG_G(last_was_newline)) {
960 				if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
961 					phpdbg_mixed_write(fd, ZEND_STRL("<phpdbg>\n" "</phpdbg>"));
962 				} else {
963 					phpdbg_mixed_write(fd, ZEND_STRL("\n"));
964 				}
965 				PHPDBG_G(last_was_newline) = 1;
966 			}
967 			if (PHPDBG_G(flags) & PHPDBG_IS_COLOURED) {
968 				msgoutlen = phpdbg_asprintf(&msgout, "\033[%sm[%.*s]\033[0m\n", PHPDBG_G(colors)[PHPDBG_COLOR_NOTICE]->code, msglen, msg);
969 			} else {
970 				msgoutlen = phpdbg_asprintf(&msgout, "[%.*s]\n", msglen, msg);
971 			}
972 			break;
973 
974 		case P_WRITELN:
975 			severity = "normal";
976 			if (msg) {
977 				msgoutlen = phpdbg_asprintf(&msgout, "%.*s\n", msglen, msg);
978 			} else {
979 				msgoutlen = 1;
980 				msgout = estrdup("\n");
981 			}
982 			PHPDBG_G(last_was_newline) = 1;
983 			break;
984 
985 		case P_WRITE:
986 			severity = "normal";
987 			if (msg) {
988 				msgout = estrndup(msg, msglen);
989 				msgoutlen = msglen;
990 				PHPDBG_G(last_was_newline) = msg[msglen - 1] == '\n';
991 			} else {
992 				msgoutlen = 0;
993 				msgout = estrdup("");
994 			}
995 			break;
996 
997 		case P_STDOUT:
998 		case P_STDERR:
999 			if (msg) {
1000 				PHPDBG_G(last_was_newline) = msg[msglen - 1] == '\n';
1001 				if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1002 					zend_string *encoded;
1003 
1004 					if (PHPDBG_G(in_script_xml) != type) {
1005 						char *stream_buf;
1006 						int stream_buflen = phpdbg_asprintf(&stream_buf, "<stream type=\"%s\">", type == P_STDERR ? "stderr" : "stdout");
1007 						phpdbg_mixed_write(fd, stream_buf, stream_buflen);
1008 						efree(stream_buf);
1009 						PHPDBG_G(in_script_xml) = type;
1010 					}
1011 					encoded = php_escape_html_entities((unsigned char *) msg, msglen, 0, ENT_NOQUOTES, PG(internal_encoding) && PG(internal_encoding)[0] ? PG(internal_encoding) : (SG(default_charset) ? SG(default_charset) : "UTF-8"));
1012 					buflen = ZSTR_LEN(encoded);
1013 					memcpy(buf = emalloc(buflen + 1), ZSTR_VAL(encoded), buflen);
1014 					phpdbg_encode_ctrl_chars(&buf, &buflen);
1015 					phpdbg_mixed_write(fd, buf, buflen);
1016 					efree(buf);
1017 				} else {
1018 					phpdbg_mixed_write(fd, msg, msglen);
1019 				}
1020 			}
1021 			return msglen;
1022 
1023 		/* no formatting on logging output */
1024 		case P_LOG:
1025 			severity = "log";
1026 			if (msg) {
1027 				struct timeval tp;
1028 				if (gettimeofday(&tp, NULL) == SUCCESS) {
1029 					msgoutlen = phpdbg_asprintf(&msgout, "[%ld %.8F]: %.*s\n", tp.tv_sec, tp.tv_usec / 1000000., msglen, msg);
1030 				} else {
1031 					msgoutlen = FAILURE;
1032 				}
1033 			}
1034 			break;
1035 		EMPTY_SWITCH_DEFAULT_CASE()
1036 	}
1037 
1038 	if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1039 		char *xmlout;
1040 
1041 		if (PHPDBG_G(req_id)) {
1042 			char *xmlbuf = NULL;
1043 			xmllen = phpdbg_asprintf(&xmlbuf, "req=\"" ZEND_ULONG_FMT "\" %.*s", PHPDBG_G(req_id), xmllen, xml);
1044 			xml = xmlbuf;
1045 		}
1046 		if (msgout) {
1047 			buflen = phpdbg_encode_xml(&buf, msgout, msgoutlen, '"', "&quot;");
1048 			xmloutlen = phpdbg_asprintf(&xmlout, "<%s severity=\"%s\" %.*s msgout=\"%.*s\" />", tag, severity, xmllen, xml, buflen, buf);
1049 
1050 			efree(buf);
1051 		} else {
1052 			xmloutlen = phpdbg_asprintf(&xmlout, "<%s severity=\"%s\" %.*s msgout=\"\" />", tag, severity, xmllen, xml);
1053 		}
1054 
1055 		phpdbg_encode_ctrl_chars(&xmlout, &xmloutlen);
1056 		phpdbg_eol_convert(&xmlout, &xmloutlen);
1057 		phpdbg_mixed_write(fd, xmlout, xmloutlen);
1058 		efree(xmlout);
1059 	} else if (msgout) {
1060 		phpdbg_eol_convert(&msgout, &msgoutlen);
1061 		phpdbg_mixed_write(fd, msgout, msgoutlen);
1062 	}
1063 
1064 	if (PHPDBG_G(req_id) && (PHPDBG_G(flags) & PHPDBG_WRITE_XML)) {
1065 		efree((char *) xml);
1066 	}
1067 
1068 	if (msgout) {
1069 		efree(msgout);
1070 	}
1071 
1072 	return msgout ? msgoutlen : xmloutlen;
1073 } /* }}} */
1074 
phpdbg_vprint(int type,int fd,const char * tag,const char * xmlfmt,const char * strfmt,va_list args)1075 PHPDBG_API int phpdbg_vprint(int type, int fd, const char *tag, const char *xmlfmt, const char *strfmt, va_list args) {
1076 	char *msg = NULL, *xml = NULL;
1077 	int msglen = 0, xmllen = 0;
1078 	int len;
1079 	va_list argcpy;
1080 
1081 	if (strfmt != NULL && strlen(strfmt) > 0L) {
1082 		va_copy(argcpy, args);
1083 		msglen = phpdbg_xml_vasprintf(&msg, strfmt, 0, argcpy);
1084 		va_end(argcpy);
1085 	}
1086 
1087 	if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1088 		if (xmlfmt != NULL && strlen(xmlfmt) > 0L) {
1089 			va_copy(argcpy, args);
1090 			xmllen = phpdbg_xml_vasprintf(&xml, xmlfmt, 1, argcpy);
1091 			va_end(argcpy);
1092 		} else {
1093 			xml = estrdup("");
1094 		}
1095 	}
1096 
1097 	if (PHPDBG_G(err_buf).active && type != P_STDOUT && type != P_STDERR) {
1098 		phpdbg_free_err_buf();
1099 
1100 		PHPDBG_G(err_buf).type = type;
1101 		PHPDBG_G(err_buf).fd = fd;
1102 		PHPDBG_G(err_buf).tag = estrdup(tag);
1103 		PHPDBG_G(err_buf).msg = msg;
1104 		PHPDBG_G(err_buf).msglen = msglen;
1105 		if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1106 			PHPDBG_G(err_buf).xml = xml;
1107 			PHPDBG_G(err_buf).xmllen = xmllen;
1108 		}
1109 
1110 		return msglen;
1111 	}
1112 
1113 	len = phpdbg_process_print(fd, type, tag, msg, msglen, xml, xmllen);
1114 
1115 	if (msg) {
1116 		efree(msg);
1117 	}
1118 
1119 	if (xml) {
1120 		efree(xml);
1121 	}
1122 
1123 	return len;
1124 }
1125 
phpdbg_free_err_buf(void)1126 PHPDBG_API void phpdbg_free_err_buf(void) {
1127 	if (PHPDBG_G(err_buf).type == 0) {
1128 		return;
1129 	}
1130 
1131 	PHPDBG_G(err_buf).type = 0;
1132 
1133 	efree(PHPDBG_G(err_buf).tag);
1134 	efree(PHPDBG_G(err_buf).msg);
1135 	if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1136 		efree(PHPDBG_G(err_buf).xml);
1137 	}
1138 }
1139 
phpdbg_activate_err_buf(zend_bool active)1140 PHPDBG_API void phpdbg_activate_err_buf(zend_bool active) {
1141 	PHPDBG_G(err_buf).active = active;
1142 }
1143 
phpdbg_output_err_buf(const char * tag,const char * xmlfmt,const char * strfmt,...)1144 PHPDBG_API int phpdbg_output_err_buf(const char *tag, const char *xmlfmt, const char *strfmt, ...) {
1145 	int len;
1146 	va_list args;
1147 	int errbuf_active = PHPDBG_G(err_buf).active;
1148 
1149 	if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
1150 		return 0;
1151 	}
1152 
1153 	PHPDBG_G(err_buf).active = 0;
1154 
1155 	va_start(args, strfmt);
1156 	len = phpdbg_vprint(PHPDBG_G(err_buf).type, PHPDBG_G(err_buf).fd, tag ? tag : PHPDBG_G(err_buf).tag, xmlfmt, strfmt, args);
1157 	va_end(args);
1158 
1159 	PHPDBG_G(err_buf).active = errbuf_active;
1160 	phpdbg_free_err_buf();
1161 
1162 	return len;
1163 }
1164 
phpdbg_print(int type,int fd,const char * tag,const char * xmlfmt,const char * strfmt,...)1165 PHPDBG_API int phpdbg_print(int type, int fd, const char *tag, const char *xmlfmt, const char *strfmt, ...) {
1166 	va_list args;
1167 	int len;
1168 
1169 	if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
1170 		return 0;
1171 	}
1172 
1173 	va_start(args, strfmt);
1174 	len = phpdbg_vprint(type, fd, tag, xmlfmt, strfmt, args);
1175 	va_end(args);
1176 
1177 	return len;
1178 }
1179 
phpdbg_xml_internal(int fd,const char * fmt,...)1180 PHPDBG_API int phpdbg_xml_internal(int fd, const char *fmt, ...) {
1181 	int len = 0;
1182 
1183 	if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
1184 		return 0;
1185 	}
1186 
1187 	if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1188 		va_list args;
1189 		char *buffer;
1190 		int buflen;
1191 
1192 		va_start(args, fmt);
1193 		buflen = phpdbg_xml_vasprintf(&buffer, fmt, 1, args);
1194 		va_end(args);
1195 
1196 		phpdbg_encode_ctrl_chars(&buffer, &buflen);
1197 
1198 		if (PHPDBG_G(in_script_xml)) {
1199 			phpdbg_mixed_write(fd, ZEND_STRL("</stream>"));
1200 			PHPDBG_G(in_script_xml) = 0;
1201 		}
1202 
1203 		len = phpdbg_mixed_write(fd, buffer, buflen);
1204 		efree(buffer);
1205 	}
1206 
1207 	return len;
1208 }
1209 
phpdbg_log_internal(int fd,const char * fmt,...)1210 PHPDBG_API int phpdbg_log_internal(int fd, const char *fmt, ...) {
1211 	va_list args;
1212 	char *buffer;
1213 	int buflen;
1214 	int len = 0;
1215 
1216 	va_start(args, fmt);
1217 	buflen = phpdbg_xml_vasprintf(&buffer, fmt, 0, args);
1218 	va_end(args);
1219 
1220 	len = phpdbg_mixed_write(fd, buffer, buflen);
1221 	efree(buffer);
1222 
1223 	return len;
1224 }
1225 
phpdbg_out_internal(int fd,const char * fmt,...)1226 PHPDBG_API int phpdbg_out_internal(int fd, const char *fmt, ...) {
1227 	va_list args;
1228 	char *buffer;
1229 	int buflen;
1230 	int len = 0;
1231 
1232 	if (PHPDBG_G(flags) & PHPDBG_DISCARD_OUTPUT) {
1233 		return 0;
1234 	}
1235 
1236 	va_start(args, fmt);
1237 	buflen = phpdbg_xml_vasprintf(&buffer, fmt, 0, args);
1238 	va_end(args);
1239 
1240 	if (PHPDBG_G(flags) & PHPDBG_WRITE_XML) {
1241 		char *msg;
1242 		int msglen;
1243 
1244 		msglen = phpdbg_encode_xml(&msg, buffer, buflen, 256, NULL);
1245 		phpdbg_encode_ctrl_chars(&msg, &msglen);
1246 		phpdbg_eol_convert(&msg, &msglen);
1247 
1248 		if (PHPDBG_G(in_script_xml)) {
1249 			phpdbg_mixed_write(fd, ZEND_STRL("</stream>"));
1250 			PHPDBG_G(in_script_xml) = 0;
1251 		}
1252 
1253 		phpdbg_mixed_write(fd, ZEND_STRL("<phpdbg>"));
1254 		len = phpdbg_mixed_write(fd, msg, msglen);
1255 		phpdbg_mixed_write(fd, ZEND_STRL("</phpdbg>"));
1256 	} else {
1257 		phpdbg_eol_convert(&buffer, &buflen);
1258 		len = phpdbg_mixed_write(fd, buffer, buflen);
1259 	}
1260 
1261 	efree(buffer);
1262 	return len;
1263 }
1264 
1265 
phpdbg_rlog_internal(int fd,const char * fmt,...)1266 PHPDBG_API int phpdbg_rlog_internal(int fd, const char *fmt, ...) { /* {{{ */
1267 	int rc = 0;
1268 
1269 	va_list args;
1270 	struct timeval tp;
1271 
1272 	va_start(args, fmt);
1273 	if (gettimeofday(&tp, NULL) == SUCCESS) {
1274 		char friendly[100];
1275 		char *format = NULL, *buffer = NULL, *outbuf = NULL;
1276 		const time_t tt = tp.tv_sec;
1277 
1278 #ifdef PHP_WIN32
1279 		strftime(friendly, 100, "%a %b %d %H.%%04d %Y", localtime(&tt));
1280 #else
1281 		strftime(friendly, 100, "%a %b %d %T.%%04d %Y", localtime(&tt));
1282 #endif
1283 		phpdbg_asprintf(&buffer, friendly, tp.tv_usec/1000);
1284 		phpdbg_asprintf(&format, "[%s]: %s\n", buffer, fmt);
1285 		rc = phpdbg_xml_vasprintf(&outbuf, format, 0, args);
1286 
1287 		if (outbuf) {
1288 			rc = phpdbg_mixed_write(fd, outbuf, rc);
1289 			efree(outbuf);
1290 		}
1291 
1292 		efree(format);
1293 		efree(buffer);
1294 	}
1295 	va_end(args);
1296 
1297 	return rc;
1298 } /* }}} */
1299