comparison Objects/stringobject.c @ 38299:ae6bbf2f2a41 legacy-trunk

needforspeed: check for overflow in replace (from Andrew Dalke)
author Fredrik Lundh <fredrik@pythonware.com>
date Thu, 25 May 2006 16:46:54 +0000
parents 41768de17ead
children 41809406a35e
comparison
equal deleted inserted replaced
38298:986bee16bb44 38299:ae6bbf2f2a41
2458 Py_ssize_t *out_len) 2458 Py_ssize_t *out_len)
2459 { 2459 {
2460 char *out_s; 2460 char *out_s;
2461 char *new_s; 2461 char *new_s;
2462 Py_ssize_t nfound, offset, new_len; 2462 Py_ssize_t nfound, offset, new_len;
2463 Py_ssize_t product, delta;
2463 2464
2464 if (len == 0 || (pat_len == 0 && sub_len == 0) || pat_len > len) 2465 if (len == 0 || (pat_len == 0 && sub_len == 0) || pat_len > len)
2465 goto return_same; 2466 goto return_same;
2466 2467
2467 /* find length of output string */ 2468 /* find length of output string */
2471 else if (nfound > count) 2472 else if (nfound > count)
2472 nfound = count; 2473 nfound = count;
2473 if (nfound == 0) 2474 if (nfound == 0)
2474 goto return_same; 2475 goto return_same;
2475 2476
2476 new_len = len + nfound*(sub_len - pat_len); 2477 delta = (sub_len - pat_len);
2478 if (delta == 0) {
2479 new_len = len;
2480 } else {
2481 product = nfound * (sub_len - pat_len);
2482 if ((product / (sub_len - pat_len)) != nfound) {
2483 PyErr_SetString(PyExc_OverflowError,
2484 "replace string is too long");
2485 return NULL;
2486 }
2487 new_len = len + product;
2488 if (new_len < 0) {
2489 PyErr_SetString(PyExc_OverflowError,
2490 "replace string is too long");
2491 return NULL;
2492 }
2493 }
2494
2477 if (new_len == 0) { 2495 if (new_len == 0) {
2478 /* Have to allocate something for the caller to free(). */ 2496 /* Have to allocate something for the caller to free(). */
2479 out_s = (char *)PyMem_MALLOC(1); 2497 out_s = (char *)PyMem_MALLOC(1);
2480 if (out_s == NULL) 2498 if (out_s == NULL)
2481 return NULL; 2499 return NULL;
2576 else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len)) 2594 else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len))
2577 return NULL; 2595 return NULL;
2578 2596
2579 new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len); 2597 new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len);
2580 if (new_s == NULL) { 2598 if (new_s == NULL) {
2581 PyErr_NoMemory(); 2599 if (!PyErr_Occurred())
2600 PyErr_NoMemory();
2582 return NULL; 2601 return NULL;
2583 } 2602 }
2584 if (out_len == -1) { 2603 if (out_len == -1) {
2585 if (PyString_CheckExact(self)) { 2604 if (PyString_CheckExact(self)) {
2586 /* we're returning another reference to self */ 2605 /* we're returning another reference to self */