1/*****************************************************************************
2
3Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved.
4
5This program is free software; you can redistribute it and/or modify it under
6the terms of the GNU General Public License as published by the Free Software
7Foundation; version 2 of the License.
8
9This program is distributed in the hope that it will be useful, but WITHOUT
10ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12
13You should have received a copy of the GNU General Public License along with
14this program; if not, write to the Free Software Foundation, Inc.,
1551 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
16
17*****************************************************************************/
18
19/******************************************************************//**
20@file include/ut0ut.h
21Various utilities
22
23Created 1/20/1994 Heikki Tuuri
24***********************************************************************/
25
26#ifndef ut0ut_h
27#define ut0ut_h
28
29/* Do not include univ.i because univ.i includes this. */
30
31#include <ostream>
32#include <sstream>
33#include <string.h>
34
35#ifndef UNIV_INNOCHECKSUM
36
37#include "db0err.h"
38
39#include <time.h>
40
41#ifndef MYSQL_SERVER
42#include <ctype.h>
43#endif /* MYSQL_SERVER */
44
45#include <stdarg.h>
46
47#include <string>
48#include <my_atomic.h>
49
50/** Index name prefix in fast index creation, as a string constant */
51#define TEMP_INDEX_PREFIX_STR "\377"
52
53/** Time stamp */
54typedef time_t ib_time_t;
55
56#if defined (__GNUC__)
57# define UT_COMPILER_BARRIER() __asm__ __volatile__ ("":::"memory")
58#elif defined (_MSC_VER)
59# define UT_COMPILER_BARRIER() _ReadWriteBarrier()
60#else
61# define UT_COMPILER_BARRIER()
62#endif
63
64/*********************************************************************//**
65Delays execution for at most max_wait_us microseconds or returns earlier
66if cond becomes true.
67@param cond in: condition to wait for; evaluated every 2 ms
68@param max_wait_us in: maximum delay to wait, in microseconds */
69# define UT_WAIT_FOR(cond, max_wait_us) \
70do { \
71 uintmax_t start_us; \
72 start_us = ut_time_us(NULL); \
73 while (!(cond) \
74 && ut_time_us(NULL) - start_us < (max_wait_us)) {\
75 \
76 os_thread_sleep(2000 /* 2 ms */); \
77 } \
78} while (0)
79
80#define ut_max std::max
81#define ut_min std::min
82
83/** Calculate the minimum of two pairs.
84@param[out] min_hi MSB of the minimum pair
85@param[out] min_lo LSB of the minimum pair
86@param[in] a_hi MSB of the first pair
87@param[in] a_lo LSB of the first pair
88@param[in] b_hi MSB of the second pair
89@param[in] b_lo LSB of the second pair */
90UNIV_INLINE
91void
92ut_pair_min(
93 ulint* min_hi,
94 ulint* min_lo,
95 ulint a_hi,
96 ulint a_lo,
97 ulint b_hi,
98 ulint b_lo);
99/******************************************************//**
100Compares two ulints.
101@return 1 if a > b, 0 if a == b, -1 if a < b */
102UNIV_INLINE
103int
104ut_ulint_cmp(
105/*=========*/
106 ulint a, /*!< in: ulint */
107 ulint b); /*!< in: ulint */
108/** Compare two pairs of integers.
109@param[in] a_h more significant part of first pair
110@param[in] a_l less significant part of first pair
111@param[in] b_h more significant part of second pair
112@param[in] b_l less significant part of second pair
113@return comparison result of (a_h,a_l) and (b_h,b_l)
114@retval -1 if (a_h,a_l) is less than (b_h,b_l)
115@retval 0 if (a_h,a_l) is equal to (b_h,b_l)
116@retval 1 if (a_h,a_l) is greater than (b_h,b_l) */
117UNIV_INLINE
118int
119ut_pair_cmp(
120 ulint a_h,
121 ulint a_l,
122 ulint b_h,
123 ulint b_l)
124 MY_ATTRIBUTE((warn_unused_result));
125
126/*************************************************************//**
127Calculates fast the remainder of n/m when m is a power of two.
128@param n in: numerator
129@param m in: denominator, must be a power of two
130@return the remainder of n/m */
131#define ut_2pow_remainder(n, m) ((n) & ((m) - 1))
132/*************************************************************//**
133Calculates the biggest multiple of m that is not bigger than n
134when m is a power of two. In other words, rounds n down to m * k.
135@param n in: number to round down
136@param m in: alignment, must be a power of two
137@return n rounded down to the biggest possible integer multiple of m */
138#define ut_2pow_round(n, m) ((n) & ~((m) - 1))
139/** Align a number down to a multiple of a power of two.
140@param n in: number to round down
141@param m in: alignment, must be a power of two
142@return n rounded down to the biggest possible integer multiple of m */
143#define ut_calc_align_down(n, m) ut_2pow_round(n, m)
144/********************************************************//**
145Calculates the smallest multiple of m that is not smaller than n
146when m is a power of two. In other words, rounds n up to m * k.
147@param n in: number to round up
148@param m in: alignment, must be a power of two
149@return n rounded up to the smallest possible integer multiple of m */
150#define ut_calc_align(n, m) (((n) + ((m) - 1)) & ~((m) - 1))
151
152/*************************************************************//**
153Calculates fast the 2-logarithm of a number, rounded upward to an
154integer.
155@return logarithm in the base 2, rounded upward */
156UNIV_INLINE
157ulint
158ut_2_log(
159/*=====*/
160 ulint n); /*!< in: number */
161/*************************************************************//**
162Calculates 2 to power n.
163@return 2 to power n */
164UNIV_INLINE
165ulint
166ut_2_exp(
167/*=====*/
168 ulint n); /*!< in: number */
169/*************************************************************//**
170Calculates fast the number rounded up to the nearest power of 2.
171@return first power of 2 which is >= n */
172ulint
173ut_2_power_up(
174/*==========*/
175 ulint n) /*!< in: number != 0 */
176 MY_ATTRIBUTE((const));
177
178/** Determine how many bytes (groups of 8 bits) are needed to
179store the given number of bits.
180@param b in: bits
181@return number of bytes (octets) needed to represent b */
182#define UT_BITS_IN_BYTES(b) (((b) + 7) / 8)
183
184/**********************************************************//**
185Returns system time. We do not specify the format of the time returned:
186the only way to manipulate it is to use the function ut_difftime.
187@return system time */
188ib_time_t
189ut_time(void);
190/*=========*/
191
192/**********************************************************//**
193Returns system time.
194Upon successful completion, the value 0 is returned; otherwise the
195value -1 is returned and the global variable errno is set to indicate the
196error.
197@return 0 on success, -1 otherwise */
198int
199ut_usectime(
200/*========*/
201 ulint* sec, /*!< out: seconds since the Epoch */
202 ulint* ms); /*!< out: microseconds since the Epoch+*sec */
203
204/**********************************************************//**
205Returns the number of microseconds since epoch. Similar to
206time(3), the return value is also stored in *tloc, provided
207that tloc is non-NULL.
208@return us since epoch */
209uintmax_t
210ut_time_us(
211/*=======*/
212 uintmax_t* tloc); /*!< out: us since epoch, if non-NULL */
213/**********************************************************//**
214Returns the number of milliseconds since some epoch. The
215value may wrap around. It should only be used for heuristic
216purposes.
217@return ms since epoch */
218ulint
219ut_time_ms(void);
220/*============*/
221
222/**********************************************************//**
223Returns the number of milliseconds since some epoch. The
224value may wrap around. It should only be used for heuristic
225purposes.
226@return ms since epoch */
227ulint
228ut_time_ms(void);
229/*============*/
230
231/**********************************************************//**
232Returns the difference of two times in seconds.
233@return time2 - time1 expressed in seconds */
234double
235ut_difftime(
236/*========*/
237 ib_time_t time2, /*!< in: time */
238 ib_time_t time1); /*!< in: time */
239
240#endif /* !UNIV_INNOCHECKSUM */
241
242/** Determines if a number is zero or a power of two.
243@param[in] n number
244@return nonzero if n is zero or a power of two; zero otherwise */
245#define ut_is_2pow(n) UNIV_LIKELY(!((n) & ((n) - 1)))
246
247/** Functor that compares two C strings. Can be used as a comparator for
248e.g. std::map that uses char* as keys. */
249struct ut_strcmp_functor
250{
251 bool operator()(
252 const char* a,
253 const char* b) const
254 {
255 return(strcmp(a, b) < 0);
256 }
257};
258
259/**********************************************************//**
260Prints a timestamp to a file. */
261void
262ut_print_timestamp(
263/*===============*/
264 FILE* file) /*!< in: file where to print */
265 ATTRIBUTE_COLD __attribute__((nonnull));
266
267#ifndef UNIV_INNOCHECKSUM
268
269/**********************************************************//**
270Sprintfs a timestamp to a buffer, 13..14 chars plus terminating NUL. */
271void
272ut_sprintf_timestamp(
273/*=================*/
274 char* buf); /*!< in: buffer where to sprintf */
275/*************************************************************//**
276Runs an idle loop on CPU. The argument gives the desired delay
277in microseconds on 100 MHz Pentium + Visual C++.
278@return dummy value */
279void
280ut_delay(
281/*=====*/
282 ulint delay); /*!< in: delay in microseconds on 100 MHz Pentium */
283/*************************************************************//**
284Prints the contents of a memory buffer in hex and ascii. */
285void
286ut_print_buf(
287/*=========*/
288 FILE* file, /*!< in: file where to print */
289 const void* buf, /*!< in: memory buffer */
290 ulint len); /*!< in: length of the buffer */
291
292/*************************************************************//**
293Prints the contents of a memory buffer in hex. */
294void
295ut_print_buf_hex(
296/*=============*/
297 std::ostream& o, /*!< in/out: output stream */
298 const void* buf, /*!< in: memory buffer */
299 ulint len) /*!< in: length of the buffer */
300 MY_ATTRIBUTE((nonnull));
301/*************************************************************//**
302Prints the contents of a memory buffer in hex and ascii. */
303void
304ut_print_buf(
305/*=========*/
306 std::ostream& o, /*!< in/out: output stream */
307 const void* buf, /*!< in: memory buffer */
308 ulint len) /*!< in: length of the buffer */
309 MY_ATTRIBUTE((nonnull));
310
311/* Forward declaration of transaction handle */
312struct trx_t;
313
314/** Get a fixed-length string, quoted as an SQL identifier.
315If the string contains a slash '/', the string will be
316output as two identifiers separated by a period (.),
317as in SQL database_name.identifier.
318 @param [in] trx transaction (NULL=no quotes).
319 @param [in] name table name.
320 @retval String quoted as an SQL identifier.
321*/
322std::string
323ut_get_name(
324 const trx_t* trx,
325 const char* name);
326
327/**********************************************************************//**
328Outputs a fixed-length string, quoted as an SQL identifier.
329If the string contains a slash '/', the string will be
330output as two identifiers separated by a period (.),
331as in SQL database_name.identifier. */
332void
333ut_print_name(
334/*==========*/
335 FILE* ef, /*!< in: stream */
336 const trx_t* trx, /*!< in: transaction */
337 const char* name); /*!< in: table name to print */
338/** Format a table name, quoted as an SQL identifier.
339If the name contains a slash '/', the result will contain two
340identifiers separated by a period (.), as in SQL
341database_name.table_name.
342@see table_name_t
343@param[in] name table or index name
344@param[out] formatted formatted result, will be NUL-terminated
345@param[in] formatted_size size of the buffer in bytes
346@return pointer to 'formatted' */
347char*
348ut_format_name(
349 const char* name,
350 char* formatted,
351 ulint formatted_size);
352
353/**********************************************************************//**
354Catenate files. */
355void
356ut_copy_file(
357/*=========*/
358 FILE* dest, /*!< in: output file */
359 FILE* src); /*!< in: input file to be appended to output */
360
361/*************************************************************//**
362Convert an error number to a human readable text message. The
363returned string is static and should not be freed or modified.
364@return string, describing the error */
365const char*
366ut_strerr(
367/*======*/
368 dberr_t num); /*!< in: error number */
369
370#endif /* !UNIV_INNOCHECKSUM */
371
372#ifdef UNIV_PFS_MEMORY
373
374/** Extract the basename of a file without its extension.
375For example, extract "foo0bar" out of "/path/to/foo0bar.cc".
376@param[in] file file path, e.g. "/path/to/foo0bar.cc"
377@param[out] base result, e.g. "foo0bar"
378@param[in] base_size size of the output buffer 'base', if there
379is not enough space, then the result will be truncated, but always
380'\0'-terminated
381@return number of characters that would have been printed if the size
382were unlimited (not including the final ‘\0’) */
383size_t
384ut_basename_noext(
385 const char* file,
386 char* base,
387 size_t base_size);
388
389#endif /* UNIV_PFS_MEMORY */
390
391namespace ib {
392
393/** This is a wrapper class, used to print any unsigned integer type
394in hexadecimal format. The main purpose of this data type is to
395overload the global operator<<, so that we can print the given
396wrapper value in hex. */
397struct hex {
398 explicit hex(uintmax_t t): m_val(t) {}
399 const uintmax_t m_val;
400};
401
402/** This is an overload of the global operator<< for the user defined type
403ib::hex. The unsigned value held in the ib::hex wrapper class will be printed
404into the given output stream in hexadecimal format.
405@param[in,out] lhs the output stream into which rhs is written.
406@param[in] rhs the object to be written into lhs.
407@retval reference to the output stream. */
408inline
409std::ostream&
410operator<<(
411 std::ostream& lhs,
412 const hex& rhs)
413{
414 std::ios_base::fmtflags ff = lhs.flags();
415 lhs << std::showbase << std::hex << rhs.m_val;
416 lhs.setf(ff);
417 return(lhs);
418}
419
420/** The class logger is the base class of all the error log related classes.
421It contains a std::ostringstream object. The main purpose of this class is
422to forward operator<< to the underlying std::ostringstream object. Do not
423use this class directly, instead use one of the derived classes. */
424class logger {
425public:
426 template<typename T>
427 ATTRIBUTE_COLD
428 logger& operator<<(const T& rhs)
429 {
430 m_oss << rhs;
431 return(*this);
432 }
433
434 /** Write the given buffer to the internal string stream object.
435 @param[in] buf the buffer whose contents will be logged.
436 @param[in] count the length of the buffer buf.
437 @return the output stream into which buffer was written. */
438 ATTRIBUTE_COLD
439 std::ostream&
440 write(
441 const char* buf,
442 std::streamsize count)
443 {
444 return(m_oss.write(buf, count));
445 }
446
447 /** Write the given buffer to the internal string stream object.
448 @param[in] buf the buffer whose contents will be logged.
449 @param[in] count the length of the buffer buf.
450 @return the output stream into which buffer was written. */
451 ATTRIBUTE_COLD
452 std::ostream&
453 write(
454 const byte* buf,
455 std::streamsize count)
456 {
457 return(m_oss.write(reinterpret_cast<const char*>(buf), count));
458 }
459
460 std::ostringstream m_oss;
461protected:
462 /* This class must not be used directly, hence making the default
463 constructor protected. */
464 ATTRIBUTE_COLD
465 logger() {}
466};
467
468/** The class info is used to emit informational log messages. It is to be
469used similar to std::cout. But the log messages will be emitted only when
470the dtor is called. The preferred usage of this class is to make use of
471unnamed temporaries as follows:
472
473info() << "The server started successfully.";
474
475In the above usage, the temporary object will be destroyed at the end of the
476statement and hence the log message will be emitted at the end of the
477statement. If a named object is created, then the log message will be emitted
478only when it goes out of scope or destroyed. */
479class info : public logger {
480public:
481 ATTRIBUTE_COLD
482 ~info();
483};
484
485/** The class warn is used to emit warnings. Refer to the documentation of
486class info for further details. */
487class warn : public logger {
488public:
489 ATTRIBUTE_COLD
490 ~warn();
491};
492
493/** The class error is used to emit error messages. Refer to the
494documentation of class info for further details. */
495class error : public logger {
496public:
497 ATTRIBUTE_COLD
498 ~error();
499};
500
501/** The class fatal is used to emit an error message and stop the server
502by crashing it. Use this class when MySQL server needs to be stopped
503immediately. Refer to the documentation of class info for usage details. */
504class fatal : public logger {
505public:
506 ATTRIBUTE_NORETURN
507 ~fatal();
508};
509
510/** Emit an error message if the given predicate is true, otherwise emit a
511warning message */
512class error_or_warn : public logger {
513public:
514 ATTRIBUTE_COLD
515 error_or_warn(bool pred)
516 : m_error(pred)
517 {}
518
519 ATTRIBUTE_COLD
520 ~error_or_warn();
521private:
522 const bool m_error;
523};
524
525/** Emit a fatal message if the given predicate is true, otherwise emit a
526error message. */
527class fatal_or_error : public logger {
528public:
529 ATTRIBUTE_COLD
530 fatal_or_error(bool pred)
531 : m_fatal(pred)
532 {}
533
534 ATTRIBUTE_COLD
535 ~fatal_or_error();
536private:
537 const bool m_fatal;
538};
539
540} // namespace ib
541
542#include "ut0ut.ic"
543
544#endif
545
546