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