From e0393f855740d87278ddd0b421bea6e497d53f33 Mon Sep 17 00:00:00 2001 From: Maksim Shabunin Date: Thu, 29 Jun 2017 16:40:22 +0300 Subject: [PATCH] Fixed some issues found by static analysis (4th round) --- modules/calib3d/src/ap3p.h | 2 +- modules/calib3d/src/epnp.cpp | 2 + modules/calib3d/src/upnp.cpp | 2 + modules/core/include/opencv2/core/cvstd.hpp | 4 +- modules/core/src/matrix.cpp | 16 ++++++ modules/dnn/src/layers/convolution_layer.cpp | 2 +- modules/dnn/src/layers/eltwise_layer.cpp | 2 +- .../dnn/src/layers/fully_connected_layer.cpp | 2 +- modules/dnn/src/layers/permute_layer.cpp | 2 +- modules/dnn/src/layers/pooling_layer.cpp | 12 +++-- modules/dnn/src/torch/THDiskFile.cpp | 8 +++ modules/features2d/src/brisk.cpp | 1 + modules/imgcodecs/src/bitstrm.cpp | 1 + modules/imgproc/src/approx.cpp | 1 + modules/imgproc/src/color.cpp | 4 +- modules/imgproc/src/contours.cpp | 12 ++++- modules/imgproc/src/convhull.cpp | 3 +- modules/imgproc/src/drawing.cpp | 1 + modules/imgproc/src/emd.cpp | 6 +-- modules/imgproc/src/histogram.cpp | 52 ++++++++++++++++--- modules/imgproc/src/thresh.cpp | 2 +- modules/imgproc/src/undistort.cpp | 8 +++ .../include/opencv2/objdetect/objdetect_c.h | 1 + .../objdetect/src/detection_based_tracker.cpp | 3 +- modules/objdetect/src/haar.cpp | 8 +-- modules/objdetect/src/hog.cpp | 14 ++++- ...fast_nlmeans_denoising_invoker_commons.hpp | 4 +- modules/videoio/src/cap_ffmpeg_impl.hpp | 38 ++++++++++---- modules/videoio/src/cap_mjpeg_decoder.cpp | 1 + 29 files changed, 168 insertions(+), 46 deletions(-) diff --git a/modules/calib3d/src/ap3p.h b/modules/calib3d/src/ap3p.h index 241e3e681b..df44198115 100644 --- a/modules/calib3d/src/ap3p.h +++ b/modules/calib3d/src/ap3p.h @@ -33,7 +33,7 @@ private: double fx, fy, cx, cy; double inv_fx, inv_fy, cx_fx, cy_fy; public: - ap3p() {} + ap3p() : fx(0), fy(0), cx(0), cy(0), inv_fx(0), inv_fy(0), cx_fx(0), cy_fy(0) {} ap3p(double fx, double fy, double cx, double cy); diff --git a/modules/calib3d/src/epnp.cpp b/modules/calib3d/src/epnp.cpp index 55971a365a..a173b88087 100644 --- a/modules/calib3d/src/epnp.cpp +++ b/modules/calib3d/src/epnp.cpp @@ -525,6 +525,8 @@ void epnp::qr_solve(CvMat * A, CvMat * b, CvMat * X) { const int nr = A->rows; const int nc = A->cols; + if (nc <= 0 || nr <= 0) + return; if (max_nr != 0 && max_nr < nr) { diff --git a/modules/calib3d/src/upnp.cpp b/modules/calib3d/src/upnp.cpp index 7074d00ec9..a674df543f 100644 --- a/modules/calib3d/src/upnp.cpp +++ b/modules/calib3d/src/upnp.cpp @@ -720,6 +720,8 @@ void upnp::qr_solve(Mat * A, Mat * b, Mat * X) { const int nr = A->rows; const int nc = A->cols; + if (nr <= 0 || nc <= 0) + return; if (max_nr != 0 && max_nr < nr) { diff --git a/modules/core/include/opencv2/core/cvstd.hpp b/modules/core/include/opencv2/core/cvstd.hpp index d401c894a1..83d5cdb5e3 100644 --- a/modules/core/include/opencv2/core/cvstd.hpp +++ b/modules/core/include/opencv2/core/cvstd.hpp @@ -49,7 +49,6 @@ #endif #include "opencv2/core/cvdef.h" - #include #include #include @@ -959,8 +958,9 @@ size_t String::find_last_of(const char* s, size_t pos) const inline String String::toLowerCase() const { + if (!cstr_) + return String(); String res(cstr_, len_); - for (size_t i = 0; i < len_; ++i) res.cstr_[i] = (char) ::tolower(cstr_[i]); diff --git a/modules/core/src/matrix.cpp b/modules/core/src/matrix.cpp index 09a074b88c..0e18ad20e0 100644 --- a/modules/core/src/matrix.cpp +++ b/modules/core/src/matrix.cpp @@ -5699,13 +5699,20 @@ double norm( const SparseMat& src, int normType ) { if( normType == NORM_INF ) for( i = 0; i < N; i++, ++it ) + { + CV_Assert(it.ptr); result = std::max(result, std::abs((double)it.value())); + } else if( normType == NORM_L1 ) for( i = 0; i < N; i++, ++it ) + { + CV_Assert(it.ptr); result += std::abs(it.value()); + } else for( i = 0; i < N; i++, ++it ) { + CV_Assert(it.ptr); double v = it.value(); result += v*v; } @@ -5714,13 +5721,20 @@ double norm( const SparseMat& src, int normType ) { if( normType == NORM_INF ) for( i = 0; i < N; i++, ++it ) + { + CV_Assert(it.ptr); result = std::max(result, std::abs(it.value())); + } else if( normType == NORM_L1 ) for( i = 0; i < N; i++, ++it ) + { + CV_Assert(it.ptr); result += std::abs(it.value()); + } else for( i = 0; i < N; i++, ++it ) { + CV_Assert(it.ptr); double v = it.value(); result += v*v; } @@ -5747,6 +5761,7 @@ void minMaxLoc( const SparseMat& src, double* _minval, double* _maxval, int* _mi float minval = FLT_MAX, maxval = -FLT_MAX; for( i = 0; i < N; i++, ++it ) { + CV_Assert(it.ptr); float v = it.value(); if( v < minval ) { @@ -5769,6 +5784,7 @@ void minMaxLoc( const SparseMat& src, double* _minval, double* _maxval, int* _mi double minval = DBL_MAX, maxval = -DBL_MAX; for( i = 0; i < N; i++, ++it ) { + CV_Assert(it.ptr); double v = it.value(); if( v < minval ) { diff --git a/modules/dnn/src/layers/convolution_layer.cpp b/modules/dnn/src/layers/convolution_layer.cpp index 50b84f7776..f5c782f4ee 100644 --- a/modules/dnn/src/layers/convolution_layer.cpp +++ b/modules/dnn/src/layers/convolution_layer.cpp @@ -289,7 +289,7 @@ public: ParallelConv() : input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0), - is1x1_(false), useAVX2(false) + biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX2(false) {} static void run( const Mat& input, Mat& output, const Mat& weights, diff --git a/modules/dnn/src/layers/eltwise_layer.cpp b/modules/dnn/src/layers/eltwise_layer.cpp index 6998c3ec42..12069e7ae3 100644 --- a/modules/dnn/src/layers/eltwise_layer.cpp +++ b/modules/dnn/src/layers/eltwise_layer.cpp @@ -120,7 +120,7 @@ public: int nstripes; const ActivationLayer* activ; - EltwiseInvoker() {} + EltwiseInvoker() : srcs(0), nsrcs(0), dst(0), coeffs(0), op(EltwiseLayer::PROD), nstripes(0), activ(0) {} static void run(const Mat** srcs, int nsrcs, Mat& dst, const std::vector& coeffs, EltwiseOp op, diff --git a/modules/dnn/src/layers/fully_connected_layer.cpp b/modules/dnn/src/layers/fully_connected_layer.cpp index 7adb0e5108..071593d7f5 100644 --- a/modules/dnn/src/layers/fully_connected_layer.cpp +++ b/modules/dnn/src/layers/fully_connected_layer.cpp @@ -119,7 +119,7 @@ public: class FullyConnected : public ParallelLoopBody { public: - FullyConnected() {} + FullyConnected() : srcMat(0), weights(0), biasMat(0), activ(0), dstMat(0), nstripes(0), useAVX2(false) {} static void run(const Mat& srcMat, const Mat& weights, const Mat& biasMat, Mat& dstMat, const ActivationLayer* activ, int nstripes) diff --git a/modules/dnn/src/layers/permute_layer.cpp b/modules/dnn/src/layers/permute_layer.cpp index c93f3ca9c7..56a2782f1d 100644 --- a/modules/dnn/src/layers/permute_layer.cpp +++ b/modules/dnn/src/layers/permute_layer.cpp @@ -195,7 +195,7 @@ public: parallel_for_(Range(0, nstripes), p, nstripes); } - PermuteInvoker() {} + PermuteInvoker() : inp(0), out(0), order(0), nstripes(0) {} void operator()(const Range& r) const { diff --git a/modules/dnn/src/layers/pooling_layer.cpp b/modules/dnn/src/layers/pooling_layer.cpp index 9da793afa5..ce99552b82 100644 --- a/modules/dnn/src/layers/pooling_layer.cpp +++ b/modules/dnn/src/layers/pooling_layer.cpp @@ -147,7 +147,7 @@ public: std::vector ofsbuf; int poolingType; - PoolingInvoker() {} + PoolingInvoker() : src(0), dst(0), mask(0), nstripes(0), computeMaxIdx(0), poolingType(PoolingLayer::MAX) {} static void run(const Mat& src, Mat& dst, Mat& mask, Size kernel, Size stride, Size pad, int poolingType, @@ -263,8 +263,11 @@ public: } v_store(dstData + x0, max_val0); v_store(dstData + x0 + 4, max_val1); - v_store(dstMaskData + x0, max_idx0); - v_store(dstMaskData + x0 + 4, max_idx1); + if (dstMaskData) + { + v_store(dstMaskData + x0, max_idx0); + v_store(dstMaskData + x0 + 4, max_idx1); + } x0 += 7; } else @@ -350,7 +353,8 @@ public: } dstData[x0] = max_val; - dstMaskData[x0] = max_index; + if (dstMaskData) + dstMaskData[x0] = max_index; } else { diff --git a/modules/dnn/src/torch/THDiskFile.cpp b/modules/dnn/src/torch/THDiskFile.cpp index 75e7d007e7..5f63ced48e 100644 --- a/modules/dnn/src/torch/THDiskFile.cpp +++ b/modules/dnn/src/torch/THDiskFile.cpp @@ -328,6 +328,8 @@ static long THDiskFile_readLong(THFile *self, int64 *data, long n) { int big_endian = !THDiskFile_isLittleEndianCPU(); int32_t *buffer = (int32_t*)THAlloc(8*n); + if (!buffer) + THError("can not allocate buffer"); nread = fread__(buffer, 8, n, dfself->handle); long i; for(i = nread; i > 0; i--) @@ -389,6 +391,8 @@ static long THDiskFile_readString(THFile *self, const char *format, char **str_) total += TBRS_BSZ; p = (char*)THRealloc(p, total); } + if (p == NULL) + THError("read error: failed to allocate buffer"); pos += fread(p+pos, 1, total-pos, dfself->handle); if (pos < total) /* eof? */ { @@ -502,9 +506,13 @@ THFile *THDiskFile_new(const char *name, const char *mode, int isQuiet) } self = (THDiskFile*)THAlloc(sizeof(THDiskFile)); + if (!self) + THError("cannot allocate memory for self"); self->handle = handle; self->name = (char*)THAlloc(strlen(name)+1); + if (!self->name) + THError("cannot allocate memory for self->name"); strcpy(self->name, name); self->isNativeEncoding = 1; self->longSize = 0; diff --git a/modules/features2d/src/brisk.cpp b/modules/features2d/src/brisk.cpp index 389650e809..955158da9c 100644 --- a/modules/features2d/src/brisk.cpp +++ b/modules/features2d/src/brisk.cpp @@ -776,6 +776,7 @@ BRISK_Impl::computeDescriptorsAndOrOrientation(InputArray _image, InputArray _ma const BriskShortPair* max = shortPairs_ + noShortPairs_; for (BriskShortPair* iter = shortPairs_; iter < max; ++iter) { + CV_Assert(iter->i < points_ && iter->j < points_); t1 = *(_values + iter->i); t2 = *(_values + iter->j); if (t1 > t2) diff --git a/modules/imgcodecs/src/bitstrm.cpp b/modules/imgcodecs/src/bitstrm.cpp index fdcbe75fdf..a7e187fa0c 100644 --- a/modules/imgcodecs/src/bitstrm.cpp +++ b/modules/imgcodecs/src/bitstrm.cpp @@ -337,6 +337,7 @@ WBaseStream::WBaseStream() { m_start = m_end = m_current = 0; m_file = 0; + m_block_pos = 0; m_block_size = BS_DEF_BLOCK_SIZE; m_is_opened = false; m_buf = 0; diff --git a/modules/imgproc/src/approx.cpp b/modules/imgproc/src/approx.cpp index ec0db30179..0960162607 100644 --- a/modules/imgproc/src/approx.cpp +++ b/modules/imgproc/src/approx.cpp @@ -83,6 +83,7 @@ CvSeq* icvApproximateChainTC89( CvChain* chain, int header_size, return cvEndWriteSeq( &writer ); } + reader.code = 0; cvStartReadChainPoints( chain, &reader ); temp.next = 0; diff --git a/modules/imgproc/src/color.cpp b/modules/imgproc/src/color.cpp index 6e554cfc35..488bdc1cc5 100644 --- a/modules/imgproc/src/color.cpp +++ b/modules/imgproc/src/color.cpp @@ -4486,7 +4486,7 @@ struct RGB2HSV_b { int b = src[bidx], g = src[1], r = src[bidx^2]; int h, s, v = b; - int vmin = b, diff; + int vmin = b; int vr, vg; CV_CALC_MAX_8U( v, g ); @@ -4494,7 +4494,7 @@ struct RGB2HSV_b CV_CALC_MIN_8U( vmin, g ); CV_CALC_MIN_8U( vmin, r ); - diff = v - vmin; + uchar diff = saturate_cast(v - vmin); vr = v == r ? -1 : 0; vg = v == g ? -1 : 0; diff --git a/modules/imgproc/src/contours.cpp b/modules/imgproc/src/contours.cpp index e05d1a935a..77af291a73 100644 --- a/modules/imgproc/src/contours.cpp +++ b/modules/imgproc/src/contours.cpp @@ -557,12 +557,12 @@ icvFetchContour( schar *ptr, else { i3 = i0; - CV_Assert(i3 != NULL); prev_s = s ^ 4; /* follow border */ for( ;; ) { + CV_Assert(i3 != NULL); s_end = s; s = std::min(s, MAX_SIZE - 1); @@ -652,7 +652,6 @@ icvTraceContour( schar *ptr, int step, schar *stop_ptr, int is_hole ) while( *i1 == 0 && s != s_end ); i3 = i0; - CV_Assert(i3 != NULL); /* check single pixel domain */ if( s != s_end ) @@ -660,6 +659,7 @@ icvTraceContour( schar *ptr, int step, schar *stop_ptr, int is_hole ) /* follow border */ for( ;; ) { + CV_Assert(i3 != NULL); s = std::min(s, MAX_SIZE - 1); while( s < MAX_SIZE - 1 ) @@ -739,12 +739,14 @@ icvFetchContourEx( schar* ptr, /* follow border */ for( ;; ) { + CV_Assert(i3 != NULL); s_end = s; s = std::min(s, MAX_SIZE - 1); while( s < MAX_SIZE - 1 ) { i4 = i3 + deltas[++s]; + CV_Assert(i4 != NULL); if( *i4 != 0 ) break; } @@ -815,6 +817,7 @@ icvFetchContourEx( schar* ptr, static int icvTraceContour_32s( int *ptr, int step, int *stop_ptr, int is_hole ) { + CV_Assert(ptr != NULL); int deltas[MAX_SIZE]; int *i0 = ptr, *i1, *i3, *i4 = NULL; int s, s_end; @@ -844,12 +847,14 @@ icvTraceContour_32s( int *ptr, int step, int *stop_ptr, int is_hole ) /* follow border */ for( ;; ) { + CV_Assert(i3 != NULL); s_end = s; s = std::min(s, MAX_SIZE - 1); while( s < MAX_SIZE - 1 ) { i4 = i3 + deltas[++s]; + CV_Assert(i4 != NULL); if( (*i4 & value_mask) == ccomp_val ) break; } @@ -873,6 +878,7 @@ icvFetchContourEx_32s( int* ptr, int _method, CvRect* _rect ) { + CV_Assert(ptr != NULL); int deltas[MAX_SIZE]; CvSeqWriter writer; int *i0 = ptr, *i1, *i3, *i4; @@ -926,11 +932,13 @@ icvFetchContourEx_32s( int* ptr, /* follow border */ for( ;; ) { + CV_Assert(i3 != NULL); s_end = s; do { i4 = i3 + deltas[++s]; + CV_Assert(i4 != NULL); } while( (*i4 & value_mask) != ccomp_val && ( s < MAX_SIZE - 1 ) ); s &= 7; diff --git a/modules/imgproc/src/convhull.cpp b/modules/imgproc/src/convhull.cpp index 1f8ef7b44b..c3287b8931 100644 --- a/modules/imgproc/src/convhull.cpp +++ b/modules/imgproc/src/convhull.cpp @@ -584,7 +584,7 @@ CV_IMPL CvSeq* cvConvexityDefects( const CvArr* array, hull = cvMakeSeqHeaderForArray( CV_SEQ_KIND_CURVE|CV_MAT_TYPE(mat->type)|CV_SEQ_FLAG_CLOSED, - sizeof(CvContour), CV_ELEM_SIZE(mat->type), mat->data.ptr, + sizeof(hull_header), CV_ELEM_SIZE(mat->type), mat->data.ptr, mat->cols + mat->rows - 1, &hull_header, &hullblock ); } @@ -664,6 +664,7 @@ CV_IMPL CvSeq* cvConvexityDefects( const CvArr* array, int t = *(int*)hull_reader.ptr; hull_next = CV_GET_SEQ_ELEM( CvPoint, ptseq, t ); } + CV_Assert(hull_next != NULL && hull_cur != NULL); dx0 = (double)hull_next->x - (double)hull_cur->x; dy0 = (double)hull_next->y - (double)hull_cur->y; diff --git a/modules/imgproc/src/drawing.cpp b/modules/imgproc/src/drawing.cpp index a31a19e995..0d1e785e97 100644 --- a/modules/imgproc/src/drawing.cpp +++ b/modules/imgproc/src/drawing.cpp @@ -2600,6 +2600,7 @@ cvDrawContours( void* _img, CvSeq* contour, void* clr = (contour->flags & CV_SEQ_FLAG_HOLE) == 0 ? ext_buf : hole_buf; cvStartReadSeq( contour, &reader, 0 ); + CV_Assert(reader.ptr != NULL); if( thickness < 0 ) pts.resize(0); diff --git a/modules/imgproc/src/emd.cpp b/modules/imgproc/src/emd.cpp index e5bc695729..3b1e4afc66 100644 --- a/modules/imgproc/src/emd.cpp +++ b/modules/imgproc/src/emd.cpp @@ -730,7 +730,7 @@ icvNewSolution( CvEMDState * state ) int i, j; float min_val = CV_EMD_INF; int steps; - CvNode2D head, *cur_x, *next_x, *leave_x = 0; + CvNode2D head = {0, {0}, 0, 0}, *cur_x, *next_x, *leave_x = 0; CvNode2D *enter_x = state->enter_x; CvNode2D **loop = state->loop; @@ -783,7 +783,7 @@ icvNewSolution( CvEMDState * state ) while( (next_x = cur_x->next[0]) != leave_x ) { cur_x = next_x; - assert( cur_x ); + CV_Assert( cur_x ); } cur_x->next[0] = next_x->next[0]; state->rows_x[i] = head.next[0]; @@ -793,7 +793,7 @@ icvNewSolution( CvEMDState * state ) while( (next_x = cur_x->next[1]) != leave_x ) { cur_x = next_x; - assert( cur_x ); + CV_Assert( cur_x ); } cur_x->next[1] = next_x->next[1]; state->cols_x[j] = head.next[1]; diff --git a/modules/imgproc/src/histogram.cpp b/modules/imgproc/src/histogram.cpp index 357038b36c..cdd10869db 100644 --- a/modules/imgproc/src/histogram.cpp +++ b/modules/imgproc/src/histogram.cpp @@ -83,7 +83,7 @@ calcHistLookupTables_8u( const Mat& hist, const SparseMat& shist, } } } - else + else if (ranges) { for( i = 0; i < dims; i++ ) { @@ -111,6 +111,10 @@ calcHistLookupTables_8u( const Mat& hist, const SparseMat& shist, } } } + else + { + CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided"); + } } @@ -938,7 +942,7 @@ calcHist_( std::vector& _ptrs, const std::vector& _deltas, } } } - else + else if (_ranges) { // non-uniform histogram const float* ranges[CV_MAX_DIM]; @@ -980,6 +984,10 @@ calcHist_( std::vector& _ptrs, const std::vector& _deltas, ptrs[i] += deltas[i*2 + 1]; } } + else + { + CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided"); + } } @@ -1457,8 +1465,10 @@ void cv::calcHist( const Mat* images, int nimages, const int* channels, if(histdata != hist.data) accumulate = false; - CV_IPP_RUN(nimages == 1 && dims == 1 && channels && channels[0] == 0 && _mask.empty() && images[0].dims <= 2, - ipp_calchist(images[0], hist, histSize[0], ranges, uniform, accumulate)); + CV_IPP_RUN( + nimages == 1 && dims == 1 && channels && channels[0] == 0 + && _mask.empty() && images[0].dims <= 2 && ranges && ranges[0], + ipp_calchist(images[0], hist, histSize[0], ranges, uniform, accumulate)); Mat ihist = hist; ihist.flags = (ihist.flags & ~CV_MAT_TYPE_MASK)|CV_32S; @@ -1537,7 +1547,7 @@ calcSparseHist_( std::vector& _ptrs, const std::vector& _deltas, ptrs[i] += deltas[i*2 + 1]; } } - else + else if (_ranges) { // non-uniform histogram const float* ranges[CV_MAX_DIM]; @@ -1577,6 +1587,10 @@ calcSparseHist_( std::vector& _ptrs, const std::vector& _deltas, ptrs[i] += deltas[i*2 + 1]; } } + else + { + CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided"); + } } @@ -1636,6 +1650,7 @@ static void calcHist( const Mat* images, int nimages, const int* channels, SparseMatIterator it = hist.begin(); for( i = 0, N = hist.nzcount(); i < N; i++, ++it ) { + CV_Assert(it.ptr != NULL); Cv32suf* val = (Cv32suf*)it.ptr; val->i = cvRound(val->f); } @@ -1666,6 +1681,7 @@ static void calcHist( const Mat* images, int nimages, const int* channels, SparseMatIterator it = hist.begin(); for( i = 0, N = hist.nzcount(); i < N; i++, ++it ) { + CV_Assert(it.ptr != NULL); Cv32suf* val = (Cv32suf*)it.ptr; val->f = (float)val->i; } @@ -1907,7 +1923,7 @@ calcBackProj_( std::vector& _ptrs, const std::vector& _deltas, } } } - else + else if (_ranges) { // non-uniform histogram const float* ranges[CV_MAX_DIM]; @@ -1949,6 +1965,10 @@ calcBackProj_( std::vector& _ptrs, const std::vector& _deltas, ptrs[i] += deltas[i*2 + 1]; } } + else + { + CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided"); + } } @@ -2153,7 +2173,7 @@ calcSparseBackProj_( std::vector& _ptrs, const std::vector& _deltas ptrs[i] += deltas[i*2 + 1]; } } - else + else if (_ranges) { // non-uniform histogram const float* ranges[CV_MAX_DIM]; @@ -2193,6 +2213,10 @@ calcSparseBackProj_( std::vector& _ptrs, const std::vector& _deltas ptrs[i] += deltas[i*2 + 1]; } } + else + { + CV_Error(Error::StsBadArg, "Either ranges, either uniform ranges should be provided"); + } } @@ -2260,7 +2284,6 @@ void cv::calcBackProject( const Mat* images, int nimages, const int* channels, dims, hist.hdr->size, ranges, uniform, ptrs, deltas, imsize, uniranges ); const double* _uniranges = uniform ? &uniranges[0] : 0; - int depth = images[0].depth(); if( depth == CV_8U ) calcSparseBackProj_8u(ptrs, deltas, imsize, hist, dims, ranges, @@ -2702,12 +2725,14 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) std::swap(PH1, PH2); SparseMatConstIterator it = PH1->begin(); + int N1 = (int)PH1->nzcount(), N2 = (int)PH2->nzcount(); if( (method == CV_COMP_CHISQR) || (method == CV_COMP_CHISQR_ALT) ) { for( i = 0; i < N1; i++, ++it ) { + CV_Assert(it.ptr != NULL); float v1 = it.value(); const SparseMat::Node* node = it.node(); float v2 = PH2->value(node->idx, (size_t*)&node->hashval); @@ -2723,6 +2748,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) for( i = 0; i < N1; i++, ++it ) { + CV_Assert(it.ptr != NULL); double v1 = it.value(); const SparseMat::Node* node = it.node(); s12 += v1*PH2->value(node->idx, (size_t*)&node->hashval); @@ -2733,6 +2759,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) it = PH2->begin(); for( i = 0; i < N2; i++, ++it ) { + CV_Assert(it.ptr != NULL); double v2 = it.value(); s2 += v2; s22 += v2*v2; @@ -2750,6 +2777,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) { for( i = 0; i < N1; i++, ++it ) { + CV_Assert(it.ptr != NULL); float v1 = it.value(); const SparseMat::Node* node = it.node(); float v2 = PH2->value(node->idx, (size_t*)&node->hashval); @@ -2763,6 +2791,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) for( i = 0; i < N1; i++, ++it ) { + CV_Assert(it.ptr != NULL); double v1 = it.value(); const SparseMat::Node* node = it.node(); double v2 = PH2->value(node->idx, (size_t*)&node->hashval); @@ -2772,7 +2801,10 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) it = PH2->begin(); for( i = 0; i < N2; i++, ++it ) + { + CV_Assert(it.ptr != NULL); s2 += it.value(); + } s1 *= s2; s1 = fabs(s1) > FLT_EPSILON ? 1./std::sqrt(s1) : 1.; @@ -2782,6 +2814,7 @@ double cv::compareHist( const SparseMat& H1, const SparseMat& H2, int method ) { for( i = 0; i < N1; i++, ++it ) { + CV_Assert(it.ptr != NULL); double v1 = it.value(); const SparseMat::Node* node = it.node(); double v2 = PH2->value(node->idx, (size_t*)&node->hashval); @@ -3444,7 +3477,10 @@ cvCalcArrHist( CvArr** img, CvHistogram* hist, int accumulate, const CvArr* mask cv::SparseMatConstIterator it = sH.begin(); int nz = (int)sH.nzcount(); for( i = 0; i < nz; i++, ++it ) + { + CV_Assert(it.ptr != NULL); *(float*)cvPtrND(sparsemat, it.node()->idx, 0, -2) = (float)*(const int*)it.ptr; + } } } diff --git a/modules/imgproc/src/thresh.cpp b/modules/imgproc/src/thresh.cpp index d740b9bd84..674d12bf28 100644 --- a/modules/imgproc/src/thresh.cpp +++ b/modules/imgproc/src/thresh.cpp @@ -206,7 +206,7 @@ thresh_8u( const Mat& _src, Mat& _dst, uchar thresh, uchar maxval, int type ) if( j_scalar < roi.width ) { const int thresh_pivot = thresh + 1; - uchar tab[256]; + uchar tab[256] = {0}; switch( type ) { case THRESH_BINARY: diff --git a/modules/imgproc/src/undistort.cpp b/modules/imgproc/src/undistort.cpp index 67bd034ea3..fbce448196 100644 --- a/modules/imgproc/src/undistort.cpp +++ b/modules/imgproc/src/undistort.cpp @@ -149,6 +149,14 @@ void cv::initUndistortRectifyMap( InputArray _cameraMatrix, InputArray _distCoef double _x = i*ir[1] + ir[2], _y = i*ir[4] + ir[5], _w = i*ir[7] + ir[8]; int j = 0; + + if (m1type == CV_16SC2) + CV_Assert(m1 != NULL && m2 != NULL); + else if (m1type == CV_32FC1) + CV_Assert(m1f != NULL && m2f != NULL); + else + CV_Assert(m1 != NULL); + #if CV_AVX2 if( USE_AVX2 ) { diff --git a/modules/objdetect/include/opencv2/objdetect/objdetect_c.h b/modules/objdetect/include/opencv2/objdetect/objdetect_c.h index b3ee7f411c..67dc2f4e66 100644 --- a/modules/objdetect/include/opencv2/objdetect/objdetect_c.h +++ b/modules/objdetect/include/opencv2/objdetect/objdetect_c.h @@ -69,6 +69,7 @@ extern "C" { (((const CvHaarClassifierCascade*)(haar))->flags & CV_MAGIC_MASK)==CV_HAAR_MAGIC_VAL) #define CV_HAAR_FEATURE_MAX 3 +#define CV_HAAR_STAGE_MAX 1000 typedef struct CvHaarFeature { diff --git a/modules/objdetect/src/detection_based_tracker.cpp b/modules/objdetect/src/detection_based_tracker.cpp index 88a1ce5fb4..4912948458 100644 --- a/modules/objdetect/src/detection_based_tracker.cpp +++ b/modules/objdetect/src/detection_based_tracker.cpp @@ -610,7 +610,8 @@ cv::DetectionBasedTracker::DetectionBasedTracker(cv::Ptr mainDetector && trackingDetector ); if (mainDetector) { - separateDetectionWork.reset(new SeparateDetectionWork(*this, mainDetector, params)); + Ptr tmp(new SeparateDetectionWork(*this, mainDetector, params)); + separateDetectionWork.swap(tmp); } weightsPositionsSmoothing.push_back(1); diff --git a/modules/objdetect/src/haar.cpp b/modules/objdetect/src/haar.cpp index c66d4de329..cb24479aa0 100644 --- a/modules/objdetect/src/haar.cpp +++ b/modules/objdetect/src/haar.cpp @@ -1848,7 +1848,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size ) sscanf( stage, "%d%n", &count, &dl ); stage += dl; - assert( count > 0 ); + CV_Assert( count > 0 && count < CV_HAAR_STAGE_MAX); cascade->stage_classifier[i].count = count; cascade->stage_classifier[i].classifier = (CvHaarClassifier*)cvAlloc( count*sizeof(cascade->stage_classifier[i].classifier[0])); @@ -1862,6 +1862,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size ) sscanf( stage, "%d%n", &classifier->count, &dl ); stage += dl; + CV_Assert( classifier->count > 0 && classifier->count< CV_HAAR_STAGE_MAX); classifier->haar_feature = (CvHaarFeature*) cvAlloc( classifier->count * ( sizeof( *classifier->haar_feature ) + sizeof( *classifier->threshold ) + @@ -1878,7 +1879,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size ) sscanf( stage, "%d%n", &rects, &dl ); stage += dl; - assert( rects >= 2 && rects <= CV_HAAR_FEATURE_MAX ); + CV_DbgAssert( rects >= 2 && rects <= CV_HAAR_FEATURE_MAX ); for( k = 0; k < rects; k++ ) { @@ -1890,7 +1891,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size ) stage += dl; classifier->haar_feature[l].rect[k].r = r; } - sscanf( stage, "%s%n", str, &dl ); + sscanf( stage, "%99s%n", str, &dl ); stage += dl; classifier->haar_feature[l].tilted = strncmp( str, "tilted", 6 ) == 0; @@ -1926,6 +1927,7 @@ icvLoadCascadeCART( const char** input_cascade, int n, CvSize orig_window_size ) } stage += dl; + CV_Assert(parent >= 0 && parent < i); cascade->stage_classifier[i].parent = parent; cascade->stage_classifier[i].next = next; cascade->stage_classifier[i].child = -1; diff --git a/modules/objdetect/src/hog.cpp b/modules/objdetect/src/hog.cpp index ed78e3bf52..ac02e67a36 100644 --- a/modules/objdetect/src/hog.cpp +++ b/modules/objdetect/src/hog.cpp @@ -3694,23 +3694,31 @@ void HOGDescriptor::readALTModel(String modelfile) String eerr("version?"); String efile(__FILE__); String efunc(__FUNCTION__); + fclose(modelfl); + throw Exception(Error::StsError, eerr, efile, efunc, __LINE__); } if(strcmp(version_buffer,"V6.01")) { String eerr("version doesnot match"); String efile(__FILE__); String efunc(__FUNCTION__); + fclose(modelfl); + throw Exception(Error::StsError, eerr, efile, efunc, __LINE__); } /* read version number */ int version = 0; if (!fread (&version,sizeof(int),1,modelfl)) - { throw Exception(); } + { + fclose(modelfl); + throw Exception(); + } if (version < 200) { String eerr("version doesnot match"); String efile(__FILE__); String efunc(__FUNCTION__); + fclose(modelfl); throw Exception(); } int kernel_type; @@ -3729,6 +3737,7 @@ void HOGDescriptor::readALTModel(String modelfile) nread=fread(&(coef_const),sizeof(double),1,modelfl); int l; nread=fread(&l,sizeof(int),1,modelfl); + CV_Assert(l >= 0 && l < 0xFFFF); char* custom = new char[l]; nread=fread(custom,sizeof(char),l,modelfl); delete[] custom; @@ -3749,11 +3758,13 @@ void HOGDescriptor::readALTModel(String modelfile) detector.clear(); if(kernel_type == 0) { /* linear kernel */ /* save linear wts also */ + CV_Assert(totwords + 1 > 0 && totwords < 0xFFFF); double *linearwt = new double[totwords+1]; int length = totwords; nread = fread(linearwt, sizeof(double), totwords + 1, modelfl); if(nread != static_cast(length) + 1) { delete [] linearwt; + fclose(modelfl); throw Exception(); } @@ -3764,6 +3775,7 @@ void HOGDescriptor::readALTModel(String modelfile) setSVMDetector(detector); delete [] linearwt; } else { + fclose(modelfl); throw Exception(); } fclose(modelfl); diff --git a/modules/photo/src/fast_nlmeans_denoising_invoker_commons.hpp b/modules/photo/src/fast_nlmeans_denoising_invoker_commons.hpp index d8eb344175..d36c85a840 100644 --- a/modules/photo/src/fast_nlmeans_denoising_invoker_commons.hpp +++ b/modules/photo/src/fast_nlmeans_denoising_invoker_commons.hpp @@ -397,7 +397,7 @@ template struct incWithWeight_ static inline void incWithWeight(IT* estimation, IT* weights_sum, WT weight, T p) { - return incWithWeight_::f(estimation, weights_sum, weight, p); + incWithWeight_::f(estimation, weights_sum, weight, p); } template struct divByWeightsSum_ @@ -434,7 +434,7 @@ template struct divByWeightsSum_ static inline void divByWeightsSum(IT* estimation, IT* weights_sum) { - return divByWeightsSum_::f(estimation, weights_sum); + divByWeightsSum_::f(estimation, weights_sum); } template struct saturateCastFromArray_ diff --git a/modules/videoio/src/cap_ffmpeg_impl.hpp b/modules/videoio/src/cap_ffmpeg_impl.hpp index afe083e523..8e6397bdf9 100644 --- a/modules/videoio/src/cap_ffmpeg_impl.hpp +++ b/modules/videoio/src/cap_ffmpeg_impl.hpp @@ -669,13 +669,13 @@ struct ImplMutex::Impl void ImplMutex::init() { - impl = (Impl*)malloc(sizeof(Impl)); + impl = new Impl(); impl->init(); } void ImplMutex::destroy() { impl->destroy(); - free(impl); + delete(impl); impl = NULL; } void ImplMutex::lock() { impl->lock(); } @@ -1387,7 +1387,7 @@ void CvVideoWriter_FFMPEG::init() static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bool alloc) { AVFrame * picture; - uint8_t * picture_buf; + uint8_t * picture_buf = 0; int size; #if LIBAVCODEC_BUILD >= (LIBAVCODEC_VERSION_MICRO >= 100 \ @@ -1416,6 +1416,7 @@ static AVFrame * icv_alloc_picture_FFMPEG(int pix_fmt, int width, int height, bo } else { } + return picture; } @@ -1511,6 +1512,8 @@ static AVStream *icv_add_video_stream_FFMPEG(AVFormatContext *oc, best= p; } } + if (best == NULL) + return NULL; c->time_base.den= best->num; c->time_base.num= best->den; } @@ -1796,25 +1799,28 @@ void CvVideoWriter_FFMPEG::close() av_free(outbuf); - if (!(fmt->flags & AVFMT_NOFILE)) + if (oc) { - /* close the output file */ + if (!(fmt->flags & AVFMT_NOFILE)) + { + /* close the output file */ #if LIBAVCODEC_VERSION_INT < ((52<<16)+(123<<8)+0) #if LIBAVCODEC_VERSION_INT >= ((51<<16)+(49<<8)+0) - url_fclose(oc->pb); + url_fclose(oc->pb); #else - url_fclose(&oc->pb); + url_fclose(&oc->pb); #endif #else - avio_close(oc->pb); + avio_close(oc->pb); #endif + } + + /* free the stream */ + avformat_free_context(oc); } - /* free the stream */ - avformat_free_context(oc); - av_freep(&aligned_input); init(); @@ -2114,6 +2120,8 @@ bool CvVideoWriter_FFMPEG::open( const char * filename, int fourcc, CvCapture_FFMPEG* cvCreateFileCapture_FFMPEG( const char* filename ) { CvCapture_FFMPEG* capture = (CvCapture_FFMPEG*)malloc(sizeof(*capture)); + if (!capture) + return 0; capture->init(); if( capture->open( filename )) return capture; @@ -2158,6 +2166,8 @@ CvVideoWriter_FFMPEG* cvCreateVideoWriter_FFMPEG( const char* filename, int four int width, int height, int isColor ) { CvVideoWriter_FFMPEG* writer = (CvVideoWriter_FFMPEG*)malloc(sizeof(*writer)); + if (!writer) + return 0; writer->init(); if( writer->open( filename, fourcc, fps, width, height, isColor != 0 )) return writer; @@ -2322,6 +2332,8 @@ AVStream* OutputMediaStream_FFMPEG::addVideoStream(AVFormatContext *oc, CV_CODEC } } + if (best == NULL) + return NULL; c->time_base.den= best->num; c->time_base.num= best->den; } @@ -2463,6 +2475,8 @@ void OutputMediaStream_FFMPEG::write(unsigned char* data, int size, int keyFrame struct OutputMediaStream_FFMPEG* create_OutputMediaStream_FFMPEG(const char* fileName, int width, int height, double fps) { OutputMediaStream_FFMPEG* stream = (OutputMediaStream_FFMPEG*) malloc(sizeof(OutputMediaStream_FFMPEG)); + if (!stream) + return 0; if (stream->open(fileName, width, height, fps)) return stream; @@ -2730,6 +2744,8 @@ bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFi InputMediaStream_FFMPEG* create_InputMediaStream_FFMPEG(const char* fileName, int* codec, int* chroma_format, int* width, int* height) { InputMediaStream_FFMPEG* stream = (InputMediaStream_FFMPEG*) malloc(sizeof(InputMediaStream_FFMPEG)); + if (!stream) + return 0; if (stream && stream->open(fileName, codec, chroma_format, width, height)) return stream; diff --git a/modules/videoio/src/cap_mjpeg_decoder.cpp b/modules/videoio/src/cap_mjpeg_decoder.cpp index 2ded72e72f..b5c5ff99f0 100644 --- a/modules/videoio/src/cap_mjpeg_decoder.cpp +++ b/modules/videoio/src/cap_mjpeg_decoder.cpp @@ -553,6 +553,7 @@ bool AviMjpegStream::parseHdrlList(MjpegInputStream& in_str) { m_is_indx_present = ((avi_hdr.dwFlags & 0x10) != 0); DWORD number_of_streams = avi_hdr.dwStreams; + CV_Assert(number_of_streams < 0xFF); m_width = avi_hdr.dwWidth; m_height = avi_hdr.dwHeight;