1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
23 //   * Redistribution's in binary form must reproduce the above copyright notice,
24 //     this list of conditions and the following disclaimer in the documentation
25 //     and/or other materials provided with the distribution.
26 //
27 //   * The name of the copyright holders may not be used to endorse or promote products
28 //     derived from this software without specific prior written permission.
29 //
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
40 //
41 //M*/
42 
43 #include "precomp.hpp"
44 
45 #include <opencv2/core/utils/logger.defines.hpp>
46 #undef CV_LOG_STRIP_LEVEL
47 #define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE + 1
48 #include <opencv2/core/utils/logger.hpp>
49 #include <opencv2/core/utils/configuration.private.hpp>
50 
51 #define CV__ALLOCATOR_STATS_LOG(...) CV_LOG_VERBOSE(NULL, 0, "alloc.cpp: " << __VA_ARGS__)
52 #include "opencv2/core/utils/allocator_stats.impl.hpp"
53 #undef CV__ALLOCATOR_STATS_LOG
54 
55 //#define OPENCV_ALLOC_ENABLE_STATISTICS
56 #define OPENCV_ALLOC_STATISTICS_LIMIT 4096  // don't track buffers less than N bytes
57 
58 
59 #ifdef HAVE_POSIX_MEMALIGN
60 #include <stdlib.h>
61 #elif defined HAVE_MALLOC_H
62 #include <malloc.h>
63 #endif
64 
65 #ifdef OPENCV_ALLOC_ENABLE_STATISTICS
66 #include <map>
67 #endif
68 
69 namespace cv {
70 
OutOfMemoryError(size_t size)71 static void* OutOfMemoryError(size_t size)
72 {
73     CV_Error_(CV_StsNoMem, ("Failed to allocate %llu bytes", (unsigned long long)size));
74 }
75 
76 CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics();
77 
78 static cv::utils::AllocatorStatistics allocator_stats;
79 
getAllocatorStatistics()80 cv::utils::AllocatorStatisticsInterface& getAllocatorStatistics()
81 {
82     return allocator_stats;
83 }
84 
85 #if defined HAVE_POSIX_MEMALIGN || defined HAVE_MEMALIGN || defined HAVE_WIN32_ALIGNED_MALLOC
readMemoryAlignmentParameter()86 static bool readMemoryAlignmentParameter()
87 {
88     bool value = true;
89 #if defined(__GLIBC__) && defined(__linux__) \
90     && !defined(CV_STATIC_ANALYSIS) \
91     && !defined(OPENCV_ENABLE_MEMORY_SANITIZER) \
92     && !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)  /* oss-fuzz */ \
93     && !defined(_WIN32)  /* MinGW? */
94     {
95         // https://github.com/opencv/opencv/issues/15526
96         value = false;
97     }
98 #endif
99     value = cv::utils::getConfigurationParameterBool("OPENCV_ENABLE_MEMALIGN", value);  // should not call fastMalloc() internally
100     // TODO add checks for valgrind, ASAN if value == false
101     return value;
102 }
103 
104 #if defined _MSC_VER
105 #pragma warning(suppress:4714)  // preventive: const marked as __forceinline not inlined
106 static __forceinline
107 #else
108 static inline
109 #endif
isAlignedAllocationEnabled()110 bool isAlignedAllocationEnabled()
111 {
112     // use construct on first use idiom https://isocpp.org/wiki/faq/ctors#static-init-order-on-first-use
113     // details: https://github.com/opencv/opencv/issues/15691
114     static bool useMemalign = readMemoryAlignmentParameter();
115     return useMemalign;
116 }
117 
118 // need for this static const is disputed; retaining as it doesn't cause harm
119 static const bool g_force_initialization_memalign_flag
120 #if defined __GNUC__
121     __attribute__((unused))
122 #endif
123     = isAlignedAllocationEnabled();
124 #endif
125 
126 #ifdef OPENCV_ALLOC_ENABLE_STATISTICS
127 static inline
fastMalloc_(size_t size)128 void* fastMalloc_(size_t size)
129 #else
130 void* fastMalloc(size_t size)
131 #endif
132 {
133 #ifdef HAVE_POSIX_MEMALIGN
134     if (isAlignedAllocationEnabled())
135     {
136         void* ptr = NULL;
137         if(posix_memalign(&ptr, CV_MALLOC_ALIGN, size))
138             ptr = NULL;
139         if(!ptr)
140             return OutOfMemoryError(size);
141         return ptr;
142     }
143 #elif defined HAVE_MEMALIGN
144     if (isAlignedAllocationEnabled())
145     {
146         void* ptr = memalign(CV_MALLOC_ALIGN, size);
147         if(!ptr)
148             return OutOfMemoryError(size);
149         return ptr;
150     }
151 #elif defined HAVE_WIN32_ALIGNED_MALLOC
152     if (isAlignedAllocationEnabled())
153     {
154         void* ptr = _aligned_malloc(size, CV_MALLOC_ALIGN);
155         if(!ptr)
156             return OutOfMemoryError(size);
157         return ptr;
158     }
159 #endif
160     uchar* udata = (uchar*)malloc(size + sizeof(void*) + CV_MALLOC_ALIGN);
161     if(!udata)
162         return OutOfMemoryError(size);
163     uchar** adata = alignPtr((uchar**)udata + 1, CV_MALLOC_ALIGN);
164     adata[-1] = udata;
165     return adata;
166 }
167 
168 #ifdef OPENCV_ALLOC_ENABLE_STATISTICS
169 static inline
fastFree_(void * ptr)170 void fastFree_(void* ptr)
171 #else
172 void fastFree(void* ptr)
173 #endif
174 {
175 #if defined HAVE_POSIX_MEMALIGN || defined HAVE_MEMALIGN
176     if (isAlignedAllocationEnabled())
177     {
178         free(ptr);
179         return;
180     }
181 #elif defined HAVE_WIN32_ALIGNED_MALLOC
182     if (isAlignedAllocationEnabled())
183     {
184         _aligned_free(ptr);
185         return;
186     }
187 #endif
188     if(ptr)
189     {
190         uchar* udata = ((uchar**)ptr)[-1];
191         CV_DbgAssert(udata < (uchar*)ptr &&
192                ((uchar*)ptr - udata) <= (ptrdiff_t)(sizeof(void*)+CV_MALLOC_ALIGN));
193         free(udata);
194     }
195 }
196 
197 #ifdef OPENCV_ALLOC_ENABLE_STATISTICS
198 
199 static
getAllocationStatisticsMutex()200 Mutex& getAllocationStatisticsMutex()
201 {
202     static Mutex* p_alloc_mutex = allocSingletonNew<Mutex>();
203     CV_Assert(p_alloc_mutex);
204     return *p_alloc_mutex;
205 }
206 
207 static std::map<void*, size_t> allocated_buffers;  // guarded by getAllocationStatisticsMutex()
208 
fastMalloc(size_t size)209 void* fastMalloc(size_t size)
210 {
211     void* res = fastMalloc_(size);
212     if (res && size >= OPENCV_ALLOC_STATISTICS_LIMIT)
213     {
214         cv::AutoLock lock(getAllocationStatisticsMutex());
215         allocated_buffers.insert(std::make_pair(res, size));
216         allocator_stats.onAllocate(size);
217     }
218     return res;
219 }
220 
fastFree(void * ptr)221 void fastFree(void* ptr)
222 {
223     {
224         cv::AutoLock lock(getAllocationStatisticsMutex());
225         std::map<void*, size_t>::iterator i = allocated_buffers.find(ptr);
226         if (i != allocated_buffers.end())
227         {
228             size_t size = i->second;
229             allocator_stats.onFree(size);
230             allocated_buffers.erase(i);
231         }
232     }
233     fastFree_(ptr);
234 }
235 
236 #endif // OPENCV_ALLOC_ENABLE_STATISTICS
237 
238 } // namespace
239 
cvAlloc(size_t size)240 CV_IMPL void* cvAlloc( size_t size )
241 {
242     return cv::fastMalloc( size );
243 }
244 
cvFree_(void * ptr)245 CV_IMPL void cvFree_( void* ptr )
246 {
247     cv::fastFree( ptr );
248 }
249 
250 /* End of file. */
251