Repository navigation
Expand file tree
/
Copy pathut0new.h
More file actions
2903 lines (2504 loc) · 110 KB
/
Copy pathut0new.h
File metadata and controls
2903 lines (2504 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
Copyright (c) 2014, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License, version 2.0, as published by the
Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
/** @file include/ut0new.h
Dynamic memory allocation routines and custom allocators specifically
crafted to support memory instrumentation through performance schema memory
engine (PFS).
*/
/** This file contains a set of libraries providing overloads for regular
dynamic allocation routines which allow for opt-in memory instrumentation
through performance schema memory engine (PFS).
In particular, _no_ regular dynamic allocation routines shall be used given
that the end goal of instrumentation through PFS is system observability
and resource control. In practice this means that we are off the chances to
use _any_ standard means of allocating the memory and that we have to
provide and re-implement our own PFS-aware variants ourselves.
This does not only apply to direct memory allocation through malloc or new
but also to data structures that may allocate dynamic memory under the hood,
like the ones from STL. For that reason, STL data structures shall always
be used with PFS-enabled custom memory allocator. STL algorithms OTOH
also _may_ allocate dynamic memory but they do not provide customization
point for user-code to provide custom memory allocation mechanism so there's
nothing that we can do about it.
Furthermore, facilities that allow safer memory management such as
std::unique_ptr, std::shared_ptr and their respective std::make_unique and
std::make_shared functions also have to be re-implemented as such so that
they become PFS-aware.
Following is the list of currently implemented PFS-enabled dynamic
allocation overloads and associated facilities:
* Primitive allocation functions:
* ut::malloc
* ut::zalloc
* ut::realloc
* ut::free
* ut::{malloc | zalloc | realloc}_withkey
* Primitive allocation functions for types with extended alignment:
* ut::aligned_alloc
* ut::aligned_zalloc
* ut::aligned_free
* ut::{aligned_alloc | aligned_zalloc}_withkey
* Primitive allocation functions for page-aligned allocations:
* ut::malloc_page
* ut::malloc_page_withkey
* ut::free_page
* Primitive allocation functions for large (huge) page aligned
allocations:
* ut::malloc_large_page
* ut::malloc_large_page_withkey
* ut::free_large_page
* Primitive allocation functions for large (huge) aligned allocations with
fallback to page-aligned allocations:
* ut::malloc_large_page(fallback_to_normal_page_t)
* ut::malloc_large_page_withkey(fallback_to_normal_page_t)
* ut::free_large_page(fallback_to_normal_page_t)
* Overloads for C++ new and delete syntax:
* ut::new_
* ut::new_arr
* ut::{new_ | new_arr_}_withkey
* ut::delete_
* ut::delete_arr
* Overloads for C++ new and delete syntax for types with extended
alignment:
* ut::aligned_new
* ut::aligned_new_arr
* ut::{aligned_new_ | aligned_new_arr_}_withkey
* ut::aligned_delete
* ut::aligned_delete_arr
* Custom memory allocators:
* ut::allocator
* Overloads for std::unique_ptr and std::shared_ptr factory functions
* ut::make_unique
* ut::make_unique_aligned
* ut::make_shared
* ut::make_shared_aligned
_withkey variants from above are the PFS-enabled dynamic allocation
overloads.
Usages of PFS-enabled library functions are trying to resemble already
familiar syntax as close as possible. For concrete examples please see
particular function documentation but in general it applies that ::foo(x)
becomes ut::foo(x) or ut::foo_withkey(key, x) where foo is some allocation
function listed above and key is PFS key to instrument the allocation with.
*/
#ifndef ut0new_h
#define ut0new_h
#include <algorithm>
#include <cerrno>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <type_traits> /* std::is_trivially_default_constructible */
#include <unordered_map>
#include <unordered_set>
#include "my_basename.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/psi/mysql_memory.h"
#include "mysql/psi/psi_memory.h"
namespace ut {
/** Can be used to extract pointer and size of the allocation provided by the
OS. It is a low level information, and is needed only to call low level
memory-related OS functions. */
struct allocation_low_level_info {
/** A pointer returned by the OS allocator. */
void *base_ptr;
/** The size of allocation that OS performed. */
size_t allocation_size;
};
} // namespace ut
#include "detail/ut0new.h"
#include "os0proc.h"
#include "os0thread.h"
#include "univ.i"
#include "ut0byte.h" /* ut_align */
#include "ut0cpu_cache.h"
#include "ut0dbg.h"
#include "ut0ut.h"
namespace ut {
/** Light-weight and type-safe wrapper around the PSI_memory_key
that eliminates the possibility of introducing silent bugs
through the course of implicit conversions and makes them
show up as compile-time errors.
Without this wrapper it was possible to say:
aligned_alloc_withkey(10*sizeof(int), key, 64))
Which would unfortunately compile just fine but it would silently
introduce a bug because it confuses the order of 10*sizeof(int) and
key input arguments. Both of them are unsigned types.
With the wrapper, aligned_alloc_withkey(10*sizeof(int), key, 64)) now
results with a compile-time error and the only proper way to accomplish
the original intent is to use PSI_memory_key_t wrapper like so:
aligned_alloc_withkey(PSI_memory_key_t{key}, 10*sizeof(int), 64))
Or by making use of the convenience function to create one:
aligned_alloc_withkey(make_psi_memory_key(key), 10*sizeof(int), 64))
*/
struct PSI_memory_key_t {
explicit PSI_memory_key_t(PSI_memory_key key) : m_key(key) {}
PSI_memory_key operator()() const { return m_key; }
PSI_memory_key m_key;
};
/** Convenience helper function to create type-safe representation of
PSI_memory_key.
@param[in] key PSI memory key to be held in type-safe PSI_memory_key_t.
@return PSI_memory_key_t which wraps the given PSI_memory_key
*/
inline PSI_memory_key_t make_psi_memory_key(PSI_memory_key key) {
return PSI_memory_key_t(key);
}
} // namespace ut
/** Maximum number of retries to allocate memory. */
extern const size_t alloc_max_retries;
/** Keys for registering allocations with performance schema.
Pointers to these variables are supplied to PFS code via the pfs_info[]
array and the PFS code initializes them via PSI_MEMORY_CALL(register_memory)().
mem_key_other and mem_key_std are special in the following way.
* If the caller has not provided a key and the file name of the caller is
unknown, then mem_key_std will be used. This happens only when called from
within std::* containers.
* If the caller has not provided a key and the file name of the caller is
known, but is not amongst the predefined names (see ut_new_boot()) then
mem_key_other will be used. Generally this should not happen and if it
happens then that means that the list of predefined names must be extended.
Keep this list alphabetically sorted. */
extern PSI_memory_key mem_key_ahi;
extern PSI_memory_key mem_key_archive;
extern PSI_memory_key mem_key_buf_buf_pool;
extern PSI_memory_key mem_key_buf_stat_per_index_t;
/** Memory key for clone */
extern PSI_memory_key mem_key_clone;
extern PSI_memory_key mem_key_dict_stats_bg_recalc_pool_t;
extern PSI_memory_key mem_key_dict_stats_index_map_t;
extern PSI_memory_key mem_key_dict_stats_n_diff_on_level;
extern PSI_memory_key mem_key_fil_space_t;
extern PSI_memory_key mem_key_lock_sys;
extern PSI_memory_key mem_key_redo_log_archive_queue_element;
extern PSI_memory_key mem_key_other;
extern PSI_memory_key mem_key_partitioning;
extern PSI_memory_key mem_key_row_log_buf;
extern PSI_memory_key mem_key_ddl;
extern PSI_memory_key mem_key_std;
extern PSI_memory_key mem_key_trx_sys_t_rw_trx_ids;
extern PSI_memory_key mem_key_undo_spaces;
extern PSI_memory_key mem_key_ut_lock_free_hash_t;
/* Please obey alphabetical order in the definitions above. */
/** Setup the internal objects needed for ut::*_withkey() to operate.
This must be called before the first call to ut::*_withkey(). */
void ut_new_boot();
/** Setup the internal objects needed for ut::*_withkey() to operate.
This must be called before the first call to ut::*_withkey(). This
version of function might be called several times and it will
simply skip all calls except the first one, during which the
initialization will happen. */
void ut_new_boot_safe();
#ifdef UNIV_PFS_MEMORY
/** List of filenames that allocate memory and are instrumented via PFS. */
static constexpr const char *auto_event_names[] = {
/* Keep this list alphabetically sorted. */
"api0api",
"api0misc",
"btr0btr",
"btr0cur",
"btr0load",
"btr0pcur",
"btr0sea",
"btr0types",
"buf",
"buf0buddy",
"buf0buf",
"buf0checksum",
"buf0dblwr",
"buf0dump",
"buf0flu",
"buf0lru",
"buf0rea",
"buf0stats",
"buf0types",
"checksum",
"crc32",
"create",
"data0data",
"data0type",
"data0types",
"db0err",
"ddl0buffer",
"ddl0builder",
"ddl0ctx",
"ddl0ddl",
"ddl0file-reader",
"ddl0loader",
"ddl0merge",
"ddl0rtree",
"ddl0par-scan",
"dict",
"dict0boot",
"dict0crea",
"dict0dd",
"dict0dict",
"dict0load",
"dict0mem",
"dict0priv",
"dict0sdi",
"dict0stats",
"dict0stats_bg",
"dict0types",
"dyn0buf",
"dyn0types",
"eval0eval",
"eval0proc",
"fil0fil",
"fil0types",
"file",
"fsp0file",
"fsp0fsp",
"fsp0space",
"fsp0sysspace",
"fsp0types",
"fts0ast",
"fts0blex",
"fts0config",
"fts0fts",
"fts0opt",
"fts0pars",
"fts0plugin",
"fts0priv",
"fts0que",
"fts0sql",
"fts0tlex",
"fts0tokenize",
"fts0types",
"fts0vlc",
"fut0fut",
"fut0lst",
"gis0geo",
"gis0rtree",
"gis0sea",
"gis0type",
"ha0ha",
"ha0storage",
"ha_innodb",
"ha_innopart",
"ha_prototypes",
"handler0alter",
"hash0hash",
"i_s",
"ib0mutex",
"ibuf0ibuf",
"ibuf0types",
"lexyy",
"lob0lob",
"lock0iter",
"lock0lock",
"lock0prdt",
"lock0priv",
"lock0types",
"lock0wait",
"log0log",
"log0recv",
"log0write",
"mach0data",
"mem",
"mem0mem",
"memory",
"mtr0log",
"mtr0mtr",
"mtr0types",
"os0atomic",
"os0event",
"os0file",
"os0numa",
"os0once",
"os0proc",
"os0thread",
"page",
"page0cur",
"page0page",
"page0size",
"page0types",
"page0zip",
"pars0grm",
"pars0lex",
"pars0opt",
"pars0pars",
"pars0sym",
"pars0types",
"que0que",
"que0types",
"read0read",
"read0types",
"rec",
"rem0cmp",
"rem0rec",
"rem0types",
"row0ext",
"row0ft",
"row0import",
"row0ins",
"row0log",
"row0mysql",
"row0purge",
"row0quiesce",
"row0row",
"row0sel",
"row0types",
"row0uins",
"row0umod",
"row0undo",
"row0upd",
"row0vers",
"sess0sess",
"srv0conc",
"srv0mon",
"srv0srv",
"srv0start",
"srv0tmp",
"sync0arr",
"sync0debug",
"sync0policy",
"sync0sharded_rw",
"sync0rw",
"sync0sync",
"sync0types",
"trx0i_s",
"trx0purge",
"trx0rec",
"trx0roll",
"trx0rseg",
"trx0sys",
"trx0trx",
"trx0types",
"trx0undo",
"trx0xa",
"usr0sess",
"usr0types",
"ut",
"ut0byte",
"ut0counter",
"ut0crc32",
"ut0dbg",
"ut0link_buf",
"ut0list",
"ut0lock_free_hash",
"ut0lst",
"ut0mem",
"ut0mutex",
"ut0new",
"ut0pool",
"ut0rbt",
"ut0rnd",
"ut0sort",
"ut0stage",
"ut0ut",
"ut0vec",
"ut0wqueue",
"zipdecompress",
};
static constexpr size_t n_auto = UT_ARR_SIZE(auto_event_names);
extern PSI_memory_key auto_event_keys[n_auto];
extern PSI_memory_info pfs_info_auto[n_auto];
/** gcc 5 fails to evaluate costexprs at compile time. */
#if defined(__GNUG__) && (__GNUG__ == 5)
/** Compute whether a string begins with a given prefix, compile-time.
@param[in] a first string, taken to be zero-terminated
@param[in] b second string (prefix to search for)
@param[in] b_len length in bytes of second string
@param[in] index character index to start comparing at
@return whether b is a prefix of a */
constexpr bool ut_string_begins_with(const char *a, const char *b, size_t b_len,
size_t index = 0) {
return (index == b_len || (a[index] == b[index] &&
ut_string_begins_with(a, b, b_len, index + 1)));
}
/** Find the length of the filename without its file extension.
@param[in] file filename, with extension but without directory
@param[in] index character index to start scanning for extension
separator at
@return length, in bytes */
constexpr size_t ut_len_without_extension(const char *file, size_t index = 0) {
return ((file[index] == '\0' || file[index] == '.')
? index
: ut_len_without_extension(file, index + 1));
}
/** Retrieve a memory key (registered with PFS), given the file name of the
caller.
@param[in] file portion of the filename - basename, with extension
@param[in] len length of the filename to check for
@param[in] index index of first PSI key to check
@return registered memory key or PSI_NOT_INSTRUMENTED if not found */
constexpr PSI_memory_key ut_new_get_key_by_base_file(const char *file,
size_t len,
size_t index = 0) {
return ((index == n_auto)
? PSI_NOT_INSTRUMENTED
: (ut_string_begins_with(auto_event_names[index], file, len)
? auto_event_keys[index]
: ut_new_get_key_by_base_file(file, len, index + 1)));
}
/** Retrieve a memory key (registered with PFS), given the file name of
the caller.
@param[in] file portion of the filename - basename, with extension
@return registered memory key or PSI_NOT_INSTRUMENTED if not found */
constexpr PSI_memory_key ut_new_get_key_by_file(const char *file) {
return (ut_new_get_key_by_base_file(file, ut_len_without_extension(file)));
}
#define UT_NEW_THIS_FILE_PSI_KEY ut_new_get_key_by_file(MY_BASENAME)
#else /* __GNUG__ == 5 */
/** Compute whether a string begins with a given prefix, compile-time.
@param[in] a first string, taken to be zero-terminated
@param[in] b second string (prefix to search for)
@param[in] b_len length in bytes of second string
@return whether b is a prefix of a */
constexpr bool ut_string_begins_with(const char *a, const char *b,
size_t b_len) {
for (size_t i = 0; i < b_len; ++i) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
/** Find the length of the filename without its file extension.
@param[in] file filename, with extension but without directory
@return length, in bytes */
constexpr size_t ut_len_without_extension(const char *file) {
for (size_t i = 0;; ++i) {
if (file[i] == '\0' || file[i] == '.') {
return i;
}
}
}
/** Retrieve a memory key (registered with PFS), given the file name of the
caller.
@param[in] file portion of the filename - basename, with extension
@param[in] len length of the filename to check for
@return index to registered memory key or -1 if not found */
constexpr int ut_new_get_key_by_base_file(const char *file, size_t len) {
for (size_t i = 0; i < n_auto; ++i) {
if (ut_string_begins_with(auto_event_names[i], file, len)) {
return static_cast<int>(i);
}
}
return -1;
}
/** Retrieve a memory key (registered with PFS), given the file name of
the caller.
@param[in] file portion of the filename - basename, with extension
@return index to memory key or -1 if not found */
constexpr int ut_new_get_key_by_file(const char *file) {
return ut_new_get_key_by_base_file(file, ut_len_without_extension(file));
}
// Sending an expression through a template variable forces the compiler to
// evaluate the expression at compile time (constexpr in itself has no such
// guarantee, only that the compiler is allowed).
template <int Value>
struct force_constexpr {
static constexpr int value = Value;
};
#define UT_NEW_THIS_FILE_PSI_INDEX \
(force_constexpr<ut_new_get_key_by_file(MY_BASENAME)>::value)
#define UT_NEW_THIS_FILE_PSI_KEY \
(UT_NEW_THIS_FILE_PSI_INDEX == -1 \
? ut::make_psi_memory_key(PSI_NOT_INSTRUMENTED) \
: ut::make_psi_memory_key(auto_event_keys[UT_NEW_THIS_FILE_PSI_INDEX]))
#endif /* __GNUG__ == 5 */
#else
#define UT_NEW_THIS_FILE_PSI_KEY ut::make_psi_memory_key(PSI_NOT_INSTRUMENTED)
#endif /* UNIV_PFS_MEMORY */
namespace ut {
#ifdef HAVE_PSI_MEMORY_INTERFACE
constexpr bool WITH_PFS_MEMORY = true;
#else
constexpr bool WITH_PFS_MEMORY = false;
#endif
/** Dynamically allocates storage of given size. Instruments the memory with
given PSI memory key in case PFS memory support is enabled.
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] size Size of storage (in bytes) requested to be allocated.
@return Pointer to the allocated storage. nullptr if dynamic storage
allocation failed.
Example:
int *x = static_cast<int*>(ut::malloc_withkey(key, 10*sizeof(int)));
*/
inline void *malloc_withkey(PSI_memory_key_t key, std::size_t size) noexcept {
using impl = detail::select_malloc_impl_t<WITH_PFS_MEMORY, false>;
using malloc_impl = detail::Alloc_<impl>;
return malloc_impl::alloc<false>(size, key());
}
/** Dynamically allocates storage of given size.
NOTE: Given that this function will _NOT_ be instrumenting the allocation
through PFS, observability for particular parts of the system which want to
use it will be lost or in best case inaccurate. Please have a strong reason
to do so.
@param[in] size Size of storage (in bytes) requested to be allocated.
@return Pointer to the allocated storage. nullptr if dynamic storage
allocation failed.
Example:
int *x = static_cast<int*>(ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY,
10*sizeof(int)));
*/
inline void *malloc(std::size_t size) noexcept {
return ut::malloc_withkey(make_psi_memory_key(PSI_NOT_INSTRUMENTED), size);
}
/** Dynamically allocates zero-initialized storage of given size. Instruments
the memory with given PSI memory key in case PFS memory support is enabled.
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] size Size of storage (in bytes) requested to be allocated.
@return Pointer to the zero-initialized allocated storage. nullptr if
dynamic storage allocation failed.
Example:
int *x = static_cast<int*>(ut::zalloc_withkey(key, 10*sizeof(int)));
*/
inline void *zalloc_withkey(PSI_memory_key_t key, std::size_t size) noexcept {
using impl = detail::select_malloc_impl_t<WITH_PFS_MEMORY, false>;
using malloc_impl = detail::Alloc_<impl>;
return malloc_impl::alloc<true>(size, key());
}
/** Dynamically allocates zero-initialized storage of given size.
NOTE: Given that this function will _NOT_ be instrumenting the allocation
through PFS, observability for particular parts of the system which want to
use it will be lost or in best case inaccurate. Please have a strong reason
to do so.
@param[in] size Size of storage (in bytes) requested to be allocated.
@return Pointer to the zero-initialized allocated storage. nullptr if
dynamic storage allocation failed.
Example:
int *x = static_cast<int*>(ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY,
10*sizeof(int)));
*/
inline void *zalloc(std::size_t size) noexcept {
return ut::zalloc_withkey(make_psi_memory_key(PSI_NOT_INSTRUMENTED), size);
}
/** Upsizes or downsizes already dynamically allocated storage to the new size.
Instruments the memory with given PSI memory key in case PFS memory support
is enabled.
It also supports standard realloc() semantics by:
* allocating size bytes of memory when passed ptr is nullptr
* freeing the memory pointed by ptr if passed size is 0
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] ptr Pointer to the memory area to be reallocated.
@param[in] size New size of storage (in bytes) requested to be reallocated.
@return Pointer to the reallocated storage. nullptr if dynamic storage
allocation failed.
Example:
int *x = static_cast<int*>(ut::malloc_withkey(key, 10*sizeof(int));
x = static_cast<int*>(ut::realloc_withkey(key, ptr, 100*sizeof(int)));
*/
inline void *realloc_withkey(PSI_memory_key_t key, void *ptr,
std::size_t size) noexcept {
using impl = detail::select_malloc_impl_t<WITH_PFS_MEMORY, false>;
using malloc_impl = detail::Alloc_<impl>;
return malloc_impl::realloc(ptr, size, key());
}
/** Upsizes or downsizes already dynamically allocated storage to the new size.
It also supports standard realloc() semantics by:
* allocating size bytes of memory when passed ptr is nullptr
* freeing the memory pointed by ptr if passed size is 0
NOTE: Given that this function will _NOT_ be instrumenting the allocation
through PFS, observability for particular parts of the system which want to
use it will be lost or in best case inaccurate. Please have a strong reason
to do so.
@param[in] ptr Pointer to the memory area to be reallocated.
@param[in] size New size of storage (in bytes) requested to be reallocated.
@return Pointer to the reallocated storage. nullptr if dynamic storage
allocation failed.
Example:
int *x = static_cast<int*>(ut::malloc_withkey(UT_NEW_THIS_FILE_PSI_KEY,
10*sizeof(int)); x = static_cast<int*>(ut::realloc(key, ptr,
100*sizeof(int)));
*/
inline void *realloc(void *ptr, std::size_t size) noexcept {
return ut::realloc_withkey(make_psi_memory_key(PSI_NOT_INSTRUMENTED), ptr,
size);
}
/** Releases storage which has been dynamically allocated through any of
the ut::malloc*(), ut::realloc* or ut::zalloc*() variants.
@param[in] ptr Pointer which has been obtained through any of the
ut::malloc*(), ut::realloc* or ut::zalloc*() variants.
Example:
ut::free(ptr);
*/
inline void free(void *ptr) noexcept {
using impl = detail::select_malloc_impl_t<WITH_PFS_MEMORY, false>;
using malloc_impl = detail::Alloc_<impl>;
malloc_impl::free(ptr);
}
/** Dynamically allocates storage for an object of type T. Constructs the object
of type T with provided Args. Instruments the memory with given PSI memory
key in case PFS memory support is enabled.
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] args Arguments one wishes to pass over to T constructor(s)
@return Pointer to the allocated storage. Throws std::bad_alloc exception
if dynamic storage allocation could not be fulfilled. Re-throws whatever
exception that may have occurred during the construction of T, in which case
it automatically cleans up the raw memory allocated for it.
Example 1:
int *ptr = ut::new_withkey<int>(key);
Example 2:
int *ptr = ut::new_withkey<int>(key, 10);
assert(*ptr == 10);
Example 3:
struct A {
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_withkey<A>(key, 1, 2);
assert(ptr->_x == 1);
assert(ptr->_y == 2);
*/
template <typename T, typename... Args>
inline T *new_withkey(PSI_memory_key_t key, Args &&...args) {
auto mem = ut::malloc_withkey(key, sizeof(T));
if (unlikely(!mem)) throw std::bad_alloc();
try {
new (mem) T(std::forward<Args>(args)...);
} catch (...) {
ut::free(mem);
throw;
}
return static_cast<T *>(mem);
}
/** Dynamically allocates storage for an object of type T. Constructs the object
of type T with provided Args.
NOTE: Given that this function will _NOT_ be instrumenting the allocation
through PFS, observability for particular parts of the system which want to
use it will be lost or in best case inaccurate. Please have a strong reason
to do so.
@param[in] args Arguments one wishes to pass over to T constructor(s)
@return Pointer to the allocated storage. Throws std::bad_alloc exception
if dynamic storage allocation could not be fulfilled. Re-throws whatever
exception that may have occurred during the construction of T, in which case
it automatically cleans up the raw memory allocated for it.
Example 1:
int *ptr = ut::new_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY);
Example 2:
int *ptr = ut::new_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY, 10);
assert(*ptr == 10);
Example 3:
struct A {
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_withkey<A>(UT_NEW_THIS_FILE_PSI_KEY, 1, 2);
assert(ptr->_x == 1);
assert(ptr->_y == 2);
*/
template <typename T, typename... Args>
inline T *new_(Args &&...args) {
return ut::new_withkey<T>(make_psi_memory_key(PSI_NOT_INSTRUMENTED),
std::forward<Args>(args)...);
}
/** Releases storage which has been dynamically allocated through any of
the ut::new*() variants. Destructs the object of type T.
@param[in] ptr Pointer which has been obtained through any of the
ut::new*() variants
Example:
ut::delete_(ptr);
*/
template <typename T>
inline void delete_(T *ptr) noexcept {
if (unlikely(!ptr)) return;
ptr->~T();
ut::free(ptr);
}
/** Dynamically allocates storage for an array of T's. Constructs objects of
type T with provided Args. Arguments that are to be used to construct some
respective instance of T shall be wrapped into a std::tuple. See examples
down below. Instruments the memory with given PSI memory key in case PFS
memory support is enabled.
To create an array of default-intialized T's, one can use this function
template but for convenience purposes one can achieve the same by using
the ut::new_arr_withkey with ut::Count overload.
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] args Tuples of arguments one wishes to pass over to T
constructor(s).
@return Pointer to the first element of allocated storage. Throws
std::bad_alloc exception if dynamic storage allocation could not be
fulfilled. Re-throws whatever exception that may have occurred during the
construction of any instance of T, in which case it automatically destroys
successfully constructed objects till that moment (if any), and finally
cleans up the raw memory allocated for T instances.
Example 1:
int *ptr = ut::new_arr_withkey<int>(key,
std::forward_as_tuple(1),
std::forward_as_tuple(2));
assert(ptr[0] == 1);
assert(ptr[1] == 2);
Example 2:
struct A {
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_arr_withkey<A>(key,
std::forward_as_tuple(0, 1), std::forward_as_tuple(2, 3),
std::forward_as_tuple(4, 5), std::forward_as_tuple(6, 7),
std::forward_as_tuple(8, 9));
assert(ptr[0]->_x == 0 && ptr[0]->_y == 1);
assert(ptr[1]->_x == 2 && ptr[1]->_y == 3);
assert(ptr[2]->_x == 4 && ptr[2]->_y == 5);
assert(ptr[3]->_x == 6 && ptr[3]->_y == 7);
assert(ptr[4]->_x == 8 && ptr[4]->_y == 9);
Example 3:
struct A {
A() : _x(10), _y(100) {}
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_arr_withkey<A>(key,
std::forward_as_tuple(0, 1), std::forward_as_tuple(2, 3),
std::forward_as_tuple(), std::forward_as_tuple(6, 7),
std::forward_as_tuple());
assert(ptr[0]->_x == 0 && ptr[0]->_y == 1);
assert(ptr[1]->_x == 2 && ptr[1]->_y == 3);
assert(ptr[2]->_x == 10 && ptr[2]->_y == 100);
assert(ptr[3]->_x == 6 && ptr[3]->_y == 7);
assert(ptr[4]->_x == 10 && ptr[4]->_y == 100);
*/
template <typename T, typename... Args>
inline T *new_arr_withkey(PSI_memory_key_t key, Args &&...args) {
using impl = detail::select_malloc_impl_t<WITH_PFS_MEMORY, true>;
using malloc_impl = detail::Alloc_<impl>;
auto mem = malloc_impl::alloc<false>(sizeof(T) * sizeof...(args), key());
if (unlikely(!mem)) throw std::bad_alloc();
size_t idx = 0;
try {
(...,
detail::construct<T>(mem, sizeof(T) * idx++, std::forward<Args>(args)));
} catch (...) {
for (size_t offset = (idx - 1) * sizeof(T); offset != 0;
offset -= sizeof(T)) {
reinterpret_cast<T *>(reinterpret_cast<std::uintptr_t>(mem) + offset -
sizeof(T))
->~T();
}
malloc_impl::free(mem);
throw;
}
return static_cast<T *>(mem);
}
/** Dynamically allocates storage for an array of T's. Constructs objects of
type T with provided Args. Arguments that are to be used to construct some
respective instance of T shall be wrapped into a std::tuple. See examples
down below.
To create an array of default-intialized T's, one can use this function
template but for convenience purposes one can achieve the same by using
the ut::new_arr_withkey with ut::Count overload.
NOTE: Given that this function will _NOT_ be instrumenting the allocation
through PFS, observability for particular parts of the system which want to
use it will be lost or in best case inaccurate. Please have a strong reason
to do so.
@param[in] args Tuples of arguments one wishes to pass over to T
constructor(s).
@return Pointer to the first element of allocated storage. Throws
std::bad_alloc exception if dynamic storage allocation could not be
fulfilled. Re-throws whatever exception that may have occurred during the
construction of any instance of T, in which case it automatically destroys
successfully constructed objects till that moment (if any), and finally
cleans up the raw memory allocated for T instances.
Example 1:
int *ptr = ut::new_arr_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY,
std::forward_as_tuple(1),
std::forward_as_tuple(2));
assert(ptr[0] == 1);
assert(ptr[1] == 2);
Example 2:
struct A {
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_arr_withkey<A>(UT_NEW_THIS_FILE_PSI_KEY,
std::forward_as_tuple(0, 1), std::forward_as_tuple(2, 3),
std::forward_as_tuple(4, 5), std::forward_as_tuple(6, 7),
std::forward_as_tuple(8, 9));
assert(ptr[0]->_x == 0 && ptr[0]->_y == 1);
assert(ptr[1]->_x == 2 && ptr[1]->_y == 3);
assert(ptr[2]->_x == 4 && ptr[2]->_y == 5);
assert(ptr[3]->_x == 6 && ptr[3]->_y == 7);
assert(ptr[4]->_x == 8 && ptr[4]->_y == 9);
Example 3:
struct A {
A() : _x(10), _y(100) {}
A(int x, int y) : _x(x), _y(y) {}
int _x, _y;
};
A *ptr = ut::new_arr_withkey<A>(UT_NEW_THIS_FILE_PSI_KEY,
std::forward_as_tuple(0, 1), std::forward_as_tuple(2, 3),
std::forward_as_tuple(), std::forward_as_tuple(6, 7),
std::forward_as_tuple());
assert(ptr[0]->_x == 0 && ptr[0]->_y == 1);
assert(ptr[1]->_x == 2 && ptr[1]->_y == 3);
assert(ptr[2]->_x == 10 && ptr[2]->_y == 100);
assert(ptr[3]->_x == 6 && ptr[3]->_y == 7);
assert(ptr[4]->_x == 10 && ptr[4]->_y == 100);
*/
template <typename T, typename... Args>
inline T *new_arr(Args &&...args) {
return ut::new_arr_withkey<T>(make_psi_memory_key(PSI_NOT_INSTRUMENTED),
std::forward<Args>(args)...);
}
/** Light-weight and type-safe wrapper which serves a purpose of
being able to select proper ut::new_arr* overload.
Without having a separate overload with this type, creating an array of
default-initialized instances of T through the ut::new_arr*(Args &&... args)
overload would have been impossible because:
int *ptr = ut::new_arr_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY, 5);
wouldn't even compile and
int *ptr = ut::new_arr_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY,
std::forward_as_tuple(5)); would compile but would not have intended effect.
It would create an array holding 1 integer element that is initialized to 5.
Given that function templates cannot be specialized, having an overload
crafted specifically for given case solves the problem:
int *ptr = ut::new_arr_withkey<int>(UT_NEW_THIS_FILE_PSI_KEY,
ut::Count{5});
*/
struct Count {
explicit Count(size_t count) : m_count(count) {}
size_t operator()() const { return m_count; }
size_t m_count;
};
/** Dynamically allocates storage for an array of T's. Constructs objects of
type T using default constructor. If T cannot be default-initialized (e.g.
default constructor does not exist), then this interface cannot be used for
constructing such an array. ut::new_arr_withkey overload with user-provided
initialization must be used then. Instruments the memory with given PSI
memory key in case PFS memory support is enabled.
@param[in] key PSI memory key to be used for PFS memory instrumentation.
@param[in] count Number of T elements in an array.
@return Pointer to the first element of allocated storage. Throws
std::bad_alloc exception if dynamic storage allocation could not be
fulfilled. Re-throws whatever exception that may have occurred during the
construction of any instance of T, in which case it automatically destroys