Debian Codegraph @

lang-maps/jni/src/jnialloc.h

raw
1 #ifndef BMCALLOC__H__INCLUDED__
2 #define BMCALLOC__H__INCLUDED__
3 /*
4 Copyright(c) 2002-2017 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com)
5
6 Permission is hereby granted, free of charge, to any person
7 obtaining a copy of this software and associated documentation
8 files (the "Software"), to deal in the Software without restriction,
9 including without limitation the rights to use, copy, modify, merge,
10 publish, distribute, sublicense, and/or sell copies of the Software,
11 and to permit persons to whom the Software is furnished to do so,
12 subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included
15 in all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
21 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 OTHER DEALINGS IN THE SOFTWARE.
24
25 For more information please visit: http://bmagic.sourceforge.net
26
27 */
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include "jni.h"
32 #include "try_throw_catch.h"
33
34 #include "bmfunc.h"
35
36 #define LOG2(x) (((x) & 8) ? 3 : (((x) & 4) ? 2 : (((x) & 2) ? 1 : 0)))
37 #define SIZE_OF_JAVA_LONG 8
38 #define DEADBEEF 0xdeadbeefdeadbeef
39
40 struct Jalloc {
41 // jlongArray ja;
42 jbyteArray ja;
43 jobject ref;
44 jsize sz;
45 };
46
47 static JavaVM *cached_jvm = 0;
48
49 JNIEXPORT jint JNICALL
50 JNI_OnLoad(JavaVM *jvm, void *reserved)
51 {
52 cached_jvm = 0; // disable java allocations
53 return JNI_VERSION_1_8;
54 }
55
56 static JNIEnv* JNU_GetEnv() {
57 JNIEnv *env;
58 jint rc = cached_jvm->GetEnv((void **)&env, JNI_VERSION_1_8);
59 if (rc == JNI_EDETACHED)
60 BM_THROW(BM_ERR_DETACHED);
61 if (rc == JNI_EVERSION)
62 BM_THROW(BM_ERR_JVM_NOT_SUPPORTED);
63
64 return env;
65 }
66
67 namespace libbm
68 {
69
70 //static void * array_alloc(int shift, size_t n) {
71 // //printf("Shift: %d\n", shift);
72 // if (shift < 0)
73 // BM_THROW(BM_ERR_BADALLOC);
74 //
75 // JNIEnv *env = JNU_GetEnv();
76 // jsize sz = (n >> shift) + 1 + (sizeof(Jalloc) >> 3) + 1 + 1; // The last one for overrun check
77 // //printf("Size to allocate: %d\n", sz);
78 // jlongArray ja = env->NewLongArray(sz);
79 // if (ja == NULL) {
80 // printf("Could not allocate %d units.", n);
81 // BM_THROW(BM_ERR_BADALLOC);
82 // }
83 //
84 // jlong *jlongbuf = env->GetLongArrayElements(ja, 0);
85 // if (jlongbuf == NULL)
86 // BM_THROW(BM_ERR_BADALLOC);
87 //
88 // // Put the marker
89 // jlongbuf[sz - 1] = 1;
90 //
91 // Jalloc *pJalloc = reinterpret_cast<Jalloc*>(jlongbuf);
92 // pJalloc->ref = env->NewGlobalRef(ja);
93 // if (pJalloc->ref == NULL)
94 // BM_THROW(BM_ERR_BADALLOC);
95 // pJalloc->ja = ja;
96 // pJalloc->sz = sz;
97 //
98 // //printf("Requested %d, allocated %p of size %d, with marker 0x%llx, ref %p, ja %p\n", n, jlongbuf, sz, jlongbuf[sz - 1], pJalloc->ref, ja);
99 // return static_cast<void*>(jlongbuf);
100 //}
101
102 //static void jni_free(void *p) {
103 // if (p != 0) {
104 // jlong *buffer = reinterpret_cast<jlong*>(static_cast<char*>(p) - sizeof(Jalloc));
105 // //printf("Freeing %p\n", buffer);
106 // Jalloc *pJalloc = reinterpret_cast<Jalloc*>(buffer);
107 // if (pJalloc->ref) {
108 // JNIEnv *env = JNU_GetEnv();
109 // // Check marker
110 // // jsize sz = env->GetArrayLength(pJalloc->ja);
111 // jsize sz = pJalloc->sz;
112 // switch (buffer[sz - 1]) {
113 // case 1L:
114 // --buffer[sz - 1];
115 // env->DeleteGlobalRef(pJalloc->ref);
116 // env->ReleaseLongArrayElements(pJalloc->ja, buffer, 0);
117 // printf("Released at %p\n", buffer);
118 // break;
119 // case 0:
120 // printf("Double deletion at %p\n", buffer);
121 // break;
122 // default:
123 // printf("Memory corruption 0x%llx at %p\n", buffer[sz - 1], buffer);
124 // }
125 // }
126 // }
127 //}
128
129 static void * array_alloc(int shift, size_t n) {
130 //printf("Shift: %d\n", shift);
131 if (shift < 0)
132 BM_THROW(BM_ERR_BADALLOC);
133
134 JNIEnv *env = JNU_GetEnv();
135 jsize sz = n + sizeof(Jalloc) + 1; // The last one for overrun check
136 printf("Sizes to allocate: n: %d, Jalloc: %d, total: %d\n", n, sizeof(Jalloc), sz);
137 jbyteArray ja = env->NewByteArray(sz);
138 if (ja == NULL) {
139 printf("Could not allocate %d units.", n);
140 BM_THROW(BM_ERR_BADALLOC);
141 }
142
143 jbyte *jbuf = env->GetByteArrayElements(ja, 0);
144 if (jbuf == NULL)
145 BM_THROW(BM_ERR_BADALLOC);
146
147 // Put the marker
148 jbuf[sz - 1] = 1;
149
150 Jalloc *pJalloc = reinterpret_cast<Jalloc*>(jbuf);
151 pJalloc->ref = env->NewGlobalRef(ja);
152 if (pJalloc->ref == NULL)
153 BM_THROW(BM_ERR_BADALLOC);
154 pJalloc->ja = ja;
155 pJalloc->sz = sz;
156
157 //printf("Requested %d, allocated %p of size %d, with marker 0x%llx, ref %p, ja %p\n", n, jlongbuf, sz, jlongbuf[sz - 1], pJalloc->ref, ja);
158 return static_cast<void*>(jbuf);
159 }
160
161 static void jni_free(void *p) {
162 if (p != 0) {
163 jbyte *buffer = reinterpret_cast<jbyte*>(static_cast<char*>(p) - sizeof(Jalloc));
164 //printf("Freeing %p\n", buffer);
165 Jalloc *pJalloc = reinterpret_cast<Jalloc*>(buffer);
166 if (pJalloc->ref) {
167 JNIEnv *env = JNU_GetEnv();
168 // Check marker
169 // jsize sz = env->GetArrayLength(pJalloc->ja);
170 jsize sz = pJalloc->sz;
171 switch (buffer[sz - 1]) {
172 case 1:
173 --buffer[sz - 1];
174 env->DeleteGlobalRef(pJalloc->ref);
175 env->ReleaseByteArrayElements(pJalloc->ja, buffer, 0);
176 printf("Released size %d at %p\n", sz, buffer);
177 break;
178 case 0:
179 printf("Double deletion, size %d at %p\n", sz, buffer);
180 break;
181 default:
182 printf("Memory corruption, size %d, 0x%x at %p\n", sz, buffer[sz - 1], buffer);
183 }
184 }
185 }
186 }
187
188 //template<typename T>
189 //T* jni_alloc(size_t n) {
190 //// printf("Allocating %d units in %s\n", n, __FUNCSIG__);
191 // //printf("Size of T: %d\n", LOG2(sizeof(T)));
192 // // Making array of longs to accommodate max value of unsigned int.
193 // // Java long size is 8 bytes
194 // int shift = LOG2(SIZE_OF_JAVA_LONG) - LOG2(sizeof(T));
195 // void* jbuffer = array_alloc(shift, n);
196 // void *mem = static_cast<char*>(jbuffer) + sizeof(Jalloc);
197 // fprintf(stderr, "Allocated %d at %p\n", n, mem);
198 // return reinterpret_cast<T*>(mem);
199 //}
200 //
201 //template <>
202 //void* jni_alloc(size_t n) {
203 // //printf("Allocating %d units in %s\n", n, __FUNCSIG__);
204 // int shift = LOG2(SIZE_OF_JAVA_LONG) - LOG2(sizeof(void*));
205 // void* jbuffer = array_alloc(shift, n);
206 // void *mem = static_cast<char*>(jbuffer) + sizeof(Jalloc);
207 // fprintf(stderr, "Allocated %d at %p\n", n, mem);
208 // return mem;
209 //}
210 //
211
212
213
214 class block_allocator
215 {
216 public:
217 static bm::word_t* allocate(size_t n, const void *)
218 {
219 bm::word_t* ptr;
220 #if defined(BMSSE2OPT) || defined(BMSSE42OPT)
221 # ifdef _MSC_VER
222 ptr = (bm::word_t*) ::_aligned_malloc(n * sizeof(bm::word_t), 16);
223 #else
224 ptr = (bm::word_t*) ::_mm_malloc(n * sizeof(bm::word_t), 16);
225 # endif
226
227 #else
228 //if (cached_jvm != 0) {
229 // ptr = jni_alloc<bm::word_t>(n);
230 //}
231 //else
232 ptr = (bm::word_t*) ::malloc(n * sizeof(bm::word_t));
233 #endif
234 if (!ptr)
235 {
236 BM_THROW( BM_ERR_BADALLOC );
237 }
238 return ptr;
239 }
240
241 static void deallocate(bm::word_t* p, size_t)
242 {
243 #if defined(BMSSE2OPT) || defined(BMSSE42OPT)
244 # ifdef _MSC_VER
245 ::_aligned_free(p);
246 #else
247 ::_mm_free(p);
248 # endif
249
250 #else
251 //if (cached_jvm != 0) {
252 // jni_free(p);
253 //}
254 //else
255 ::free(p);
256 #endif
257 }
258
259 };
260
261 class ptr_allocator
262 {
263 public:
264 static void* allocate(size_t n, const void *)
265 {
266 void* ptr = 0;
267 //if (cached_jvm != 0) {
268 // ptr = jni_alloc<void>(n);
269 //}
270 //else
271 ptr = ::malloc(n * sizeof(void*));
272
273 if (!ptr)
274 {
275 BM_THROW( BM_ERR_BADALLOC );
276 }
277 return ptr;
278 }
279
280 static void deallocate(void* p, size_t)
281 {
282 //if (cached_jvm != 0)
283 // jni_free(p);
284 //else
285 ::free(p);
286 }
287 };
288
289 /*
290 template<class BA, class PA> class mem_alloc
291 {
292 public:
293 typedef BA block_allocator_type;
294 typedef PA ptr_allocator_type;
295
296 public:
297 mem_alloc(const BA& block_alloc = BA(), const PA& ptr_alloc = PA())
298 : block_alloc_(block_alloc),
299 ptr_alloc_(ptr_alloc)
300 {}
301
302 block_allocator_type get_block_allocator() const
303 {
304 return BA(block_alloc_);
305 }
306
307 ptr_allocator_type get_ptr_allocator() const
308 {
309 return PA(block_alloc_);
310 }
311
312 bm::word_t* alloc_bit_block(unsigned alloc_factor = 1)
313 {
314 return block_alloc_.allocate(bm::set_block_size * alloc_factor, 0);
315 }
316
317 void free_bit_block(bm::word_t* block, unsigned alloc_factor = 1)
318 {
319 block_alloc_.deallocate(block, bm::set_block_size * alloc_factor);
320 }
321
322 bm::gap_word_t* alloc_gap_block(unsigned level,
323 const bm::gap_word_t* glevel_len)
324 {
325 unsigned len =
326 (unsigned)(glevel_len[level] / (sizeof(bm::word_t) / sizeof(bm::gap_word_t)));
327
328 return (bm::gap_word_t*)block_alloc_.allocate(len, 0);
329 }
330
331 void free_gap_block(bm::gap_word_t* block,
332 const bm::gap_word_t* glevel_len)
333 {
334 unsigned len = bm::gap_capacity(block, glevel_len);
335 len /= (unsigned)(sizeof(bm::word_t) / sizeof(bm::gap_word_t));
336 block_alloc_.deallocate((bm::word_t*)block, len);
337 }
338
339 void* alloc_ptr(unsigned size = bm::set_array_size)
340 {
341 return ptr_alloc_.allocate(size, 0);
342 }
343
344 void free_ptr(void* p, unsigned size = bm::set_array_size)
345 {
346 if (p)
347 ptr_alloc_.deallocate(p, size);
348 }
349 private:
350 BA block_alloc_;
351 PA ptr_alloc_;
352 };
353 */
354
355 /*
356 template<class BA, class PA> class alloc_pool;
357 typedef bm::alloc_pool<block_allocator, ptr_allocator> standard_alloc_pool;
358
359 template<class BA = block_allocator, class PA = ptr_allocator, class APool = standard_alloc_pool > class mem_alloc;
360 */
361
362 class pointer_pool_array
363 {
364 public:
365 enum params
366 {
367 n_pool_max_size = BM_DEFAULT_POOL_SIZE
368 };
369
370 pointer_pool_array() : size_(0)
371 {
372 allocate_pool(n_pool_max_size);
373 }
374
375 pointer_pool_array(const pointer_pool_array&) = delete;
376 pointer_pool_array& operator=(const pointer_pool_array&) = delete;
377
378 ~pointer_pool_array()
379 {
380 free_pool();
381 }
382
383 /// Push pointer to the pool (if it is not full)
384 ///
385 /// @return 0 if pointer is not accepted (pool is full)
386 unsigned push(void* ptr)
387 {
388 if (size_ == n_pool_max_size - 1)
389 return 0;
390 pool_ptr_[size_++] = ptr;
391 return size_;
392 }
393
394 /// Get a pointer if there are any vacant
395 ///
396 void* pop()
397 {
398 if (size_ == 0)
399 return 0;
400 return pool_ptr_[--size_];
401 }
402 private:
403 void allocate_pool(size_t pool_size)
404 {
405 pool_ptr_ = (void**)::malloc(sizeof(void*) * pool_size);
406 if (!pool_ptr_)
407 {
408 BM_THROW(BM_ERR_BADALLOC);
409 }
410 }
411
412 void free_pool()
413 {
414 ::free(pool_ptr_);
415 }
416 private:
417 void** pool_ptr_; ///< array of pointers in the pool
418 unsigned size_; ///< current size
419 };
420
421 template<class BA, class PA>
422 class alloc_pool
423 {
424 public:
425 typedef BA block_allocator_type;
426 typedef PA ptr_allocator_type;
427
428 public:
429
430 alloc_pool() {}
431 ~alloc_pool()
432 {
433 free_pools();
434 }
435
436 bm::word_t* alloc_bit_block()
437 {
438 bm::word_t* ptr = (bm::word_t*)block_pool_.pop();
439 if (ptr == 0)
440 ptr = block_alloc_.allocate(bm::set_block_size, 0);
441 return ptr;
442 }
443
444 void free_bit_block(bm::word_t* block)
445 {
446 if (!block_pool_.push(block))
447 {
448 block_alloc_.deallocate(block, bm::set_block_size);
449 }
450 }
451
452 void free_pools()
453 {
454 bm::word_t* block;
455 do
456 {
457 block = (bm::word_t*)block_pool_.pop();
458 if (block)
459 block_alloc_.deallocate(block, bm::set_block_size);
460 } while (block);
461 }
462
463 protected:
464 pointer_pool_array block_pool_;
465 BA block_alloc_;
466 };
467
468
469 template<class BA, class PA, class APool=alloc_pool<BA, PA> >
470 class mem_alloc
471 {
472 public:
473
474 typedef BA block_allocator_type;
475 typedef PA ptr_allocator_type;
476 typedef APool allocator_pool_type;
477
478 public:
479
480 mem_alloc(const BA& block_alloc = BA(), const PA& ptr_alloc = PA())
481 : block_alloc_(block_alloc),
482 ptr_alloc_(ptr_alloc),
483 alloc_pool_p_(0)
484 {}
485
486 mem_alloc(const mem_alloc& ma)
487 : block_alloc_(ma.block_alloc_),
488 ptr_alloc_(ma.ptr_alloc_),
489 alloc_pool_p_(0) // do not inherit pool (has to be explicitly defined)
490 {}
491
492 mem_alloc& operator=(const mem_alloc& ma)
493 {
494 block_alloc_ = ma.block_alloc_;
495 ptr_alloc_ = ma.ptr_alloc_;
496 // alloc_pool_p_ - do not inherit pool (has to be explicitly defined)
497 return *this;
498 }
499
500 /*! @brief Returns copy of the block allocator object
501 */
502 block_allocator_type get_block_allocator() const
503 {
504 return BA(block_alloc_);
505 }
506
507 /*! @brief Returns copy of the ptr allocator object
508 */
509 ptr_allocator_type get_ptr_allocator() const
510 {
511 return PA(block_alloc_);
512 }
513
514 /*! @brief set pointer to external pool */
515 void set_pool(allocator_pool_type* pool)
516 {
517 alloc_pool_p_ = pool;
518 }
519
520 /*! @brief get pointer to allocation pool (if set) */
521 allocator_pool_type* get_pool()
522 {
523 return alloc_pool_p_;
524 }
525
526 /*! @brief Allocates and returns bit block.
527 @param alloc_factor
528 indicated how many blocks we want to allocate in chunk
529 total allocation is going to be bm::set_block_size * alloc_factor
530 Default allocation factor is 1
531 */
532 bm::word_t* alloc_bit_block(unsigned alloc_factor = 1)
533 {
534 if (alloc_pool_p_ && alloc_factor == 1)
535 return alloc_pool_p_->alloc_bit_block();
536 return block_alloc_.allocate(bm::set_block_size * alloc_factor, 0);
537 }
538
539 /*! @brief Frees bit block allocated by alloc_bit_block.
540 */
541 void free_bit_block(bm::word_t* block, unsigned alloc_factor = 1)
542 {
543 if (alloc_pool_p_ && alloc_factor == 1)
544 alloc_pool_p_->free_bit_block(block);
545 else
546 block_alloc_.deallocate(block, bm::set_block_size * alloc_factor);
547 }
548
549 /*! @brief Allocates GAP block using bit block allocator (BA).
550
551 GAP blocks in BM library belong to levels. Each level has a
552 correspondent length described in bm::gap_len_table<>
553
554 @param level GAP block level.
555 @param glevel_len table of level lengths
556 */
557 bm::gap_word_t* alloc_gap_block(unsigned level,
558 const bm::gap_word_t* glevel_len)
559 {
560 unsigned len =
561 (unsigned)(glevel_len[level] / (sizeof(bm::word_t) / sizeof(bm::gap_word_t)));
562
563 return (bm::gap_word_t*)block_alloc_.allocate(len, 0);
564 }
565
566 /*! @brief Frees GAP block using bot block allocator (BA)
567 */
568 void free_gap_block(bm::gap_word_t* block,
569 const bm::gap_word_t* glevel_len)
570 {
571 unsigned len = bm::gap_capacity(block, glevel_len);
572 len /= (unsigned)(sizeof(bm::word_t) / sizeof(bm::gap_word_t));
573 block_alloc_.deallocate((bm::word_t*)block, len);
574 }
575
576 /*! @brief Allocates block of pointers.
577 */
578 void* alloc_ptr(unsigned size = bm::set_array_size)
579 {
580 return ptr_alloc_.allocate(size, 0);
581 }
582
583 /*! @brief Frees block of pointers.
584 */
585 void free_ptr(void* p, unsigned size = bm::set_array_size)
586 {
587 if (p)
588 ptr_alloc_.deallocate(p, size);
589 }
590 private:
591 BA block_alloc_;
592 PA ptr_alloc_;
593 allocator_pool_type* alloc_pool_p_;
594 };
595
596
597 typedef mem_alloc<block_allocator, ptr_allocator, alloc_pool<block_allocator, ptr_allocator> > standard_allocator;
598
599
600 /// Aligned malloc (unlike classic malloc it throws bad_alloc exception)
601 ///
602 /// @internal
603 inline
604 void* aligned_new_malloc(size_t size)
605 {
606 void* ptr;
607
608 #ifdef BM_ALLOC_ALIGN
609 #ifdef _MSC_VER
610 ptr = ::_aligned_malloc(size, BM_ALLOC_ALIGN);
611 #else
612 ptr = ::_mm_malloc(size, BM_ALLOC_ALIGN);
613 #endif
614 #else
615 ptr = ::malloc(size);
616 #endif
617 if (!ptr)
618 {
619 #ifndef BM_NO_STL
620 throw std::bad_alloc();
621 #else
622 BM_THROW(BM_ERR_BADALLOC);
623 #endif
624 }
625 return ptr;
626 }
627
628 /// Aligned free (safe to pass NULL ptr)
629 ///
630 /// @internal
631 inline
632 void aligned_free(void* ptr)
633 {
634 if (!ptr)
635 return;
636 #ifdef BM_ALLOC_ALIGN
637 # ifdef _MSC_VER
638 ::_aligned_free(ptr);
639 #else
640 ::_mm_free(ptr);
641 # endif
642 #else
643 ::free(ptr);
644 #endif
645 }
646
647
648 } // namespace libbm
649
650
651 #endif