diff --git a/TSRM/tsrm_win32.c b/TSRM/tsrm_win32.c index b60be0cc9cb..4d1d3d303af 100644 --- a/TSRM/tsrm_win32.c +++ b/TSRM/tsrm_win32.c @@ -273,8 +273,8 @@ TSRM_API int shmget(int key, int size, int flags) return -1; } - sprintf(shm_segment, "TSRM_SHM_SEGMENT:%d", key); - sprintf(shm_info, "TSRM_SHM_DESCRIPTOR:%d", key); + snprintf(shm_segment, sizeof(shm_segment), "TSRM_SHM_SEGMENT:%d", key); + snprintf(shm_info, sizeof(shm_info), "TSRM_SHM_DESCRIPTOR:%d", key); shm_handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, shm_segment); info_handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, shm_info); diff --git a/Zend/zend.c b/Zend/zend.c index c809759665f..87342e2a466 100644 --- a/Zend/zend.c +++ b/Zend/zend.c @@ -147,7 +147,7 @@ static void print_hash(zend_write_func_t write_func, HashTable *ht, int indent, case HASH_KEY_IS_LONG: { char key[25]; - sprintf(key, "%ld", num_key); + snprintf(key, sizeof(key), "%ld", num_key); ZEND_PUTS_EX(key); } break; @@ -214,8 +214,7 @@ ZEND_API void zend_make_printable_zval(zval *expr, zval *expr_copy, int *use_cop } break; case IS_RESOURCE: - expr_copy->value.str.val = (char *) emalloc(sizeof("Resource id #") + MAX_LENGTH_OF_LONG); - expr_copy->value.str.len = sprintf(expr_copy->value.str.val, "Resource id #%ld", expr->value.lval); + expr_copy->value.str.len = zend_spprintf(&expr_copy->value.str.val, 0, "Resource id #%ld", expr->value.lval); break; case IS_ARRAY: expr_copy->value.str.len = sizeof("Array")-1; @@ -1201,8 +1200,7 @@ ZEND_API char *zend_make_compiled_string_description(char *name TSRMLS_DC) cur_lineno = 0; } - compiled_string_description = emalloc(sizeof(COMPILED_STRING_DESCRIPTION_FORMAT)+strlen(name)+strlen(cur_filename)+MAX_LENGTH_OF_LONG); - sprintf(compiled_string_description, COMPILED_STRING_DESCRIPTION_FORMAT, cur_filename, cur_lineno, name); + zend_spprintf(&compiled_string_description, 0, COMPILED_STRING_DESCRIPTION_FORMAT, cur_filename, cur_lineno, name); return compiled_string_description; } diff --git a/Zend/zend_builtin_functions.c b/Zend/zend_builtin_functions.c index d5befcc4042..ed2ba749c40 100644 --- a/Zend/zend_builtin_functions.c +++ b/Zend/zend_builtin_functions.c @@ -24,6 +24,7 @@ #include "zend_builtin_functions.h" #include "zend_constants.h" #include "zend_ini.h" +#include "zend_exceptions.h" #undef ZEND_TEST_EXCEPTIONS @@ -1471,8 +1472,7 @@ ZEND_FUNCTION(create_function) +2 /* for the curly braces */ +Z_STRLEN_PP(z_function_code); - eval_code = (char *) emalloc(eval_code_length); - sprintf(eval_code, "function " LAMBDA_TEMP_FUNCNAME "(%s){%s}", Z_STRVAL_PP(z_function_args), Z_STRVAL_PP(z_function_code)); + zend_spprintf(&eval_code, 0, "function " LAMBDA_TEMP_FUNCNAME "(%s){%s}", Z_STRVAL_PP(z_function_args), Z_STRVAL_PP(z_function_code)); eval_name = zend_make_compiled_string_description("runtime-created function" TSRMLS_CC); retval = zend_eval_string(eval_code, NULL, eval_name TSRMLS_CC); diff --git a/Zend/zend_compile.c b/Zend/zend_compile.c index d0b0b70b673..8f21d5f250c 100644 --- a/Zend/zend_compile.c +++ b/Zend/zend_compile.c @@ -25,6 +25,7 @@ #include "zend_constants.h" #include "zend_llist.h" #include "zend_API.h" +#include "zend_exceptions.h" #ifdef ZEND_MULTIBYTE #include "zend_multibyte.h" @@ -83,14 +84,13 @@ static void build_runtime_defined_function_key(zval *result, char *name, int nam /* NULL, name length, filename length, last accepting char position length */ result->value.str.len = 1+name_length+strlen(filename)+char_pos_len; - result->value.str.val = (char *) emalloc(result->value.str.len+1); #ifdef ZEND_MULTIBYTE /* must be binary safe */ + result->value.str.val = (char *) safe_emalloc(result->value.str.len, 1, 1); result->value.str.val[0] = '\0'; - memcpy(result->value.str.val+1, name, name_length); - sprintf(result->value.str.val+1+name_length, "%s%s", filename, char_pos_buf); + sprintf(result->value.str.val+1, "%s%s%s", name, filename, char_pos_buf); #else - sprintf(result->value.str.val, "%c%s%s%s", '\0', name, filename, char_pos_buf); + zend_spprintf(&result->value.str.val, 0, "%c%s%s%s", '\0', name, filename, char_pos_buf); #endif /* ZEND_MULTIBYTE */ result->type = IS_STRING; result->refcount = 1; diff --git a/Zend/zend_language_scanner.l b/Zend/zend_language_scanner.l index c981aa86428..bf76d9773c7 100644 --- a/Zend/zend_language_scanner.l +++ b/Zend/zend_language_scanner.l @@ -59,6 +59,7 @@ #include "zend_operators.h" #include "zend_API.h" #include "zend_strtod.h" +#include "zend_exceptions.h" #ifdef HAVE_STDARG_H # include @@ -1334,13 +1335,11 @@ NEWLINE ("\r"|"\n"|"\r\n") len += strlen(func_name); } - zendlval->value.str.val = emalloc(len+1); - zendlval->value.str.len = sprintf(zendlval->value.str.val, "%s%s%s", + zendlval->value.str.len = zend_spprintf(&zendlval->value.str.val, 0, "%s%s%s", class_name ? class_name : "", class_name && func_name ? "::" : "", func_name ? func_name : "" ); - zendlval->value.str.len = strlen(zendlval->value.str.val); zendlval->type = IS_STRING; return T_METHOD_C; } diff --git a/Zend/zend_operators.c b/Zend/zend_operators.c index 0a9281c8a40..505b12c8aa3 100644 --- a/Zend/zend_operators.c +++ b/Zend/zend_operators.c @@ -29,6 +29,7 @@ #include "zend_API.h" #include "zend_multiply.h" #include "zend_strtod.h" +#include "zend_exceptions.h" #define LONG_SIGN_MASK (1L << (8*sizeof(long)-1)) @@ -550,21 +551,18 @@ ZEND_API void _convert_to_string(zval *op ZEND_FILE_LINE_DC) TSRMLS_FETCH(); zend_list_delete(op->value.lval); - op->value.str.val = (char *) emalloc(sizeof("Resource id #") + MAX_LENGTH_OF_LONG); - op->value.str.len = sprintf(op->value.str.val, "Resource id #%ld", tmp); + op->value.str.len = zend_spprintf(&op->value.str.val, 0, "Resource id #%ld", tmp); break; } case IS_LONG: lval = op->value.lval; - op->value.str.val = (char *) emalloc_rel(MAX_LENGTH_OF_LONG + 1); - op->value.str.len = zend_sprintf(op->value.str.val, "%ld", lval); /* SAFE */ + op->value.str.len = zend_spprintf(&op->value.str.val, 0, "%ld", lval); /* SAFE */ break; case IS_DOUBLE: { TSRMLS_FETCH(); dval = op->value.dval; - op->value.str.val = (char *) emalloc_rel(MAX_LENGTH_OF_DOUBLE + EG(precision) + 1); - op->value.str.len = zend_sprintf(op->value.str.val, "%.*G", (int) EG(precision), dval); /* SAFE */ + op->value.str.len = zend_spprintf(&op->value.str.val, 0, "%.*G", (int) EG(precision), dval); /* SAFE */ /* %G already handles removing trailing zeros from the fractional part, yay */ break; } @@ -2031,13 +2029,9 @@ ZEND_API void zend_compare_objects(zval *result, zval *o1, zval *o2 TSRMLS_DC) ZEND_API void zend_locale_sprintf_double(zval *op ZEND_FILE_LINE_DC) { - double dval = op->value.dval; - TSRMLS_FETCH(); - - op->value.str.val = (char *) emalloc_rel(MAX_LENGTH_OF_DOUBLE + EG(precision) + 1); - sprintf(op->value.str.val, "%.*G", (int) EG(precision), dval); - op->value.str.len = strlen(op->value.str.val); + + op->value.str.len = zend_spprintf(&op->value.str.val, 0, "%.*G", (int) EG(precision), (double)op->value.dval); } /* diff --git a/ext/bcmath/libbcmath/src/output.c b/ext/bcmath/libbcmath/src/output.c index ab49b0e3661..ad4e3754677 100644 --- a/ext/bcmath/libbcmath/src/output.c +++ b/ext/bcmath/libbcmath/src/output.c @@ -71,7 +71,7 @@ bc_out_long (val, size, space, out_char) int len, ix; if (space) (*out_char) (' '); - sprintf (digits, "%ld", val); + snprintf(digits, sizeof(digits), "%ld", val); len = strlen (digits); while (size > len) { diff --git a/ext/bcmath/libbcmath/src/rt.c b/ext/bcmath/libbcmath/src/rt.c index 2479104fe45..d652021f895 100644 --- a/ext/bcmath/libbcmath/src/rt.c +++ b/ext/bcmath/libbcmath/src/rt.c @@ -45,7 +45,7 @@ void bc_rt_warn (char *mesg ,...) char error_mesg [255]; va_start (args, mesg); - vsprintf (error_mesg, mesg, args); + vsnprintf (error_mesg, sizeof(error_msg), mesg, args); va_end (args); fprintf (stderr, "bc math warning: %s\n", error_mesg); @@ -58,7 +58,7 @@ void bc_rt_error (char *mesg ,...) char error_mesg [255]; va_start (args, mesg); - vsprintf (error_mesg, mesg, args); + vsnprintf (error_mesg, sizeof(error_msg), mesg, args); va_end (args); fprintf (stderr, "bc math error: %s\n", error_mesg); diff --git a/ext/com_dotnet/com_wrapper.c b/ext/com_dotnet/com_wrapper.c index 4cc81aa04b1..b698affa220 100644 --- a/ext/com_dotnet/com_wrapper.c +++ b/ext/com_dotnet/com_wrapper.c @@ -74,7 +74,7 @@ static inline void trace(char *fmt, ...) va_list ap; char buf[4096]; - sprintf(buf, "T=%08x ", GetCurrentThreadId()); + snprintf(buf, sizeof(buf), "T=%08x ", GetCurrentThreadId()); OutputDebugString(buf); va_start(ap, fmt); @@ -474,7 +474,7 @@ static void generate_dispids(php_dispatchex *disp TSRMLS_DC) &namelen, &pid, 0, &pos))) { char namebuf[32]; if (keytype == HASH_KEY_IS_LONG) { - sprintf(namebuf, "%d", pid); + snprintf(namebuf, sizeof(namebuf), "%d", pid); name = namebuf; namelen = strlen(namebuf)+1; } @@ -506,7 +506,7 @@ static void generate_dispids(php_dispatchex *disp TSRMLS_DC) char namebuf[32]; if (keytype == HASH_KEY_IS_LONG) { - sprintf(namebuf, "%d", pid); + snprintf(namebuf, sizeof(namebuf), "%d", pid); name = namebuf; namelen = strlen(namebuf) + 1; } diff --git a/ext/date/php_date.c b/ext/date/php_date.c index 14534b846da..2ea2c42e2e0 100644 --- a/ext/date/php_date.c +++ b/ext/date/php_date.c @@ -2244,7 +2244,7 @@ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_su int rs; timelib_time *t; timelib_tzinfo *tzi; - char retstr[6]; + char *retstr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|ldddd", &time, &retformat, &latitude, &longitude, &zenith, &gmt_offset) == FAILURE) { RETURN_FALSE; @@ -2310,8 +2310,8 @@ static void php_do_date_sunrise_sunset(INTERNAL_FUNCTION_PARAMETERS, int calc_su } switch (retformat) { case SUNFUNCS_RET_STRING: - sprintf(retstr, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); - RETURN_STRINGL(retstr, 5, 1); + spprintf(&retstr, 0, "%02d:%02d", (int) N, (int) (60 * (N - (int) N))); + RETURN_STRINGL(retstr, 5, 0); break; case SUNFUNCS_RET_DOUBLE: RETURN_DOUBLE(N); diff --git a/ext/dbase/dbf_head.c b/ext/dbase/dbf_head.c index 42935c2ea45..9c9363dfbbe 100644 --- a/ext/dbase/dbf_head.c +++ b/ext/dbase/dbf_head.c @@ -215,7 +215,7 @@ void put_dbf_info(dbhead_t *dbh) int fcnt; if ((cp = db_cur_date(NULL))) { - strncpy(dbh->db_date, cp, 8); + strlcpy(dbh->db_date, cp, 8); free(cp); } put_dbf_head(dbh); @@ -232,16 +232,16 @@ char *get_dbf_f_fmt(dbfield_t *dbf) /* build the field format for printf */ switch (dbf->db_type) { case 'C': - sprintf(format, "%%-%ds", dbf->db_flen); + snprintf(format, sizeof(format), "%%-%ds", dbf->db_flen); break; case 'N': case 'L': case 'D': case 'F': - sprintf(format, "%%%ds", dbf->db_flen); + snprintf(format, sizeof(format), "%%%ds", dbf->db_flen); break; case 'M': - strcpy(format, "%s"); + strlcpy(format, "%s", sizeof(format)); break; default: return NULL; diff --git a/ext/dbase/dbf_misc.c b/ext/dbase/dbf_misc.c index ad17bd4e3fb..d5727839642 100644 --- a/ext/dbase/dbf_misc.c +++ b/ext/dbase/dbf_misc.c @@ -114,12 +114,7 @@ void db_set_date(char *cp, int year, int month, int day) month = 0; if (day > 31) day = 0; - sprintf(cp, "%d", year); - cp[4] = month / 10 + '0'; - cp[5] = month % 10 + '0'; - cp[6] = day / 10 + '0'; - cp[7] = day % 10 + '0'; - cp[8] = 0; + snprintf(cp, 9, "%04d%02d%02d", year, month, day); } int db_date_year(char *cp) diff --git a/ext/exif/exif.c b/ext/exif/exif.c index d44ca16ba96..f69f73f7611 100644 --- a/ext/exif/exif.c +++ b/ext/exif/exif.c @@ -1035,22 +1035,22 @@ static unsigned char* exif_char_dump(unsigned char * addr, int len, int offset) static unsigned char tmp[20]; int c, i, p=0, n = 5+31; - p += sprintf(buf+p, "\nDump Len: %08X (%d)", len, len); + p += snprintf(buf+p, sizeof(buf)-p, "\nDump Len: %08X (%d)", len, len); if (len) { for(i=0; i=32 ? c : '.'; tmp[(i%16)+1] = '\0'; } else { - p += sprintf(buf+p, " "); + p += snprintf(buf+p, sizeof(buf)-p, " "); } if (i%16==15) { - p += sprintf(buf+p, " %s", tmp); + p += snprintf(buf+p, sizeof(buf)-p, " %s", tmp); if (i>=len) { break; } @@ -1181,44 +1181,44 @@ char * exif_dump_data(int *dump_free, int format, int components, int length, in case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: case TAG_FMT_SBYTE: - dump = erealloc(dump, len + 4); - sprintf(dump + len, "0x%02X", *value_ptr); + dump = erealloc(dump, len + 4 + 1); + snprintf(dump + len, 4, "0x%02X", *value_ptr); len += 4; value_ptr++; break; case TAG_FMT_USHORT: case TAG_FMT_SSHORT: - dump = erealloc(dump, len + 6); - sprintf(dump + len, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel)); + dump = erealloc(dump, len + 6 + 1); + snprintf(dump + len, 6, "0x%04X", php_ifd_get16s(value_ptr, motorola_intel)); len += 6; value_ptr += 2; break; case TAG_FMT_ULONG: case TAG_FMT_SLONG: - dump = erealloc(dump, len + 6); - sprintf(dump + len, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel)); + dump = erealloc(dump, len + 6 + 1); + snprintf(dump + len, 6, "0x%04X", php_ifd_get32s(value_ptr, motorola_intel)); len += 6; value_ptr += 4; break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: - dump = erealloc(dump, len + 13); - sprintf(dump + len, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel)); + dump = erealloc(dump, len + 13 + 1); + snprintf(dump + len, 13, "0x%04X/0x%04X", php_ifd_get32s(value_ptr, motorola_intel), php_ifd_get32s(value_ptr+4, motorola_intel)); len += 13; value_ptr += 8; break; } if (components > 0) { - dump = erealloc(dump, len + 2); - sprintf(dump + len, ", "); + dump = erealloc(dump, len + 4 + 1); + snprintf(dump + len, 4, ", "); len += 2; components--; } else{ break; } } - dump = erealloc(dump, len + 2); - sprintf(dump + len, "}"); + dump = erealloc(dump, len + 2 + 1); + snprintf(dump + len, 2, "}"); return dump; } /* }}} */ @@ -1448,18 +1448,18 @@ static tag_table_type exif_get_tag_table(int section) */ static char *exif_get_sectionlist(int sectionlist TSRMLS_DC) { - int i, len=0; + int i, len, ml = 0; char *sections; for(i=0; i= 2) { convert_to_string_ex(p_sections_needed); - sections_str = safe_emalloc(strlen(Z_STRVAL_PP(p_sections_needed)), 1, 3); - sprintf(sections_str, ",%s,", Z_STRVAL_PP(p_sections_needed)); + spprintf(§ions_str, 0, ",%s,", Z_STRVAL_PP(p_sections_needed)); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while(*++s) { diff --git a/ext/fbsql/php_fbsql.c b/ext/fbsql/php_fbsql.c index 27f11589bac..65ef8ed416d 100644 --- a/ext/fbsql/php_fbsql.c +++ b/ext/fbsql/php_fbsql.c @@ -851,7 +851,7 @@ PHP_MINFO_FUNCTION(fbsql) php_info_print_table_row(2, "Active Links", buf); /* - sprintf(buf, "%ld", FB_SQL_G(resultCount)); + snprintf(buf, sizeof(buf), "%ld", FB_SQL_G(resultCount)); php_info_print_table_row(2, "Active Results", buf); */ @@ -2944,7 +2944,7 @@ void phpfbColumnAsString(PHPFBResult* result, int column, void* data , int* leng for (i = 0; i < nBits / 8; i++) { char c[4]; - sprintf(c, "%02x", ptr->bytes[i]); + snprintf(c, sizeof(c), "%02x", ptr->bytes[i]); r[i*2+2] = c[0]; r[i*2+3] = c[1]; } diff --git a/ext/ftp/ftp.c b/ext/ftp/ftp.c index 400e017a6fc..6bc2d6c3b90 100644 --- a/ext/ftp/ftp.c +++ b/ext/ftp/ftp.c @@ -586,11 +586,7 @@ ftp_chmod(ftpbuf_t *ftp, const int mode, const char *filename, const int filenam return 0; } - if (!(buffer = emalloc(32 + filename_len + 1))) { - return 0; - } - - sprintf(buffer, "CHMOD %o %s", mode, filename); + spprintf(&buffer, 0, "CHMOD %o %s", mode, filename); if (!ftp_putcmd(ftp, "SITE", buffer)) { efree(buffer); @@ -810,7 +806,7 @@ ftp_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, ftptype_t type, php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP cannot handle files greater than 2147483647 bytes."); goto bail; } - sprintf(arg, "%u", resumepos); + snprintf(arg, sizeof(arg), "%u", resumepos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } @@ -907,7 +903,7 @@ ftp_put(ftpbuf_t *ftp, const char *path, php_stream *instream, ftptype_t type, i php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP cannot handle files with a size greater than 2147483647 bytes."); goto bail; } - sprintf(arg, "%u", startpos); + snprintf(arg, sizeof(arg), "%u", startpos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } @@ -1106,13 +1102,13 @@ ftp_putcmd(ftpbuf_t *ftp, const char *cmd, const char *args) if (strlen(cmd) + strlen(args) + 4 > FTP_BUFSIZE) { return 0; } - size = sprintf(ftp->outbuf, "%s %s\r\n", cmd, args); + size = snprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s %s\r\n", cmd, args); } else { /* "cmd\r\n\0" */ if (strlen(cmd) + 3 > FTP_BUFSIZE) { return 0; } - size = sprintf(ftp->outbuf, "%s\r\n", cmd); + size = snprintf(ftp->outbuf, sizeof(ftp->outbuf), "%s\r\n", cmd); } data = ftp->outbuf; @@ -1438,7 +1434,7 @@ ftp_getdata(ftpbuf_t *ftp TSRMLS_DC) char eprtarg[INET6_ADDRSTRLEN + sizeof("|x||xxxxx|")]; char out[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &((struct sockaddr_in6*) sa)->sin6_addr, out, sizeof(out)); - sprintf(eprtarg, "|2|%s|%hu|", out, ntohs(((struct sockaddr_in6 *) &addr)->sin6_port)); + snprintf(eprtarg, sizeof(eprtag), "|2|%s|%hu|", out, ntohs(((struct sockaddr_in6 *) &addr)->sin6_port)); if (!ftp_putcmd(ftp, "EPRT", eprtarg)) { goto bail; @@ -1456,7 +1452,7 @@ ftp_getdata(ftpbuf_t *ftp TSRMLS_DC) /* send the PORT */ ipbox.ia[0] = ((struct sockaddr_in*) sa)->sin_addr; ipbox.s[2] = ((struct sockaddr_in*) &addr)->sin_port; - sprintf(arg, "%u,%u,%u,%u,%u,%u", ipbox.c[0], ipbox.c[1], ipbox.c[2], ipbox.c[3], ipbox.c[4], ipbox.c[5]); + snprintf(arg, sizeof(arg), "%u,%u,%u,%u,%u,%u", ipbox.c[0], ipbox.c[1], ipbox.c[2], ipbox.c[3], ipbox.c[4], ipbox.c[5]); if (!ftp_putcmd(ftp, "PORT", arg)) { goto bail; @@ -1713,7 +1709,7 @@ ftp_nb_get(ftpbuf_t *ftp, php_stream *outstream, const char *path, ftptype_t typ php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP cannot handle files greater than 2147483648 bytes."); goto bail; } - sprintf(arg, "%u", resumepos); + snprintf(arg, sizeof(arg), "%u", resumepos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } @@ -1831,7 +1827,7 @@ ftp_nb_put(ftpbuf_t *ftp, const char *path, php_stream *instream, ftptype_t type php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP cannot handle files with a size greater than 2147483647 bytes."); goto bail; } - sprintf(arg, "%u", startpos); + snprintf(arg, sizeof(arg), "%u", startpos); if (!ftp_putcmd(ftp, "REST", arg)) { goto bail; } diff --git a/ext/gd/libgd/gdtest.c b/ext/gd/libgd/gdtest.c index f4300bb3fd5..24b75038642 100644 --- a/ext/gd/libgd/gdtest.c +++ b/ext/gd/libgd/gdtest.c @@ -56,7 +56,7 @@ main (int argc, char **argv) /* */ /* Send to PNG File then Ptr */ /* */ - sprintf (of, "%s.png", argv[1]); + snprintf (of, sizeof(of), "%s.png", argv[1]); out = fopen (of, "wb"); gdImagePng (im, out); fclose (out); @@ -88,7 +88,7 @@ main (int argc, char **argv) /* */ /* Send to GD2 File then Ptr */ /* */ - sprintf (of, "%s.gd2", argv[1]); + snprintf (of, sizeof(of), "%s.gd2", argv[1]); out = fopen (of, "wb"); gdImageGd2 (im, out, 128, 2); fclose (out); @@ -123,7 +123,7 @@ main (int argc, char **argv) /* */ /* Send to GD File then Ptr */ /* */ - sprintf (of, "%s.gd", argv[1]); + snprintf (of, sizeof(of), "%s.gd", argv[1]); out = fopen (of, "wb"); gdImageGd (im, out); fclose (out); @@ -180,7 +180,7 @@ main (int argc, char **argv) ** Test gdImagePngToSink' * */ - sprintf (of, "%s.snk", argv[1]); + snprintf (of, sizeof(of), "%s.snk", argv[1]); out = fopen (of, "wb"); imgsnk.sink = fwriteWrapper; imgsnk.context = out; diff --git a/ext/gd/libgd/webpng.c b/ext/gd/libgd/webpng.c index 81a00e749c7..c01dd82f23d 100644 --- a/ext/gd/libgd/webpng.c +++ b/ext/gd/libgd/webpng.c @@ -252,7 +252,7 @@ usage: /* Open a temporary file. */ /* "temp.tmp" is not good temporary filename. */ - sprintf (outFn, "webpng.tmp%d", getpid ()); + snprintf (outFn, sizeof(outFn), "webpng.tmp%d", getpid ()); out = fopen (outFn, "wb"); if (!out) diff --git a/ext/imap/php_imap.c b/ext/imap/php_imap.c index 34aa01a10bb..1ca0d42e419 100644 --- a/ext/imap/php_imap.c +++ b/ext/imap/php_imap.c @@ -1173,7 +1173,7 @@ PHP_FUNCTION(imap_headers) tmp[3] = cache->answered ? 'A' : ' '; tmp[4] = cache->deleted ? 'D' : ' '; tmp[5] = cache->draft ? 'X' : ' '; - sprintf(tmp + 6, "%4ld) ", cache->msgno); + snprintf(tmp + 6, sizeof(tmp) - 6, "%4ld) ", cache->msgno); mail_date(tmp+11, cache); tmp[22] = ' '; tmp[23] = '\0'; @@ -1625,13 +1625,13 @@ PHP_FUNCTION(imap_headerinfo) add_property_string(return_value, "Deleted", cache->deleted ? "D" : " ", 1); add_property_string(return_value, "Draft", cache->draft ? "X" : " ", 1); - sprintf(dummy, "%4ld", cache->msgno); + snprintf(dummy, sizeof(dummy), "%4ld", cache->msgno); add_property_string(return_value, "Msgno", dummy, 1); mail_date(dummy, cache); add_property_string(return_value, "MailDate", dummy, 1); - sprintf(dummy, "%ld", cache->rfc822_size); + snprintf(dummy, sizeof(dummy), "%ld", cache->rfc822_size); add_property_string(return_value, "Size", dummy, 1); add_property_long(return_value, "udate", mail_longdate(cache)); @@ -3377,7 +3377,8 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * char *tsm_errmsg = NULL; ADDRESS *addr; char *bufferTo = NULL, *bufferCc = NULL, *bufferBcc = NULL, *bufferHeader = NULL; - int offset, bufferLen = 0;; + int offset, bufferLen = 0; + size_t bt_len; if (headers) { bufferLen += strlen(headers); @@ -3399,7 +3400,9 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * strlcat(bufferHeader, to, bufferLen + 1); strlcat(bufferHeader, "\r\n", bufferLen + 1); tempMailTo = estrdup(to); - bufferTo = (char *)emalloc(strlen(to) + 1); + bt_len = strlen(to); + bufferTo = (char *)safe_emalloc(bt_len, 1, 1); + bt_len++; offset = 0; addr = NULL; rfc822_parse_adrlist(&addr, tempMailTo, NULL); @@ -3407,7 +3410,11 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * if (strcmp(addr->host, ERRHOST) == 0) { PHP_IMAP_BAD_DEST; } else { - offset += sprintf(bufferTo + offset, "%s@%s,", addr->mailbox, addr->host); + bufferTo = safe_erealloc(bufferTo, bt_len, 1, strlen(addr->mailbox)); + bt_len += strlen(addr->mailbox); + bufferTo = safe_erealloc(bufferTo, bt_len, 1, strlen(addr->host)); + bt_len += strlen(addr->host); + offset += snprintf(bufferTo + offset, bt_len - offset, "%s@%s,", addr->mailbox, addr->host); } addr = addr->next; } @@ -3422,7 +3429,9 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * strlcat(bufferHeader, cc, bufferLen + 1); strlcat(bufferHeader, "\r\n", bufferLen + 1); tempMailTo = estrdup(cc); - bufferCc = (char *)emalloc(strlen(cc) + 1); + bt_len = strlen(cc); + bufferCc = (char *)safe_emalloc(bt_len, 1, 1); + bt_len++; offset = 0; addr = NULL; rfc822_parse_adrlist(&addr, tempMailTo, NULL); @@ -3430,7 +3439,11 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * if (strcmp(addr->host, ERRHOST) == 0) { PHP_IMAP_BAD_DEST; } else { - offset += sprintf(bufferCc + offset, "%s@%s,", addr->mailbox, addr->host); + bufferCc = safe_erealloc(bufferCc, bt_len, 1, strlen(addr->mailbox)); + bt_len += strlen(addr->mailbox); + bufferCc = safe_erealloc(bufferCc, bt_len, 1, strlen(addr->host)); + bt_len += strlen(addr->host); + offset += snprintf(bufferCc + offset, bt_len - offset, "%s@%s,", addr->mailbox, addr->host); } addr = addr->next; } @@ -3442,7 +3455,9 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * if (bcc && *bcc) { tempMailTo = estrdup(bcc); - bufferBcc = (char *)emalloc(strlen(bcc) + 1); + bt_len = strlen(bcc); + bufferBcc = (char *)safe_emalloc(bt_len, 1, 1); + bt_len++; offset = 0; addr = NULL; rfc822_parse_adrlist(&addr, tempMailTo, NULL); @@ -3450,7 +3465,11 @@ int _php_imap_mail(char *to, char *subject, char *message, char *headers, char * if (strcmp(addr->host, ERRHOST) == 0) { PHP_IMAP_BAD_DEST; } else { - offset += sprintf(bufferBcc + offset, "%s@%s,", addr->mailbox, addr->host); + bufferBcc = safe_erealloc(bufferBcc, bt_len, 1, strlen(addr->mailbox)); + bt_len += strlen(addr->mailbox); + bufferBcc = safe_erealloc(bufferBcc, bt_len, 1, strlen(addr->host)); + bt_len += strlen(addr->host); + offset += snprintf(bufferBcc + offset, bt_len - offset, "%s@%s,", addr->mailbox, addr->host); } addr = addr->next; } diff --git a/ext/interbase/ibase_blobs.c b/ext/interbase/ibase_blobs.c index d622359c9d7..4625281a118 100644 --- a/ext/interbase/ibase_blobs.c +++ b/ext/interbase/ibase_blobs.c @@ -74,16 +74,15 @@ int _php_ibase_string_to_quad(char const *id, ISC_QUAD *qd) /* {{{ */ char *_php_ibase_quad_to_string(ISC_QUAD const qd) /* {{{ */ { - char *result = (char *) emalloc(BLOB_ID_LEN+1); + char *result; /* shortcut for most common case */ if (sizeof(ISC_QUAD) == sizeof(ISC_UINT64)) { - sprintf(result, "0x%0*" LL_MASK "x", 16, *(ISC_UINT64*)(void *) &qd); + spprintf(&result, BLOB_ID_LEN+1, "0x%0*" LL_MASK "x", 16, *(ISC_UINT64*)(void *) &qd); } else { ISC_UINT64 res = ((ISC_UINT64) qd.gds_quad_high << 0x20) | qd.gds_quad_low; - sprintf(result, "0x%0*" LL_MASK "x", 16, res); + spprintf(&result, BLOB_ID_LEN+1, "0x%0*" LL_MASK "x", 16, res); } - result[BLOB_ID_LEN] = '\0'; return result; } /* }}} */ diff --git a/ext/interbase/ibase_query.c b/ext/interbase/ibase_query.c index c78d0618bb4..3de5879688a 100644 --- a/ext/interbase/ibase_query.c +++ b/ext/interbase/ibase_query.c @@ -1317,17 +1317,17 @@ static int _php_ibase_var_zval(zval *val, void *data, int type, int len, /* {{{ goto _sql_long; #else if (scale == 0) { - l = sprintf(string_data, "%" LL_MASK "d", *(ISC_INT64 *) data); + l = snprintf(string_data, sizeof(string_data), "%" LL_MASK "d", *(ISC_INT64 *) data); ZVAL_STRINGL(val,string_data,l,1); } else { ISC_INT64 n = *(ISC_INT64 *) data, f = scales[-scale]; if (n >= 0) { - l = sprintf(string_data, "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, n % f); + l = snprintf(string_data, sizeof(string_data), "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, n % f); } else if (n <= -f) { - l = sprintf(string_data, "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, -n % f); + l = snprintf(string_data, sizeof(string_data), "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -scale, -n % f); } else { - l = sprintf(string_data, "-0.%0*" LL_MASK "d", -scale, -n % f); + l = snprintf(string_data, sizeof(string_data), "-0.%0*" LL_MASK "d", -scale, -n % f); } ZVAL_STRINGL(val,string_data,l,1); } @@ -1342,11 +1342,11 @@ static int _php_ibase_var_zval(zval *val, void *data, int type, int len, /* {{{ long f = (long) scales[-scale]; if (n >= 0) { - l = sprintf(string_data, "%ld.%0*ld", n / f, -scale, n % f); + l = snprintf(string_data, sizeof(string_data), "%ld.%0*ld", n / f, -scale, n % f); } else if (n <= -f) { - l = sprintf(string_data, "%ld.%0*ld", n / f, -scale, -n % f); + l = snprintf(string_data, sizeof(string_data), "%ld.%0*ld", n / f, -scale, -n % f); } else { - l = sprintf(string_data, "-0.%0*ld", -scale, -n % f); + l = snprintf(string_data, sizeof(string_data), "-0.%0*ld", -scale, -n % f); } ZVAL_STRINGL(val,string_data,l,1); } @@ -1386,14 +1386,14 @@ format_date_time: #else switch (type & ~1) { default: - l = sprintf(string_data, "%02d/%02d/%4d %02d:%02d:%02d", t.tm_mon+1, t.tm_mday, + l = snprintf(string_data, sizeof(string_data), "%02d/%02d/%4d %02d:%02d:%02d", t.tm_mon+1, t.tm_mday, t.tm_year + 1900, t.tm_hour, t.tm_min, t.tm_sec); break; case SQL_TYPE_DATE: - l = sprintf(string_data, "%02d/%02d/%4d", t.tm_mon + 1, t.tm_mday, t.tm_year+1900); + l = snprintf(string_data, sizeof(string_data), "%02d/%02d/%4d", t.tm_mon + 1, t.tm_mday, t.tm_year+1900); break; case SQL_TYPE_TIME: - l = sprintf(string_data, "%02d:%02d:%02d", t.tm_hour, t.tm_min, t.tm_sec); + l = snprintf(string_data, sizeof(string_data), "%02d:%02d:%02d", t.tm_hour, t.tm_min, t.tm_sec); break; } #endif @@ -1525,7 +1525,7 @@ static void _php_ibase_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, int fetch_type) Z_ARRVAL_P(return_value),alias,strlen(alias)+1,&p)) { case '\0': - sprintf(alias = buf, "%s_%02d", base, i++); + snprintf(alias = buf, sizeof(buf), "%s_%02d", base, i++); } } } diff --git a/ext/interbase/ibase_service.c b/ext/interbase/ibase_service.c index 4d610aa6ee5..4ddb74e0d65 100644 --- a/ext/interbase/ibase_service.c +++ b/ext/interbase/ibase_service.c @@ -322,7 +322,7 @@ query_loop: heap_p = heap_buf + res_size; } result += 2; - sprintf(heap_p, "%s\n", result); + snprintf(heap_p, sizeof(heap_buf_size), "%s\n", result); heap_p += line_len +2; goto query_loop; /* repeat until result is exhausted */ diff --git a/ext/interbase/interbase.c b/ext/interbase/interbase.c index 63d09e0eb3b..a040cc68457 100644 --- a/ext/interbase/interbase.c +++ b/ext/interbase/interbase.c @@ -542,7 +542,7 @@ PHP_MINFO_FUNCTION(ibase) #endif #ifdef FB_API_VER - sprintf( (s = tmp), "Firebird API version %d", FB_API_VER); + snprintf( (s = tmp), sizeof(tmp), "Firebird API version %d", FB_API_VER); #elif (SQLDA_CURRENT_VERSION > 1) s = "Interbase 7.0 and up"; #elif !defined(DSC_null) @@ -607,7 +607,7 @@ int _php_ibase_attach_db(char **args, int *len, long *largs, isc_db_handle *db T buf_len -= dpb_len; } if (largs[SYNC] && buf_len > 0) { - dpb_len = sprintf(dpb, buf_len, "%c\1%c", isc_dpb_force_write, largs[SYNC] == isc_spb_prp_wm_sync ? 1 : 0); + dpb_len = snprintf(dpb, buf_len, "%c\1%c", isc_dpb_force_write, largs[SYNC] == isc_spb_prp_wm_sync ? 1 : 0); dpb += dpb_len; buf_len -= dpb_len; } @@ -1170,7 +1170,7 @@ PHP_FUNCTION(ibase_gen_id) PHP_IBASE_LINK_TRANS(link, ib_link, trans); - sprintf(query, "SELECT GEN_ID(%s,%ld) FROM rdb$database", generator, inc); + snprintf(query, sizeof(query), "SELECT GEN_ID(%s,%ld) FROM rdb$database", generator, inc); /* allocate a minimal descriptor area */ out_sqlda.sqln = out_sqlda.sqld = 1; @@ -1192,10 +1192,11 @@ PHP_FUNCTION(ibase_gen_id) /* don't return the generator value as a string unless it doesn't fit in a long */ #if SIZEOF_LONG < 8 if (result < LONG_MIN || result > LONG_MAX) { - char res[24]; + char *res; + int l - sprintf(res, "%" LL_MASK "d", result); - RETURN_STRING(res,1); + l = spprintf(&res, 0, "%" LL_MASK "d", result); + RETURN_STRINGL(res, l, 0); } #endif RETURN_LONG((long)result); diff --git a/ext/mbstring/mbstring.c b/ext/mbstring/mbstring.c index c258cc4e751..7e1f821236d 100644 --- a/ext/mbstring/mbstring.c +++ b/ext/mbstring/mbstring.c @@ -1048,7 +1048,7 @@ PHP_MINFO_FUNCTION(mbstring) { char buf[32]; php_info_print_table_row(2, "Multibyte (japanese) regex support", "enabled"); - sprintf(buf, "%d.%d.%d", + snprintf(buf, sizeof(buf), "%d.%d.%d", ONIGURUMA_VERSION_MAJOR,ONIGURUMA_VERSION_MINOR,ONIGURUMA_VERSION_TEENY); php_info_print_table_row(2, "Multibyte regex (oniguruma) version", buf); #ifdef USE_COMBINATION_EXPLOSION_CHECK diff --git a/ext/mbstring/oniguruma/regerror.c b/ext/mbstring/oniguruma/regerror.c index 93066f7209b..0e0174d8a85 100644 --- a/ext/mbstring/oniguruma/regerror.c +++ b/ext/mbstring/oniguruma/regerror.c @@ -306,7 +306,7 @@ onig_snprintf_with_pattern(buf, bufsize, enc, pat, pat_end, fmt, va_alist) int blen; while (len-- > 0) { - sprintf((char* )bs, "\\%03o", *p++ & 0377); + snprintf((char* )bs, sizeof(bs), "\\%03o", *p++ & 0377); blen = onigenc_str_bytelen_null(ONIG_ENCODING_ASCII, bs); bp = bs; while (blen-- > 0) *s++ = *bp++; @@ -315,7 +315,7 @@ onig_snprintf_with_pattern(buf, bufsize, enc, pat, pat_end, fmt, va_alist) } else if (!ONIGENC_IS_CODE_PRINT(enc, *p) && !ONIGENC_IS_CODE_SPACE(enc, *p)) { - sprintf((char* )bs, "\\%03o", *p++ & 0377); + snprintf((char* )bs, sizeof(bs), "\\%03o", *p++ & 0377); len = onigenc_str_bytelen_null(ONIG_ENCODING_ASCII, bs); bp = bs; while (len-- > 0) *s++ = *bp++; diff --git a/ext/mbstring/oniguruma/regposerr.c b/ext/mbstring/oniguruma/regposerr.c index e54b5c4089e..26f89f223f7 100644 --- a/ext/mbstring/oniguruma/regposerr.c +++ b/ext/mbstring/oniguruma/regposerr.c @@ -76,7 +76,7 @@ regerror(int posix_ecode, const regex_t* reg, char* buf, size_t size) s = ""; } else { - sprintf(tbuf, "undefined error code (%d)", posix_ecode); + snprintf(tbuf, sizeof(tbuf), "undefined error code (%d)", posix_ecode); s = tbuf; } diff --git a/ext/mbstring/oniguruma/regversion.c b/ext/mbstring/oniguruma/regversion.c index d1e01d75d3b..f12a2538657 100644 --- a/ext/mbstring/oniguruma/regversion.c +++ b/ext/mbstring/oniguruma/regversion.c @@ -35,7 +35,7 @@ onig_version(void) { static char s[12]; - sprintf(s, "%d.%d.%d", + snprintf(s, sizeof(s), "%d.%d.%d", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY); @@ -47,7 +47,7 @@ onig_copyright(void) { static char s[58]; - sprintf(s, "Oniguruma %d.%d.%d : Copyright (C) 2002-2007 K.Kosako", + snprintf(s, sizeof(s), "Oniguruma %d.%d.%d : Copyright (C) 2002-2007 K.Kosako", ONIGURUMA_VERSION_MAJOR, ONIGURUMA_VERSION_MINOR, ONIGURUMA_VERSION_TEENY); diff --git a/ext/mhash/mhash.c b/ext/mhash/mhash.c index 2722ffa23c5..3387d44b15c 100644 --- a/ext/mhash/mhash.c +++ b/ext/mhash/mhash.c @@ -83,7 +83,7 @@ PHP_MINFO_FUNCTION(mhash) { char version[32]; - sprintf(version,"%d", MHASH_API_VERSION); + snprintf(version, sizeof(version), "%d", MHASH_API_VERSION); php_info_print_table_start(); php_info_print_table_row(2, "MHASH support", "Enabled"); diff --git a/ext/msql/php_msql.c b/ext/msql/php_msql.c index 4e78f120f08..196bb174615 100644 --- a/ext/msql/php_msql.c +++ b/ext/msql/php_msql.c @@ -250,9 +250,7 @@ static void php_msql_do_connect(INTERNAL_FUNCTION_PARAMETERS,int persistent) } convert_to_string(yyhost); host = Z_STRVAL_P(yyhost); - hashed_details_length = Z_STRLEN_P(yyhost)+4+1; - hashed_details = emalloc(hashed_details_length+1); - sprintf(hashed_details,"msql_%s",Z_STRVAL_P(yyhost)); /* SAFE */ + hashed_details_length = spprintf(&hashed_details, 0, "msql_%s",Z_STRVAL_P(yyhost)); } break; default: diff --git a/ext/mssql/php_mssql.c b/ext/mssql/php_mssql.c index 764151a3d31..417c3110c4d 100644 --- a/ext/mssql/php_mssql.c +++ b/ext/mssql/php_mssql.c @@ -373,9 +373,9 @@ PHP_MINFO_FUNCTION(mssql) php_info_print_table_start(); php_info_print_table_header(2, "MSSQL Support", "enabled"); - sprintf(buf, "%ld", MS_SQL_G(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", MS_SQL_G(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); - sprintf(buf, "%ld", MS_SQL_G(num_links)); + snprintf(buf, sizeof(buf), "%ld", MS_SQL_G(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_row(2, "Library version", MSSQL_VERSION); @@ -391,7 +391,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) char *hashed_details; int hashed_details_length, new_link = 0; mssql_link mssql, *mssql_ptr; - char buffer[32]; + char buffer[40]; switch(ZEND_NUM_ARGS()) { case 0: /* defaults */ @@ -409,9 +409,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) convert_to_string_ex(yyhost); host = Z_STRVAL_PP(yyhost); user=passwd=NULL; - hashed_details_length = Z_STRLEN_PP(yyhost)+5+3; - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details,"mssql_%s__",Z_STRVAL_PP(yyhost)); + hashed_details_length = spprintf(&hashed_details, 0, "mssql_%s__", Z_STRVAL_PP(yyhost)); } break; case 2: { @@ -425,9 +423,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) host = Z_STRVAL_PP(yyhost); user = Z_STRVAL_PP(yyuser); passwd=NULL; - hashed_details_length = Z_STRLEN_PP(yyhost)+Z_STRLEN_PP(yyuser)+5+3; - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details,"mssql_%s_%s_",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser)); + hashed_details_length = spprintf(&hashed_details, 0, "mssql_%s_%s_",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser)); } break; case 3: { @@ -442,9 +438,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) host = Z_STRVAL_PP(yyhost); user = Z_STRVAL_PP(yyuser); passwd = Z_STRVAL_PP(yypasswd); - hashed_details_length = Z_STRLEN_PP(yyhost)+Z_STRLEN_PP(yyuser)+Z_STRLEN_PP(yypasswd)+5+3; - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details,"mssql_%s_%s_%s",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser),Z_STRVAL_PP(yypasswd)); /* SAFE */ + hashed_details_length = spprintf(&hashed_details,0,"mssql_%s_%s_%s",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser),Z_STRVAL_PP(yypasswd)); } break; case 4: { @@ -461,9 +455,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) user = Z_STRVAL_PP(yyuser); passwd = Z_STRVAL_PP(yypasswd); new_link = Z_LVAL_PP(yynew_link); - hashed_details_length = Z_STRLEN_PP(yyhost)+Z_STRLEN_PP(yyuser)+Z_STRLEN_PP(yypasswd)+5+3; - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details,"mssql_%s_%s_%s",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser),Z_STRVAL_PP(yypasswd)); /* SAFE */ + hashed_details_length = spprintf(&hashed_details,0,"mssql_%s_%s_%s",Z_STRVAL_PP(yyhost),Z_STRVAL_PP(yyuser),Z_STRVAL_PP(yypasswd)); } break; default: @@ -554,7 +546,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) #ifndef HAVE_FREETDS if (MS_SQL_G(textlimit) != -1) { - sprintf(buffer, "%li", MS_SQL_G(textlimit)); + snprintf(buffer, sizeof(buffer), "%li", MS_SQL_G(textlimit)); if (DBSETOPT(mssql.link, DBTEXTLIMIT, buffer)==FAIL) { efree(hashed_details); dbfreelogin(mssql.login); @@ -564,7 +556,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) } #endif if (MS_SQL_G(textsize) != -1) { - sprintf(buffer, "SET TEXTSIZE %li", MS_SQL_G(textsize)); + snprintf(buffer, sizeof(buffer), "SET TEXTSIZE %li", MS_SQL_G(textsize)); dbcmd(mssql.link, buffer); dbsqlexec(mssql.link); dbresults(mssql.link); @@ -681,7 +673,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) #ifndef HAVE_FREETDS if (MS_SQL_G(textlimit) != -1) { - sprintf(buffer, "%li", MS_SQL_G(textlimit)); + snprintf(buffer, sizeof(buffer), "%li", MS_SQL_G(textlimit)); if (DBSETOPT(mssql.link, DBTEXTLIMIT, buffer)==FAIL) { efree(hashed_details); dbfreelogin(mssql.login); @@ -691,7 +683,7 @@ static void php_mssql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) } #endif if (MS_SQL_G(textsize) != -1) { - sprintf(buffer, "SET TEXTSIZE %li", MS_SQL_G(textsize)); + snprintf(buffer, sizeof(buffer), "SET TEXTSIZE %li", MS_SQL_G(textsize)); dbcmd(mssql.link, buffer); dbsqlexec(mssql.link); dbresults(mssql.link); @@ -929,8 +921,7 @@ static void php_mssql_get_column_content_with_type(mssql_link *mssql_ptr,int off } res_length = 19; - res_buf = (unsigned char *) emalloc(res_length+1); - sprintf(res_buf, "%d-%02d-%02d %02d:%02d:%02d" , dateinfo.year, dateinfo.month, dateinfo.day, dateinfo.hour, dateinfo.minute, dateinfo.second); + spprintf(&res_buf, 0, "%d-%02d-%02d %02d:%02d:%02d" , dateinfo.year, dateinfo.month, dateinfo.day, dateinfo.hour, dateinfo.minute, dateinfo.second); } ZVAL_STRINGL(result, res_buf, res_length, 0); @@ -999,8 +990,7 @@ static void php_mssql_get_column_content_without_type(mssql_link *mssql_ptr,int } res_length = 19; - res_buf = (unsigned char *) emalloc(res_length+1); - sprintf(res_buf, "%d-%02d-%02d %02d:%02d:%02d" , dateinfo.year, dateinfo.month, dateinfo.day, dateinfo.hour, dateinfo.minute, dateinfo.second); + spprintf(&res_buf, 0, "%d-%02d-%02d %02d:%02d:%02d" , dateinfo.year, dateinfo.month, dateinfo.day, dateinfo.hour, dateinfo.minute, dateinfo.second); } ZVAL_STRINGL(result, res_buf, res_length, 0); diff --git a/ext/mysql/php_mysql.c b/ext/mysql/php_mysql.c index e8847471274..91df858c968 100644 --- a/ext/mysql/php_mysql.c +++ b/ext/mysql/php_mysql.c @@ -447,9 +447,9 @@ PHP_MINFO_FUNCTION(mysql) php_info_print_table_start(); php_info_print_table_header(2, "MySQL Support", "enabled"); - sprintf(buf, "%ld", MySG(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", MySG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); - sprintf(buf, "%ld", MySG(num_links)); + snprintf(buf, sizeof(buf), "%ld", MySG(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_row(2, "Client API version", mysql_get_client_info()); #if !defined (PHP_WIN32) && !defined (NETWARE) @@ -519,9 +519,7 @@ static void php_mysql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) } host_and_port=passwd=NULL; user=php_get_current_user(); - hashed_details_length = strlen(user)+5+3; - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details, "mysql__%s_", user); + hashed_details_length = spprintf(&hashed_details, 0, "mysql__%s_", user); client_flags = CLIENT_INTERACTIVE; } else { host_and_port = MySG(default_host); @@ -617,9 +615,7 @@ static void php_mysql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) } } - hashed_details_length = sizeof("mysql___")-1 + strlen(SAFE_STRING(host_and_port))+strlen(SAFE_STRING(user))+strlen(SAFE_STRING(passwd)); - hashed_details = (char *) emalloc(hashed_details_length+1); - sprintf(hashed_details, "mysql_%s_%s_%s", SAFE_STRING(host_and_port), SAFE_STRING(user), SAFE_STRING(passwd)); + hashed_details_length = spprintf(&hashed_details, 0, "mysql_%s_%s_%s", SAFE_STRING(host_and_port), SAFE_STRING(user), SAFE_STRING(passwd)); } /* We cannot use mysql_port anymore in windows, need to use @@ -1235,9 +1231,9 @@ static void php_mysql_do_query_general(zval **query, zval **mysql_link, int link if (!strncasecmp("select", Z_STRVAL_PP(query), 6)){ MYSQL_ROW row; - char *newquery = (char *)emalloc(Z_STRLEN_PP(query) + 10); - sprintf ((char *)newquery, "EXPLAIN %s", Z_STRVAL_PP(query)); - mysql_real_query(&mysql->conn, newquery, strlen(newquery)); + char *newquery; + int newql = spprintf (&newquery, 0, "EXPLAIN %s", Z_STRVAL_PP(query)); + mysql_real_query(&mysql->conn, newquery, newql); efree (newquery); if (mysql_errno(&mysql->conn)) { php_error_docref("http://www.mysql.com/doc" TSRMLS_CC, E_WARNING, "%s", mysql_error(&mysql->conn)); diff --git a/ext/mysqli/mysqli.c b/ext/mysqli/mysqli.c index e31d09a2c70..764e53b2cd7 100644 --- a/ext/mysqli/mysqli.c +++ b/ext/mysqli/mysqli.c @@ -1037,7 +1037,7 @@ int php_local_infile_init(void **ptr, const char *filename, void *userdata) mysql->li_stream = php_stream_open_wrapper_ex((char *)filename, "r", 0, NULL, context); if (mysql->li_stream == NULL) { - sprintf((char *)data->error_msg, "Can't find file '%-.64s'.", filename); + snprintf((char *)data->error_msg, sizeof(data->error_msg), "Can't find file '%-.64s'.", filename); return 1; } diff --git a/ext/mysqli/mysqli_api.c b/ext/mysqli/mysqli_api.c index b7d0e510412..69c944894f2 100644 --- a/ext/mysqli/mysqli_api.c +++ b/ext/mysqli/mysqli_api.c @@ -710,7 +710,7 @@ PHP_FUNCTION(mysqli_stmt_fetch) * may be negative. Therefor we cannot use MYSQLI_LLU_SPEC and must * use MYSQLI_LL_SPEC. */ - sprintf((char *)&tmp, (stmt->stmt->fields[i].flags & UNSIGNED_FLAG)? MYSQLI_LLU_SPEC : MYSQLI_LL_SPEC, llval); + snprintf(tmp, sizeof(tmp), (stmt->stmt->fields[i].flags & UNSIGNED_FLAG)? MYSQLI_LLU_SPEC : MYSQLI_LL_SPEC, llval); ZVAL_STRING(stmt->result.vars[i], tmp, 1); } else { ZVAL_LONG(stmt->result.vars[i], llval); diff --git a/ext/mysqli/mysqli_prop.c b/ext/mysqli/mysqli_prop.c index 9923cb8b27f..fd0b8a21fa4 100644 --- a/ext/mysqli/mysqli_prop.c +++ b/ext/mysqli/mysqli_prop.c @@ -85,9 +85,9 @@ static int __func(mysqli_object *obj, zval **retval TSRMLS_DC) \ if (l < LONG_MAX) {\ ZVAL_LONG(*retval, l);\ } else { \ - char ret[40]; \ - sprintf(ret, MYSQLI_LLU_SPEC, (my_ulonglong)l); \ - ZVAL_STRING(*retval, ret, 1); \ + char *ret; \ + int l = spprintf(&ret, 0, MYSQLI_LLU_SPEC, (my_ulonglong)l); \ + ZVAL_STRINGL(*retval, ret, l, 0); \ } \ }\ return SUCCESS;\ @@ -175,9 +175,9 @@ static int link_affected_rows_read(mysqli_object *obj, zval **retval TSRMLS_DC) if (rc < LONG_MAX) { ZVAL_LONG(*retval, rc); } else { - char ret[40]; - sprintf(ret, MYSQLI_LLU_SPEC, (my_ulonglong) rc); - ZVAL_STRING(*retval, ret, 1); + char *ret; + int l = spprintf(&ret, 0, MYSQLI_LLU_SPEC, (my_ulonglong) rc); + ZVAL_STRINGL(*retval, ret, l, 0); } } return SUCCESS; @@ -294,9 +294,9 @@ static int stmt_affected_rows_read(mysqli_object *obj, zval **retval TSRMLS_DC) if (rc < LONG_MAX) { ZVAL_LONG(*retval, rc); } else { - char ret[40]; - sprintf(ret, MYSQLI_LLU_SPEC, (my_ulonglong) rc); - ZVAL_STRING(*retval, ret, 1); + char *ret; + int l = spprintf(&ret, 0, MYSQLI_LLU_SPEC, (my_ulonglong) rc); + ZVAL_STRINGL(*retval, ret, l, 0); } } return SUCCESS; diff --git a/ext/mysqli/php_mysqli.h b/ext/mysqli/php_mysqli.h index c1785099b65..2e962bd1409 100644 --- a/ext/mysqli/php_mysqli.h +++ b/ext/mysqli/php_mysqli.h @@ -243,9 +243,9 @@ PHP_MYSQLI_EXPORT(zend_object_value) mysqli_objects_new(zend_class_entry * TSRML if ((__val) < LONG_MAX) { \ RETURN_LONG((__val)); \ } else { \ - char ret[40]; \ - sprintf(ret, "%llu", (__val)); \ - RETURN_STRING(ret,1); \ + char *ret; \ + int l = spprintf(ret, "%llu", (__val)); \ + RETURN_STRINGL(ret, l, 0); \ } \ } diff --git a/ext/oci8/oci8.c b/ext/oci8/oci8.c index 60c4436f975..cf4c3210662 100644 --- a/ext/oci8/oci8.c +++ b/ext/oci8/oci8.c @@ -676,9 +676,9 @@ PHP_MINFO_FUNCTION(oci) php_info_print_table_row(2, "Version", "1.2.3"); php_info_print_table_row(2, "Revision", "$Revision$"); - sprintf(buf, "%ld", OCI_G(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", OCI_G(num_persistent)); php_info_print_table_row(2, "Active Persistent Connections", buf); - sprintf(buf, "%ld", OCI_G(num_links)); + snprintf(buf, sizeof(buf), "%ld", OCI_G(num_links)); php_info_print_table_row(2, "Active Connections", buf); #if !defined(PHP_WIN32) && !defined(HAVE_OCI_INSTANT_CLIENT) @@ -687,7 +687,7 @@ PHP_MINFO_FUNCTION(oci) php_info_print_table_row(2, "Libraries Used", PHP_OCI8_SHARED_LIBADD ); #else # if defined(HAVE_OCI_INSTANT_CLIENT) && defined(OCI_MAJOR_VERSION) && defined(OCI_MINOR_VERSION) - sprintf(buf, "%d.%d", OCI_MAJOR_VERSION, OCI_MINOR_VERSION); + snprintf(buf, sizeof(buf), "%d.%d", OCI_MAJOR_VERSION, OCI_MINOR_VERSION); php_info_print_table_row(2, "Oracle Instant Client Version", buf); # endif #endif diff --git a/ext/odbc/php_odbc.c b/ext/odbc/php_odbc.c index bb97e27c59b..d82e0efaa11 100644 --- a/ext/odbc/php_odbc.c +++ b/ext/odbc/php_odbc.c @@ -544,9 +544,9 @@ PHP_MINFO_FUNCTION(odbc) php_info_print_table_start(); php_info_print_table_header(2, "ODBC Support", "enabled"); - sprintf(buf, "%ld", ODBCG(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", ODBCG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); - sprintf(buf, "%ld", ODBCG(num_links)); + snprintf(buf, sizeof(buf), "%ld", ODBCG(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_row(2, "ODBC library", PHP_ODBC_TYPE); #ifndef PHP_WIN32 @@ -588,8 +588,8 @@ void odbc_sql_error(ODBC_SQL_ERROR_PARAMS) */ rc = SQLError(henv, conn, stmt, state, &error, errormsg, sizeof(errormsg)-1, &errormsgsize); if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) { - sprintf(state, "HY000"); - sprintf(errormsg, "Failed to fetch error message"); + snprintf(state, sizeof(state), "HY000"); + snprintf(errormsg, sizeof(errormsg), "Failed to fetch error message"); } if (conn_resource) { memcpy(conn_resource->laststate, state, sizeof(state)); @@ -1162,7 +1162,7 @@ PHP_FUNCTION(odbc_cursor) result->stmt, state, &error, errormsg, sizeof(errormsg)-1, &errormsgsize); if (!strncmp(state,"S1015",5)) { - sprintf(cursorname,"php_curs_%d", (int)result->stmt); + snprintf(cursorname, max_len+1, "php_curs_%d", (int)result->stmt); if (SQLSetCursorName(result->stmt,cursorname,SQL_NTS) != SQL_SUCCESS) { odbc_sql_error(result->conn_ptr, result->stmt, "SQLSetCursorName"); RETVAL_FALSE; @@ -2155,8 +2155,7 @@ int odbc_sqlconnect(odbc_connection **conn, char *db, char *uid, char *pwd, int if (strstr((char*)db, ";")) { direct = 1; if (uid && !strstr ((char*)db, "uid") && !strstr((char*)db, "UID")) { - ldb = (char*) emalloc(strlen(db) + strlen(uid) + strlen(pwd) + 12); - sprintf(ldb, "%s;UID=%s;PWD=%s", db, uid, pwd); + spprintf(&ldb, 0, "%s;UID=%s;PWD=%s", db, uid, pwd); } else { ldb_len = strlen(db)+1; ldb = (char*) emalloc(ldb_len); diff --git a/ext/openssl/openssl.c b/ext/openssl/openssl.c index 3ccde2f27b4..c4335650436 100644 --- a/ext/openssl/openssl.c +++ b/ext/openssl/openssl.c @@ -316,7 +316,7 @@ static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ /* This is how the time string is formatted: - sprintf(p,"%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, + snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ diff --git a/ext/pcre/pcrelib/pcregrep.c b/ext/pcre/pcrelib/pcregrep.c index 0e57e56514c..4db73485d69 100644 --- a/ext/pcre/pcrelib/pcregrep.c +++ b/ext/pcre/pcrelib/pcregrep.c @@ -1188,8 +1188,7 @@ if ((sep = isdirectory(pathname)) != 0) while ((nextfile = readdirectory(dir)) != NULL) { int frc, blen; - sprintf(buffer, "%.512s%c%.128s", pathname, sep, nextfile); - blen = strlen(buffer); + blen = snprintf(buffer, sizeof(buffer), "%.512s%c%.128s", pathname, sep, nextfile); if (exclude_compiled != NULL && pcre_exec(exclude_compiled, NULL, buffer, blen, 0, 0, NULL, 0) >= 0) @@ -1281,7 +1280,7 @@ for (op = optionlist; op->one_char != 0; op++) { int n; char s[4]; - if (op->one_char > 0) sprintf(s, "-%c,", op->one_char); else strcpy(s, " "); + if (op->one_char > 0) snprintf(s, sizeof(s), "-%c,", op->one_char); else strcpy(s, " "); printf(" %s --%s%n", s, op->long_name, &n); n = 30 - n; if (n < 1) n = 1; @@ -1355,7 +1354,7 @@ ordin(int n) { static char buffer[8]; char *p = buffer; -sprintf(p, "%d", n); +snprintf(p, sizeof(buffer), "%d", n); while (*p != 0) p++; switch (n%10) { @@ -1401,7 +1400,7 @@ if (pattern_count >= MAX_PATTERN_COUNT) return FALSE; } -sprintf(buffer, "%s%.*s%s", prefix[process_options], MBUFTHIRD, pattern, +snprintf(buffer, sizeof(buffer), "%s%.*s%s", prefix[process_options], MBUFTHIRD, pattern, suffix[process_options]); pattern_list[pattern_count] = pcre_compile(buffer, options, &error, &errptr, pcretables); @@ -1463,7 +1462,7 @@ if ((process_options & PO_FIXED_STRINGS) != 0) char *p = end_of_line(pattern, eop, &ellength); if (ellength == 0) return compile_single_pattern(pattern, options, filename, count); - sprintf(buffer, "%.*s", p - pattern - ellength, pattern); + snprintf(buffer, sizeof(buffer), "%.*s", p - pattern - ellength, pattern); pattern = p; if (!compile_single_pattern(buffer, options, filename, count)) return FALSE; @@ -1579,8 +1578,8 @@ for (i = 1; i < argc; i++) char buff1[24]; char buff2[24]; int baselen = opbra - op->long_name; - sprintf(buff1, "%.*s", baselen, op->long_name); - sprintf(buff2, "%s%.*s", buff1, strlen(op->long_name) - baselen - 2, + snprintf(buff1, sizeof(buff1), "%.*s", baselen, op->long_name); + snprintf(buff2, sizeof(buff2), "%s%.*s", buff1, strlen(op->long_name) - baselen - 2, opbra + 1); if (strcmp(arg, buff1) == 0 || strcmp(arg, buff2) == 0) break; @@ -1935,7 +1934,7 @@ for (j = 0; j < pattern_count; j++) if (error != NULL) { char s[16]; - if (pattern_count == 1) s[0] = 0; else sprintf(s, " number %d", j); + if (pattern_count == 1) s[0] = 0; else snprintf(s, sizeof(s), " number %d", j); fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error); return 2; } diff --git a/ext/pcre/pcrelib/pcreposix.c b/ext/pcre/pcrelib/pcreposix.c index 31c7a31ab3e..3cee2aa33fa 100644 --- a/ext/pcre/pcrelib/pcreposix.c +++ b/ext/pcre/pcrelib/pcreposix.c @@ -158,7 +158,7 @@ addlength = (preg != NULL && (int)preg->re_erroffset != -1)? if (errbuf_size > 0) { if (addlength > 0 && errbuf_size >= length + addlength) - sprintf(errbuf, "%s%s%-6d", message, addmessage, (int)preg->re_erroffset); + snprintf(errbuf, errbuf_size, "%s%s%-6d", message, addmessage, (int)preg->re_erroffset); else { strncpy(errbuf, message, errbuf_size - 1); diff --git a/ext/pdo_firebird/firebird_statement.c b/ext/pdo_firebird/firebird_statement.c index f48acfdbb68..f7ab90f14aa 100644 --- a/ext/pdo_firebird/firebird_statement.c +++ b/ext/pdo_firebird/firebird_statement.c @@ -211,6 +211,8 @@ static void set_param_type(enum pdo_param_type *param_type, XSQLVAR const *var) #define FETCH_BUF(buf,type,len,lenvar) ((buf) = (buf) ? (buf) : \ emalloc((len) ? (len * sizeof(type)) : ((*(unsigned long*)lenvar) = sizeof(type)))) +#define CHAR_BUF_LEN 24 + /* fetch a blob into a fetch buffer */ static int firebird_fetch_blob(pdo_stmt_t *stmt, int colno, char **ptr, /* {{{ */ unsigned long *len, ISC_QUAD *blob_id TSRMLS_DC) @@ -322,16 +324,16 @@ static int firebird_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, /* {{ n = *(ISC_INT64*)var->sqldata; } - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); if (n >= 0) { - *len = sprintf(*ptr, "%" LL_MASK "d.%0*" LL_MASK "d", + *len = snprintf(*ptr, CHAR_BUF_LEN, "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -var->sqlscale, n % f); } else if (n < -f) { - *len = sprintf(*ptr, "%" LL_MASK "d.%0*" LL_MASK "d", + *len = snprintf(*ptr, CHAR_BUF_LEN, "%" LL_MASK "d.%0*" LL_MASK "d", n / f, -var->sqlscale, -n % f); } else { - *len = sprintf(*ptr, "-0.%0*" LL_MASK "d", -var->sqlscale, -n % f); + *len = snprintf(*ptr, CHAR_BUF_LEN, "-0.%0*" LL_MASK "d", -var->sqlscale, -n % f); } } else { switch (var->sqltype & ~1) { @@ -353,24 +355,24 @@ static int firebird_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, /* {{ break; /* --- cut here --- */ case SQL_SHORT: - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); - *len = sprintf(*ptr, "%d", *(short*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%d", *(short*)var->sqldata); break; case SQL_LONG: - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); - *len = sprintf(*ptr, "%ld", *(ISC_LONG*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%ld", *(ISC_LONG*)var->sqldata); break; case SQL_INT64: - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); - *len = sprintf(*ptr, "%" LL_MASK "d", *(ISC_INT64*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%" LL_MASK "d", *(ISC_INT64*)var->sqldata); break; case SQL_FLOAT: - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); - *len = sprintf(*ptr, "%F", *(float*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%F", *(float*)var->sqldata); break; case SQL_DOUBLE: - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 24, NULL); - *len = sprintf(*ptr, "%F" , *(double*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%F" , *(double*)var->sqldata); break; /* --- cut here --- */ #if abies_0 @@ -391,8 +393,8 @@ static int firebird_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, /* {{ #if SIZEOF_LONG == 8 *ptr = var->sqldata; #else - *ptr = FETCH_BUF(S->fetch_buf[colno], char, 20, NULL); - *len = sprintf(*ptr, "%" LL_MASK "d", *(ISC_INT64*)var->sqldata); + *ptr = FETCH_BUF(S->fetch_buf[colno], char, CHAR_BUF_LEN, NULL); + *len = snprintf(*ptr, CHAR_BUF_LEN, "%" LL_MASK "d", *(ISC_INT64*)var->sqldata); #endif break; case SQL_FLOAT: diff --git a/ext/pdo_odbc/odbc_driver.c b/ext/pdo_odbc/odbc_driver.c index 53e5281997b..dad21762d49 100755 --- a/ext/pdo_odbc/odbc_driver.c +++ b/ext/pdo_odbc/odbc_driver.c @@ -427,8 +427,8 @@ static int pdo_odbc_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_D /* Force UID and PWD to be set in the DSN */ if (dbh->username && *dbh->username && !strstr(dbh->data_source, "uid") && !strstr(dbh->data_source, "UID")) { - char *dsn = pemalloc(strlen(dbh->data_source) + strlen(dbh->username) + strlen(dbh->password) + sizeof(";UID=;PWD="), dbh->is_persistent); - sprintf(dsn, "%s;UID=%s;PWD=%s", dbh->data_source, dbh->username, dbh->password); + char *dsn; + spprintf(&dsn, 0, "%s;UID=%s;PWD=%s", dbh->data_source, dbh->username, dbh->password); pefree((char*)dbh->data_source, dbh->is_persistent); dbh->data_source = dsn; } diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c index e5c1332321d..73e25af3653 100644 --- a/ext/pgsql/pgsql.c +++ b/ext/pgsql/pgsql.c @@ -599,9 +599,9 @@ PHP_MINFO_FUNCTION(pgsql) php_info_print_table_row(2, "SSL support", "disabled"); #endif #endif /* HAVE_PG_CONFIG_H */ - sprintf(buf, "%ld", PGG(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", PGG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); - sprintf(buf, "%ld", PGG(num_links)); + snprintf(buf, sizeof(buf), "%ld", PGG(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_end(); diff --git a/ext/pspell/pspell.c b/ext/pspell/pspell.c index c9e5b806a2a..fc8f2937cce 100644 --- a/ext/pspell/pspell.c +++ b/ext/pspell/pspell.c @@ -783,7 +783,7 @@ static PHP_FUNCTION(pspell_config_ignore) convert_to_long_ex(pignore); ignore = Z_LVAL_PP(pignore); - sprintf(ignore_str, "%ld", ignore); + snprintf(ignore_str, sizeof(ignore_str), "%ld", ignore); pspell_config_replace(config, "ignore", ignore_str); RETURN_TRUE; diff --git a/ext/session/mod_mm.c b/ext/session/mod_mm.c index 24e263a150e..7a5150a02e8 100644 --- a/ext/session/mod_mm.c +++ b/ext/session/mod_mm.c @@ -262,7 +262,7 @@ PHP_MINIT_FUNCTION(ps_mm) return FAILURE; } - if (!(euid_len = sprintf(euid,"%d", geteuid()))) { + if (!(euid_len = snprintf(euid, sizeof(euid), "%d", geteuid()))) { return FAILURE; } diff --git a/ext/session/session.c b/ext/session/session.c index a87e312ad97..50dd3a52976 100644 --- a/ext/session/session.c +++ b/ext/session/session.c @@ -731,10 +731,8 @@ PHPAPI char *php_session_create_id(PS_CREATE_SID_ARGS) remote_addr = Z_STRVAL_PP(token); } - buf = emalloc(100); - /* maximum 15+19+19+10 bytes */ - sprintf(buf, "%.15s%ld%ld%0.8F", remote_addr ? remote_addr : "", + spprintf(&buf, 0, "%.15s%ld%ld%0.8F", remote_addr ? remote_addr : "", tv.tv_sec, (long int)tv.tv_usec, php_combined_lcg(TSRMLS_C) * 10); switch (PS(hash_func)) { @@ -952,7 +950,7 @@ static void strcpy_gmt(char *ubuf, time_t *when) php_gmtime_r(when, &tm); - n = sprintf(buf, "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */ + n = snprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */ week_days[tm.tm_wday], tm.tm_mday, month_names[tm.tm_mon], tm.tm_year + 1900, tm.tm_hour, tm.tm_min, @@ -997,7 +995,7 @@ CACHE_LIMITER_FUNC(public) strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now); ADD_HEADER(buf); - sprintf(buf, "Cache-Control: public, max-age=%ld", PS(cache_expire) * 60); /* SAFE */ + snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=%ld", PS(cache_expire) * 60); /* SAFE */ ADD_HEADER(buf); last_modified(TSRMLS_C); @@ -1007,7 +1005,7 @@ CACHE_LIMITER_FUNC(private_no_expire) { char buf[MAX_STR + 1]; - sprintf(buf, "Cache-Control: private, max-age=%ld, pre-check=%ld", PS(cache_expire) * 60, PS(cache_expire) * 60); /* SAFE */ + snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=%ld, pre-check=%ld", PS(cache_expire) * 60, PS(cache_expire) * 60); /* SAFE */ ADD_HEADER(buf); last_modified(TSRMLS_C); diff --git a/ext/skeleton/skeleton.c b/ext/skeleton/skeleton.c index ae07e5373f6..08868874e84 100644 --- a/ext/skeleton/skeleton.c +++ b/ext/skeleton/skeleton.c @@ -138,14 +138,14 @@ PHP_FUNCTION(confirm_extname_compiled) { char *arg = NULL; int arg_len, len; - char string[256]; + char *strg; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) { return; } - len = sprintf(string, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "extname", arg); - RETURN_STRINGL(string, len, 1); + len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "extname", arg); + RETURN_STRINGL(strg, len, 0); } /* }}} */ /* The previous line is meant for vim and emacs, so it can correctly fold and diff --git a/ext/soap/php_encoding.c b/ext/soap/php_encoding.c index 154a570a353..f86b9d6045e 100644 --- a/ext/soap/php_encoding.c +++ b/ext/soap/php_encoding.c @@ -937,7 +937,7 @@ static xmlNodePtr to_xml_long(encodeTypePtr type, zval *data, int style, xmlNode if (Z_TYPE_P(data) == IS_DOUBLE) { char s[256]; - sprintf(s, "%0.0F",floor(Z_DVAL_P(data))); + snprintf(s, sizeof(s), "%0.0F",floor(Z_DVAL_P(data))); xmlNodeSetContent(ret, BAD_CAST(s)); } else { zval tmp = *data; @@ -2678,12 +2678,12 @@ static xmlNodePtr to_xml_datetime_ex(encodeTypePtr type, zval *data, char *forma /* Time zone support */ #ifdef HAVE_TM_GMTOFF - sprintf(tzbuf, "%c%02d:%02d", (ta->tm_gmtoff < 0) ? '-' : '+', abs(ta->tm_gmtoff / 3600), abs( (ta->tm_gmtoff % 3600) / 60 )); + snprintf(tzbuf, sizeof(tzbuf), "%c%02d:%02d", (ta->tm_gmtoff < 0) ? '-' : '+', abs(ta->tm_gmtoff / 3600), abs( (ta->tm_gmtoff % 3600) / 60 )); #else # ifdef __CYGWIN__ - sprintf(tzbuf, "%c%02d:%02d", ((ta->tm_isdst ? _timezone - 3600:_timezone)>0)?'-':'+', abs((ta->tm_isdst ? _timezone - 3600 : _timezone) / 3600), abs(((ta->tm_isdst ? _timezone - 3600 : _timezone) % 3600) / 60)); + snprintf(tzbuf, sizeof(tzbuf), "%c%02d:%02d", ((ta->tm_isdst ? _timezone - 3600:_timezone)>0)?'-':'+', abs((ta->tm_isdst ? _timezone - 3600 : _timezone) / 3600), abs(((ta->tm_isdst ? _timezone - 3600 : _timezone) % 3600) / 60)); # else - sprintf(tzbuf, "%c%02d:%02d", ((ta->tm_isdst ? timezone - 3600:timezone)>0)?'-':'+', abs((ta->tm_isdst ? timezone - 3600 : timezone) / 3600), abs(((ta->tm_isdst ? timezone - 3600 : timezone) % 3600) / 60)); + snprintf(tzbuf, sizeof(tzbuf), "%c%02d:%02d", ((ta->tm_isdst ? timezone - 3600:timezone)>0)?'-':'+', abs((ta->tm_isdst ? timezone - 3600 : timezone) / 3600), abs(((ta->tm_isdst ? timezone - 3600 : timezone) % 3600) / 60)); # endif #endif if (strcmp(tzbuf,"+00:00") == 0) { diff --git a/ext/soap/php_http.c b/ext/soap/php_http.c index a54c1c70b50..0d27bb591b6 100644 --- a/ext/soap/php_http.c +++ b/ext/soap/php_http.c @@ -472,7 +472,7 @@ try_again: unsigned int ctx; PHP_MD5Init(&md5ctx); - sprintf(cnonce, "%d", php_rand_r(&ctx)); + snprintf(cnonce, sizeof(cnonce), "%d", php_rand_r(&ctx)); PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce)); PHP_MD5Final(hash, &md5ctx); make_digest(cnonce, hash); diff --git a/ext/soap/soap.c b/ext/soap/soap.c index 7c990fd33b0..8714a8321a8 100644 --- a/ext/soap/soap.c +++ b/ext/soap/soap.c @@ -444,8 +444,7 @@ static void php_soap_prepare_globals() if (defaultEncoding[i].details.type_str) { if (defaultEncoding[i].details.ns != NULL) { char *ns_type; - ns_type = emalloc(strlen(defaultEncoding[i].details.ns) + strlen(defaultEncoding[i].details.type_str) + 2); - sprintf(ns_type, "%s:%s", defaultEncoding[i].details.ns, defaultEncoding[i].details.type_str); + spprintf(&ns_type, 0, "%s:%s", defaultEncoding[i].details.ns, defaultEncoding[i].details.type_str); zend_hash_add(&defEnc, ns_type, strlen(ns_type) + 1, &enc, sizeof(encodePtr), NULL); efree(ns_type); } else { diff --git a/ext/standard/dns.c b/ext/standard/dns.c index eca8eeb6414..fd408061678 100644 --- a/ext/standard/dns.c +++ b/ext/standard/dns.c @@ -422,7 +422,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int switch (type) { case DNS_T_A: add_assoc_string(*subarray, "type", "A", 1); - sprintf(name, "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); + snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]); add_assoc_string(*subarray, "ip", name, 1); cp += dlen; break; diff --git a/ext/standard/head.c b/ext/standard/head.c index af945ff8e02..7240d777d3c 100644 --- a/ext/standard/head.c +++ b/ext/standard/head.c @@ -94,8 +94,6 @@ PHPAPI int php_setcookie(char *name, int name_len, char *value, int value_len, t if (domain) { len += domain_len; } - cookie = emalloc(len + 100); - if (value && value_len == 0) { /* * MSIE doesn't delete a cookie when you set it to a null value @@ -104,10 +102,10 @@ PHPAPI int php_setcookie(char *name, int name_len, char *value, int value_len, t */ time_t t = time(NULL) - 31536001; dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC); - sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt); + spprintf(&cookie, 0, "Set-Cookie: %s=deleted; expires=%s", name, dt); efree(dt); } else { - sprintf(cookie, "Set-Cookie: %s=%s", name, value ? encoded_value : ""); + spprintf(&cookie, 0, "Set-Cookie: %s=%s", name, value ? encoded_value : ""); if (expires > 0) { strlcat(cookie, "; expires=", len + 100); dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, expires, 0 TSRMLS_CC); diff --git a/ext/standard/image.c b/ext/standard/image.c index 5e7d5e7c756..804f185cdf1 100644 --- a/ext/standard/image.c +++ b/ext/standard/image.c @@ -454,7 +454,7 @@ static int php_read_APP(php_stream * stream, unsigned int marker, zval *info TSR return 0; } - sprintf(markername, "APP%d", marker - M_APP0); + snprintf(markername, sizeof(markername), "APP%d", marker - M_APP0); if (zend_hash_find(Z_ARRVAL_P(info), markername, strlen(markername)+1, (void **) &tmp) == FAILURE) { /* XXX we onyl catch the 1st tag of it's kind! */ diff --git a/ext/standard/pack.c b/ext/standard/pack.c index 9946469473a..569266ea1ad 100644 --- a/ext/standard/pack.c +++ b/ext/standard/pack.c @@ -644,10 +644,10 @@ PHP_FUNCTION(unpack) if (arg != 1 || namelen == 0) { /* Need to add element number to name */ - sprintf(n, "%.*s%d", namelen, name, i + 1); + snprintf(n, sizeof(n), "%.*s%d", namelen, name, i + 1); } else { /* Truncate name to next format code or end of string */ - sprintf(n, "%.*s", namelen, name); + snprintf(n, sizeof(n), "%.*s", namelen, name); } if (size != 0 && size != -1 && INT_MAX - size + 1 < inputpos) { diff --git a/ext/standard/proc_open.c b/ext/standard/proc_open.c index 7f92554ed1e..15cea0d8363 100644 --- a/ext/standard/proc_open.c +++ b/ext/standard/proc_open.c @@ -747,8 +747,7 @@ PHP_FUNCTION(proc_open) if (bypass_shell) { newprocok = CreateProcess(NULL, command, &security, &security, TRUE, NORMAL_PRIORITY_CLASS, env.envp, cwd, &si, &pi); } else { - command_with_cmd = emalloc(command_len + sizeof(COMSPEC_9X) + 1 + sizeof(" /c ")); - sprintf(command_with_cmd, "%s /c %s", GetVersion() < 0x80000000 ? COMSPEC_NT : COMSPEC_9X, command); + spprintf(&command_with_cmd, 0, "%s /c %s", GetVersion() < 0x80000000 ? COMSPEC_NT : COMSPEC_9X, command); newprocok = CreateProcess(NULL, command_with_cmd, &security, &security, TRUE, NORMAL_PRIORITY_CLASS, env.envp, cwd, &si, &pi); diff --git a/ext/standard/scanf.c b/ext/standard/scanf.c index e82d9140fc6..baddeb24b22 100644 --- a/ext/standard/scanf.c +++ b/ext/standard/scanf.c @@ -1094,7 +1094,7 @@ PHPAPI int php_sscanf_internal( char *string, char *format, *end = '\0'; value = (int) (*fn)(buf, NULL, base); if ((flags & SCAN_UNSIGNED) && (value < 0)) { - sprintf(buf, "%u", value); /* INTL: ISO digit */ + snprintf(buf, sizeof(buf), "%u", value); /* INTL: ISO digit */ if (numVars && objIndex >= argCount) { break; } else if (numVars) { diff --git a/ext/standard/string.c b/ext/standard/string.c index 355792778b5..a82aa0c34f5 100644 --- a/ext/standard/string.c +++ b/ext/standard/string.c @@ -905,7 +905,7 @@ PHPAPI void php_implode(zval *delim, zval *arr, zval *return_value TSRMLS_DC) case IS_LONG: { char stmp[MAX_LENGTH_OF_LONG + 1]; - str_len = sprintf(stmp, "%ld", Z_LVAL_PP(tmp)); + str_len = snprintf(stmp, sizeof(stmp), "%ld", Z_LVAL_PP(tmp)); smart_str_appendl(&implstr, stmp, str_len); } break; @@ -2915,7 +2915,7 @@ char *php_strerror(int errnum) return(sys_errlist[errnum]); } - (void) sprintf(BG(str_ebuf), "Unknown error: %d", errnum); + (void) snprintf(BG(str_ebuf), sizeof(php_basic_globals.str_ebuf), "Unknown error: %d", errnum); return(BG(str_ebuf)); } /* }}} */ diff --git a/ext/standard/type.c b/ext/standard/type.c index a8ea3909d1f..268040903a6 100644 --- a/ext/standard/type.c +++ b/ext/standard/type.c @@ -64,8 +64,7 @@ PHP_FUNCTION(gettype) int res_len; res_len = sizeof("object of type ")-1 + Z_OBJCE_P(arg)->name_length; - result = (char *) emalloc(res_len+1); - sprintf(result, "object of type %s", Z_OBJCE_P(arg)->name); + spprintf(&result, 0, "object of type %s", Z_OBJCE_P(arg)->name); RETVAL_STRINGL(result, res_len, 0); } */ diff --git a/ext/sybase_ct/php_sybase_ct.c b/ext/sybase_ct/php_sybase_ct.c index 8cd752dded9..10358c96c40 100644 --- a/ext/sybase_ct/php_sybase_ct.c +++ b/ext/sybase_ct/php_sybase_ct.c @@ -996,8 +996,7 @@ PHP_FUNCTION(sybase_select_db) ZEND_FETCH_RESOURCE2(sybase_ptr, sybase_link *, sybase_link_index, id, "Sybase-Link", le_link, le_plink); convert_to_string_ex(db); - cmdbuf = (char *) emalloc(sizeof("use ")+Z_STRLEN_PP(db)+1); - sprintf(cmdbuf, "use %s", Z_STRVAL_PP(db)); /* SAFE */ + spprintf(&cmdbuf, 0, "use %s", Z_STRVAL_PP(db)); /* SAFE */ if (exec_cmd(sybase_ptr, cmdbuf)==FAILURE) { efree(cmdbuf); @@ -2115,16 +2114,16 @@ PHP_MINFO_FUNCTION(sybase) php_info_print_table_start(); php_info_print_table_header(2, "Sybase_CT Support", "enabled" ); - sprintf(buf, "%ld", SybCtG(num_persistent)); + snprintf(buf, sizeof(buf), "%ld", SybCtG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); - sprintf(buf, "%ld", SybCtG(num_links)); + snprintf(buf, sizeof(buf), "%ld", SybCtG(num_links)); php_info_print_table_row(2, "Active Links", buf); - sprintf(buf, "%ld", SybCtG(min_server_severity)); + snprintf(buf, sizeof(buf), "%ld", SybCtG(min_server_severity)); php_info_print_table_row(2, "Min server severity", buf); - sprintf(buf, "%ld", SybCtG(min_client_severity)); + snprintf(buf, sizeof(buf), "%ld", SybCtG(min_client_severity)); php_info_print_table_row(2, "Min client severity", buf); php_info_print_table_row(2, "Application Name", SybCtG(appname)); - sprintf(buf, "%ld", SybCtG(deadlock_retry_count)); + snprintf(buf, sizeof(buf), "%ld", SybCtG(deadlock_retry_count)); php_info_print_table_row(2, "Deadlock retry count", buf); php_info_print_table_end(); diff --git a/ext/wddx/wddx.c b/ext/wddx/wddx.c index b4900eb662b..4c883ded2cc 100644 --- a/ext/wddx/wddx.c +++ b/ext/wddx/wddx.c @@ -284,7 +284,7 @@ PS_SERIALIZER_DECODE_FUNC(wddx) switch (hash_type) { case HASH_KEY_IS_LONG: - key_length = sprintf(tmp, "%ld", idx) + 1; + key_length = snprintf(tmp, sizeof(tmp), "%ld", idx) + 1; key = tmp; /* fallthru */ case HASH_KEY_IS_STRING: @@ -409,7 +409,7 @@ static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var) { char tmp_buf[WDDX_BUF_LEN]; - sprintf(tmp_buf, WDDX_BOOLEAN, Z_LVAL_P(var) ? "true" : "false"); + snprintf(tmp_buf, sizeof(tmp_buf), WDDX_BOOLEAN, Z_LVAL_P(var) ? "true" : "false"); php_wddx_add_chunk(packet, tmp_buf); } /* }}} */ @@ -501,7 +501,7 @@ static void php_wddx_serialize_object(wddx_packet *packet, zval *obj) zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name); php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC); } else { - key_len = sprintf(tmp_buf, "%ld", idx); + key_len = snprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } @@ -556,7 +556,7 @@ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) if (is_struct) { php_wddx_add_chunk_static(packet, WDDX_STRUCT_S); } else { - sprintf(tmp_buf, WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); + snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash)); php_wddx_add_chunk(packet, tmp_buf); } @@ -572,7 +572,7 @@ static void php_wddx_serialize_array(wddx_packet *packet, zval *arr) if (ent_type == HASH_KEY_IS_STRING) { php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC); } else { - key_len = sprintf(tmp_buf, "%ld", idx); + key_len = snprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx); php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC); } } else @@ -724,7 +724,7 @@ static void php_wddx_push_element(void *user_data, const XML_Char *name, const X if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) { char tmp_buf[2]; - sprintf(tmp_buf, "%c", (char)strtol(atts[i], NULL, 16)); + snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } diff --git a/ext/zip/lib/zip_close.c b/ext/zip/lib/zip_close.c index f077b8df052..a5a1bc094de 100644 --- a/ext/zip/lib/zip_close.c +++ b/ext/zip/lib/zip_close.c @@ -533,7 +533,7 @@ _zip_create_temp_output(struct zip *za, FILE **outp) return NULL; } - sprintf(temp, "%s.XXXXXX", za->zn); + snprintf(temp, sizeof(temp), "%s.XXXXXX", za->zn); if ((tfd=mkstemp(temp)) == -1) { _zip_error_set(&za->error, ZIP_ER_TMPOPEN, errno); diff --git a/ext/zip/lib/zip_error_strerror.c b/ext/zip/lib/zip_error_strerror.c index f14f7190e66..e6eee081dfb 100644 --- a/ext/zip/lib/zip_error_strerror.c +++ b/ext/zip/lib/zip_error_strerror.c @@ -54,7 +54,7 @@ _zip_error_strerror(struct zip_error *err) _zip_error_fini(err); if (err->zip_err < 0 || err->zip_err >= _zip_nerr_str) { - sprintf(buf, "Unknown error %d", err->zip_err); + snprintf(buf, sizeof(buf), "Unknown error %d", err->zip_err); zs = NULL; ss = buf; } @@ -78,11 +78,11 @@ _zip_error_strerror(struct zip_error *err) if (ss == NULL) return zs; else { - if ((s=(char *)malloc(strlen(ss) - + (zs ? strlen(zs)+2 : 0) + 1)) == NULL) + int l = strlen(ss) + (zs ? strlen(zs)+2 : 0) + 1; + if ((s=(char *)malloc(l)) == NULL) return _zip_err_str[ZIP_ER_MEMORY]; - sprintf(s, "%s%s%s", + snprintf(s, l, "%s%s%s", (zs ? zs : ""), (zs ? ": " : ""), ss); diff --git a/main/SAPI.c b/main/SAPI.c index d9c13d7284e..db43b32ab80 100644 --- a/main/SAPI.c +++ b/main/SAPI.c @@ -663,8 +663,7 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) ptr_len = strlen(ptr); MAKE_STD_ZVAL(repl_temp); Z_TYPE_P(repl_temp) = IS_STRING; - Z_STRVAL_P(repl_temp) = emalloc(32); - Z_STRLEN_P(repl_temp) = sprintf(Z_STRVAL_P(repl_temp), "realm=\"\\1-%ld\"", myuid); + Z_STRLEN_P(repl_temp) = spprintf(&Z_STRVAL_P(repl_temp), 0, "realm=\"\\1-%ld\"", myuid); /* Modify quoted realm value */ result = php_pcre_replace("/realm=\"(.*?)\"/i", 16, ptr, ptr_len, @@ -672,7 +671,8 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) 0, &result_len, -1, NULL TSRMLS_CC); if(result_len==ptr_len) { efree(result); - sprintf(Z_STRVAL_P(repl_temp), "realm=\\1-%ld\\2", myuid); + efree(Z_STRVAL_P(repl_temp)); + Z_STRLEN_P(repl_temp) = spprintf(&Z_STRVAL_P(repl_temp), 0, "realm=\\1-%ld\\2", myuid); /* modify unquoted realm value */ result = php_pcre_replace("/realm=([^\\s]+)(.*)/i", 21, ptr, ptr_len, @@ -687,7 +687,7 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) /* If there is no realm string at all, append one */ if(!strstr(lower_temp,"realm")) { efree(result); - conv_len = sprintf(conv_temp, " realm=\"%ld\"",myuid); + conv_len = snprintf(conv_temp, sizeof(conv_temp), " realm=\"%ld\"",myuid); result = emalloc(ptr_len+conv_len+1); result_len = ptr_len+conv_len; memcpy(result, ptr, ptr_len); @@ -697,9 +697,7 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) efree(lower_temp); } } - newlen = sizeof("WWW-Authenticate: ") - 1 + result_len; - newheader = emalloc(newlen+1); - sprintf(newheader,"WWW-Authenticate: %s", result); + newlen = spprintf(&newheader, 0, "WWW-Authenticate: %s", result); efree(header_line); sapi_header.header = newheader; sapi_header.header_len = newlen; @@ -820,7 +818,7 @@ SAPI_API int sapi_send_headers(TSRMLS_D) http_status_line.header_len = strlen(SG(sapi_headers).http_status_line); } else { http_status_line.header = buf; - http_status_line.header_len = sprintf(buf, "HTTP/1.0 %d X", SG(sapi_headers).http_response_code); + http_status_line.header_len = snprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code); } sapi_module.send_header(&http_status_line, SG(server_context) TSRMLS_CC); } diff --git a/main/fopen_wrappers.c b/main/fopen_wrappers.c index 6886a563926..ebcdb711fa7 100644 --- a/main/fopen_wrappers.c +++ b/main/fopen_wrappers.c @@ -297,13 +297,10 @@ PHPAPI int php_fopen_primary_script(zend_file_handle *file_handle TSRMLS_DC) pw = getpwnam(user); #endif if (pw && pw->pw_dir) { - filename = emalloc(strlen(PG(user_dir)) + strlen(path_info) + strlen(pw->pw_dir) + 4); - if (filename) { - sprintf(filename, "%s%c%s%c%s", pw->pw_dir, PHP_DIR_SEPARATOR, + spprintf(&filename, 0, "%s%c%s%c%s", pw->pw_dir, PHP_DIR_SEPARATOR, PG(user_dir), PHP_DIR_SEPARATOR, s+1); /* Safe */ - STR_FREE(SG(request_info).path_translated); - SG(request_info).path_translated = filename; - } + STR_FREE(SG(request_info).path_translated); + SG(request_info).path_translated = filename; } #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX) efree(pwbuf); diff --git a/main/php_ini.c b/main/php_ini.c index 56b184928ac..781014b0b77 100644 --- a/main/php_ini.c +++ b/main/php_ini.c @@ -441,8 +441,8 @@ int php_init_config(TSRMLS_D) /* Search php-%sapi-module-name%.ini file in search path */ if (!fh.handle.fp) { const char *fmt = "php-%s.ini"; - char *ini_fname = emalloc(strlen(fmt) + strlen(sapi_module.name)); - sprintf(ini_fname, fmt, sapi_module.name); + char *ini_fname; + spprintf(&ini_fname, 0, fmt, sapi_module.name); fh.handle.fp = php_fopen_with_path(ini_fname, "r", php_ini_search_path, &php_ini_opened_path TSRMLS_CC); efree(ini_fname); if (fh.handle.fp) { diff --git a/main/rfc1867.c b/main/rfc1867.c index 2a8089e4e26..a069f924f46 100644 --- a/main/rfc1867.c +++ b/main/rfc1867.c @@ -365,12 +365,9 @@ static multipart_buffer *multipart_buffer_new(char *boundary, int boundary_len) self->buffer = (char *) ecalloc(1, minsize + 1); self->bufsize = minsize; - self->boundary = (char *) ecalloc(1, boundary_len + 3); - sprintf(self->boundary, "--%s", boundary); + spprintf(&self->boundary, 0, "--%s", boundary); - self->boundary_next = (char *) ecalloc(1, boundary_len + 4); - sprintf(self->boundary_next, "\n--%s", boundary); - self->boundary_next_len = boundary_len + 3; + self->boundary_next_len = spprintf(&self->boundary_next, 0, "\n--%s", boundary); self->buf_begin = self->buffer; self->bytes_in_buffer = 0; @@ -797,6 +794,7 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) int fd=-1; zend_llist header; void *event_extra_data = NULL; + int llen = 0; if (SG(request_info).content_length > SG(post_max_size)) { sapi_module.sapi_error(E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); @@ -1159,17 +1157,18 @@ SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) } /* Add $foo_name */ - if (lbuf) { - efree(lbuf); + if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) { + llen = strlen(param); + lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1); + llen += MAX_SIZE_OF_INDEX + 1; } - lbuf = (char *) emalloc(strlen(param) + MAX_SIZE_OF_INDEX + 1); if (is_arr_upload) { if (abuf) efree(abuf); abuf = estrndup(param, strlen(param)-array_len); - sprintf(lbuf, "%s_name[%s]", abuf, array_index); + snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index); } else { - sprintf(lbuf, "%s_name", param); + snprintf(lbuf, llen, "%s_name", param); } #if HAVE_MBSTRING && !defined(COMPILE_DL_MBSTRING) @@ -1227,9 +1226,9 @@ filedone: /* Add $foo[name] */ if (is_arr_upload) { - sprintf(lbuf, "%s[name][%s]", abuf, array_index); + snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index); } else { - sprintf(lbuf, "%s[name]", param); + snprintf(lbuf, llen, "%s[name]", param); } if (s && s > filename) { register_http_post_files_variable(lbuf, s+1, http_post_files, 0 TSRMLS_CC); @@ -1252,9 +1251,9 @@ filedone: /* Add $foo_type */ if (is_arr_upload) { - sprintf(lbuf, "%s_type[%s]", abuf, array_index); + snprintf(lbuf, llen, "%s_type[%s]", abuf, array_index); } else { - sprintf(lbuf, "%s_type", param); + snprintf(lbuf, llen, "%s_type", param); } if (!is_anonymous) { safe_php_register_variable(lbuf, cd, strlen(cd), NULL, 0 TSRMLS_CC); @@ -1262,9 +1261,9 @@ filedone: /* Add $foo[type] */ if (is_arr_upload) { - sprintf(lbuf, "%s[type][%s]", abuf, array_index); + snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index); } else { - sprintf(lbuf, "%s[type]", param); + snprintf(lbuf, llen, "%s[type]", param); } register_http_post_files_variable(lbuf, cd, http_post_files, 0 TSRMLS_CC); @@ -1286,9 +1285,9 @@ filedone: /* Add $foo[tmp_name] */ if (is_arr_upload) { - sprintf(lbuf, "%s[tmp_name][%s]", abuf, array_index); + snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index); } else { - sprintf(lbuf, "%s[tmp_name]", param); + snprintf(lbuf, llen, "%s[tmp_name]", param); } add_protected_variable(lbuf TSRMLS_CC); register_http_post_files_variable(lbuf, temp_filename, http_post_files, 1 TSRMLS_CC); @@ -1311,17 +1310,17 @@ filedone: } if (is_arr_upload) { - sprintf(lbuf, "%s[error][%s]", abuf, array_index); + snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index); } else { - sprintf(lbuf, "%s[error]", param); + snprintf(lbuf, llen, "%s[error]", param); } register_http_post_files_variable_ex(lbuf, &error_type, http_post_files, 0 TSRMLS_CC); /* Add $foo_size */ if (is_arr_upload) { - sprintf(lbuf, "%s_size[%s]", abuf, array_index); + snprintf(lbuf, llen, "%s_size[%s]", abuf, array_index); } else { - sprintf(lbuf, "%s_size", param); + snprintf(lbuf, llen, "%s_size", param); } if (!is_anonymous) { safe_php_register_variable_ex(lbuf, &file_size, NULL, 0 TSRMLS_CC); @@ -1329,9 +1328,9 @@ filedone: /* Add $foo[size] */ if (is_arr_upload) { - sprintf(lbuf, "%s[size][%s]", abuf, array_index); + snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index); } else { - sprintf(lbuf, "%s[size]", param); + snprintf(lbuf, llen, "%s[size]", param); } register_http_post_files_variable_ex(lbuf, &file_size, http_post_files, 0 TSRMLS_CC); } @@ -1339,6 +1338,9 @@ filedone: } } fileupload_done: + if (lbuf) { + efree(lbuf); + } if (php_rfc1867_callback != NULL) { multipart_event_end event_end; diff --git a/sapi/apache/php_apache.c b/sapi/apache/php_apache.c index 98a85a5a077..99d338f151e 100644 --- a/sapi/apache/php_apache.c +++ b/sapi/apache/php_apache.c @@ -207,20 +207,20 @@ PHP_MINFO_FUNCTION(apache) } #ifdef APACHE_RELEASE - sprintf(output_buf, "%d", APACHE_RELEASE); + snprintf(output_buf, sizeof(output_buf), "%d", APACHE_RELEASE); php_info_print_table_row(2, "Apache Release", output_buf); #endif - sprintf(output_buf, "%d", MODULE_MAGIC_NUMBER); + snprintf(output_buf, sizeof(output_buf), "%d", MODULE_MAGIC_NUMBER); php_info_print_table_row(2, "Apache API Version", output_buf); snprintf(output_buf, sizeof(output_buf), "%s:%u", serv->server_hostname, serv->port); php_info_print_table_row(2, "Hostname:Port", output_buf); #if !defined(WIN32) && !defined(WINNT) snprintf(output_buf, sizeof(output_buf), "%s(%d)/%d", user_name, (int)user_id, (int)group_id); php_info_print_table_row(2, "User/Group", output_buf); - sprintf(output_buf, "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests_per_child, serv->keep_alive ? "on":"off", serv->keep_alive_max); + snprintf(output_buf, sizeof(output_buf), "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests_per_child, serv->keep_alive ? "on":"off", serv->keep_alive_max); php_info_print_table_row(2, "Max Requests", output_buf); #endif - sprintf(output_buf, "Connection: %d - Keep-Alive: %d", serv->timeout, serv->keep_alive_timeout); + snprintf(output_buf, sizeof(output_buf), "Connection: %d - Keep-Alive: %d", serv->timeout, serv->keep_alive_timeout); php_info_print_table_row(2, "Timeouts", output_buf); #if !defined(WIN32) && !defined(WINNT) /* diff --git a/sapi/apache2handler/php_functions.c b/sapi/apache2handler/php_functions.c index 4b924aaf84a..fd6e34ef111 100644 --- a/sapi/apache2handler/php_functions.c +++ b/sapi/apache2handler/php_functions.c @@ -403,7 +403,7 @@ PHP_MINFO_FUNCTION(apache) if (apv && *apv) { php_info_print_table_row(2, "Apache Version", apv); } - sprintf(tmp, "%d", MODULE_MAGIC_NUMBER); + snprintf(tmp, sizeof(tmp), "%d", MODULE_MAGIC_NUMBER); php_info_print_table_row(2, "Apache API Version", tmp); if (serv->server_admin && *(serv->server_admin)) { @@ -419,7 +419,7 @@ PHP_MINFO_FUNCTION(apache) #endif ap_mpm_query(AP_MPMQ_MAX_REQUESTS_DAEMON, &max_requests); - sprintf(tmp, "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests, (serv->keep_alive ? "on":"off"), serv->keep_alive_max); + snprintf(tmp, sizeof(tmp), "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests, (serv->keep_alive ? "on":"off"), serv->keep_alive_max); php_info_print_table_row(2, "Max Requests", tmp); apr_snprintf(tmp, sizeof tmp, diff --git a/sapi/apache_hooks/php_apache.c b/sapi/apache_hooks/php_apache.c index ce916d6a01c..fb56d3dfb8c 100644 --- a/sapi/apache_hooks/php_apache.c +++ b/sapi/apache_hooks/php_apache.c @@ -1609,20 +1609,20 @@ PHP_MINFO_FUNCTION(apache) php_info_print_table_row(2, "Apache Version", SERVER_VERSION); #ifdef APACHE_RELEASE - sprintf(output_buf, "%d", APACHE_RELEASE); + snprintf(output_buf, sizeof(output_buf), "%d", APACHE_RELEASE); php_info_print_table_row(2, "Apache Release", output_buf); #endif - sprintf(output_buf, "%d", MODULE_MAGIC_NUMBER); + snprintf(output_buf, sizeof(output_buf), "%d", MODULE_MAGIC_NUMBER); php_info_print_table_row(2, "Apache API Version", output_buf); snprintf(output_buf, sizeof(output_buf), "%s:%u", serv->server_hostname, serv->port); php_info_print_table_row(2, "Hostname:Port", output_buf); #if !defined(WIN32) && !defined(WINNT) snprintf(output_buf, sizeof(output_buf), "%s(%d)/%d", user_name, (int)user_id, (int)group_id); php_info_print_table_row(2, "User/Group", output_buf); - sprintf(output_buf, "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests_per_child, serv->keep_alive ? "on":"off", serv->keep_alive_max); + snprintf(output_buf, sizeof(output_buf), "Per Child: %d - Keep Alive: %s - Max Per Connection: %d", max_requests_per_child, serv->keep_alive ? "on":"off", serv->keep_alive_max); php_info_print_table_row(2, "Max Requests", output_buf); #endif - sprintf(output_buf, "Connection: %d - Keep-Alive: %d", serv->timeout, serv->keep_alive_timeout); + snprintf(output_buf, sizeof(output_buf), "Connection: %d - Keep-Alive: %d", serv->timeout, serv->keep_alive_timeout); php_info_print_table_row(2, "Timeouts", output_buf); #if !defined(WIN32) && !defined(WINNT) /* diff --git a/sapi/cgi/cgi_main.c b/sapi/cgi/cgi_main.c index c1982fa863c..fba7686f730 100644 --- a/sapi/cgi/cgi_main.c +++ b/sapi/cgi/cgi_main.c @@ -333,7 +333,7 @@ static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) } } else { - len = sprintf(buf, "Status: %d\r\n", SG(sapi_headers).http_response_code); + len = snprintf(buf, sizeof(buf), "Status: %d\r\n", SG(sapi_headers).http_response_code); } PHPWRITE_H(buf, len); diff --git a/sapi/cli/php_cli_readline.c b/sapi/cli/php_cli_readline.c index 23c5ae0c1d8..8d442a7d41c 100644 --- a/sapi/cli/php_cli_readline.c +++ b/sapi/cli/php_cli_readline.c @@ -418,9 +418,10 @@ TODO: efree(class_name); } if (pce && retval) { - char *tmp = malloc(class_name_len + 2 + strlen(retval) + 1); + int len = class_name_len + 2 + strlen(retval) + 1; + char *tmp = malloc(len); - sprintf(tmp, "%s::%s", (*pce)->name, retval); + snprintf(tmp, len, "%s::%s", (*pce)->name, retval); free(retval); retval = tmp; } diff --git a/sapi/nsapi/nsapi.c b/sapi/nsapi/nsapi.c index b747c596030..9e0bd47ffea 100644 --- a/sapi/nsapi/nsapi.c +++ b/sapi/nsapi/nsapi.c @@ -642,7 +642,7 @@ static void sapi_nsapi_register_server_variables(zval *track_vars_array TSRMLS_D nsapi_free(value); } - sprintf(buf, "%d", conf_getglobals()->Vport); + snprintf(buf, sizeof(buf), "%d", conf_getglobals()->Vport); php_register_variable("SERVER_PORT", buf, track_vars_array TSRMLS_CC); php_register_variable("SERVER_NAME", conf_getglobals()->Vserver_hostname, track_vars_array TSRMLS_CC); @@ -695,7 +695,7 @@ static void sapi_nsapi_register_server_variables(zval *track_vars_array TSRMLS_D /* special variables in error mode */ if (rc->http_error) { - sprintf(buf, "%d", rc->http_error); + snprintf(buf, sizeof(buf), "%d", rc->http_error); php_register_variable("ERROR_TYPE", buf, track_vars_array TSRMLS_CC); } } diff --git a/sapi/tux/php_tux.c b/sapi/tux/php_tux.c index 23ca6ab0ec8..fd11bd8a42d 100644 --- a/sapi/tux/php_tux.c +++ b/sapi/tux/php_tux.c @@ -116,7 +116,7 @@ static int sapi_tux_send_headers(sapi_headers_struct *sapi_headers) status_line = malloc(30); /* safe sprintf use */ - len = sprintf(status_line, "HTTP/1.1 %d NA\r\n", SG(sapi_headers).http_response_code); + len = snprintf(status_line, 30, "HTTP/1.1 %d NA\r\n", SG(sapi_headers).http_response_code); vec[0].iov_base = status_line; vec[0].iov_len = len; @@ -195,7 +195,7 @@ static void sapi_tux_register_variables(zval *track_vars_array TSRMLS_DC) sapi_header_line ctr = {0}; ctr.line = buf; - ctr.line_len = sprintf(buf, "Server: %s", TUXAPI_version); + ctr.line_len = snprintf(buf, sizeof(buf), "Server: %s", TUXAPI_version); sapi_header_op(SAPI_HEADER_REPLACE, &ctr TSRMLS_CC); php_register_variable("PHP_SELF", SG(request_info).request_uri, track_vars_array TSRMLS_CC); @@ -215,7 +215,7 @@ static void sapi_tux_register_variables(zval *track_vars_array TSRMLS_DC) ADD_STRING("REMOTE_HOST"); } - sprintf(buf, "%d", CGI_SERVER_PORT(TG(req))); + snprintf(buf, sizeof(buf), "%d", CGI_SERVER_PORT(TG(req))); ADD_STRING("SERVER_PORT"); #if 0 @@ -241,7 +241,7 @@ static void sapi_tux_register_variables(zval *track_vars_array TSRMLS_DC) #if 0 if (TG(hc)->contentlength != -1) { - sprintf(buf, "%ld", (long) TG(hc)->contentlength); + snprintf(buf, sizeof(buf), "%ld", (long) TG(hc)->contentlength); ADD_STRING("CONTENT_LENGTH"); } #endif diff --git a/win32/registry.c b/win32/registry.c index e96bf918718..752bc381281 100644 --- a/win32/registry.c +++ b/win32/registry.c @@ -217,8 +217,7 @@ void UpdateIniFromRegistry(char *path TSRMLS_DC) while (*cwd == '\\' || *cwd == '/') { cwd++; } - path = (char *) emalloc(2+strlen(cwd)+1+strlen(orig_path)+1); - sprintf(path, "%c\\%s\\%s", drive_letter, cwd, orig_path); + spprintf(&path, 0, "%c\\%s\\%s", drive_letter, cwd, orig_path); efree(orig_path); orig_path = path; } diff --git a/win32/sendmail.c b/win32/sendmail.c index 850fa61492f..85af4d923f1 100644 --- a/win32/sendmail.c +++ b/win32/sendmail.c @@ -405,7 +405,7 @@ static int SendText(char *RPath, char *Subject, char *mailTo, char *mailCc, char return (BAD_MSG_DESTINATION); */ - sprintf(Buffer, "HELO %s\r\n", LocalHost); + snprintf(Buffer, sizeof(Buffer), "HELO %s\r\n", LocalHost); /* in the beggining of the dialog */ /* attempt reconnect if the first Post fail */ @@ -699,16 +699,13 @@ static int PostHeader(char *RPath, char *Subject, char *mailTo, char *xheaders T } } - if (NULL == (header_buffer = ecalloc(1, MAIL_BUFFER_SIZE))) { - efree(headers_lc); - return OUT_OF_MEMORY; - } + header_buffer = ecalloc(1, MAIL_BUFFER_SIZE); if (!xheaders || !strstr(headers_lc, "date:")) { time_t tNow = time(NULL); char *dt = php_format_date("r", 1, tNow, 1 TSRMLS_CC); - sprintf(header_buffer, "Date: %s\r\n", dt); + snprintf(header_buffer, MAIL_BUFFER_SIZE, "Date: %s\r\n", dt); efree(dt); }